Cleaning up the scenario and progressive integration into the main impl
This commit is contained in:
parent
5b3972a906
commit
f3bb2c9d80
|
|
@ -3,46 +3,56 @@
|
|||
//! Test use case of a scenario
|
||||
//!
|
||||
//!
|
||||
use charming::component::Legend;
|
||||
use charming::element::Orient;
|
||||
use clap::Parser;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
/// Basic cli
|
||||
pub struct ParserCLIArgs {
|
||||
/// The path to save to.
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
use charming::HtmlRenderer;
|
||||
use charming::{
|
||||
Chart,
|
||||
component::{
|
||||
Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox,
|
||||
ToolboxDataZoom,
|
||||
},
|
||||
element::{AxisType, Tooltip, Trigger},
|
||||
series::Line,
|
||||
};
|
||||
use std::path::Path;
|
||||
use weaponry::interfaces::ToAnalysis;
|
||||
|
||||
// TODO : All of these should likely be in the prelude if used like this
|
||||
use weaponry::weaponry_structs::CrossRecipeScenario;
|
||||
use weaponry::weaponry_structs::equipement_scenario::ConfigMock;
|
||||
use weaponry::weaponry_structs::equipement_scenario::ConfigEquipementScenario;
|
||||
use weaponry::{
|
||||
interfaces::{Reportable, Scenario, ToCSV},
|
||||
weaponry_structs::RefinedEquipementList,
|
||||
};
|
||||
// use weaponry::interfaces::
|
||||
fn main() {
|
||||
let save_path = "data/first_data";
|
||||
let scenarios = CrossRecipeScenario::new_with_config(ConfigMock {}).unwrap();
|
||||
let mut refined_list = scenarios.generate_refined_recipes().unwrap();
|
||||
// Render as html
|
||||
render_data(&mut refined_list, save_path);
|
||||
// // Export as csv
|
||||
let args = CLIArgs::parse();
|
||||
let save_path = args.path.unwrap_or("data/first_data".into());
|
||||
let scenarios = CrossRecipeScenario::new_with_config(ConfigEquipementScenario {
|
||||
table_name: "Equipements".into(),
|
||||
db_path: "./databases/weapons.db".into(),
|
||||
shape: args.shapes.then_some(()),
|
||||
materials: args.materials,
|
||||
nature: args.natures.then_some(()),
|
||||
finishing: args.finishing.then_some(()),
|
||||
})
|
||||
.unwrap();
|
||||
let refined_list = scenarios.generate_refined_recipes().unwrap();
|
||||
|
||||
// if args.html_export{}
|
||||
refined_list.write_html(&save_path).unwrap();
|
||||
|
||||
// if args.csv_export{}
|
||||
// export_as_csv(&refined_list, save_path);
|
||||
}
|
||||
#[derive(Parser, Debug)]
|
||||
/// Basic cli
|
||||
pub struct CLIArgs {
|
||||
/// The path to save to.
|
||||
pub path: Option<String>,
|
||||
/// Wether to generate shapes
|
||||
#[arg(short, long, default_value_t = true)]
|
||||
pub shapes: bool,
|
||||
/// Wether to generate materials
|
||||
#[arg(short, long)]
|
||||
pub materials: Option<usize>,
|
||||
/// Wether to generate all natures
|
||||
#[arg(short, long, default_value_t = true)]
|
||||
pub natures: bool,
|
||||
/// Wether to generate all finishing
|
||||
#[arg(short, long, default_value_t = false)]
|
||||
pub finishing: bool,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) {
|
||||
|
|
@ -53,106 +63,3 @@ fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) {
|
|||
refined_list.write_csv(Path::new(&format!("{save_path}.csv")))
|
||||
);
|
||||
}
|
||||
|
||||
pub fn make_chart(data: &mut RefinedEquipementList) -> Chart {
|
||||
data.inner
|
||||
.sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe));
|
||||
let raw_data = data.inner.iter().map(|refeq| {
|
||||
(
|
||||
&refeq.advanced.display_name,
|
||||
refeq.advanced.dps_safe,
|
||||
refeq.advanced.max_damage_per_action,
|
||||
refeq.advanced.armor_break_per_turn,
|
||||
)
|
||||
});
|
||||
let mut data_list = vec![];
|
||||
let mut dps_safe = vec![];
|
||||
let mut max_damage_per_action = vec![];
|
||||
let mut armor_break_per_turn = vec![];
|
||||
|
||||
raw_data.into_iter().for_each(|(index, dps_s, dpa, abpt)| {
|
||||
data_list.push(index);
|
||||
dps_safe.push(dps_s);
|
||||
max_damage_per_action.push(dpa);
|
||||
armor_break_per_turn.push(abpt);
|
||||
});
|
||||
|
||||
Chart::new()
|
||||
.title(
|
||||
Title::new()
|
||||
.text("Damage for all cross-gen products")
|
||||
.left("center"),
|
||||
)
|
||||
.legend(
|
||||
Legend::new()
|
||||
.left(10)
|
||||
.top("middle")
|
||||
.orient(Orient::Vertical)
|
||||
.data(vec![
|
||||
"dps_safe",
|
||||
"max_damage_per_action",
|
||||
"armor_break_per_turn",
|
||||
]),
|
||||
)
|
||||
.tooltip(Tooltip::new().trigger(Trigger::Axis))
|
||||
.x_axis(
|
||||
Axis::new()
|
||||
.data(data_list.to_vec())
|
||||
.type_(AxisType::Category),
|
||||
)
|
||||
.y_axis(Axis::new())
|
||||
.grid(Grid::new().contain_label(true))
|
||||
.series(
|
||||
Line::new().data(dps_safe).name("dps_safe"), // .line_style(LineStyle::new().color("paleblue")),
|
||||
)
|
||||
.series(
|
||||
Line::new()
|
||||
.data(max_damage_per_action)
|
||||
.name("max_damage_per_action"),
|
||||
)
|
||||
.series(
|
||||
Line::new()
|
||||
.data(armor_break_per_turn)
|
||||
.name("armor_break_per_turn"),
|
||||
)
|
||||
.data_zoom(
|
||||
DataZoom::new()
|
||||
.type_(DataZoomType::Inside)
|
||||
.start(0)
|
||||
.end(100),
|
||||
)
|
||||
.data_zoom(DataZoom::new().start(0).end(100))
|
||||
.toolbox(
|
||||
Toolbox::new().feature(
|
||||
Feature::new()
|
||||
.data_zoom(ToolboxDataZoom::new().y_axis_index("none"))
|
||||
.restore(Restore::new())
|
||||
.save_as_image(SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])),
|
||||
),
|
||||
)
|
||||
.tooltip(Tooltip::new().trigger(Trigger::Axis))
|
||||
}
|
||||
|
||||
fn render_data(data: &mut RefinedEquipementList, save_path: &str) {
|
||||
let mut renderer =
|
||||
HtmlRenderer::new("Ravenous Balancing", 4000, 2000).theme(charming::theme::Theme::Dark);
|
||||
// Save the chart as HTML file.
|
||||
println!("Saving to {save_path}.html");
|
||||
renderer
|
||||
.save(&make_chart(data), format!("{save_path}.html"))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// // Load DB
|
||||
// let db = EquipementDatabase::new("./databases/weapons.db").unwrap();
|
||||
// // Do a first deserialisation
|
||||
// let initial_deserialisation = db.serialize_vec_from_table::<DatabaseEquipementStats>("Equipements", None).unwrap();
|
||||
// // Follow up by parsing this deserialisation by a transformation into the right intermediate representation
|
||||
// let intermediate_deserialisation = initial_deserialisation.into_iter().map(InnerEquipementStats::try_from).collect::<Vec<_>>();
|
||||
|
||||
// // // Inspect the sucesses/filures
|
||||
// // let f = intermediate_deserialisation.iter().fold((0, 0), |val, res| (val.0 + res.is_ok() as usize, val.1 + 1_usize));
|
||||
// // println!("Succeded in parsing {}/{}", f.0, f.1);
|
||||
|
||||
// // println!("Final data {:#?}", intermediate_deserialisation);
|
||||
// // println!("Failed to parse: {:#?}", intermediate_deserialisation.into_iter().filter_map(|v| v.err()).collect::<Vec<_>>());
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
//! Inner weaponry error definition
|
||||
#![allow(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
|
||||
use charming::EchartsError;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
|
|
@ -32,22 +33,28 @@ pub enum FatalEquipementError {
|
|||
|
||||
#[error("Couldn't convert into type {origin_type} with data {data}")]
|
||||
Conversion { origin_type: String, data: String },
|
||||
|
||||
#[error("An error occured with your current CLI configuration: {0}")]
|
||||
CLISelection(String),
|
||||
|
||||
#[error("Couldn't save the chart as an error occured during the process : {0}")]
|
||||
SaveCharmingChart(#[from] EchartsError),
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
/// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program
|
||||
pub enum LocalEquipementError {
|
||||
#[error("Very simple error")]
|
||||
Oops,
|
||||
}
|
||||
// #[derive(Error, Debug)]
|
||||
// /// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program
|
||||
// pub enum LocalEquipementError {
|
||||
// #[error("Very simple error")]
|
||||
// Oops,
|
||||
// }
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
/// An equipement error, either unrecoverable, indicating a that the execution
|
||||
/// flow must be stopped and only an user input can solve the issue
|
||||
pub enum EquipementError {
|
||||
#[error("An unrecoverable error occured: {0}")]
|
||||
Fatal(#[from] FatalEquipementError),
|
||||
// #[derive(Error, Debug)]
|
||||
// /// An equipement error, either unrecoverable, indicating a that the execution
|
||||
// /// flow must be stopped and only an user input can solve the issue
|
||||
// pub enum EquipementError {
|
||||
// #[error("An unrecoverable error occured: {0}")]
|
||||
// Fatal(#[from] FatalEquipementError),
|
||||
|
||||
#[error("A local error occured an wasn't recovered from: {0}")]
|
||||
Local(#[from] LocalEquipementError),
|
||||
}
|
||||
// #[error("A local error occured an wasn't recovered from: {0}")]
|
||||
// Local(#[from] LocalEquipementError),
|
||||
// }
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ use std::{path::Path, rc::Rc};
|
|||
use more_fields::FieldsAsSlice;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::error::{EquipementError, FatalEquipementError};
|
||||
use crate::error::FatalEquipementError;
|
||||
|
||||
/// Trait representing a view table
|
||||
///
|
||||
|
|
@ -42,7 +42,7 @@ pub trait ViewTable {
|
|||
/// While it is possible to enforce from_recipe_collection, doing so would require the viewtable
|
||||
/// lock itseld to a particular recipe.
|
||||
/// While it is the case as of now, matters are not yet set in stone
|
||||
pub trait RefinedList {
|
||||
pub trait RefinedList: ToTex + ToCSV + ToAnalysis {
|
||||
// Must implement From<RecipeCollection>, is it worth adding as a prerequite type ?
|
||||
// type OriginCollection: Into<Self>;
|
||||
}
|
||||
|
|
@ -150,6 +150,14 @@ pub trait ToCSV {
|
|||
fn write_csv(&self, path: &Path) -> csv::Result<()>;
|
||||
}
|
||||
|
||||
/// This element can be converted to an interactive .html
|
||||
pub trait ToAnalysis {
|
||||
/// Write as html
|
||||
fn write_html(&self, path: &str) -> Result<(), FatalEquipementError>;
|
||||
|
||||
// TODO: Add sorting methods as no analysis can be done without filtering and sorting
|
||||
}
|
||||
|
||||
/// A generic database+connection, handling all the deserialization of the inner types
|
||||
pub trait RecipeDatabase {
|
||||
/// Create the database from a file
|
||||
|
|
@ -205,45 +213,16 @@ pub trait Reportable {
|
|||
pub trait Scenario {
|
||||
/// The inner database type
|
||||
type DatabaseType: RecipeDatabase;
|
||||
/// The type of viewtable that must be returned by the scenario
|
||||
// Could also use dyn dispatch but since all of it is so tied down...
|
||||
type ViewTableType: ViewTable;
|
||||
/// The type of the final recipe list
|
||||
type FinalListType: RefinedList;
|
||||
type FinalListType: RefinedList + ToTex + ToCSV + ToAnalysis;
|
||||
/// Inner configuration
|
||||
type Config;
|
||||
|
||||
/// Create a Scenario from a given config
|
||||
fn new_with_config(config: Self::Config) -> Result<Self, EquipementError>
|
||||
fn new_with_config(config: Self::Config) -> Result<Self, FatalEquipementError>
|
||||
where
|
||||
Self: Sized;
|
||||
|
||||
// /// Load all database into intermediate representation
|
||||
// fn load_from_database() -> Result<Self, FatalEquipementError>
|
||||
// where
|
||||
// Self: std::marker::Sized;
|
||||
|
||||
// /// Configure the scenario to the user's needs
|
||||
// fn configure_scenario(&mut self, config: Self::Config) -> Result<(), FatalEquipementError>;
|
||||
|
||||
// All these steps should be implemented but not required
|
||||
// enforcing them helps writing new impls more easily but is not really nice in any way
|
||||
//
|
||||
// /// Process the inner representations and get a list of results
|
||||
// fn process_inner_representation(&self) -> Result<(), FatalEquipementError>; //Result<(), EquipementError>
|
||||
|
||||
// /// Process inner recipes into a Final list
|
||||
// ///
|
||||
// /// This will generate the recipe list using the prefered method of the Scenario (Fixed Recipes or Cross Recipes or Whatever)
|
||||
// fn process_recipes(&self);
|
||||
|
||||
// /// Process the recipes into a Refined Recipes
|
||||
// fn refine_recipes(&self);
|
||||
|
||||
/// Generate the final list type
|
||||
fn generate_refined_recipes(&self) -> Result<Self::FinalListType, EquipementError>;
|
||||
|
||||
/// Gather the selected view tables
|
||||
/// All the inner generation is done gradually and populate all section to finally generate the views
|
||||
fn generate_view_tables(&self, equipement_list: Self::FinalListType) -> Self::ViewTableType;
|
||||
fn generate_refined_recipes(&self) -> Result<Self::FinalListType, FatalEquipementError>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,11 @@
|
|||
use core::f64;
|
||||
use std::fmt::Display;
|
||||
|
||||
use crate::interfaces::RefinedList;
|
||||
use crate::{
|
||||
error::FatalEquipementError,
|
||||
interfaces::{RefinedList, ToAnalysis, ToTex},
|
||||
};
|
||||
use charming::element::Orient;
|
||||
use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS};
|
||||
use probability::prelude::{Binomial, Discrete};
|
||||
use serde::Serialize;
|
||||
|
|
@ -64,6 +68,126 @@ pub struct RefinedEquipementList {
|
|||
|
||||
// Just a checkmark
|
||||
impl RefinedList for RefinedEquipementList {}
|
||||
impl ToTex for RefinedEquipementList {
|
||||
fn to_tex(&self) -> String {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
impl ToAnalysis for RefinedEquipementList {
|
||||
fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> {
|
||||
let mut renderer = charming::HtmlRenderer::new("Ravenous Balancing", 4000, 2000)
|
||||
.theme(charming::theme::Theme::Dark);
|
||||
// Save the chart as HTML file.
|
||||
renderer.save(&make_chart(self), format!("{save_path}.html"))?;
|
||||
return Ok(());
|
||||
|
||||
// TODO: Migrate this into the view / renderer
|
||||
// TODO: End the view idea and only focus on this renderer
|
||||
pub fn make_chart(data: &RefinedEquipementList) -> charming::Chart {
|
||||
// TODO: Add back sorting
|
||||
// data.inner
|
||||
// .sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe));
|
||||
|
||||
// TODO: Convert to macro
|
||||
let raw_data = data.inner.iter().map(|refeq| {
|
||||
(
|
||||
&refeq.advanced.display_name,
|
||||
refeq.advanced.dps_safe,
|
||||
refeq.advanced.max_damage_per_action,
|
||||
refeq.advanced.damage_per_turn,
|
||||
refeq.advanced.armor_break_per_turn,
|
||||
)
|
||||
});
|
||||
let mut data_list = vec![];
|
||||
let mut dps_safe = vec![];
|
||||
let mut max_damage_per_action = vec![];
|
||||
let mut max_damage_per_turn = vec![];
|
||||
let mut armor_break_per_turn = vec![];
|
||||
|
||||
raw_data
|
||||
.into_iter()
|
||||
.for_each(|(index, dps_s, dpa, dpt, abpt)| {
|
||||
data_list.push(index);
|
||||
dps_safe.push(dps_s);
|
||||
max_damage_per_action.push(dpa);
|
||||
max_damage_per_turn.push(dpt);
|
||||
armor_break_per_turn.push(abpt);
|
||||
});
|
||||
|
||||
// TODO: End of macro conversion
|
||||
|
||||
// TODO: Call this iteratively with all elements in macro
|
||||
charming::Chart::new()
|
||||
.title(
|
||||
charming::component::Title::new()
|
||||
.text("Damage for all cross-gen products")
|
||||
.left("center"),
|
||||
)
|
||||
.legend(
|
||||
charming::component::Legend::new()
|
||||
.left(10)
|
||||
.top("middle")
|
||||
.orient(Orient::Vertical)
|
||||
.data(vec![
|
||||
"dps_safe",
|
||||
"max_damage_per_action",
|
||||
"max_damage_per_turn",
|
||||
"armor_break_per_turn",
|
||||
]),
|
||||
)
|
||||
.tooltip(
|
||||
charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis),
|
||||
)
|
||||
.x_axis(
|
||||
charming::component::Axis::new()
|
||||
.data(data_list.to_vec())
|
||||
.type_(charming::element::AxisType::Category),
|
||||
)
|
||||
.y_axis(charming::component::Axis::new())
|
||||
.grid(charming::component::Grid::new().contain_label(true))
|
||||
.series(
|
||||
charming::series::Line::new()
|
||||
.data(dps_safe)
|
||||
.name("dps_safe"), // .line_style(LineStyle::new().color("paleblue")),
|
||||
)
|
||||
.series(
|
||||
charming::series::Line::new()
|
||||
.data(max_damage_per_action)
|
||||
.name("max_damage_per_action"),
|
||||
)
|
||||
.series(
|
||||
charming::series::Line::new()
|
||||
.data(max_damage_per_turn)
|
||||
.name("max_damage_per_turn"),
|
||||
)
|
||||
.series(
|
||||
charming::series::Line::new()
|
||||
.data(armor_break_per_turn)
|
||||
.name("armor_break_per_turn"),
|
||||
)
|
||||
.data_zoom(
|
||||
charming::component::DataZoom::new()
|
||||
.type_(charming::component::DataZoomType::Inside)
|
||||
.start(0)
|
||||
.end(100),
|
||||
)
|
||||
.data_zoom(charming::component::DataZoom::new().start(0).end(100))
|
||||
.toolbox(
|
||||
charming::component::Toolbox::new().feature(
|
||||
charming::component::Feature::new()
|
||||
.data_zoom(
|
||||
charming::component::ToolboxDataZoom::new().y_axis_index("none"),
|
||||
)
|
||||
.restore(charming::component::Restore::new())
|
||||
.save_as_image(charming::component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])),
|
||||
),
|
||||
)
|
||||
.tooltip(
|
||||
charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<InitialEquipementList> for RefinedEquipementList {
|
||||
fn from(value: InitialEquipementList) -> Self {
|
||||
|
|
@ -225,17 +349,23 @@ impl DamageMatrix {
|
|||
}
|
||||
|
||||
/// Calculate the binomial distribution and average the damage from there
|
||||
fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, dices: usize) -> f64 {
|
||||
let p = ((precision as i8 + value.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10);
|
||||
fn binomial_dice_distribution(
|
||||
equipement: &InnerEquipementStats,
|
||||
precision: usize,
|
||||
dices: usize,
|
||||
) -> f64 {
|
||||
let p = ((precision as i8 + equipement.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10);
|
||||
let binomial = Binomial::new(dices, p);
|
||||
|
||||
(0..dices + 1)
|
||||
.map(|target_dices| {
|
||||
let probability_success = binomial.mass(target_dices); // Let's have weird half dices as usize;
|
||||
if target_dices >= 1 {
|
||||
(value.damage as f64
|
||||
+ value.p_damage as f64
|
||||
* (target_dices.clamp(0, value.rmax as usize).saturating_sub(1)) as f64)
|
||||
(equipement.damage as f64
|
||||
+ equipement.p_damage as f64
|
||||
* (target_dices
|
||||
.clamp(0, equipement.rmax as usize)
|
||||
.saturating_sub(1)) as f64)
|
||||
* probability_success
|
||||
} else {
|
||||
0.
|
||||
|
|
@ -244,6 +374,8 @@ fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, di
|
|||
.fold(0., |a, b| a + b)
|
||||
}
|
||||
|
||||
// TODO: Change this to be a thin type and replace enum by new(nb) et high(), med() etc..
|
||||
// : And add a way to do ranges easily
|
||||
/// The precision infered for a damage calculation event
|
||||
#[derive(EnumIter, Clone, Copy, Display)]
|
||||
#[allow(clippy::missing_docs_in_private_items)]
|
||||
|
|
|
|||
|
|
@ -39,29 +39,16 @@ impl From<EqMaterial> for Equipement {
|
|||
}
|
||||
}
|
||||
|
||||
// TODO: Change this into tryfrom
|
||||
impl From<EqNature> for Equipement {
|
||||
fn from(val: EqNature) -> Self {
|
||||
Self {
|
||||
stats: val.stats,
|
||||
// TODO : Checks that this is exactly desired behavious
|
||||
// :Also check for Cross Weapon/Armor contamination
|
||||
// Checks that the nature is compatible with the previous iteration
|
||||
filter_function: FilterFunction::new(filter_id_unique_and_right_category()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// (Some(a), Some(b)) => {
|
||||
// println!("{} {}", a, b);
|
||||
// a == b
|
||||
// }
|
||||
// // There is no target and the part about to be added is generic
|
||||
// (None, None) => true,
|
||||
// // There is a specific target but the part about to be added is generic
|
||||
// (Some(_), None) => true,
|
||||
// // There is restriction on the target and the recipient
|
||||
// (None, Some(_)) => true,
|
||||
impl From<EqFinishing> for Equipement {
|
||||
fn from(val: EqFinishing) -> Self {
|
||||
Self {
|
||||
|
|
|
|||
|
|
@ -2,11 +2,9 @@
|
|||
// File: weaponry/src/weaponry_structs/equipement_impl_io.rs
|
||||
//! All implementation IO specific (mainly export and serde)
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::interfaces::ToCSV;
|
||||
|
||||
use super::equipement_advanced_repr::RefinedEquipementList;
|
||||
use crate::interfaces::ToCSV;
|
||||
use std::path::Path;
|
||||
|
||||
impl ToCSV for RefinedEquipementList {
|
||||
fn write_csv(&self, path: &Path) -> csv::Result<()> {
|
||||
|
|
|
|||
|
|
@ -7,54 +7,48 @@
|
|||
//! and therefore mostly serves as a TO-DO list
|
||||
//!
|
||||
|
||||
#![allow(dead_code)]
|
||||
use crate::error::FatalEquipementError;
|
||||
#[allow(unused_imports)]
|
||||
use crate::interfaces::Reportable;
|
||||
use crate::weaponry_structs::InitialEquipementList;
|
||||
use crate::weaponry_structs::equipement_structs::DatabaseEquipementStats;
|
||||
use crate::weaponry_structs::equipement_structs::EqFinishing;
|
||||
use crate::weaponry_structs::equipement_structs::EqMaterial;
|
||||
use crate::weaponry_structs::equipement_structs::EqNature;
|
||||
use crate::weaponry_structs::equipement_structs::EqShape;
|
||||
use crate::{
|
||||
error::EquipementError,
|
||||
interfaces::{RecipeCollection, RecipeDatabase, Scenario, ViewTable},
|
||||
error::FatalEquipementError,
|
||||
interfaces::{RecipeCollection, RecipeDatabase, Scenario},
|
||||
weaponry_structs::{
|
||||
Equipement, InitialEquipementList, RefinedEquipementList,
|
||||
equipement_impl_database::EquipementDatabase,
|
||||
equipement_structs::{
|
||||
DatabaseEquipementStats, EqFinishing, EqMaterial, EqNature, EqShape,
|
||||
InnerEquipementStats,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
use super::Equipement;
|
||||
use super::equipement_advanced_repr::RefinedEquipementList;
|
||||
use super::equipement_impl_database::EquipementDatabase;
|
||||
use super::equipement_structs::InnerEquipementStats;
|
||||
|
||||
/// Mock config
|
||||
pub struct ConfigMock {}
|
||||
/// Mock Viewtable
|
||||
pub struct ViewtableMock {}
|
||||
impl ViewTable for ViewtableMock {
|
||||
type InterestElementList = RefinedEquipementList;
|
||||
|
||||
fn index_of_interest_points(&self) -> Vec<usize> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn find_points_of_interest(representation: &Self::InterestElementList) -> Self {
|
||||
let _ = representation;
|
||||
todo!()
|
||||
}
|
||||
/// Base Equipement Scenario config
|
||||
pub struct ConfigEquipementScenario {
|
||||
/// Table Name
|
||||
pub table_name: String,
|
||||
/// Database path
|
||||
pub db_path: String,
|
||||
// TODO[2]: Add something smart here to take care of the selection process
|
||||
/// Wether the shapes are selected
|
||||
pub shape: Option<()>,
|
||||
/// Wether the materials are selected, and how many iteration there are
|
||||
pub materials: Option<usize>,
|
||||
/// Wether the natures are selected
|
||||
pub nature: Option<()>,
|
||||
/// Wether the finishing touches are selected
|
||||
pub finishing: Option<()>,
|
||||
}
|
||||
|
||||
/// A simple cross recipe scenario
|
||||
#[allow(clippy::missing_docs_in_private_items)]
|
||||
pub struct CrossRecipeScenario {
|
||||
// TODO: Should obv be inside the config
|
||||
database_name: String,
|
||||
database: EquipementDatabase,
|
||||
config: ConfigMock,
|
||||
config: ConfigEquipementScenario,
|
||||
}
|
||||
|
||||
impl CrossRecipeScenario {
|
||||
/// Automatically deserialize into an equipement
|
||||
// TODO: Add to trait
|
||||
// TODO: Add an optionnal filter
|
||||
fn deserde_into_equipement<T>(
|
||||
&self,
|
||||
name: &str,
|
||||
|
|
@ -62,10 +56,12 @@ impl CrossRecipeScenario {
|
|||
where
|
||||
T: TryFrom<InnerEquipementStats> + From<InnerEquipementStats> + Into<Equipement>,
|
||||
{
|
||||
// TODO: This likely has too high a complexity and should either be a blanket implementation
|
||||
// : or require the inner workings to implement methods to easily allow this deserialisation
|
||||
Ok(InitialEquipementList::from_vectored(
|
||||
self.database
|
||||
.serialize_vec_from_table::<DatabaseEquipementStats>(
|
||||
&self.database_name,
|
||||
&self.config.table_name,
|
||||
Some(&format!("META_CATEGORY LIKE '{}'", name)),
|
||||
)?
|
||||
.into_iter()
|
||||
|
|
@ -77,63 +73,59 @@ impl CrossRecipeScenario {
|
|||
.collect::<Result<Vec<_>, FatalEquipementError>>()?,
|
||||
))
|
||||
}
|
||||
|
||||
/// Generate all the operations to be processed with the current config
|
||||
// TODO: Defer this to a custom type in the config some sort of OperationSelector
|
||||
fn generate_selected_operation(
|
||||
&self,
|
||||
) -> Result<Vec<InitialEquipementList>, FatalEquipementError> {
|
||||
let mut operations = Vec::with_capacity(8);
|
||||
if self.config.shape.is_some() {
|
||||
operations.push(self.deserde_into_equipement::<EqShape>("Shape")?);
|
||||
}
|
||||
if let Some(qt) = self.config.materials {
|
||||
for _ in 0..qt {
|
||||
operations.push(self.deserde_into_equipement::<EqMaterial>("Materials")?);
|
||||
}
|
||||
}
|
||||
if self.config.nature.is_some() {
|
||||
operations.push(self.deserde_into_equipement::<EqNature>("Nature")?);
|
||||
}
|
||||
if self.config.finishing.is_some() {
|
||||
operations.push(self.deserde_into_equipement::<EqFinishing>("Finishing")?);
|
||||
}
|
||||
if operations.is_empty() {
|
||||
return Err(FatalEquipementError::CLISelection(
|
||||
"No step was selected for generation, please select at least one step".into(),
|
||||
));
|
||||
};
|
||||
Ok(operations)
|
||||
}
|
||||
}
|
||||
|
||||
impl Scenario for CrossRecipeScenario {
|
||||
type DatabaseType = EquipementDatabase;
|
||||
type ViewTableType = ViewtableMock;
|
||||
type FinalListType = RefinedEquipementList;
|
||||
type Config = ConfigMock;
|
||||
type Config = ConfigEquipementScenario;
|
||||
|
||||
fn new_with_config(config: Self::Config) -> Result<Self, EquipementError>
|
||||
fn new_with_config(config: Self::Config) -> Result<Self, FatalEquipementError>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Ok(Self {
|
||||
// TODO: Correct this relative path abomination
|
||||
database_name: "Equipements".into(),
|
||||
database: Self::DatabaseType::new("./databases/weapons.db")?,
|
||||
database: Self::DatabaseType::new(&config.db_path)?,
|
||||
config,
|
||||
})
|
||||
}
|
||||
|
||||
fn generate_refined_recipes(&self) -> Result<Self::FinalListType, EquipementError> {
|
||||
// TODO: Depending on config, a different filter might be given here
|
||||
let eq_shape = self.deserde_into_equipement::<EqShape>("Shape")?;
|
||||
let eq_material = self.deserde_into_equipement::<EqMaterial>("Materials")?;
|
||||
let eq_nature = self.deserde_into_equipement::<EqNature>("Nature")?;
|
||||
#[allow(unused_variables)]
|
||||
let eq_finishing = self.deserde_into_equipement::<EqFinishing>("Finishing")?;
|
||||
fn generate_refined_recipes(&self) -> Result<Self::FinalListType, FatalEquipementError> {
|
||||
let operations = self.generate_selected_operation()?;
|
||||
|
||||
// println!(
|
||||
// "{}\n{}\n{}\n{}",
|
||||
// eq_shape.get_report(Some("EqShape ")),
|
||||
// eq_material.get_report(Some("EqMaterials")),
|
||||
// eq_nature.get_report(Some("EqNature ")),
|
||||
// eq_finishing.get_report(Some("EqFinishing"))
|
||||
// );
|
||||
let mut opertation_it = operations.into_iter();
|
||||
let mut refined_list = opertation_it.next().unwrap();
|
||||
|
||||
// No op, just clarity
|
||||
// TODO: Depending on config this step might differ
|
||||
let mut f_list = eq_shape;
|
||||
println!("{}", f_list.get_report(Some("Initial Weapons ")));
|
||||
f_list.combine_all(&eq_material);
|
||||
println!("{}", f_list.get_report(Some("Combined with Materials")));
|
||||
f_list.combine_all(&eq_material);
|
||||
println!("{}", f_list.get_report(Some("Combined with Materials")));
|
||||
f_list.combine_all(&eq_nature);
|
||||
println!("{}", f_list.get_report(Some("Combined with Natures ")));
|
||||
// f_list.combine_all(&eq_finishing);
|
||||
// println!("{}", f_list.get_report(Some("Combined with Finishing")));
|
||||
// TODO: The finishes are interesting if they are configured or at least tamed a little
|
||||
// TODO: As a high cost finish cannot hope to compete with a low one
|
||||
// TODO: and therefore need a special metric and fixed entry data to be mesured
|
||||
Ok(f_list.into())
|
||||
}
|
||||
opertation_it.for_each(|operation| refined_list.combine_all(&operation));
|
||||
|
||||
fn generate_view_tables(&self, equipement_list: Self::FinalListType) -> Self::ViewTableType {
|
||||
// TODO: Change this depending on the config ? or maybe a scenario is inerently tied to a viewtable ?
|
||||
// The polymorphism will depend on many factors not yet known :(
|
||||
Self::ViewTableType::find_points_of_interest(&equipement_list)
|
||||
Ok(refined_list.into())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue