diff --git a/.gitignore b/.gitignore index 0b8a7fc..37057dd 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,9 @@ Cargo.lock .cargo/ .tracey/ +*.json.gz +callgrind* +cache.out +tarpaulin-report.html +*.bkp +coverage/ diff --git a/.ignore b/.ignore new file mode 100644 index 0000000..523ea06 --- /dev/null +++ b/.ignore @@ -0,0 +1,2 @@ +*.drawio +*.db diff --git a/.run_status.toml b/.run_status.toml new file mode 100644 index 0000000..d6c2a0d --- /dev/null +++ b/.run_status.toml @@ -0,0 +1,8 @@ +[last_run_clean] +run_status = "Success" +lines_parsed = 134 +coverage = 22.47 + +[last_run_clean.run_duration] +secs = 70 +nanos = 324790325 diff --git a/Cargo.toml b/Cargo.toml index b7db504..26bd5d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,10 @@ resolver = "3" # [workspace.package] # edition = "2024" # license = "MIT OR Apache-2.0" +[workspace.package] +version = "0.3.0" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [profile.dev] debug = 0 diff --git a/README.md b/README.md index 5baf08d..4c10907 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,10 @@ +![version](badges/version.svg) ![code coverage](badges/coverage.svg) + # ravenous-tools -Set of tools to handle ravenous rulebook creation \ No newline at end of file +Set of tools to handle ravenous rulebook creation + +# Installation +Now depends on libsqlite3-dev and sqlite3 +A bundled implementation should be added on all releases + diff --git a/badges/coverage.svg b/badges/coverage.svg new file mode 100644 index 0000000..6f62b2a --- /dev/null +++ b/badges/coverage.svg @@ -0,0 +1 @@ +test-coverage: 22%test-coverage22% diff --git a/badges/test.svg b/badges/test.svg new file mode 100644 index 0000000..a7859aa --- /dev/null +++ b/badges/test.svg @@ -0,0 +1 @@ +test: passingtestpassing diff --git a/badges/version.svg b/badges/version.svg new file mode 100644 index 0000000..a22915f --- /dev/null +++ b/badges/version.svg @@ -0,0 +1 @@ +version: 0.2.0version0.2.0 diff --git a/crates/cli_parser/src/lib.rs b/crates/cli_parser/src/lib.rs index f8d31d4..b3d1a51 100644 --- a/crates/cli_parser/src/lib.rs +++ b/crates/cli_parser/src/lib.rs @@ -4,11 +4,12 @@ use clap::{Args, Parser, Subcommand}; use config::{ + analysis::AnalysisConfig, formatter::FormatterConfig, graph::GraphConfig, make::{ - HELP_BLOCK_SELECTION, HELP_BUILD_TARGET_LIST, HELP_VERBOSITY_LEVEL, MakeTargets, - VerboseLevel, + MakeTargets, VerboseLevel, HELP_BLOCK_SELECTION, HELP_BUILD_TARGET_LIST, + HELP_VERBOSITY_LEVEL, }, statsolver::StatConfig, tablegen::{Craft, TableArgs}, @@ -45,6 +46,8 @@ pub enum Commands { Graphs(GraphConfig), /// Format the file given on input Format(FormatterConfig), + /// Generate analysis data + Analysis(AnalysisConfig), } #[derive(Debug, Args)] @@ -65,6 +68,8 @@ pub struct ConfigArgs { #[derive(Deserialize)] /// The config struct, holding all runtime information pub struct Config { + /// Config specific for data generation + pub data_generation: Datagen, /// Config specific for the classes table generation pub classes: Classes, /// Config for all the tables @@ -84,6 +89,13 @@ pub struct Classes { pub end: String, } +#[derive(Deserialize)] +/// The data generation configuration +pub struct Datagen { + /// Where to find the data generation database + pub database: String, +} + // The make structs #[derive(Args, Debug, Clone)] diff --git a/crates/config/src/analysis.rs b/crates/config/src/analysis.rs new file mode 100644 index 0000000..8e5ca1f --- /dev/null +++ b/crates/config/src/analysis.rs @@ -0,0 +1,54 @@ +// Workspace: config +// File: config/src/graph.rs +//! The inner config for the analysis module +//! + +use clap::{Parser, ValueEnum}; + +#[derive(Parser, Debug)] +/// Basic analisys CLI +pub struct AnalysisConfig { + #[arg(help = format!("The target to perform an analysis on [{:?}]", AnalysisTarget::value_variants()))] + /// The analysis target + pub target: AnalysisTarget, + + /// The path to save to. + pub path: Option, + /// Wether to generate shapes + #[arg(short('S'), long, default_value_t)] + pub no_shapes: bool, + /// Wether to generate materials + #[arg(short, long)] + pub materials: Option, + /// Wether to generate all natures + #[arg(short('N'), long)] + pub no_natures: bool, + /// Wether to generate all finishing + #[arg(short, long, default_value_t = false)] + pub finishing: bool, + #[arg(long, default_value_t = String::from("safe"))] + /// What function to sort by + pub sort: String, + // An html export path -h or -o + // A csv export path -c or --csv + // A presort --sort + // A prefilter with some filters ? + // - weapons + // - shields + // - armors + // - damage + // Data manipulation ?? + // - decimate + // - average per category +} + +#[derive(ValueEnum, Clone, Debug)] +/// The type of analysis to perform +pub enum AnalysisTarget { + /// Analysis over weapons + Weapon, + /// Analysis over armors + Armors, + /// Analysis over shields + Shields, +} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index cb79b28..e6b05c2 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -7,6 +7,7 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] // Internal Modules +pub mod analysis; pub mod fast_tables; pub mod formatter; pub mod graph; diff --git a/crates/make/src/lib.rs b/crates/make/src/lib.rs index bc35f63..2ecb392 100644 --- a/crates/make/src/lib.rs +++ b/crates/make/src/lib.rs @@ -2,7 +2,7 @@ // File: make/src/lib.rs //! The module `makepdf` is responsible for making a pdf using pdflatex. //! -//! The main function, [`make_pdf`](crate::makepdf::make_pdf), orchestrates the entire process of preparing, +//! The main function, [`make_pdf`], orchestrates the entire process of preparing, //! building, and cleaning up LaTeX files to produce a final PDF. It relies on several other modules //! within the `makepdf` workspace to perform specific tasks. //! diff --git a/crates/more_fields/Cargo.toml b/crates/more_fields/Cargo.toml new file mode 100644 index 0000000..1c83567 --- /dev/null +++ b/crates/more_fields/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "more_fields" +edition = "2024" +version.workspace = true + +[dependencies] +more_fields_macro = {path ="../more_fields_macro"} + +[dev-dependencies] +pretty_assertions = "1.4.1" + +[features] +expand_macro = [] diff --git a/crates/more_fields/src/lib.rs b/crates/more_fields/src/lib.rs new file mode 100644 index 0000000..6bfd4df --- /dev/null +++ b/crates/more_fields/src/lib.rs @@ -0,0 +1,66 @@ +// Workspace: more_fields +// File: more_fields/src/lib.rs +//! Get all the fields as a Vec<("attribute", "type")> +//! Note that this map is implemented without self, allowing us to use it only as a generic, +//! however this limitation is completely artificial + +pub use more_fields_macro::FieldsAsSlice; + +pub trait FieldsAsSlice { + fn attributes_slice() -> &'static [(&'static str, &'static str)]; +} + +// fn iter(&self) -> std::vec::IntoIter<(&'static str, &'static str)>; + +// #[cfg(feature = "expand_macro")] +// #[derive(FieldsAsSlice, Default)] +// struct Bob { +// #[TEXT] +// field_ouane: u16, +// #[INTEGER] +// field_2: u16, +// #[BLOB] +// field_3: u16, +// #[NULL] +// field_4: u16, +// #[REAL] +// field_5: u16, +// field_6: u16, +// } + +#[cfg(test)] +mod test { + use crate::FieldsAsSlice; + use pretty_assertions::assert_eq; + + #[allow(dead_code)] + #[derive(FieldsAsSlice, Default)] + struct Bob { + #[TEXT] + field_ouane: u16, + #[INTEGER] + field_2: u16, + #[BLOB] + field_3: u16, + #[NULL] + field_4: u16, + #[REAL] + field_5: u16, + field_6: u16, + } + #[test] + fn test_derive_impl() { + println!("{:?}", Bob::attributes_slice()); + // assert!( + let b_hash = vec![ + ("field_ouane", "TEXT"), + ("field_2", "INTEGER"), + ("field_3", "BLOB"), + ("field_4", "NULL"), + ("field_5", "REAL"), + ("field_6", "TEXT"), + ]; + + assert_eq!(Bob::attributes_slice(), b_hash); + } +} diff --git a/crates/more_fields_macro/Cargo.toml b/crates/more_fields_macro/Cargo.toml new file mode 100644 index 0000000..aee9a23 --- /dev/null +++ b/crates/more_fields_macro/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "more_fields_macro" +edition = "2024" +version.workspace = true + +[lib] +proc-macro = true + +[dependencies] +quote = "1.0.38" +syn = "2.0.98" diff --git a/crates/more_fields_macro/src/lib.rs b/crates/more_fields_macro/src/lib.rs new file mode 100644 index 0000000..25ad5d2 --- /dev/null +++ b/crates/more_fields_macro/src/lib.rs @@ -0,0 +1,83 @@ +// Workspace: more_fields_macro +// File: more_fields_macro/src/lib.rs +//! A very simple proc macro in chage of giving a field slice over ("name","sql_type") +//! This macro is a fork of the excellent work of : +//! +//! Other ressources include: +//! - +//! - +//! - +//! - +//! +// use proc_macro::TokenStream; +// use quote::quote; +// use syn::{Data, DeriveInput, Fields, parse_macro_input}; +#![feature(coverage_attribute)] +extern crate proc_macro; + +use proc_macro::{Span, TokenStream}; +use quote::quote; +use syn::DeriveInput; +use syn::Ident; +use syn::parse_macro_input; +use syn::{Data, Fields}; + +#[coverage(off)] +#[proc_macro_derive(FieldsAsSlice, attributes(INTEGER, NULL, REAL, TEXT, BLOB))] +pub fn derive_iterable(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + + let struct_name = input.ident; + let fields = match input.data { + Data::Struct(data_struct) => { + // let list_attrs = input.attrs.iter().map(|v| v.path()); + match data_struct.fields { + Fields::Named(fields_named) => fields_named.named, + _ => panic!("Only structs with named fields are supported"), + } + } + _ => panic!("Only structs are supported"), + }; + + let fields_iter = fields.iter().map(|field| { + let field_ident = &field.ident; + let val = field + .attrs + .iter() + .map(|v| v.path().get_ident()) + .next() + .flatten() + .cloned() + .unwrap_or_else(|| syn::Ident::new("TEXT", Span::call_site().into())) + .to_string(); + let field_name = field_ident.as_ref().unwrap().to_string(); + quote! { + (#field_name, #val) + } + }); + + let name_of_static_str = struct_name.to_string().to_ascii_uppercase() + "_ATTR_SLICE"; + let name_of_static = Ident::new(&name_of_static_str, Span::call_site().into()); + + let expanded = quote! { + /// Derived implementation of a (attribute, type) slice + /// allowing a constant time serialisation & deserialisation into rusqlite + const #name_of_static: &[(&str, &str)] = &[ + #(#fields_iter),* + ]; + + impl FieldsAsSlice for #struct_name { + /// Gives a precompiled slice of the &[(fields: &str, sqlite_type: &str)] + fn attributes_slice<'a>() -> &'static [(&'static str, &'static str)] { + #name_of_static + } + } + }; + + TokenStream::from(expanded) +} + +// As an hashmap (incorrect as of no ordering) +// let mut h = std::collections::HashMap::new(); +// #(h.insert(#fields_iter);)* +// h diff --git a/crates/ravenous-tools/Cargo.toml b/crates/ravenous-tools/Cargo.toml index 7f7d29e..d3947d5 100644 --- a/crates/ravenous-tools/Cargo.toml +++ b/crates/ravenous-tools/Cargo.toml @@ -1,7 +1,7 @@ # cargo-features = ["codegen-backend"] [package] name = "ravenous-tools" -version = "0.1.7" +version = "0.1.8" edition = "2024" [dependencies] @@ -12,6 +12,7 @@ cli_parser = {path = "../cli_parser"} stats = {path = "../stats"} make = {path = "../make"} formatter = {path = "../formatter"} +weaponry = {path = "../weaponry"} anyhow = "1.0.95" clap = { version = "4.5.28", features = ["derive"] } diff --git a/crates/ravenous-tools/src/main.rs b/crates/ravenous-tools/src/main.rs index cabeab5..a172e64 100644 --- a/crates/ravenous-tools/src/main.rs +++ b/crates/ravenous-tools/src/main.rs @@ -11,6 +11,7 @@ use graphs::make_graphs; use make::make_pdf; use stats::stat_solver; use tablegen::table_gen; +use weaponry::analysis::launch_analysis; // External imports use anyhow::{Context, Result}; @@ -33,6 +34,7 @@ fn main() -> Result<()> { Commands::Make(args) => make_pdf(&args, &config), Commands::Graphs(args) => make_graphs(&args, &config), Commands::Format(args) => format_file(&args, &config), + Commands::Analysis(args) => Ok(launch_analysis(&args, &config)?), // Not using anyhow but a custom error } } diff --git a/crates/weaponry/.run_status.toml b/crates/weaponry/.run_status.toml new file mode 100644 index 0000000..4ac0f3f --- /dev/null +++ b/crates/weaponry/.run_status.toml @@ -0,0 +1,8 @@ +[last_run_clean] +run_status = "Success" +lines_parsed = 57 +coverage = 60.03 + +[last_run_clean.run_duration] +secs = 19 +nanos = 961545465 diff --git a/crates/weaponry/Cargo.toml b/crates/weaponry/Cargo.toml index 66ccf03..089a28d 100644 --- a/crates/weaponry/Cargo.toml +++ b/crates/weaponry/Cargo.toml @@ -4,4 +4,32 @@ version = "0.1.1" edition = "2024" [dependencies] -rayon = "1.10.0" +config = {path = "../config"} +cli_parser = {path = "../cli_parser"} +more_fields = {path ="../more_fields"} +comfy-table = "7.1.4" +csv = "1.3.1" +probability = "0.20.3" +rusqlite = { version = "0.33.0" } # , features = ["bundled"] +serde = { version = "1.0.217", features = ["derive"] } +serde_rusqlite = "0.37.0" +serde_json = { version = "1.0.138", features = ["alloc"] } +strum = { version = "0.27.0", features = ["derive"] } +thiserror = "2.0.11" +regex = "1.11.1" +charming = { version = "0.4.0", features = [] } + +[dev-dependencies] +fastrand = "2.3.0" +criterion = { version = "0.5" } +regex = "1.11.1" +pretty_assertions = "^1.4" +logos = "^0.15" +clap = { version = "4.5.30", features = ["derive"] } + +[[bench]] +name = "iter_creation" +harness = false + +# [lints.rust] +# unexpected_cfgs = { level = "warn", check-cfg = ['cfg(tarpaulin_include)'] } diff --git a/crates/weaponry/benches/iter_creation.rs b/crates/weaponry/benches/iter_creation.rs new file mode 100644 index 0000000..801cb45 --- /dev/null +++ b/crates/weaponry/benches/iter_creation.rs @@ -0,0 +1,52 @@ +use criterion::{Criterion, criterion_group, criterion_main}; +use std::{hint::black_box, time::Duration}; +use weaponry::{ + interfaces::RecipeCollection, + weaponry_structs::{Equipement, InitialEquipementList}, +}; + +fn criterion_benchmark(c: &mut Criterion) { + let blk_steps = [ + InitialEquipementList::from_vectored(vec![Equipement::default(); 100]), + InitialEquipementList::from_vectored(vec![Equipement::default(); 100]), + InitialEquipementList::from_vectored(vec![Equipement::default(); 100]), + ]; + c.bench_function("creating 100 Elements", |b| { + b.iter(|| { + InitialEquipementList::from_vectored(black_box(vec![ + black_box(Equipement::default()); + 100 + ])) + }) + }); + c.bench_function("IterGenBlanket: 100x100x100", |b| { + b.iter(|| { + let mut s = blk_steps[0].clone(); + s.combine_all(black_box(&blk_steps[1])); + s.combine_all(black_box(&blk_steps[2])); + }) + }); + // c.bench_function("IterGen: 100x100x100x100", |b| { + // b.iter(|| { + // let mut s = steps[0].clone(); + // s.combine_all(steps[1].clone()); + // s.combine_all(steps[2].clone()); + // s.combine_all(steps[2].clone()); + // }) + // }); + // c.bench_function("IterGenPar: 100x100x100x100", |b| { + // b.iter(|| { + // let mut s = par_steps[0].clone(); + // s.combine_all(par_steps[1].clone()); + // s.combine_all(par_steps[2].clone()); + // s.combine_all(par_steps[2].clone()); + // }) + // }); +} + +criterion_group! { + name = benches; + config = Criterion::default().measurement_time(Duration::from_secs(10)); + targets= criterion_benchmark +} +criterion_main!(benches); diff --git a/crates/weaponry/databases/weapons.db b/crates/weaponry/databases/weapons.db new file mode 100644 index 0000000..7b39a9e Binary files /dev/null and b/crates/weaponry/databases/weapons.db differ diff --git a/crates/weaponry/examples/.rustfmt.toml b/crates/weaponry/examples/.rustfmt.toml new file mode 100644 index 0000000..9a9035c --- /dev/null +++ b/crates/weaponry/examples/.rustfmt.toml @@ -0,0 +1 @@ +# max_width = 278 diff --git a/crates/weaponry/examples/bench_serialisation_wl.rs b/crates/weaponry/examples/bench_serialisation_wl.rs new file mode 100644 index 0000000..4d86296 --- /dev/null +++ b/crates/weaponry/examples/bench_serialisation_wl.rs @@ -0,0 +1,21 @@ +// Workspace: weaponry +// File: examples/test_serialisation_wl.rs +//! Test of an initial serialisation and scenario wl +//! Doing this work on an example will help writing it as an integration test afterwards + +use weaponry::interfaces::RecipeDatabase; +use weaponry::weaponry_structs::equipement_impl_database::EquipementDatabase; +use weaponry::weaponry_structs::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}; + +fn main() { + let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); + let initial_deserialisation = db.serialize_vec_from_table::("Equipements", None); + // println!("Initial deserialisation in DatabaseEquipementStats: {:?}", initial_deserialisation); + // println!("First entry: {:?}", initial_deserialisation.as_ref().unwrap()[0]); + + let intermediate_deserialisation = initial_deserialisation.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::>(); + let f = intermediate_deserialisation.iter().fold((0, 0), |val, res| (val.0 + res.is_ok() as usize, val.1 + 1_usize)); + // println!("Final data {:#?}", intermediate_deserialisation); + println!("Failed to parse: {:#?}", intermediate_deserialisation.into_iter().filter_map(|v| v.err()).collect::>()); + println!("Succeded in parsing {}/{}", f.0, f.1); +} diff --git a/crates/weaponry/examples/typical_wl_recipe.rs b/crates/weaponry/examples/typical_wl_recipe.rs new file mode 100644 index 0000000..1efcc8a --- /dev/null +++ b/crates/weaponry/examples/typical_wl_recipe.rs @@ -0,0 +1,40 @@ +// Workspace: weaponry +// File: examples/typical_wl_recipe.rs +//! Example of a typical workload + +use std::time::Instant; + +use weaponry::{ + interfaces::RecipeCollection, + weaponry_structs::{Equipement, InitialEquipementList}, +}; + +fn main() { + let blk_steps = [ + InitialEquipementList::from_vectored( + [1; 100].iter().map(|_| Equipement::default()).collect(), + ), + InitialEquipementList::from_vectored( + [1; 100].iter().map(|_| Equipement::default()).collect(), + ), + InitialEquipementList::from_vectored( + [1; 100].iter().map(|_| Equipement::default()).collect(), + ), + ]; + + // #[cfg(test)] + // println!("{:#?}", blk_steps); + let now = Instant::now(); + let mut s = blk_steps[0].clone(); + println!("First size {}", s.ref_inner().len()); + s.combine_all(&blk_steps[0]); + println!("Second size {}", s.ref_inner().len()); + s.combine_all(&blk_steps[0]); + println!("Third size {}", s.ref_inner().len()); + s.combine_all(&blk_steps[0]); + + // println!("{:#?}", blk_steps); + // println!("{:#?}", s); + println!("Final size {}", s.ref_inner().len()); + println!("Ellapsed: {:?}", Instant::now().duration_since(now)); +} diff --git a/crates/weaponry/examples/usage_scenario.rs b/crates/weaponry/examples/usage_scenario.rs new file mode 100644 index 0000000..42a3a5e --- /dev/null +++ b/crates/weaponry/examples/usage_scenario.rs @@ -0,0 +1,137 @@ +// Workspace: weaponry +// File: examples/usage_scenario.rs +//! Test use case of a scenario +//! +//! +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 +use weaponry::weaponry_structs::CrossRecipeScenario; +use weaponry::weaponry_structs::equipement_scenario::ConfigEquipementScenario; +use weaponry::{ + interfaces::{Reportable, Scenario, ToCSV}, + weaponry_structs::RefinedEquipementList, +}; + +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.no_shapes).then_some(()), + materials: args.materials, + nature: (!args.no_natures).then_some(()), + finishing: args.finishing.then_some(()), + }) + .unwrap(); + + let mut refined_list = scenarios + .generate_refined_recipes() + .unwrap() + // .inner_filter(|e| (e.advanced.max_damage_per_attack > 0.)) + .inner_filter(|e| { + e.inner.category_base.as_ref().is_some_and(|v| { + !matches!(v, weaponry::weaponry_structs::WeaponBaseShape::Shields) + && !matches!(v, weaponry::weaponry_structs::WeaponBaseShape::Armors) + }) + }); + + match cmd_to_filter(&args.sort) { + Ok(cmd) => { + refined_list.inner_sort(cmd); + } + Err(FatalEquipementError::CLIParseError(a)) => { + println!("Argument incorrect '{a}'. Ignoring the sort.") + } + Err(e) => panic!("{e}"), + } + // if args.html_export{} + refined_list.write_html(&save_path).unwrap(); + + // if args.csv_export{} + // export_as_csv(&refined_list, save_path); +} +#[derive(Parser, Debug)] +/// Basic cli +pub struct CLIArgs { + /// The path to save to. + pub path: Option, + /// Wether to generate shapes + #[arg(short('S'), long, default_value_t)] + pub no_shapes: bool, + /// Wether to generate materials + #[arg(short, long)] + pub materials: Option, + /// Wether to generate all natures + #[arg(short('N'), long)] + pub no_natures: bool, + /// Wether to generate all finishing + #[arg(short, long, default_value_t = false)] + pub finishing: bool, + #[arg(long, default_value_t = String::from("safe"))] + 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)] +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"))) + ); +} + +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_2a_huge_hit); + return_if_starts_with!(speed); + return_if_starts_with!(scenario_damage); + return_if_starts_with!(defensive); + return_if_starts_with!(earlygame_sustained_damage_per_turn); + return_if_starts_with!(midgame_sustained_damage_per_turn); + return_if_starts_with!(endgame_sustained_damage_per_turn); + return_if_starts_with!(variance); + return_if_starts_with!(variance_pct); + Err(FatalEquipementError::CLIParseError(og_entry.to_string())) +} diff --git a/crates/weaponry/flow_and_structure.md b/crates/weaponry/flow_and_structure.md new file mode 100644 index 0000000..d5cba4e --- /dev/null +++ b/crates/weaponry/flow_and_structure.md @@ -0,0 +1,40 @@ +# Introduction +The generic nature of the recipe generator makes it rather complicated to navigate and comprehend; +however while suffering from many developpement mistakes and shortcommings, a good deal of code reuse was averted + +# Structure +The inner structures follow the following. + +| Underlaying data | Encapsulating Element | Encapsulating list of elements | +|-----------------------|----------------------------|--------------------------------| +| DatabaseInner (DeSer) | None | None | +| BaseInner (Converted) | InitialElement | InitialElementList | +| AdvancedInner (Calc) | RefinedElement (+BaseInner)| RefinedElementList | + + +# Explainations +| Category | Explainations | Traits | Impls | +|---------------------|------------------------------|----------------------------------------|------------------------| +| DatabaseInner | Deserialization InnerData | FieldsAsSclice | DatabaseEquipementStats| +| BaseInner | BuildingBlock InnerData | FieldAsSlice, Add, From | InnerEquipementStats | +| AdvancedInner | Calculated data for analysis | Serialize, From | AdvancedStats | +| IntermediateElement | Setup InitialElement | | EqFinishing, etc.. | +| InitialElement | Real Elements by Combination | From, Combinable | Equipement | +| RefinedElement | Export & Analysis | Serialize | RefinedEquipement | +| InitialElementList | Create list by cross combin. | RecipeCollection | InitialEquipementList | +| RefinedElementList | Analysis & Export | From + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/crates/weaponry/src/analysis.rs b/crates/weaponry/src/analysis.rs new file mode 100644 index 0000000..7188e54 --- /dev/null +++ b/crates/weaponry/src/analysis.rs @@ -0,0 +1,160 @@ +// Workspace: weaponry +// File: weaponry/src/analysis.rs +//! The one stop shop for analysis + +use std::{cmp::Ordering, path::Path}; + +use cli_parser::Config; +use config::analysis::AnalysisConfig; + +use crate::{ + error::FatalEquipementError, + interfaces::{Reportable, Scenario, ToAnalysis, ToCSV, ToTex}, + weaponry_structs::{ + CrossRecipeScenario, RefinedEquipement, RefinedEquipementList, + equipement_scenario::ConfigEquipementScenario, + }, +}; + +/// Launch the analysis of the selected data and export it to html for human processing +pub fn launch_analysis(args: &AnalysisConfig, config: &Config) -> Result<(), FatalEquipementError> { + match args.target { + config::analysis::AnalysisTarget::Weapon => create_graphs( + args, + config, + Box::new(|e: &RefinedEquipement| { + e.inner.category_base.as_ref().is_some_and(|v| { + !matches!(v, crate::weaponry_structs::WeaponBaseShape::Shields) + && !matches!(v, crate::weaponry_structs::WeaponBaseShape::Armors) + }) + }), + ), + config::analysis::AnalysisTarget::Armors => create_graphs( + args, + config, + Box::new(|e: &RefinedEquipement| { + e.inner + .category_base + .as_ref() + .is_some_and(|v| matches!(v, crate::weaponry_structs::WeaponBaseShape::Armors)) + }), + ), + config::analysis::AnalysisTarget::Shields => create_graphs( + args, + config, + Box::new(|e: &RefinedEquipement| { + e.inner + .category_base + .as_ref() + .is_some_and(|v| matches!(v, crate::weaponry_structs::WeaponBaseShape::Shields)) + }), + ), + } + Ok(()) +} + +/// Create all graphs with +fn create_graphs(args: &AnalysisConfig, config: &Config, filter: DynamicFilterType) { + let save_path = args.path.clone().unwrap_or("data/first_data".into()); + let scenarios = CrossRecipeScenario::new_with_config(ConfigEquipementScenario { + table_name: "Equipements".into(), + db_path: config.data_generation.database.clone(), + shape: (!args.no_shapes).then_some(()), + materials: args.materials, + nature: (!args.no_natures).then_some(()), + finishing: args.finishing.then_some(()), + }) + .unwrap(); + + let mut refined_list = scenarios + .generate_refined_recipes() + .unwrap() + // .inner_filter(|e| (e.advanced.max_damage_per_attack > 0.)) + .inner_filter(filter); + + match cmd_to_filter(&args.sort) { + Ok(cmd) => { + refined_list.inner_sort(cmd); + } + Err(FatalEquipementError::CLIParseError(a)) => { + println!("Argument incorrect '{a}'. Ignoring the sort.") + } + Err(e) => panic!("{e}"), + } + // if args.html_export{} + refined_list.write_html(&save_path).unwrap(); + + // if args.csv_export{} + // export_as_csv(&refined_list, &save_path); + + // if args.tex_export{} + // export_as_tex(&refined_list, &save_path); +} + +#[allow(dead_code)] +/// Export as a csv a refine equipement list +/// +/// Rarely used and likely on it's way to deprecation +fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) { + println!("{}", refined_list.get_report(Some("Refined List"))); + println!( + "Saved initial data as {}.html: {:?}", + save_path, + refined_list.write_csv(Path::new(&format!("{save_path}.csv"))) + ); +} +/// Export as a tex file in the given directory +/// +/// Generic function dispatching any specific demand to different functions +fn export_as_tex(refined_list: &RefinedEquipementList, save_path: &str) { + println!("{}", refined_list.to_tex()); // TexType + // println!( + // "Saved initial data as {}.html: {:?}", + // save_path, + // refined_list.write_csv(Path::new(&format!("{save_path}.csv"))) + // ); +} + +/// A dynamic filtertype, as a boxed function over two equipement references +// #[allow(dead_code)] +type DynamicSortType = Box Ordering>; + +/// A dynamic filter type +type DynamicFilterType = Box bool>; + +/// Create a filter from a user typed filter +/// +/// This informal implementation function as a mini language, +/// without any form of formalism, consistency or fixed API +fn cmd_to_filter(og_entry: &str) -> Result { + let (category, entry) = if og_entry.starts_with("cat+") { + (true, og_entry.split_at(4).1) + } else { + (false, og_entry) + }; + + macro_rules! return_if_starts_with { + ($iden:ident) => { + if stringify!($iden).starts_with(entry) { + return match category { + true => Ok(Box::new(crate::sort_by_cat_then!($iden))), + false => Ok(Box::new(crate::sort_by!($iden))), + }; + }; + }; + } + return_if_starts_with!(max_damage_per_attack); + return_if_starts_with!(armor_break_per_attack); + return_if_starts_with!(expected_armor_break_per_attack); + return_if_starts_with!(avg_damage_2a_safe); + return_if_starts_with!(avg_damage_2a_huge_hit); + return_if_starts_with!(speed); + return_if_starts_with!(scenario_damage); + return_if_starts_with!(defensive); + return_if_starts_with!(earlygame_sustained_damage_per_turn); + return_if_starts_with!(midgame_sustained_damage_per_turn); + return_if_starts_with!(endgame_sustained_damage_per_turn); + return_if_starts_with!(variance); + return_if_starts_with!(variance_pct); + Err(FatalEquipementError::CLIParseError(og_entry.to_string())) +} diff --git a/crates/weaponry/src/database.rs b/crates/weaponry/src/database.rs index 1ac040d..5f5c048 100644 --- a/crates/weaponry/src/database.rs +++ b/crates/weaponry/src/database.rs @@ -2,3 +2,142 @@ // File: weaponry/src/database.rs //! Database handiling module //! Implements the basics deserialisation from a database to the weaponry components +//! Should dump whole database in a vec of structs from weaponry_structs +#![allow(dead_code)] +use rusqlite::{self}; +use serde::de::DeserializeOwned; + +use crate::error::FatalEquipementError; + +/// Public function to get data from db. Returns the result as a vec with structs +pub fn get_data( + conn: &rusqlite::Connection, + table_name: &str, + filter: Option<&str>, +) -> Result, FatalEquipementError> +where + T: DeserializeOwned + more_fields::FieldsAsSlice, +{ + let mut connection = conn.prepare(&generate_select_query::(table_name, filter))?; + let rows = connection.query([])?; + serde_rusqlite::from_rows::(rows) + .enumerate() + .map(|(row_id, result)| { + result.map_err(|error| FatalEquipementError::SerdeRusqlite { error, row_id }) + }) + .collect() +} + +/// Generate a SELECT query with fields generated from a struct. Returns a SQL request as a String +#[inline] +#[coverage(off)] // INCORRECT: Error with line report +fn generate_select_query( + table_name: &str, + filter: Option<&str>, +) -> String { + format!( + "SELECT {} FROM {}{};", + T::attributes_slice() + .iter() + .map(|(k, _v)| k.to_owned()) + .collect::>() + .join(","), + table_name, + filter.map_or_else(String::default, |j| " WHERE ".to_string() + j) + ) +} + +/// Generate create table_name with fields as columns +/// This function expects a hash map containing (column name, sqlite type) +pub fn generate_create_table_query(table_name: &str, fields: &[(&str, &str)]) -> String { + format!( + "CREATE TABLE IF NOT EXISTS {} ({}, PRIMARY KEY('id' AUTOINCREMENT));", + table_name, + fields + .iter() + .map(|(k, v)| format!("{} {}", k, v)) + .collect::>() + .join(",") + ) +} + +#[cfg(test)] +mod test { + use super::*; + use crate::{ + interfaces::RecipeDatabase, weaponry_structs::equipement_impl_database::EquipementDatabase, + }; + use more_fields::FieldsAsSlice; + use pretty_assertions::assert_eq; + use serde::Deserialize; + + #[derive(FieldsAsSlice, Deserialize, Debug, PartialEq)] + struct TestStruct { + #[INTEGER] + id: usize, + #[TEXT] + name: String, + } + /// setting up test db and table, also adding arbitrary data inside + fn mock_set_up(db_filename: &str) -> EquipementDatabase { + let _ = std::fs::remove_file(db_filename); + let equip_db = EquipementDatabase::new(db_filename).unwrap(); + equip_db.conn.execute("CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",()).unwrap(); + equip_db + .conn + .execute( + "INSERT INTO TestStruct (id, name) VALUES (1, 'dupont'), (2, 'durand');", + (), + ) + .unwrap(); + equip_db + } + /// tearing down all test setup + fn tear_down(filename: &str, db_conn: rusqlite::Connection) { + db_conn.close().unwrap(); + std::fs::remove_file(filename).unwrap(); + } + + #[test] + fn test_generate_query() { + assert_eq!( + generate_select_query::("TestStruct", None), + "SELECT id,name FROM TestStruct;" + ); + assert_eq!( + generate_select_query::("TestStruct", Some("id=id")), + "SELECT id,name FROM TestStruct WHERE id=id;" + ); + } + + #[test] + fn get_data_from_fields() { + let filename = "test.db"; + let conn = mock_set_up(filename); + let result = conn + .serialize_vec_from_table::("TestStruct", None) + .unwrap(); + tear_down(filename, conn.conn); + assert_eq!( + result, + vec![ + TestStruct { + id: 1, + name: "dupont".to_string() + }, + TestStruct { + id: 2, + name: "durand".to_string() + } + ] + ) + } + + #[test] + fn test_generate_create_table_query() { + let query = generate_create_table_query("TestStruct", TestStruct::attributes_slice()); + assert_eq!( + query, "CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER,name TEXT, PRIMARY KEY('id' AUTOINCREMENT));".to_string() + ) + } +} diff --git a/crates/weaponry/src/error.rs b/crates/weaponry/src/error.rs new file mode 100644 index 0000000..ffc4737 --- /dev/null +++ b/crates/weaponry/src/error.rs @@ -0,0 +1,66 @@ +// Workspace: weaponry +// File: weaponry/src/error.rs +//! Inner weaponry error definition +#![allow(missing_docs, clippy::missing_docs_in_private_items)] + +use charming::EchartsError; +use thiserror::Error; + +#[derive(Error, Debug)] +/// Unrecoverable Error, all these error cannot gracefully fail and must return to the User for further handling +pub enum FatalEquipementError { + #[error("Rusqlite failed to connect to the given path {0}")] + RusqliteConnection(#[from] rusqlite::Error), + + #[error("Deserialization from object failed : rowid {row_id} \n{error}")] + SerdeRusqlite { + error: serde_rusqlite::Error, + row_id: usize, + }, + + #[error("Deserialisation from json failed : {0}")] + SerdeJSON(#[from] serde_json::Error), + + #[error( + "Deserialisation from json failed at line {line} on file {file} while trying to parse the value: {parsed_value}: {error}]" + )] + SerdeJSONAt { + line: String, + file: String, + error: serde_json::Error, + parsed_value: String, + }, + + #[error("Couldn't convert into type {origin_type} with data {data}")] + Conversion { origin_type: String, data: String }, + + #[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), + + #[error("Couldn't parse the CLI argument given \"{0}\"")] + CLIParseError(String), + + #[error("Couldn't serialize the object to make a query: \n{0}")] + SerdeRSQLite(#[from] serde_rusqlite::Error), +} + +// #[derive(Error, Debug)] +// /// 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), + +// #[error("A local error occured an wasn't recovered from: {0}")] +// Local(#[from] LocalEquipementError), +// } diff --git a/crates/weaponry/src/export.rs b/crates/weaponry/src/export.rs index 03cffb7..6b87b9f 100644 --- a/crates/weaponry/src/export.rs +++ b/crates/weaponry/src/export.rs @@ -1,3 +1,183 @@ // Workspace: weaponry // File: weaponry/src/export.rs -//! Export module in charge of transforming data structure into their tex counterpart through the appropriate traits +//! Module regrouping all generic function related to the exporting +//! +//! Mostly graphs and csv auto conversion + +use charming::{ + Chart, + component::{self, Axis, Grid, Title}, + element::{Tooltip, Trigger}, +}; + +/// A very complex macro created to add criterias to the graph +/// without repeating self explanatory parameter names in strings +/// +/// 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, +/// ), +/// |ref_equipement| { +/// ( +/// &ref_equipement.advanced.display_name, +/// ref_equipement.advanced.max_damage_per_attack, +/// ) +/// } +/// ); +/// ``` +/// +/// # 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 +// 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 $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),)* + ]), + ) + }; + } +} + +/// Generate a generic graph, ready to be filled with data +pub fn initial_chart(chart_name: &str) -> Chart { + Chart::new() + .title(component::Title::new().text(chart_name).left("center")) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) + .data_zoom( + component::DataZoom::new() + .type_(component::DataZoomType::Inside) + .start(0) + .end(100), + ) + .data_zoom(component::DataZoom::new().start(0).end(100)) + .toolbox( + component::Toolbox::new().feature( + component::Feature::new() + .data_zoom(component::ToolboxDataZoom::new().y_axis_index("none")) + .restore(component::Restore::new()) + .save_as_image(component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + ), + ) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) + .y_axis(component::Axis::new()) + .grid(component::Grid::new().contain_label(true)) +} + +/// Generate a new plot chart +pub fn initial_plot_chart(chart_name: &str, sub_charts: &[&str]) -> Chart { + // charming::Chart::new() + Chart::new() + .title(Title::new().text(chart_name).left("center")) + .title(Title::new().text(sub_charts[0]).left("17%").top("5%")) + .title(Title::new().text(sub_charts[1]).left("17%").top("52%")) + .title(Title::new().text(sub_charts[2]).right("12%").top("5%")) + .title(Title::new().text(sub_charts[3]).right("12%").top("52%")) + .tooltip(Tooltip::new().trigger(Trigger::Axis)) + .data_zoom( + component::DataZoom::new() + .type_(component::DataZoomType::Inside) + .start(0) + .end(100), + ) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) + .toolbox( + component::Toolbox::new().feature( + component::Feature::new() + .data_zoom(component::ToolboxDataZoom::new().y_axis_index("none")) + .restore(component::Restore::new()) + .save_as_image(component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + ), + ) + .grid( + Grid::new() + .left("7%") + .top("7%") + .width("38%") + .height("38%") + .contain_label(true), + ) + .grid( + Grid::new() + .right("7%") + .top("7%") + .width("38%") + .height("38%") + .contain_label(true), + ) + .grid( + Grid::new() + .left("7%") + .bottom("7%") + .width("38%") + .height("38%") + .contain_label(true), + ) + .grid( + Grid::new() + .right("7%") + .bottom("7%") + .width("38%") + .height("38%") + .contain_label(true), + ) + .x_axis(Axis::new().grid_index(0).min(1)) + .x_axis(Axis::new().grid_index(1).min(1)) + .x_axis(Axis::new().grid_index(2).min(1)) + .x_axis(Axis::new().grid_index(3).min(1)) + .y_axis(Axis::new().grid_index(0).min(0)) + .y_axis(Axis::new().grid_index(1).min(0)) + .y_axis(Axis::new().grid_index(2).min(0)) + .y_axis(Axis::new().grid_index(3).min(0)) +} diff --git a/crates/weaponry/src/interfaces.rs b/crates/weaponry/src/interfaces.rs index 32b050c..3831367 100644 --- a/crates/weaponry/src/interfaces.rs +++ b/crates/weaponry/src/interfaces.rs @@ -5,8 +5,359 @@ //! handling of the whole crafting process when the times comes #![allow(dead_code)] -/// This element can be converted to tex -pub trait ToTex {} +use std::{path::Path, rc::Rc}; -/// Specify this element can be made from parts (Unsure, maybe a way to ensure Add is presend ?) -pub trait FromParts {} +use more_fields::FieldsAsSlice; +use rusqlite::Connection; +use serde::{Serialize, de::DeserializeOwned}; + +use crate::error::FatalEquipementError; + +/// Trait representing a view table +/// +/// These table exist to allow to link several point of interest to a RecipeCollection +/// Please note that while FinalRepresentations and ViewTable are two separate traits, +/// they are always tied together as a view table will alway take specific assumptions +/// on the data present inside therefore not allowing many variations on the underlying +/// implementation of the representation +pub trait ViewTable { + /// The inner type of element that one would be peeking into + /// + /// Usually the final representation of an Item + type InterestElementList: RefinedList; + + /// Give a list of interesting element indicises to further analyse + fn index_of_interest_points(&self) -> Vec; + + /// Interrogate the FinalRepresentation to find interesting elements + fn find_points_of_interest(representation: &Self::InterestElementList) -> Self; + // An alternative, non Self::Typed way of doing since there is only one usage for now + // fn find_points_of_interest(&self, representation: &impl FinalRepresentation); +} + +/// Trait implemented by any struct holding the final representation of a RecipeCollection +/// +/// This trait is rather placeholder, reminding the user to give only objects that are indeed +/// final representations and contains all important fields calculated +/// +/// While it is possible to enforce from_recipe_collection, doing so would require the viewtable +/// lock itseld to a particular recipe. +/// While it is the case as of now, matters are not yet set in stone +pub trait RefinedList: ToTex + ToCSV + ToAnalysis { + // Must implement From, is it worth adding as a prerequite type ? + // type OriginCollection: Into; +} + +/// Trait implemented for the final collection of a recipe, allowing it to be combined with parts +/// +/// A recipe list will be combined with a part list to be updated and generate all combinaisons, so on and so forth +pub trait RecipeCollection +where + for<'a> &'a <::Recipes as Combinable>::Inner: std::ops::Add, +{ + /// The type of the inner recipes, this type must be combinable + type Recipes: Combinable; + + /// A blanket implementation giving all combinaisons of recipes with another RecipeCollection + /// + /// This method doesn't make use of parallel iterators as the workload is way faster than would be the memory dispatch + #[coverage(off)] // Tarpaulin cannot deal with iter and long lines + fn combine_all(&mut self, other: &G) + where + G: RecipeCollection, + { + self.assign_inner( + self.ref_inner() + .iter() // Iterate over every recipe + .flat_map(|inner_recipes| { + other + .ref_inner() // Take a reference of recipe + .iter() // Iterate overe every recipe + .filter(|&external_recipes| external_recipes.backward_filter(inner_recipes)) + .map(|external_recipes: &Self::Recipes| { + inner_recipes.add_ref_to_self(external_recipes) + }) + .collect::>() // Collect all a vector of recipe + }) // Flatten all the vector of recipes into a big vector + .collect::>(), // Updates the inner collection to the collected recipes + ); + } + + /// Assign the inner value from an owned value, used for blanket implementations + fn assign_inner(&mut self, inner: Vec); + + /// Gives access to a reference of the inner list + /// + /// This allows to only clone when needed + fn ref_inner(&self) -> &Vec; + + /// Create a collection from a vector + fn from_vectored(list: Vec) -> Self; + + /// Create a collection from an iterator of intermediate values T + #[coverage(off)] // INCORRECT: Error with line report + fn from_iter_intermediate( + iter_inter: impl Iterator>, + ) -> Result + where + Self: std::marker::Sized, + T: Into, + { + Ok(Self::from_vectored( + iter_inter + .map(|r| r.map(|eq_inter| Into::::into(eq_inter))) + .collect::, FatalEquipementError>>()?, + )) + } +} + +/// Trait that ensure that two elements of a recipe are combinable, +/// +/// Being combinable means it can be coerced into elements that implement add +pub trait Combinable +where + for<'a> &'a ::Inner: std::ops::Add, +{ + /// The inner type of the combined elements, this type must implement Add<&Inner> + type Inner; + + /// Give access to a reference of the underlying data to be combined + /// + /// The designed combinaison method is std::ops::Add + fn combinable_part(&self) -> &Self::Inner; + + /// Add an element to self and generate a new Self + /// + /// As the signature implies, it will not mutate self not rhs and will generate a new value from the operation + /// This pushes the actual requirement to &Inner : Add<&Inner> + fn add_ref_to_self(&self, rhs: &T) -> Self + where + T: Combinable; + + /// Filter to decide if the addition should be done + /// + /// + /// Please note that this comparison is done from the new element perspective, + /// asking it if it will allow itself to be added as There is as of now no forward filtering + /// Most filters will defer an internal FilterFunction into the Inner to do all inner working, + /// but the implementation specifics are left open + fn backward_filter(&self, lhs: &T) -> bool + where + T: Combinable; +} + +/// Type alias represinting the inner function parameter +// #![feature(trait_alias)] +pub(super) type FilterFunctionType = dyn Fn(&T, &T) -> bool; +/// Type alias representing a filter +pub(super) type FilterType = Box>>; + +#[derive(Clone)] +/// A generic Filtering function +// DONE: Not implementing deref and allowing for a super pub allows +// implementation to be a little more flexible, however this might +// also be an oversight +pub(crate) struct FilterFunction(pub(super) FilterType); + +/// This element can be converted to tex +pub trait ToTex { + /// Export the object to a Tex string + fn to_tex(&self) -> String; +} + +/// This element can be converted to a csv for further analysis +pub trait ToCSV { + /// Convert this object into a csv + 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; + + /// Apply a filter to the inner data + /// + /// Careful this filter will consume the original data to avoir reallocating + fn inner_filter(self, closure: T) -> Self + where + T: FnMut(&Self::InnerData) -> bool; + + /// Write as html + fn write_html(&self, path: &str) -> Result<(), FatalEquipementError>; +} + +/// A generic database+connection, handling all the deserialization of the inner types +pub trait RecipeDatabase { + /// The initial Deserialisation struct, SQL will be deserialized into this + type DeserialisationType: DeserializeOwned; + /// The used type that Deserialisation type will be converted into + type InnerType: TryFrom; + + /// Create the database from a file + fn new(origin: &str) -> Result + where + Self: std::marker::Sized; + + /// Serialize a vector of objects of the given type in the specified table with an optional filter of the underlying database + /// The FROM type is the original data, directly deserialized from the table + // POI: This element is partly responsible for the difficulty simplifying and generalizing deserialisation + fn serialize_vec_from_table( + &self, + table: &str, + filter: Option<&str>, + ) -> Result, crate::error::FatalEquipementError> { + crate::database::get_data(self.get_connection(), table, filter) + } + + /// Get a reference to the underlying database connection + fn get_connection(&self) -> &Connection; + + /// Initialize an empty database & table + fn initialize_empty_table( + &self, + table: &str, + ) -> Result<(), crate::error::FatalEquipementError> { + // A vector of + self.get_connection().execute( + crate::database::generate_create_table_query(table, T::attributes_slice()).as_str(), + (), + )?; + Ok(()) + } + + /// Insert a row inside the database, while mostly unused this function is needed to initialize the empty table with an empty row if needed + #[coverage(off)] // INCORRECT: Error with line report + fn insert_row( + &self, + table_name: &str, + row: T, + ) -> Result<(), FatalEquipementError> { + let query = format!( + "INSERT INTO {} ({}) VALUES ({});", + table_name, + T::attributes_slice() + .iter() + .map(|(k, _v)| *k) + .collect::>() + .join(","), + T::attributes_slice() + .iter() + .map(|(k, _v)| ":".to_owned() + *k) + .collect::>() + .join(","), + ); + self.get_connection().execute( + &query, + serde_rusqlite::to_params_named(row)?.to_slice().as_slice(), + )?; + Ok(()) + } + + /// Serialize a request into an intermediate T representation, + /// T having all the implementation specifics of the part in details + /// eg. EqShape, EqPart etc.. + fn serialize_into_intermediate( + &self, + table: &str, + filter: Option<&str>, + ) -> Result> + '_, FatalEquipementError> + where + T: From; +} + +/// Trait implemented by any struct aiming to be a public recipe +pub trait FixedRecipe { + // /// Struct representing the database type, most likely a string + // type Database; + /// Struct representing the keylist type, most likely a usize + type KeyList; // TODO: Add the restriction &traits to use the result afterwards + + /// Get the list of elements corresponding to the recipe + /// + /// These elements will either be iteratively fetched from the database or scoured through in the data depending on the scenario + fn get_elements_from_table( + &self, + table: &str, + ) -> Result, FatalEquipementError>; +} + +/// Trait ensuring a status report can be inferred from the structure +pub trait Reportable { + /// Get a detailled inner status report with as many useful informations as possible + /// + /// This report should give detailled information about the inner data, without showing the actual inner data + fn get_report(&self, title: Option<&str>) -> String; +} + +/// A recipe full stack scenario, from loading database through view table generation +/// +/// The inner working while somehow abstracted are very tied together and tied to the impl +pub trait Scenario where for<'a> &'a <<::InitialEquipementListType as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add +// where +// for<'a> &'a <::Recipe as Combinable>::Inner: std::ops::Add, for<'a> &'a <<::InitialEquipementListType as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add +{ + /// The inner database type + type DatabaseType: RecipeDatabase; + /// The type of the final recipe list + type FinalListType: RefinedList + ToTex + ToCSV + ToAnalysis; + /// Inner configuration + type Config; + /// The initial equipement type, the database serialisation will be to be converted into this type + // TODO[!]: Try to remove as it is present in Database + type InitialEquipementType; + /// The initial equipement list, about to be converted into a refined list + type InitialEquipementListType: RecipeCollection; //: Into>; + + // /// The inner element that all serialised data will be serialized into after the intermediate step + // type Recipe; + + // for<'a> &'a <::Recipes as Combinable>::Inner: std::ops::Add, + + /// Create a Scenario from a given config + fn new_with_config(config: Self::Config) -> Result + where + Self: Sized; + + /// Generate the final list type + fn generate_refined_recipes(&self) -> Result; + + /// Retrieve a reference to the inner database + fn get_database(&self) -> &Self::DatabaseType; + + /// Retrieve A config + fn get_tablename(&self) -> &str; + + + /// Automatically deserialize into an equipement + fn deserde_into_processed_representation( + &self, + filter: Option<&str>, + ) -> Result + where + T: From<<::DatabaseType as RecipeDatabase>::InnerType> + + Into<<::InitialEquipementListType as RecipeCollection>::Recipes>, + { + RecipeCollection::from_iter_intermediate::( + self.get_database() + .serialize_into_intermediate::(self.get_tablename(), filter)?, + ) + } +} +#[cfg(test)] +mod test { + use super::RecipeCollection; + use crate::weaponry_structs::{InitialEquipementList, equipement_structs::EqShape}; + + #[test] + fn test_from_iter_intermediate() { + let _b = ::from_iter_intermediate::( + [Ok(EqShape::default()), Ok(EqShape::default())].into_iter(), + ); + } +} diff --git a/crates/weaponry/src/lib.rs b/crates/weaponry/src/lib.rs index dc0d79d..e82b2e9 100644 --- a/crates/weaponry/src/lib.rs +++ b/crates/weaponry/src/lib.rs @@ -2,10 +2,23 @@ // File: weaponry/src/lib.rs //! Weaponry module, handling all weaponry creation and analysis +#![feature(coverage_attribute)] +#![feature(int_roundings)] #![warn(missing_docs, clippy::missing_docs_in_private_items)] +#![feature(iter_intersperse)] +pub mod analysis; mod database; -mod export; -mod interfaces; -mod strategy; -mod weaponry_structs; +pub mod error; +pub mod export; +pub mod interfaces; +#[macro_use] +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/crates/weaponry/src/weaponry_structs.rs b/crates/weaponry/src/weaponry_structs.rs deleted file mode 100644 index 73c6389..0000000 --- a/crates/weaponry/src/weaponry_structs.rs +++ /dev/null @@ -1,168 +0,0 @@ -// Workspace: weaponry -// File: weaponry/src/weaponry_structs.rs -//! All weaponry intermod structures - -#![allow(dead_code)] - -/// The inner statistics of the equipement, used across all parts and final weapon -// #[derive(Default)] -#[allow(clippy::missing_docs_in_private_items)] -pub struct InnerStats { - id: usize, - name: String, - rarity: u8, - cost: u8, - difficulty: u8, - tier: u8, - damage: u8, - p_damage: u8, - precision: u8, - rmax: u8, - armor_break: u8, - armor_pierce: u8, - antimaterial: u8, - damage_type: DamageMod, - protection: u8, - integrity: u8, - torque_two_handed: Option, - torque_one_handed: Option, - dodge: u8, - parry: u8, - speed: u8, - stealth: u8, - category: WeaponCategory, - special: Vec, - action_cost: u8, - reload_cost: Option, - range: u8, - agility_bonus: u8, -} - -/// The final equipement, obtained by combining all parts -pub struct Equipement { - /// The inner stats used by the equipement - stats: InnerStats, -} - -/// Shape of the equipement, first mandatory part of an equipement -pub struct EqShape { - /// The inner stats of the part - stats: InnerStats, -} - -/// Material used for the equipement, all equipements are crafted with 1-2 materials -pub struct EqMaterial { - /// The inner stats of the part - stats: InnerStats, -} - -/// Nature of the equipement, some natures are reserved and some can be chained -/// -/// Deciding on the combinaison can be tricky an will need an extra field -pub struct EqNature { - /// The inner stats of the part - stats: InnerStats, - /// Which kind of target this nature applies to - target: NatureTarget, -} - -/// Finishing touches, since all of them have a cost, they are treated in a special fashion -pub struct EqFinishing { - /// The inner stats of the part - stats: InnerStats, -} - -/// The kind of target this nature can apply to -pub enum NatureTarget { - /// Can apply to a weapon and is unique - WeaponUnique, - /// Can apply to a weapon and must be combined with another - WeaponCombined, - /// Can apply to an armor (all armor nature are unique) - Armor, -} - -/// Enum of all different physical weapon damage types -#[allow(clippy::missing_docs_in_private_items)] -pub enum PhysicalDamageType { - Blunt, - Slash, - Pierce, -} - -impl From<&str> for PhysicalDamageType { - fn from(value: &str) -> Self { - let _ = value; - // Matchcase for all damage types - todo!() - } -} - -/// Weapon damage, combining the base weapon damage type and it's level -/// -/// Signifying wether the damage is pure or [secondary] or [[tertiary]] -#[allow(clippy::missing_docs_in_private_items)] -pub enum DamageMod { - Primary(PhysicalDamageType), - Secondary(PhysicalDamageType), - Tertiary(PhysicalDamageType), -} - -impl From<&str> for DamageMod { - fn from(value: &str) -> Self { - let _ = value; - // Detect [] and recurse from - todo!() - } -} - -/// Combined damage type, as a vector of all damage types -/// -/// Meant to be serialised to tex and deserialized directly from the table -pub struct DamageType(Vec); - -impl From<&str> for DamageType { - fn from(value: &str) -> Self { - let _ = value; - // Split by , then recurse from and collect - todo!() - } -} - -/// List all weapon categories -#[allow(clippy::missing_docs_in_private_items)] -pub enum WeaponCategory { - Exotic, - Dagger, - Claws, - Blade, - Haroth, - Axe, - Kahml, - Hammer, - Rhodarak, - Staff, - Lance, - Landscapper, - Bow, - Crossbow, - Cannon, -} - -impl From<&str> for WeaponCategory { - fn from(value: &str) -> Self { - let _ = value; - todo!() - } -} - -#[cfg(test)] -mod test { - // use super::*; - - #[test] - fn test_data_serialisation() {} - - #[test] - fn test_data_deserialisation() {} -} diff --git a/crates/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/crates/weaponry/src/weaponry_structs/equipement_advanced_repr.rs new file mode 100644 index 0000000..0c6ed8c --- /dev/null +++ b/crates/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -0,0 +1,409 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_advanced_repr.rs +//! Give an advanced representation of the equipement, infering more fields (such a dpt, max_dps etc...) +//! +//! The generation of this fields is primordial to allow post filtering and visualisation +//! +//! Note that while ALL fields and representation will likely be backed into a megablob, +//! nothing prevents us to implement the trait for other objects and avoid massive computation +//! of all the fields even when the user will not be interested in them +#![allow(dead_code)] +use super::{ + equipement_advanced_tools::{ + BestDamageScenarios, get_damage_with_simulation, get_sustained_damage, + }, + equipement_thin_types::{Actions, Attacks}, +}; +use crate::{ + add_field_to_chart, + error::FatalEquipementError, + export::{initial_chart, initial_plot_chart}, + interfaces::{RecipeCollection, RefinedList, ToAnalysis}, + weaponry_structs::{ + Equipement, InitialEquipementList, + equipement_structs::InnerEquipementStats, + equipement_thin_types::{Dices, Precision}, + }, +}; +use charming::{Chart, component::LegendSelectedMode}; +use core::f64; +use serde::Serialize; +use std::{cmp::Ordering, ops::Deref}; + +/// The final representation of the equipement inplementing all the fields needed for processing +// TODO: Add a public getter for the inner data +pub struct RefinedEquipement { + /// The original inner stats + /// + /// This structs takes ownership of the inner data + pub inner: InnerEquipementStats, + + /// Advanced stats + pub advanced: AdvancedStats, +} + +/// The complete equipement list, refined with all advanced stats +pub struct RefinedEquipementList { + /// Inner list of Refined Equipements + // TODO[!]: The use of pub stays for the usage of the example showcasing the macro in export + pub inner: Vec, +} + +// DONE: The use of Deref could be a subtle gotcha +impl Deref for RefinedEquipementList { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +// Just a checkmark +impl RefinedList for RefinedEquipementList {} + +impl ToAnalysis for RefinedEquipementList { + type InnerData = RefinedEquipement; + + fn inner_sort(&mut self, closure: T) + where + T: FnMut(&RefinedEquipement, &RefinedEquipement) -> Ordering, + { + self.inner.sort_by(closure) + } + + fn inner_filter(self, closure: T) -> Self + where + T: FnMut(&RefinedEquipement) -> bool, + { + Self { + inner: self.inner.into_iter().filter(closure).collect::>(), + } + } + + // DONE: While a custom config would allow some personalisation, there is no reason to beleive a more meaningfull name would be choosen + fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> { + let mut renderer = charming::HtmlRenderer::new("Ravenous Balancing", 4000, 2000) + .theme(charming::theme::Theme::Dark); + + let initial_chart = self.make_regular_graph(); + renderer.save(&initial_chart, format!("{save_path}.html"))?; + + let plot_chart = self.make_cross_plots_graph(); + renderer.save(&plot_chart, format!("{save_path}_plots.html"))?; + Ok(()) + } +} + +impl RefinedEquipementList { + /// Make the cross graphs + fn make_cross_plots_graph(&self) -> Chart { + let mut plot_chart = initial_plot_chart( + "Damage Gradients Dice/Precision", + &["Damage 4+2A", "Damage 5+2A", "Damage 5+3A", "Damage 6+3A"], + ); + let mut names = Vec::with_capacity(self.inner.len()); + + for wpn in self.inner.iter() { + let data_4_a2: Vec> = custom_scenario(&wpn.inner, Actions(4), Attacks(2)); + let data_5_a2: Vec> = custom_scenario(&wpn.inner, Actions(5), Attacks(2)); + let data_5_a3: Vec> = custom_scenario(&wpn.inner, Actions(5), Attacks(3)); + let data_6_a3: Vec> = custom_scenario(&wpn.inner, Actions(6), Attacks(3)); + plot_chart = add_serie(plot_chart, 0, wpn, data_4_a2); + plot_chart = add_serie(plot_chart, 1, wpn, data_5_a2); + plot_chart = add_serie(plot_chart, 2, wpn, data_5_a3); + plot_chart = add_serie(plot_chart, 3, wpn, data_6_a3); + names.push(wpn.advanced.display_name.as_str()); + } + + plot_chart = plot_chart.legend( + charming::component::Legend::new() + .left(10) + .top("middle") + .orient(charming::element::Orient::Vertical) + .data(names) + .selected_mode(LegendSelectedMode::Multiple), + ); + plot_chart + } + + /// Max the regular balancing plots + fn make_regular_graph(&self) -> Chart { + let initial_chart: Chart = initial_chart(&format!( + "Damage for all cross-gen products ({} Elements)", + self.inner.len() + )); + + macro_rules! round { + ($a:expr) => { + ($a * 100.).round() / 100. + }; + } + add_field_to_chart!( + self, + initial_chart, + ( + index # &String, + max_damage_per_attack # f64, + armor_break_per_attack # f64, + // expected_armor_break_per_attack # f64, + avg_damage_2a_safe # f64, + avg_damage_2a_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, + 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_2a_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 ), + ) + } + ); + initial_chart + } +} + +/// Inner function to add a serie to a plot +fn add_serie(plot_chart: Chart, id: u8, wpn: &RefinedEquipement, serie: Vec>) -> Chart { + plot_chart.series( + charming::series::Line::new() + .x_axis_index(id) + .y_axis_index(id) + .data(serie) + .name(&wpn.advanced.display_name), + ) +} + +/// Custom scenario for creating scatter plot +fn custom_scenario( + equipement_stats: &InnerEquipementStats, + actions: Actions, + attacks: Attacks, +) -> Vec> { + (1..11) + .map(|dice| { + vec![ + dice as f64, + BestDamageScenarios::from_action_constraints_it( + equipement_stats, + actions, + attacks, + Dices(dice), + Precision(9), + ) + .unwrap_or_default() + .damage_done, + ] + }) + .collect() +} + +/// The list of advanced stats infered from an Equipement +#[derive(Serialize)] +pub struct AdvancedStats { + /// 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_2a_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_it( + value, + Actions(2), + Attacks(2), + Dices(4), + Precision(8), + ) + .map(|f| *f) + .unwrap_or_default(), + avg_damage_2a_huge_hit: BestDamageScenarios::from_action_constraints_it( + value, + Actions(2), + Attacks(2), + Dices(10), + 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 { + inner: value + .inner + .into_iter() + .map(RefinedEquipement::from) + .collect(), + } + } +} + +// #[cfg(test)] // Used in exemples +impl Default for RefinedEquipementList { + fn default() -> Self { + let eq = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]); + RefinedEquipementList::from(eq) + } +} +#[macro_export] +/// A simple macro to sort the inner advanced field by a specific field +// TODO[6] find a way to not have to import the refinedequipement +macro_rules! sort_by { + ($field:ident) => { + |a: &RefinedEquipement, b: &RefinedEquipement| { + a.advanced.$field.total_cmp(&b.advanced.$field) + } + }; +} +#[macro_export] +/// A simple macro to sort the inner advanced field by a specific field +// TODO[6] find a way to not have to import the refinedequipement +macro_rules! sort_by_weapon_then { + ($field:ident) => { + |a, b| match a.inner.id[0].cmp(&b.inner.id[0]) { + std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field), + ord => ord, + } + }; +} + +#[macro_export] +/// Sort by size first, then by the given field +macro_rules! sort_by_cat_then { + ($field:ident) => { + |a, b| { + if let (Some(c), Some(d)) = ( + a.inner.category_size.as_ref(), + b.inner.category_size.as_ref(), + ) { + match c.cmp(d) { + std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field), + ord => ord, + } + } else { + a.advanced.$field.total_cmp(&b.advanced.$field) + } + } + }; +} + +#[macro_export] +/// A simple macro to sort the inner advanced field by a specific field +// TODO[6] find a way to not have to import the refinedequipement +macro_rules! sort_by_size_then { + ($field:ident) => { + |a, b| match a.inner.category_size.cmp(&b.inner.category_size) { + std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field), + ord => ord, + } + }; +} diff --git a/crates/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/crates/weaponry/src/weaponry_structs/equipement_advanced_tools.rs new file mode 100644 index 0000000..39d045b --- /dev/null +++ b/crates/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -0,0 +1,615 @@ +// 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 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) +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 >= 5) || (value.range > 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 +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, + }) = BestDamageScenarios::from_action_constraints_it( + 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, Default)] +#[cfg_attr(test, derive(Clone))] +pub struct BestDamageScenarios { + /// How many actions were used by the best attack + pub actions_used: Actions, + /// Attacks actions used by the scenario + pub attacks_used: Attacks, + /// Resulting damage + pub damage_done: f64, + /// Remaining actions that need to be used to finish reload + pub reload_remaining: Actions, +} + +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, + } + } +} +impl Deref for BestDamageScenarios { + type Target = f64; + + fn deref(&self) -> &Self::Target { + &self.damage_done + } +} + +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) + // DONE: While this abomination is really subpar code, there is no time to clean things that work + pub fn from_action_constraints_it( + equipement_stats: &InnerEquipementStats, + actions_allowed: Actions, + attacks_allowed: Attacks, + dices_allowed: Dices, + precision: Precision, + ) -> Option { + let full_attack_cost = + equipement_stats.action_cost + equipement_stats.reload_cost.unwrap_or_default(); + if full_attack_cost == 0 { + return None; + } + let nb_max_attacks_reload = actions_allowed.div_euclid(full_attack_cost); + let remaining_actions = actions_allowed.rem_euclid(full_attack_cost); + let (remaining_reload, extra_attack) = if remaining_actions >= equipement_stats.action_cost + { + (-(remaining_actions - *attacks_allowed), Attacks(1)) + } else { + (0, Attacks(0)) + }; + + // Loop from the extra attack and go down + let mut values: Vec<(i8, i8, f64)> = (1..=(nb_max_attacks_reload + *extra_attack) + .clamp(0, *attacks_allowed)) + .map(|attacks| { + ( + attacks, + { + if nb_max_attacks_reload + *extra_attack == attacks { + remaining_reload + } else { + 0 + } + }, + stack_binomials(equipement_stats, dices_allowed, precision, attacks), + ) + }) + .collect(); + + values.sort_by(|(_, _, v1), (_, _, v2)| v2.total_cmp(v1)); + (!values.is_empty()).then(|| Self { + actions_used: Actions((values[0].0 * full_attack_cost).clamp(0, *actions_allowed)), + attacks_used: Attacks(values[0].0), + damage_done: values[0].2, + reload_remaining: Actions(values[0].1), + }) + } +} + +/// Do as many binomials as there are attacks +fn stack_binomials( + equipement_stats: &InnerEquipementStats, + dices_allowed: Dices, + precision: Precision, + attacks: i8, +) -> f64 { + (binomial_dice_distribution( + equipement_stats, + precision, + Dices(dices_allowed.div_euclid(attacks.try_into().unwrap())), + ) * (attacks - 1) as f64) + + (binomial_dice_distribution( + equipement_stats, + precision, + Dices( + dices_allowed.div_euclid(attacks.try_into().unwrap()) + + dices_allowed.rem_euclid(attacks.try_into().unwrap()), + ), + )) +} + +/// Calculate the binomial distribution and average the damage from there +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) +} + +#[cfg(test)] +mod test { + use crate::weaponry_structs::{ + equipement_structs::InnerEquipementStats, + equipement_thin_types::{Actions, Attacks}, + }; + + use super::{ + BestDamageScenarios, Dices, Precision, binomial_dice_distribution, + get_damage_with_simulation, + }; + + 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_it() { + 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, + speed: 10, + action_cost: 2, + ..Default::default() + }; + let eq3 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + range: 10, + action_cost: 2, + reload_cost: Some(2), + ..Default::default() + }; + let known_data = &[ + ( + BestDamageScenarios::from_action_constraints_it( + &eq, + Actions(2), + Attacks(1), + Dices(3), + Precision(10), + ), + 14., + ), + ( + BestDamageScenarios::from_action_constraints_it( + &eq, + Actions(2), + Attacks(2), + Dices(3), + Precision(10), + ), + 22., + ), + ( + BestDamageScenarios::from_action_constraints_it( + &eq, + Actions(3), + Attacks(3), + Dices(3), + Precision(10), + ), + 30., + ), + ( + BestDamageScenarios::from_action_constraints_it( + &eq, + Actions(3), + Attacks(3), + Dices(6), + Precision(10), + ), + 36., + ), + ( + BestDamageScenarios::from_action_constraints_it( + &eq, + Actions(3), + Attacks(3), + Dices(6), + Precision(10), + ), + 36., + ), + ( + BestDamageScenarios::from_action_constraints_it( + &eq2, + Actions(1), + Attacks(1), + Dices(3), + Precision(10), + ), + 0., + ), + ( + BestDamageScenarios::from_action_constraints_it( + &eq2, + Actions(2), + Attacks(1), + Dices(3), + Precision(10), + ), + 14., + ), + ( + BestDamageScenarios::from_action_constraints_it( + &eq2, + Actions(4), + Attacks(2), + Dices(3), + Precision(10), + ), + 22., + ), + ( + BestDamageScenarios::from_action_constraints_it( + &eq2, + Actions(5), + Attacks(3), + Dices(6), + Precision(10), + ), + 28., + ), + ( + BestDamageScenarios::from_action_constraints_it( + &eq2, + Actions(6), + Attacks(3), + Dices(6), + Precision(10), + ), + 36., + ), + ( + BestDamageScenarios::from_action_constraints_it( + &eq3, + Actions(2), + Attacks(1), + Dices(3), + Precision(10), + ), + 14., + ), + ( + BestDamageScenarios::from_action_constraints_it( + &eq3, + Actions(4), + Attacks(2), + Dices(3), + Precision(10), + ), + 14., + ), + ( + BestDamageScenarios::from_action_constraints_it( + &eq3, + Actions(6), + Attacks(2), + Dices(3), + Precision(10), + ), + 22., + ), + ( + BestDamageScenarios::from_action_constraints_it( + &eq3, + Actions(6), + Attacks(3), + Dices(6), + Precision(10), + ), + 28., + ), + ( + BestDamageScenarios::from_action_constraints_it( + &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); + }); + } + + #[test] + fn test_scenario_damage() { + let eq1 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + action_cost: 2, + ..Default::default() + }; + let eq2 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + speed: 10, + action_cost: 2, + ..Default::default() + }; + let eq3 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + range: 10, + action_cost: 2, + reload_cost: Some(2), + ..Default::default() + }; + assert_close!( + get_damage_with_simulation(&eq1, Actions(2), Attacks(1)), + 8.3998 + ); + assert_close!( + get_damage_with_simulation(&eq2, Actions(2), Attacks(1)), + 9.6936 + ); + assert_close!( + get_damage_with_simulation(&eq3, Actions(2), Attacks(1)), + 9.6936 + ); + } + #[test] + fn test_basic_impl_damage_scenario() { + let eq1 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + action_cost: 2, + ..Default::default() + }; + let d1 = BestDamageScenarios::from_action_constraints_it( + &eq1, + Actions(2), + Attacks(2), + Dices(2), + Precision(2), + ) + .unwrap(); + let d2 = d1.clone() + d1; + let _deref_damage = *d2; + } +} diff --git a/crates/weaponry/src/weaponry_structs/equipement_fields.rs b/crates/weaponry/src/weaponry_structs/equipement_fields.rs new file mode 100644 index 0000000..e3924e7 --- /dev/null +++ b/crates/weaponry/src/weaponry_structs/equipement_fields.rs @@ -0,0 +1,288 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_fields.rs +//! The inner fields used by the super structs + +use serde::{Deserialize, Serialize}; +use std::fmt::Display; +use std::ops::{Add, Deref, DerefMut}; +use strum::Display; + +#[derive(Clone, Default, Debug, Deserialize, Serialize)] +#[cfg_attr(test, derive(PartialEq))] +/// The special category, a vec of string, for display purposes only +pub struct SpecialField(Vec); + +impl SpecialField { + /// Create a special field from a vector + pub fn new(inner_data: Vec) -> Self { + Self(inner_data) + } +} +impl Deref for SpecialField { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for SpecialField { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +// TODO[6]: This cross target specification existed for combines weapons, +// : that do not really need any balancing and only rendering +// : therefore migh need cleanup +/// The kind of target this nature can apply to +#[derive(Clone)] +pub enum NatureTarget { + /// Can apply to a weapon and is unique + WeaponUnique, + /// Can apply to a weapon and must be combined with another + WeaponCombined, + /// Can apply to an armor (all armor nature are unique) + Armor, +} + +/// Enum of all different physical weapon damage types +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive(Clone, Debug, Deserialize, Serialize)] +#[cfg_attr(test, derive(PartialEq))] +pub enum PhysicalDamageType { + Blunt, + Slash, + Pierce, +} + +/// Weapon damage, combining the base weapon damage type and it's level +/// +/// Signifying wether the damage is pure or \[secondary\] or \[\[tertiary\]\] +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive(Clone, Debug, Display, Deserialize, Serialize)] +#[cfg_attr(test, derive(PartialEq))] +pub enum DamageMod { + Primary(PhysicalDamageType), + Secondary(PhysicalDamageType), + Tertiary(PhysicalDamageType), +} + +/// Combined damage type, as a vector of all damage types +/// +/// Meant to be serialised to tex and deserialized directly from the table +#[derive(Clone, Debug, Deserialize, Serialize)] +#[cfg_attr(test, derive(PartialEq))] +// TODO: avoid pub make an impl ? +pub struct DamageType(Vec); + +impl Deref for DamageType { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DamageType { + /// Create a new DamageType from a vector of *DamageMod* + pub fn new(inner_data: Vec) -> Self { + Self(inner_data) + } +} + +impl Display for DamageType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + self.0 + .iter() + .fold(String::new(), |res, new| format!("{res}, {new}")) + ) + } +} + +impl Add for DamageType { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self(self.0.iter().chain(rhs.0.iter()).cloned().collect()) + } +} + +#[cfg(test)] +mod test { + // use super::*; + + #[ignore] + #[test] + fn test_fields_serialisation() { + unimplemented!() + } + + #[ignore] + #[test] + fn test_fields_deserialisation() { + 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 EquipementSerializedCategory { + Staves, + Blunt, + Slash, + Ranged, + Exotic, + /// Armor generic category, will be converted into EquipementSection + Armors, + /// Shield generic category, will be converted into EquipementSection + Shields, + /// A custom None category, used to forbid a part to be cast upon or from + None, + /// Light size, will be converted to a WeaponBaseSize + Light, + /// Medium size, will be converted to a WeaponBaseSize + Medium, + /// Heavy size, will be converted to a WeaponBaseSize + Heavy, + /// SuperHeavy size, will be converted to a WeaponBaseSize + SuperHeavy, +} + +// TODO[!] : This is the corrected real initial shape +// : 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)] +#[cfg_attr(test, derive(PartialEq))] +pub enum WeaponBaseShape { + Staves, + Blunt, + Slash, + Ranged, + Armors, + Shields, + Exotic, + None, +} + +// TODO[!]: While maybe not directly filling a field these categories should be inferred by the BaseShape for comparison +// [!]: However using a new column for this Section will greatly help in the Serde soundness and avoidance on over-reliance of implicit conversions +/// Specifies the exact nature of the weapon, used for generic filter mainly +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[allow(dead_code, clippy::missing_docs_in_private_items, missing_docs)] +pub enum EquipementTargets { + Weapons, + Armors, + Shields, + Ranged, +} + +impl EquipementTargets { + /// Assert wether a target can be applied to an original shape + pub fn can_apply_onto(&self, lsh: &WeaponBaseShape) -> bool { + match (self, lsh) { + (EquipementTargets::Weapons, WeaponBaseShape::Staves) => true, + (EquipementTargets::Weapons, WeaponBaseShape::Blunt) => true, + (EquipementTargets::Weapons, WeaponBaseShape::Slash) => true, + (EquipementTargets::Weapons, WeaponBaseShape::Ranged) => true, + (EquipementTargets::Weapons, WeaponBaseShape::Exotic) => true, + // You can apply weapon modifiers to shields, not the best behaviour but well + (EquipementTargets::Weapons, WeaponBaseShape::Shields) => true, + (EquipementTargets::Armors, WeaponBaseShape::Armors) => true, + (EquipementTargets::Shields, WeaponBaseShape::Shields) => true, + (EquipementTargets::Ranged, WeaponBaseShape::Ranged) => true, + _ => false, + } + } +} + +// TODO[!] : This part is initialized by the natures subtable and might be better of being a new column in the database +/// The Base Size of the weapon, used to infer the final category of the weapon +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive( + Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Display, Deserialize, Serialize, strum::EnumString, +)] +// #[cfg_attr(test, derive(PartialEq))] +pub enum WeaponBaseSize { + Light, + Medium, + Heavy, + SuperHeavy, +} diff --git a/crates/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/crates/weaponry/src/weaponry_structs/equipement_impl_basics.rs new file mode 100644 index 0000000..01f4383 --- /dev/null +++ b/crates/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -0,0 +1,373 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_impl_basics.rs +// TODO: At some point a trait might want to be used to use these into instead of calling it directly +// : Doing so would ensure all prerequists are met +// : Another way of doing so might be to instead use Into instead +// : Another way would be to add a filter field that would allow or not the combinaison and abstract all +// logic that would be into doing multi traits things +//! Implementations to transform all Specialized equipement into a generic Equipement +//! A specific implementation could be preferable, but this simplicity might allow for easier developpement + +use super::equipement_structs::InnerEquipementStats; +use crate::interfaces::{FilterFunction, Reportable}; +use crate::weaponry_structs::{SpecialField, WeaponBaseShape}; +use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; +use std::{ + fmt::{Debug, Display}, + rc::Rc, +}; + +use super::{ + Equipement, InitialEquipementList, + equipement_advanced_repr::RefinedEquipementList, + equipement_structs::{ + EqFinishing, EqMaterial, EqNature, EqShape, filter_id_unique_and_right_category, + }, +}; + +impl From for Equipement { + fn from(val: EqShape) -> Self { + Self { + stats: val.stats, + ..Default::default() + } + } +} + +impl From for Equipement { + fn from(val: EqMaterial) -> Self { + Self { + stats: val.stats, + filter_function: FilterFunction::new(filter_id_unique_and_right_category()), + } + } +} + +impl From for Equipement { + fn from(val: EqNature) -> Self { + Self { + stats: val.stats, + // Checks that the nature is compatible with the previous iteration + filter_function: FilterFunction::new(filter_id_unique_and_right_category()), + } + } +} + +impl From for Equipement { + fn from(val: EqFinishing) -> Self { + Self { + stats: val.stats, + ..Default::default() + } + } +} + +impl Display for Equipement { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.stats) + } +} + +impl Display for InnerEquipementStats { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut table = Table::new(); + table.apply_modifier(UTF8_ROUND_CORNERS); + table.add_row(vec![format!( + "Ids: {}, Names:{}", + self.id + .iter() + .fold(String::new(), |res, new| format!("{res} {new}")), + self.name.join(" & ") + )]); + table.add_row(vec![format!( + "Rarity: {}, Cost {}, Difficulty: {}, Tier: {} [{}+{}]", + self.rarity, + self.cost, + self.difficulty, + self.tier, + self.category_base + .clone() + .map_or_else(|| "ø".to_string(), |v| v.to_string()), + self.category_size + .clone() + .map_or_else(|| "ø".to_string(), |v| v.to_string()) + )]); + table.add_row_if( + |_, _| self.damage > 0, + vec![format!( + "Damage: {}/+{} P:{}, AB:{} AM:{} A:{} [{}]", + self.damage, + self.p_damage, + self.precision, + self.armor_break, + self.antimaterial, + self.action_cost, + self.clone() + .damage_type + .map_or_else(|| "ø".to_string(), |damage| damage.to_string()) + )], + ); + table.add_row_if( + |_, _| self.protection > 0, + vec![format!("Prot:{} Int:{}", self.protection, self.integrity)], + ); + table.add_row(vec![format!( + "T1/T2 {:?}/{:?} Dodge:{} Parry:{} Speed:{} Stealth:{} Agility: {}", + self.torque_one_handed, + self.torque_two_handed, + self.dodge, + self.parry, + self.speed, + self.stealth, + self.agility_bonus, + )]); + table.add_row_if( + |_, _| (self.range > 0) | (self.armor_pierce > 0), + vec![format!( + "Rg:{}, AP:{}, Rel:{}", + self.range, + self.armor_pierce, + self.reload_cost + .map_or_else(|| "ø".to_string(), |v| format!("{v}")) + )], + ); + table.add_row_if( + |_, _| !self.special.is_empty(), + vec![ + self.special + .iter() + .intersperse(&",".to_string()) + .fold(String::new(), |res, new| format!("{}; {}", res, new)), + ], + ); + write!(f, "{table}") + } +} + +// impl Display for InitialEquipementList { +// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +// for v in self.ref_inner() { +// write!(f, "{v}")?; +// } +// Ok(()) +// } +// } + +impl Reportable for InitialEquipementList { + fn get_report(&self, title: Option<&str>) -> String { + let mut table = Table::new(); + table.apply_modifier(UTF8_ROUND_CORNERS); + match title { + Some(t) => table.add_row(vec![format!("[IEL] {t}")]), + None => table.add_row(vec![format!("Initial Equipement List")]), + }; + table.add_row(vec![format!("Rows: {}", self.inner.len())]); + table.to_string() + } +} + +impl Reportable for RefinedEquipementList { + fn get_report(&self, title: Option<&str>) -> String { + let mut table = Table::new(); + table.apply_modifier(UTF8_ROUND_CORNERS); + match title { + Some(t) => table.add_row(vec![format!("[REL] {t}")]), + None => table.add_row(vec![format!("Refined Equipement List")]), + }; + table.add_row(vec![format!("Rows: {}", self.len())]); + table.to_string() + } +} + +impl Debug for FilterFunction { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Filter:{}", std::any::type_name::()) + } +} +impl Default for FilterFunction { + fn default() -> Self { + FilterFunction(Box::new(Rc::new(|_, _| true))) + } +} +impl PartialEq for FilterFunction { + #[coverage(off)] // INCORRECT: Error with line report + fn eq(&self, _other: &Self) -> bool { + true + } +} + +/// Add a new vector to a clone of a inner field +macro_rules! add_to_vec { + ($self: expr, $rhs: expr) => {{ + let mut new = $self.clone(); + new.append(&mut $rhs.clone()); + new + }}; +} + +/// Adds either of the vectors or merge them +macro_rules! add_two_options { + ($self: expr, $rhs: expr) => {{ + match ($self.as_ref(), $rhs.as_ref()) { + (None, None) => None, + (None, Some(a)) => Some(a.clone()), + (Some(a), None) => Some(a.clone()), + (Some(a), Some(b)) => Some(a.clone() + b.clone()), + } + }}; +} + +/// Clones the first option that has some data +macro_rules! first_correct_option { + ($self:expr, $rhs:expr) => { + match ($self.as_ref(), $rhs.as_ref()) { + (Some(a), _) => Some(a.clone()), + (_, Some(b)) => Some(b.clone()), + _ => None, + } + }; +} + +impl std::ops::Add for &InnerEquipementStats { + type Output = InnerEquipementStats; + + fn add(self, rhs: Self) -> Self::Output { + InnerEquipementStats { + id: add_to_vec!(self.id, rhs.id), + name: add_to_vec!(self.name, rhs.name), + rarity: self.rarity + rhs.rarity, + cost: self.cost + rhs.cost, + difficulty: self.difficulty + rhs.difficulty, + tier: self.tier + rhs.tier, + damage: self.damage + rhs.damage, + p_damage: self.p_damage + rhs.p_damage, + precision: self.precision + rhs.precision, + rmax: self.rmax + rhs.rmax, + armor_break: self.armor_break + rhs.armor_break, + armor_pierce: { + if self.armor_pierce > 0 + || matches!(self.category_base, Some(WeaponBaseShape::Ranged)) + { + self.armor_pierce + rhs.armor_pierce + } else { + 0 + } + }, + antimaterial: self.antimaterial + rhs.antimaterial, + damage_type: add_two_options!(self.damage_type, rhs.damage_type), + protection: self.protection + rhs.protection, + integrity: self.integrity + rhs.integrity, + torque_two_handed: add_two_options!(self.torque_two_handed, rhs.torque_two_handed), + torque_one_handed: add_two_options!(self.torque_one_handed, rhs.torque_one_handed), + dodge: self.dodge + rhs.dodge, + parry: self.parry + rhs.parry, + speed: self.speed + rhs.speed, + stealth: self.stealth + rhs.stealth, + special: self.special.clone() + rhs.special.clone(), // Can be further optimized + action_cost: self.action_cost + rhs.action_cost, + reload_cost: self.reload_cost.or(rhs.reload_cost), + range: self.range + rhs.range, + agility_bonus: self.agility_bonus + rhs.agility_bonus, + category_base: first_correct_option!(self.category_base, rhs.category_base), + category_size: first_correct_option!(self.category_size, rhs.category_size), + target_category: first_correct_option!(self.target_category, rhs.target_category), + } + } +} + +impl std::ops::Add for SpecialField { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + let mut c = self.clone(); + c.append(&mut rhs.clone()); + c + } +} + +#[cfg(test)] +mod test { + use crate::{ + interfaces::{FilterFunction, RecipeCollection, Reportable}, + weaponry_structs::{ + Equipement, InitialEquipementList, + equipement_advanced_repr::RefinedEquipementList, + equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}, + }, + }; + + #[test] + fn test_filter_weapons() { + let _ = format!("{:?}", FilterFunction::::default()); + let r = FilterFunction::::new(&|_, _| false) == FilterFunction::default(); + assert!(r); + } + #[allow(dead_code)] + /// A manually implemented hashmap of all values + #[doc(hidden)] + macro_rules! r { + () => { + fastrand::i8(1..20) + }; + } + impl InnerEquipementStats { + /// Testing function to fuzz data + pub fn random_new() -> Self { + Self { + id: vec![r!() as u8], + range: (r!() - 10) as i16, + damage: r!() - 10, + p_damage: r!() - 10, + protection: r!() - 10, + ..Default::default() + } + } + } + impl DatabaseEquipementStats { + /// Testing function to fuzz data + pub fn random_new() -> Self { + Self { + id: r!() as u8, + range: r!() - 19, + damage: r!() - 10, + p_damage: r!() - 10, + protection: r!() - 10, + ..Default::default() + } + } + } + #[test] + fn test_format() { + let equi = Equipement { + stats: InnerEquipementStats::random_new(), + ..Default::default() + }; + print!("{}", equi); + } + + #[test] + fn test_report() { + let eqlist = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]); + let feqlist: RefinedEquipementList = eqlist.clone().into(); + + println!("{}", feqlist.get_report(None)); + println!("{}", eqlist.get_report(None)); + } + + #[test] + fn test_macros() { + assert_eq!(first_correct_option!(None::, None::), None); + assert_eq!(first_correct_option!(Some(3), None::), Some(3)); + assert_eq!(first_correct_option!(None::, Some(4)), Some(4)); + assert_eq!(first_correct_option!(Some(1), Some(3)), Some(1)); + + assert_eq!(add_two_options!(Some(1), Some(3)), Some(4)); + assert_eq!(add_two_options!(Some(3), None::), Some(3)); + assert_eq!(add_two_options!(None::, Some(4)), Some(4)); + + let a = vec![1, 2]; + let b = vec![3]; + + assert_eq!(add_to_vec!(a, b), vec![1, 2, 3]); + } +} diff --git a/crates/weaponry/src/weaponry_structs/equipement_impl_database.rs b/crates/weaponry/src/weaponry_structs/equipement_impl_database.rs new file mode 100644 index 0000000..5a5c4c9 --- /dev/null +++ b/crates/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -0,0 +1,154 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_impl_database.rs +//! All database specific implementations + +use super::EquipementSerializedCategory; +use super::equipement_fields::{WeaponBaseShape, WeaponBaseSize}; +use super::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}; +use crate::error::FatalEquipementError; +use crate::interfaces::{FixedRecipe, RecipeDatabase}; +use rusqlite::Connection; + +/// Struct for database connection. +#[derive(Debug)] +pub struct EquipementDatabase { + /// Connection parameter for rusqlite + pub conn: rusqlite::Connection, +} + +impl RecipeDatabase for EquipementDatabase { + type DeserialisationType = DatabaseEquipementStats; + type InnerType = InnerEquipementStats; + + fn new(filename: &str) -> Result { + Ok(EquipementDatabase { + conn: Connection::open(filename)?, + }) + } + + fn get_connection(&self) -> &Connection { + &self.conn + } + + #[coverage(off)] // INCORRECT: Error with line report + fn serialize_into_intermediate( + &self, + table: &str, + filter: Option<&str>, + ) -> Result> + '_, FatalEquipementError> + where + T: From, + { + // Start with Self::DatabaseType + Ok(self + .serialize_vec_from_table::(table, filter)? + .into_iter() + .map(|db_element| { + Self::InnerType::try_from(db_element).map(|inner_eq| T::from(inner_eq)) + })) + } +} +#[allow(missing_docs)] +pub struct EquipementFixedRecipe { + pub conn: rusqlite::Connection, +} + +#[allow(missing_docs)] +pub struct MockRecipe {} + +// TODO[1] : Add fixed recipes +impl FixedRecipe for EquipementFixedRecipe { + type KeyList = MockRecipe; + + fn get_elements_from_table( + &self, + table: &str, + ) -> Result, FatalEquipementError> { + let _ = table; + todo!() + } +} + +// 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) => { + serde_json::from_str(&$value).map_err(|error| FatalEquipementError::SerdeJSONAt { + line: line!().to_string(), + file: file!().to_string(), + parsed_value: $value.to_string(), + error, + }) + }; +} + +// #[allow(clippy::useless_conversion)] +impl TryFrom for InnerEquipementStats { + type Error = FatalEquipementError; + + fn try_from(value: DatabaseEquipementStats) -> Result { + let (category_base, category_size): SubCategories = + get_sub_categories_from_serde(&value.category)?; + Ok(Self { + id: vec![value.id], // Special case where manual is better than serde + name: vec![value.name], + rarity: value.rarity, // Generic case, into(), serde or cast are equivalent + cost: value.cost, + difficulty: value.difficulty, + // tier: value.tier, + tier: 0, + damage: value.damage, + p_damage: value.p_damage, + precision: value.precision, + rmax: value.rmax, + armor_break: value.armor_break, + armor_pierce: value.armor_pierce, + antimaterial: value.antimaterial, + damage_type: from_serde!(&value.damage_type)?, // Serde and derive are godsent + protection: value.protection, + integrity: value.integrity, + torque_two_handed: from_serde!(&value.torque_two_handed)?, + torque_one_handed: from_serde!(&value.torque_one_handed)?, + dodge: value.dodge, + parry: value.parry, + speed: value.speed, + stealth: value.stealth, + // macro_category: from_serde!(&value.category)?, + // target: from_serde!(&value.target)?, + special: from_serde!(&value.special)?, + action_cost: value.action_cost, + reload_cost: from_serde!(&value.reload_cost)?, + range: value.range as i16, + agility_bonus: value.agility_bonus, + category_base, + category_size, + target_category: from_serde!(value.target)?, + }) + } +} + +/// A type englobing the three subcategores +type SubCategories = (Option, Option); + +/// Infer all subcategories from a deserialized DatabaseCategory +#[coverage(off)] // A test would literally be a copy paste of this match +fn get_sub_categories_from_serde(category: &str) -> Result { + Ok(if let Some(category) = from_serde!(category)? { + match category { + EquipementSerializedCategory::Staves => (Some(WeaponBaseShape::Staves), None), + EquipementSerializedCategory::Blunt => (Some(WeaponBaseShape::Blunt), None), + EquipementSerializedCategory::Slash => (Some(WeaponBaseShape::Slash), None), + EquipementSerializedCategory::Ranged => (Some(WeaponBaseShape::Ranged), None), + EquipementSerializedCategory::Exotic => (Some(WeaponBaseShape::Exotic), None), + EquipementSerializedCategory::Armors => (Some(WeaponBaseShape::Armors), None), + EquipementSerializedCategory::Shields => (Some(WeaponBaseShape::Shields), None), + EquipementSerializedCategory::None => (Some(WeaponBaseShape::None), None), + EquipementSerializedCategory::Light => (None, Some(WeaponBaseSize::Light)), + EquipementSerializedCategory::Medium => (None, Some(WeaponBaseSize::Medium)), + EquipementSerializedCategory::Heavy => (None, Some(WeaponBaseSize::Heavy)), + EquipementSerializedCategory::SuperHeavy => (None, Some(WeaponBaseSize::SuperHeavy)), + } + } else { + (None, None) + }) +} diff --git a/crates/weaponry/src/weaponry_structs/equipement_impl_io.rs b/crates/weaponry/src/weaponry_structs/equipement_impl_io.rs new file mode 100644 index 0000000..acafc60 --- /dev/null +++ b/crates/weaponry/src/weaponry_structs/equipement_impl_io.rs @@ -0,0 +1,59 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_impl_io.rs +//! All implementation IO specific (mainly export and serde) + +use super::equipement_advanced_repr::RefinedEquipementList; +use crate::interfaces::{ToCSV, ToTex}; +use std::path::Path; + +impl ToCSV for RefinedEquipementList { + fn write_csv(&self, path: &Path) -> csv::Result<()> { + let mut wtr = csv::Writer::from_path(path)?; // wtr.serialize + for record in self.iter() { + wtr.serialize(record)?; + } + Ok(()) + } +} + +impl ToTex for RefinedEquipementList { + // Nom & \rotbx{Rareté} & \rotbx{Dégâts} & + & \rotbx{R.Max} & \rotbx{Armr.B} & \rotbx{Protbx} & \rotbx{Int.} & \rotbx{Deux M} & \rotbx{Une M} & \rotbx{Esq.} & \rotbx{Parr.} & \rotbx{Vitesse} & \rotbx{Discr.} & \rotbx{Catégorie} & \rotbx{Modes} & \rotbx{Spécial} \\ + fn to_tex(&self) -> String { + self.inner.iter().for_each(|m| println!("{:?}", m.inner)); + todo!() + } +} + +#[cfg(test)] +mod test { + // use super::*; + + use std::path::Path; + + use crate::{ + interfaces::ToCSV, + weaponry_structs::{ + equipement_advanced_repr::{AdvancedStats, RefinedEquipementList}, + equipement_structs::InnerEquipementStats, + }, + }; + + #[test] + fn test_structs_serialisation() { + let adv = AdvancedStats::from(&InnerEquipementStats::default()); + // let mut wtr = csv::Writer::from_path("bob.csv").unwrap(); // wtr.serialize + let mut wtr = csv::Writer::from_writer(Vec::new()); + wtr.serialize(adv).unwrap(); + wtr.flush().unwrap(); + + RefinedEquipementList::default() + .write_csv(Path::new("/dev/null")) + .unwrap(); + } + + #[ignore] + #[test] + fn test_structs_deserialisation() { + unimplemented!() + } +} diff --git a/crates/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/crates/weaponry/src/weaponry_structs/equipement_impl_logic.rs new file mode 100644 index 0000000..0a6799b --- /dev/null +++ b/crates/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -0,0 +1,187 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_impl_logic.rs +//! Implementation of the logic traits, used for equipement generation + +use crate::interfaces::{Combinable, RecipeCollection}; + +use super::{Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats}; + +impl Combinable for Equipement { + type Inner = InnerEquipementStats; + + fn combinable_part(&self) -> &Self::Inner { + &self.stats + } + + fn add_ref_to_self(&self, rhs: &T) -> Self + where + T: Combinable, + { + Self { + stats: self.combinable_part() + rhs.combinable_part(), + ..Default::default() + } + } + + fn backward_filter(&self, lhs: &T) -> bool + where + T: Combinable, + { + self.filter_function.0(self.combinable_part(), lhs.combinable_part()) + } +} + +impl RecipeCollection for InitialEquipementList { + type Recipes = Equipement; + + // Should likely be internal + fn from_vectored(list: Vec) -> Self { + Self { inner: list } + } + + fn ref_inner(&self) -> &Vec { + &self.inner + } + + fn assign_inner(&mut self, inner: Vec) { + self.inner = inner; + } +} + +#[cfg(test)] +mod test { + use crate::{ + interfaces::RecipeCollection, + weaponry_structs::{ + DamageMod, DamageType, Equipement, InitialEquipementList, SpecialField, + equipement_fields::{PhysicalDamageType, WeaponBaseShape}, + equipement_structs::InnerEquipementStats, + }, + }; + use pretty_assertions::assert_eq; + + #[test] + fn test_blanket_struct_generation() { + let mut f = InitialEquipementList::from_vectored(vec![ + Equipement::newish(&["a"], 1), + Equipement::newish(&["b"], 2), + ]); + let g = InitialEquipementList::from_vectored(vec![ + Equipement::newish(&["c"], 4), + Equipement::newish(&["d"], 8), + ]); + + assert_eq!( + f.ref_inner(), + &vec![Equipement::newish(&["a"], 1), Equipement::newish(&["b"], 2)] + ); + + f.combine_all(&g); + assert_eq!( + f, + InitialEquipementList::from_vectored(vec![ + Equipement::newish(&["a", "c"], 5), + Equipement::newish(&["a", "d"], 9), + Equipement::newish(&["b", "c"], 6), + Equipement::newish(&["b", "d"], 10) + ]) + ); + } + + #[test] + fn test_base_operation() { + let i1 = InnerEquipementStats { + rarity: 1, + integrity: 2, + range: 3, + agility_bonus: 4., + category_base: Some(WeaponBaseShape::Staves), + special: SpecialField::new(vec!["zero".into()]), + damage_type: Some(DamageType::new(vec![DamageMod::Secondary( + PhysicalDamageType::Slash, + )])), + ..Default::default() + }; + let i2 = InnerEquipementStats { + integrity: 3, + agility_bonus: 5., + damage: 10, + damage_type: Some(DamageType::new(vec![DamageMod::Primary( + PhysicalDamageType::Blunt, + )])), + special: SpecialField::new(vec!["one".into(), "two".into()]), + ..Default::default() + }; + assert_eq!( + &i1 + &i2, + InnerEquipementStats { + rarity: 1, + integrity: 5, + agility_bonus: 9., + damage: 10, + range: 3, + category_base: Some(WeaponBaseShape::Staves), + special: SpecialField::new(vec!["zero".into(), "one".into(), "two".into()]), + damage_type: Some(DamageType::new(vec![ + DamageMod::Secondary(PhysicalDamageType::Slash,), + DamageMod::Primary(PhysicalDamageType::Blunt,), + ])), + ..Default::default() + } + ); + assert_eq!( + &InnerEquipementStats { + damage_type: Some(DamageType::new(vec![ + DamageMod::Secondary(PhysicalDamageType::Slash,), + DamageMod::Primary(PhysicalDamageType::Blunt,), + ])), + ..Default::default() + } + &InnerEquipementStats::default(), + InnerEquipementStats { + damage_type: Some(DamageType::new(vec![ + DamageMod::Secondary(PhysicalDamageType::Slash,), + DamageMod::Primary(PhysicalDamageType::Blunt,), + ])), + ..Default::default() + }, + ); + assert_eq!( + &InnerEquipementStats::default() + + &InnerEquipementStats { + damage_type: Some(DamageType::new(vec![ + DamageMod::Secondary(PhysicalDamageType::Slash,), + DamageMod::Primary(PhysicalDamageType::Blunt,), + ])), + ..Default::default() + }, + InnerEquipementStats { + damage_type: Some(DamageType::new(vec![ + DamageMod::Secondary(PhysicalDamageType::Slash,), + DamageMod::Primary(PhysicalDamageType::Blunt,), + ])), + ..Default::default() + }, + ); + } + + #[ignore] + #[test] + fn test_generator_function() {} + + #[ignore] + #[test] + fn test_basic_logic() {} + + impl Equipement { + fn newish(name: &[&str], i: i8) -> Self { + Equipement { + stats: InnerEquipementStats { + name: name.iter().map(|s| s.to_string()).collect(), + rarity: i, + ..Default::default() + }, + ..Default::default() + } + } + } +} diff --git a/crates/weaponry/src/weaponry_structs/equipement_scenario.rs b/crates/weaponry/src/weaponry_structs/equipement_scenario.rs new file mode 100644 index 0000000..1722064 --- /dev/null +++ b/crates/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -0,0 +1,187 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_scenario.rs +//! Implementations of a full scenario, +//! +//! These implementation must take care of everything from database retrieval to view exporting, +//! however all they mostly do is glue together all the parts designed in the interface, +//! and therefore mostly serves as a TO-DO list +//! + +use crate::{ + error::FatalEquipementError, + interfaces::{RecipeCollection, RecipeDatabase, Scenario}, + weaponry_structs::{ + InitialEquipementList, RefinedEquipementList, + equipement_impl_database::EquipementDatabase, + equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats}, + }, +}; + +/// 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 { + database: EquipementDatabase, + config: ConfigEquipementScenario, +} + +/// All recipes +#[allow(clippy::missing_docs_in_private_items, dead_code)] +pub struct RecipesScenario { + database: EquipementDatabase, + config: ConfigEquipementScenario, +} + +/// A scenario exporting all individual elements +#[allow(clippy::missing_docs_in_private_items, dead_code)] +pub struct IndividualElementsScenario { + database: EquipementDatabase, + config: ConfigEquipementScenario, +} + +impl CrossRecipeScenario { + /// Generate all the operations to be processed with the current config + // TODO[!]: Consider adding to interface + fn generate_selected_operation( + &self, + ) -> Result, FatalEquipementError> { + let mut operations = Vec::with_capacity(8); + if self.config.shape.is_some() { + operations.push(self.deserde_into_processed_representation::(Some( + "META_CATEGORY LIKE 'Shape'", + ))?); + } + if let Some(qt) = self.config.materials { + for _ in 0..qt { + operations.push( + self.deserde_into_processed_representation::(Some( + "META_CATEGORY LIKE 'Materials'", + ))?, + ); + } + } + if self.config.nature.is_some() { + operations.push(self.deserde_into_processed_representation::(Some( + "META_CATEGORY LIKE 'Nature'", + ))?); + } + if self.config.finishing.is_some() { + operations.push( + self.deserde_into_processed_representation::(Some( + "META_CATEGORY LIKE '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 FinalListType = RefinedEquipementList; + type Config = ConfigEquipementScenario; + type InitialEquipementType = InnerEquipementStats; + type InitialEquipementListType = InitialEquipementList; + // type Recipe = Equipement; + + fn new_with_config(config: Self::Config) -> Result + where + Self: Sized, + { + Ok(Self { + database: Self::DatabaseType::new(&config.db_path)?, + config, + }) + } + + fn generate_refined_recipes(&self) -> Result { + let operations = self.generate_selected_operation()?; + + let mut opertation_it = operations.into_iter(); + let mut refined_list = opertation_it.next().unwrap(); + + opertation_it.for_each(|operation| refined_list.combine_all(&operation)); + + Ok(refined_list.into()) + } + + // type InitialElementList; + + // type InitialDatabaseStruct; + + fn get_tablename(&self) -> &str { + &self.config.table_name + } + + fn get_database(&self) -> &Self::DatabaseType { + &self.database + } +} + +#[cfg(test)] +mod test { + use crate::{ + interfaces::{RecipeDatabase, Scenario}, + weaponry_structs::{ + equipement_impl_database::EquipementDatabase, + equipement_structs::{DatabaseEquipementStats, EqFinishing}, + }, + }; + + use super::{ConfigEquipementScenario, CrossRecipeScenario}; + + #[test] + fn test_scenario() {} + #[test] + fn test_deserde_into() { + let b = CrossRecipeScenario { + database: EquipementDatabase { + conn: rusqlite::Connection::open_in_memory().unwrap(), + }, + config: ConfigEquipementScenario { + table_name: "Finishing".to_owned(), + db_path: "None".to_owned(), + shape: None, + materials: None, + nature: None, + finishing: None, + }, + }; + + b.get_database() + .initialize_empty_table::("Finishing") + .unwrap(); + b.get_database() + .insert_row::( + "Finishing", + DatabaseEquipementStats::random_new(), + ) + .unwrap(); + ::get_database(&b); + let r = b + .deserde_into_processed_representation::(None) + .unwrap(); + assert_eq!(r.inner.len(), 1); + } +} diff --git a/crates/weaponry/src/weaponry_structs/equipement_structs.rs b/crates/weaponry/src/weaponry_structs/equipement_structs.rs new file mode 100644 index 0000000..28891e6 --- /dev/null +++ b/crates/weaponry/src/weaponry_structs/equipement_structs.rs @@ -0,0 +1,317 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_structs.rs +//! Base equipement structures + +use std::rc::Rc; + +use crate::interfaces::{FilterFunction, FilterFunctionType}; +use more_fields::FieldsAsSlice; +use serde::{Deserialize, Serialize}; + +use super::{ + DamageType, SpecialField, + equipement_fields::{ + EquipementSerializedCategory, EquipementTargets, WeaponBaseShape, WeaponBaseSize, + }, +}; + +/// The final equipement list +/// +/// This list is initialized with the base part and updated by succesive combinaisons +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] +pub struct InitialEquipementList { + /// Inner List of final equipements + pub(super) inner: Vec, +} + +/// The final equipement, obtained by combining all parts +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] +pub struct Equipement { + /// The inner stats used by the equipement + pub(super) stats: InnerEquipementStats, + /// The filter, used to determine if adding is warranted + pub(super) filter_function: FilterFunction, +} + +impl Default for Equipement { + fn default() -> Self { + Self { + filter_function: FilterFunction::new(filter_id_unique()), + stats: InnerEquipementStats::default(), + } + } +} + +/// The default filter to use, usefull to implement a new filter function that also uses the default filter +pub(crate) fn filter_id_unique() +-> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool { + &|self_, lhs| lhs.id.iter().all(|a| *a != self_.id[0]) +} + +/// Create a new filter function mandating the object be of the right category +// TODO[5]: Testing this method should be a priority for refactoring +pub(crate) fn filter_id_unique_and_right_category() +-> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool { + &|sel, lhs| { + lhs.id.iter().all(|a| *a != sel.id[0]) + & match (&sel.target_category, &lhs.category_base) { + // There is a specific target and the part about to be added has a category + (Some(a), Some(b)) => a.can_apply_onto(b), + // TODO: Unsound to have a generic nature, this should be caught at serialisation + // There is no target and the part about to be added is generic + (None, _) => false, //panic!("The part about to be added cannot be generic"), + (Some(_), None) => false, //panic!("The part about to be added unto cannot be generic"), + } + } +} +impl FilterFunction { + /// Generate and save a new filter, + /// the use of a static reference allows for reuse of a generic filter + pub fn new(filter: &'static FilterFunctionType) -> Self { + Self(Box::new(Rc::new(filter))) + } +} +/// The inner statistics of the equipement, used across all parts and final weapon +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive(Clone, Default, FieldsAsSlice, Debug)] +#[cfg_attr(test, derive(PartialEq))] +pub struct InnerEquipementStats { + pub id: Vec, + pub name: Vec, + pub(super) rarity: i8, + pub(super) cost: i8, + pub(super) difficulty: i8, + pub(super) tier: i8, + pub(super) damage: i8, + pub(super) p_damage: i8, + pub(super) precision: i8, + pub(super) rmax: i8, + pub(super) armor_break: i8, + pub(super) armor_pierce: i8, + pub(super) antimaterial: i8, + pub(super) damage_type: Option, + pub(super) protection: i8, + pub(super) integrity: i8, + pub(super) torque_two_handed: Option, // Might be option (single claw) + pub(super) torque_one_handed: Option, // Should be option (bows) + pub(super) dodge: f32, // I could also use a custom HalfValue + pub(super) parry: i8, + pub(super) speed: i8, + pub(super) stealth: i8, + /// The category as [WeaponBaseShape] representing what kind of equipement is used + /// + /// The categories are: Staves, Blunt, Slash, Ranged, Armors, Shields, Exotic, None, + pub category_base: Option, + /// The category size as WeaponBaseSize + /// + /// Categories are : (Light, Medium, Heavy and SuperHeavy) + pub category_size: Option, + /// The section of an equipement (Weapon, Shield, Armor) + /// The Section the target applies to + pub target_category: Option, + pub(super) special: SpecialField, + pub(super) action_cost: i8, + pub(super) reload_cost: Option, // Shouldn't it be Option ? + pub(super) range: i16, // Shoudln't it be Option ? + pub(super) agility_bonus: f32, // Also convert this one to HalfValue +} + +// TODO: This implementation of default is painfull +// : Have either an auto-macro implementation or a manual one +// : This implementation is Quasi-redondant +// : Have a way to limit code duplication +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive(Clone, FieldsAsSlice, Debug, Deserialize, Serialize)] +#[cfg_attr(test, derive(PartialEq))] +pub struct DatabaseEquipementStats { + #[INTEGER] + pub id: u8, + pub meta_category: String, + pub name: String, + #[INTEGER] + pub rarity: i8, + #[INTEGER] + pub cost: i8, + #[INTEGER] + pub difficulty: i8, + #[INTEGER] + pub tier: i8, + #[INTEGER] + pub damage: i8, + #[INTEGER] + pub p_damage: i8, + #[INTEGER] + pub precision: i8, + #[INTEGER] + pub rmax: i8, + #[INTEGER] + pub armor_break: i8, + #[INTEGER] + pub armor_pierce: i8, + #[INTEGER] + pub antimaterial: i8, + pub damage_type: String, + #[INTEGER] + pub protection: i8, + #[INTEGER] + pub integrity: i8, + pub torque_two_handed: String, + pub torque_one_handed: String, + #[REAL] + pub dodge: f32, + #[INTEGER] + pub parry: i8, + #[INTEGER] + pub speed: i8, + #[INTEGER] + pub stealth: i8, + pub category: String, + pub target: String, + pub special: String, + #[INTEGER] + pub action_cost: i8, + pub reload_cost: String, + #[INTEGER] + pub range: i8, + #[REAL] + pub agility_bonus: f32, +} + +impl Default for DatabaseEquipementStats { + fn default() -> Self { + Self { + id: 0, + meta_category: "EqShape".to_string(), + name: String::new(), + damage_type: serde_json::to_string(&None::).unwrap(), + category: serde_json::to_string(&None::).unwrap(), + target: serde_json::to_string(&None::).unwrap(), + special: serde_json::to_string(&SpecialField::default()).unwrap(), + reload_cost: serde_json::to_string(&None::).unwrap(), + rarity: 0, + cost: 0, + difficulty: 0, + tier: 0, + damage: 0, + p_damage: 0, + precision: 0, + rmax: 0, + armor_break: 0, + armor_pierce: 0, + antimaterial: 0, + protection: 0, + integrity: 0, + torque_two_handed: serde_json::to_string(&0).unwrap(), + torque_one_handed: serde_json::to_string(&None::).unwrap(), + dodge: 0., + parry: 0, + speed: 0, + stealth: 0, + range: 0, + agility_bonus: 0., + action_cost: 0, + } + } +} + +/// Shape of the equipement, first mandatory part of an equipement +#[derive(Default)] +pub struct EqShape { + /// The inner stats of the part + pub(super) stats: InnerEquipementStats, +} + +impl From for EqShape { + fn from(value: InnerEquipementStats) -> Self { + Self { stats: value } + } +} + +/// Material used for the equipement, all equipements are crafted with 1-2 materials +#[derive(Default)] +pub struct EqMaterial { + /// The inner stats of the part + pub(super) stats: InnerEquipementStats, +} + +impl From for EqMaterial { + fn from(value: InnerEquipementStats) -> Self { + Self { stats: value } + } +} + +/// Nature of the equipement, some natures are reserved and some can be chained +/// +/// Deciding on the combinaison can be tricky an will need an extra field +#[derive(Default)] +pub struct EqNature { + /// The inner stats of the part + pub(super) stats: InnerEquipementStats, +} + +impl From for EqNature { + fn from(value: InnerEquipementStats) -> Self { + Self { stats: value } + } +} + +/// Finishing touches, since all of them have a cost, they are treated in a special fashion +#[derive(Default)] +pub struct EqFinishing { + /// The inner stats of the part + pub(super) stats: InnerEquipementStats, +} + +impl From for EqFinishing { + fn from(value: InnerEquipementStats) -> Self { + Self { stats: value } + } +} + +#[cfg(test)] +mod test { + use super::{ + EqFinishing, EqMaterial, EqShape, Equipement, InitialEquipementList, InnerEquipementStats, + }; + use crate::interfaces::RecipeCollection; + + fn list_equip() -> Vec { + (0..10) + .map(|_| Equipement { + ..Default::default() + }) + .collect::>() + } + + #[test] + fn test_struct_creation() { + let _stats = InnerEquipementStats::default(); + let _eq1 = Equipement { + ..Default::default() + }; + + let _list_eq = list_equip(); + } + + #[test] + fn test_creating_all_equipements() { + let shape = vec![EqShape::default().into(), EqShape::default().into()]; + + // let _nature: Vec = vec![EqNature::default().into(), EqNature::default().into()]; + let material = vec![EqMaterial::default().into(), EqMaterial::default().into()]; + let finishing = vec![EqFinishing::default().into(), EqMaterial::default().into()]; + + let mut leq = InitialEquipementList::from_vectored(shape); + // leq.combine_all(&InitialEquipementList::from_vectored(nature)); + leq.combine_all(&InitialEquipementList::from_vectored(material)); + leq.combine_all(&InitialEquipementList::from_vectored(finishing)); + } + + #[ignore] + #[test] + fn test_default_behaviour() { + unimplemented!() + } +} diff --git a/crates/weaponry/src/weaponry_structs/equipement_thin_types.rs b/crates/weaponry/src/weaponry_structs/equipement_thin_types.rs new file mode 100644 index 0000000..ce834cf --- /dev/null +++ b/crates/weaponry/src/weaponry_structs/equipement_thin_types.rs @@ -0,0 +1,120 @@ +// 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) + } +} + +#[cfg(test)] +mod test { + use crate::weaponry_structs::equipement_thin_types::{Actions, Attacks, Dices, Precision}; + + #[test] + fn test_displays() { + println!( + "{}, {}, {}, {}", + Attacks(0), + Actions(1), + Precision(2), + Dices(3) + ); + } +} diff --git a/crates/weaponry/src/weaponry_structs/mod.rs b/crates/weaponry/src/weaponry_structs/mod.rs new file mode 100644 index 0000000..21051c9 --- /dev/null +++ b/crates/weaponry/src/weaponry_structs/mod.rs @@ -0,0 +1,49 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/mod.rs +//! All weaponry intermod structures + +// #![allow(dead_code)] +// use mimalloc::MiMalloc; + +// #[global_allocator] +// static GLOBAL: MiMalloc = MiMalloc; + +// #[cfg(not(target_env = "msvc"))] +// use tikv_jemallocator::Jemalloc; + +// #[cfg(not(target_env = "msvc"))] +// #[global_allocator] +// static GLOBAL: Jemalloc = Jemalloc; + +#[macro_use] +mod equipement_advanced_repr; +mod equipement_advanced_tools; +mod equipement_fields; +mod equipement_impl_basics; +pub mod equipement_impl_database; +mod equipement_impl_io; +mod equipement_impl_logic; +pub mod equipement_scenario; +pub mod equipement_structs; +pub mod equipement_thin_types; + +// Republishes the most used symbols +// All generic structs +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, EquipementSerializedCategory, NatureTarget, SpecialField, + WeaponBaseShape, +}; +// Likely ? Final Re-Exports +pub use equipement_scenario::CrossRecipeScenario; + +// // TODO[!]: Add a sensible prelude +// mod prelude{ + +// } diff --git a/helper_config.toml b/helper_config.toml index 305c592..d77bfaf 100644 --- a/helper_config.toml +++ b/helper_config.toml @@ -1,3 +1,8 @@ +[data_generation] +# This value should be overwriten by a relative path +database = "../ravenous-tools/weaponry/databases/weapons.db" + + [classes] header = '''\begin{}[ presep = 0pt, postsep = 0pt, diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..5d56faf --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "nightly"