Many usefull impls on scenarios

This commit is contained in:
Dandaedre 2025-02-24 06:57:36 +01:00
parent cb6c7ebc2a
commit 56289649a4
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
4 changed files with 328 additions and 191 deletions

View File

@ -5,8 +5,8 @@
//!
use clap::Parser;
use std::path::Path;
use weaponry::filter_by;
use weaponry::interfaces::ToAnalysis;
use weaponry::sort_by;
use weaponry::weaponry_structs::RefinedEquipement;
// TODO : All of these should likely be in the prelude if used like this
@ -23,15 +23,23 @@ fn main() {
let scenarios = CrossRecipeScenario::new_with_config(ConfigEquipementScenario {
table_name: "Equipements".into(),
db_path: "./databases/weapons.db".into(),
shape: args.shapes.then_some(()),
shape: (!args.no_shapes).then_some(()),
materials: args.materials,
nature: args.natures.then_some(()),
nature: (!args.no_natures).then_some(()),
finishing: args.finishing.then_some(()),
})
.unwrap();
let mut refined_list = scenarios.generate_refined_recipes().unwrap();
refined_list.inner_sort(filter_by!(max_damage_per_action));
match args.sort.as_str() {
"max_per_turn" => refined_list.inner_sort(sort_by!(max_damage_per_turn)),
"avg_huge" => refined_list.inner_sort(sort_by!(avg_damage_single_huge_hit)),
"avg_safe" => refined_list.inner_sort(sort_by!(avg_damage_2a_safe)),
"max_armor" => refined_list.inner_sort(sort_by!(armor_break_per_attack)),
// "id" => refined_list.inner_sort(|a, b| a.inner.id[0].cmp(&b.inner.id[0])), // It's actually the natural sorted way
_ => (),
}
// if args.html_export{}
refined_list.write_html(&save_path).unwrap();
@ -45,17 +53,19 @@ pub struct CLIArgs {
/// The path to save to.
pub path: Option<String>,
/// Wether to generate shapes
#[arg(short, long, default_value_t = true)]
pub shapes: bool,
#[arg(short('S'), long, default_value_t)]
pub no_shapes: bool,
/// Wether to generate materials
#[arg(short, long)]
pub materials: Option<usize>,
/// Wether to generate all natures
#[arg(short, long, default_value_t = true)]
pub natures: bool,
#[arg(short('N'), long)]
pub no_natures: bool,
/// Wether to generate all finishing
#[arg(short, long, default_value_t = false)]
pub finishing: bool,
#[arg(long, default_value_t = String::from("safe"))]
pub sort: String,
}
#[allow(dead_code)]

View File

@ -23,15 +23,11 @@
/// (
/// index # &String,
/// dps_safe # f64,
/// max_damage_per_action # f64,
/// armor_break_per_turn # f64,
/// ),
/// |ref_equipement| {
/// (
/// &ref_equipement.advanced.display_name,
/// ref_equipement.advanced.max_damage_per_action,
/// ref_equipement.advanced.damage_per_turn,
/// ref_equipement.advanced.armor_break_per_turn,
/// ref_equipement.advanced.max_damage_per_turn,
/// )
/// }
/// );
@ -44,36 +40,39 @@
/// which could easily reach 600k elements
///
/// Knowing this tradeoff, the difficulty to maintain is considered an acceptable tradeoff
// TODO[4]: If the field accessed are only in advanced, remove the closure entirely and auto_generate it
#[macro_export]
macro_rules! add_field_to_chart {
($base_struct:expr, $chart:ident, ($names:ident # $name_type:ty, $($table_names:ident # $table_type:ty),* $(,)*), | $closure_name:ident | {($($fields:expr,)*)}
) => {
let data_collection = $base_struct.inner.iter().map(|$closure_name| ( $($fields,)*) );
let ($names, $($table_names),*) = data_collection.collect::<(Vec<$name_type>, $(Vec<$table_type>,)*)>();
let $chart = $chart
.x_axis(
charming::component::Axis::new()
.data($names.to_vec())
.type_(charming::element::AxisType::Category),
);
$(
let $chart = $chart
.series(
charming::series::Line::new()
.data($table_names)
.name(stringify!($table_names)),
);
)*
let $chart = {
let data_collection = $base_struct.inner.iter().map(|$closure_name| ( $($fields,)*) );
let ($names, $($table_names),*) = data_collection.collect::<(Vec<$name_type>, $(Vec<$table_type>,)*)>();
let $chart = $chart
.x_axis(
charming::component::Axis::new()
.data($names.to_vec())
.type_(charming::element::AxisType::Category),
);
$(
let $chart = $chart
.series(
charming::series::Line::new()
.data($table_names)
.name(stringify!($table_names)),
);
)*
let $chart = $chart.legend(
charming::component::Legend::new()
.left(10)
.top("middle")
.orient(charming::element::Orient::Vertical)
.data(vec![
$(stringify!($table_names),)*
]),
);
$chart.legend(
charming::component::Legend::new()
.left(10)
.top("middle")
.orient(charming::element::Orient::Vertical)
.data(vec![
$(stringify!($table_names),)*
]),
)
};
}
}

View File

@ -2,6 +2,7 @@
// File: weaponry/src/lib.rs
//! Weaponry module, handling all weaponry creation and analysis
#![feature(int_roundings)]
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
#![feature(iter_intersperse, generic_arg_infer)]
@ -11,3 +12,11 @@ pub mod export;
pub mod interfaces;
mod strategy;
pub mod weaponry_structs;
/// Signals the function running is unfinished
#[macro_export]
macro_rules! unfinished {
() => {
println!("UNFINISHED FUNCTION CALLED AT {} LINE {}", file!(), line!());
};
}

View File

@ -8,25 +8,27 @@
//! nothing prevents us to implement the trait for other objects and avoid massive computation
//! of all the fields even when the user will not be interested in them
#![allow(dead_code)]
use crate::{add_field_to_chart, export::initial_chart, interfaces::RecipeCollection};
use core::f64;
use std::{cmp::Ordering, fmt::Display};
use crate::{
add_field_to_chart,
error::FatalEquipementError,
interfaces::{RefinedList, ToAnalysis, ToTex},
export::initial_chart,
interfaces::{RecipeCollection, RefinedList, ToAnalysis, ToTex},
unfinished,
weaponry_structs::{
Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats,
},
};
use core::f64;
use std::{
cmp::Ordering,
fmt::{Debug, Display},
ops::{Add, Deref},
};
use charming::Chart;
use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS};
use probability::prelude::{Binomial, Discrete};
use serde::Serialize;
use strum::{Display, EnumIter, IntoEnumIterator};
use super::{
Equipement, InitialEquipementList, WeaponMacroCategory,
equipement_structs::InnerEquipementStats,
};
use strum::{Display, EnumIter};
/// The final representation of the equipement inplementing all the fields needed for processing
// TODO: Add a public getter for the inner data
@ -78,7 +80,7 @@ impl ToTex for RefinedEquipementList {
#[macro_export]
/// A simple macro to sort the inner advanced field by a specific field
// TODO[6] find a way to not have to import the refinedequipement
macro_rules! filter_by {
macro_rules! sort_by {
($field:ident) => {
|a: &RefinedEquipement, b: &RefinedEquipement| {
a.advanced.$field.total_cmp(&b.advanced.$field)
@ -111,29 +113,44 @@ impl ToAnalysis for RefinedEquipementList {
let mut renderer = charming::HtmlRenderer::new("Ravenous Balancing", 4000, 2000)
.theme(charming::theme::Theme::Dark);
let initial_chart: Chart = initial_chart("Damage for all cross-gen products");
let initial_chart: Chart = initial_chart(&format!(
"Damage for all cross-gen products ({} Elements)",
self.inner.len()
));
add_field_to_chart!(
self,
initial_chart,
(
index # &String,
dps_safe # f64,
max_damage_per_action # f64,
armor_break_per_turn # f64,
dps_huge # f64,
// max_damage_per_turn # f64,
// max_damage_per_attack # f64,
// speed # f64,
// armor_break_per_attack # f64,
// expected_armor_break_per # f64,
avg_damage_safe # f64,
avg_damage_single_huge_hit # f64,
// scenario_damage # f64,
// defensive # f64,
mini_scenario_damage # f64
),
|ref_equipement| {
(
&ref_equipement.advanced.display_name,
ref_equipement.advanced.avg_dps_safe,
ref_equipement.advanced.max_damage_per_action,
ref_equipement.advanced.armor_break_per_turn,
ref_equipement.advanced.avg_huge_hit,
// ref_equipement.advanced.max_damage_per_turn,
// ref_equipement.advanced.max_damage_per_attack,
// ref_equipement.advanced.speed,
// ref_equipement.advanced.armor_break_per_attack,
// ref_equipement.advanced.expected_armor_break_per_2a,
ref_equipement.advanced.avg_damage_2a_safe,
ref_equipement.advanced.avg_damage_single_huge_hit,
// ref_equipement.advanced.scenario_damage,
// ref_equipement.advanced.defensive,
ref_equipement.advanced.mini_scenario_damage,
)
}
);
renderer.save(&initial_chart, format!("{save_path}.html"))?;
Ok(())
}
@ -166,137 +183,236 @@ impl Default for RefinedEquipementList {
#[derive(Serialize)]
pub struct AdvancedStats {
pub display_name: String,
pub damage_per_attack: f64,
pub damage_per_turn: f64,
pub max_damage_per_action: f64,
pub max_damage_per_attack: f64,
pub max_damage_per_turn: f64,
pub armor_break_per_attack: f64,
pub armor_break_per_turn: f64,
pub armor_break_per_action: f64,
pub damage_matrix: DamageMatrix,
pub category: Option<WeaponMacroCategory>,
// pub category: Option<WeaponMacroCategory>,
/// Armor break factoring in the damage output: While a weapon might have high AB, not having any damage will seriously hinder that AB
pub expected_armor_break_per_turn: f64,
pub expected_armor_break_per_2a: f64,
/// Dps with two actions and 5 dices
pub avg_dps_safe: f64,
pub avg_damage_2a_safe: f64,
// /// Dps with four actions and 11 dices
// pub dps_unsafe: f64,
// All other criterias are already in the inner as raw criterias
/// Avg damage for bit attack
pub avg_huge_hit: f64,
pub avg_damage_single_huge_hit: f64,
pub speed: f64,
pub scenario_damage: f64,
pub defensive: f64,
pub mini_scenario_damage: f64,
}
impl From<&InnerEquipementStats> for AdvancedStats {
fn from(value: &InnerEquipementStats) -> Self {
let damage_per_attack =
let max_damage_per_attack =
(value.damage + value.p_damage * (value.rmax.saturating_sub(1))) as f64;
let armor_break_per_attack = (value.armor_break as f64).min(damage_per_attack);
let damage_matrix = DamageMatrix::calculate_for(value);
let armor_break_per_attack = (value.armor_break as f64).min(max_damage_per_attack);
Self {
category: value.macro_category.clone(),
display_name: value.name.join(" "),
damage_per_attack,
damage_per_turn: damage_per_attack * 2.,
max_damage_per_action: damage_per_attack / (value.action_cost as f64),
armor_break_per_attack,
armor_break_per_turn: armor_break_per_attack * 2.,
armor_break_per_action: armor_break_per_attack / value.action_cost as f64,
// Adds the base strength, substracts the expected protection
expected_armor_break_per_turn: (damage_per_attack + 6. - 8.)
.min(armor_break_per_attack),
avg_huge_hit: damage_matrix.get_damage(FixedPrecision::High, FixedDiceNumber::Many),
avg_dps_safe: damage_matrix.get_safe_dmg(value.action_cost),
// UNUSED METRICS
// avg_dps_unsafe: damage_matrix.get_unsafe_dmg(value.action_cost),
damage_matrix,
max_damage_per_turn: max_damage_per_attack * 2., // TODO: Not Sure
// Defensive metrics
// SOL Metrics ?
// IMPORTANT METRICS
display_name: value.name.join(" "),
speed: value.speed.into(),
armor_break_per_attack,
expected_armor_break_per_2a: (max_damage_per_attack + 6. - 8.)
.min(armor_break_per_attack)
* 2.
/ value.action_cost as f64, // Adds the base strength, substracts the expected protection
max_damage_per_attack,
avg_damage_single_huge_hit: value.average_damage(&[Precision(9)], &[Dices(7)]), // A huge hit but definitely not a "FULL THROTTLE" hit
avg_damage_2a_safe: value.average_damage(&[Precision(7)], &[Dices(5)]), // damage_matrix.get_safe_dmg(value.action_cost),
// .average_damage(&[Precision(9), Precision(7), Precision(5)], &[Dices(5)]), // damage_matrix.get_safe_dmg(value.action_cost),
scenario_damage: get_damage_with_simulation(value),
mini_scenario_damage: (value.damage > 0)
.then(|| get_sustained_damage(value))
.unwrap_or_default(),
defensive: (value.parry as f64).max(value.dodge.into()), // TODO[b]: Integrity and prot should be taken into account
}
}
}
/// A damage matrix, crossing damage conditions (high dice to low dice) with precision (high precision to low precision)
///
/// This simulation does only calculate a very limited preset of damage values
// TODO[9]: Rewrite with (HashMap,HashMap) if it becomes needed
#[cfg_attr(test, derive(Debug))]
pub struct DamageMatrix {
/// The inner damage matrix
damage_matrix: Vec<f64>,
/// Create the damage profile with the following simulation:
/// 10turns total
/// - 1 turn no damage
/// - 2 turns full damage (12 dice, 130% precision)
/// - 2 turns safe attacks (5 dice, 50%p)
/// - 1 turn highspeed/range hit (7 dice, 80% precision)
/// - 4 turns normal damage (7 dice, 90% precision)
// TODO[!] Implementation
fn get_damage_with_simulation(value: &InnerEquipementStats) -> f64 {
let _ = value;
// unfinished!();
0.
}
impl DamageMatrix {
/// Get the damage value from given condition
pub fn get_damage(&self, precision: FixedPrecision, dices: FixedDiceNumber) -> f64 {
self.damage_matrix[precision as usize + 3 * dices as usize]
}
/// The "safe" damage, as in 5 dices, 2 attacks
// TODO: This safe damage actually uses 5 dices * 2 instead of doing max(5 * 1 , 2 * 1 + 3 * 1)
pub fn get_safe_dmg(&self, attack_cost: i8) -> f64 {
let _ = attack_cost;
(self.get_damage(FixedPrecision::Low, FixedDiceNumber::Few)
+ self.get_damage(FixedPrecision::Medium, FixedDiceNumber::Few)
+ self.get_damage(FixedPrecision::High, FixedDiceNumber::Few))
/ 3.
/// Sustained damage
///
/// Average damage factoring reload, calculated with 9 dice and 90% precision
// TODO[!] Replace avg_damage with this
fn get_sustained_damage(value: &InnerEquipementStats) -> f64 {
// unfinished!();
// Actions total and damage total are arbitrarely choosen
// With reload, damage calculation is rather complicated, since you can half reload but cant half attack
// so a reload is valid even if you don't reload fully, but you have to start your turn with less actions
// instead of building a complex scenario, the attack pattern is always: Ac:Attack + Re:Reload(and maybe reminder) every turn
// value.damage.into()
BestDamageScenarios::from_action_constraints(value, 6, 3, Dices(14), Precision(7))
.map_or(0., |v| v.damage_done)
}
/// The best resulting attack pattern of a virtual scenrio where some conditions are given
#[derive(Debug)]
pub struct BestDamageScenarios {
/// How many actions were used by the best attack
actions_used: i8,
/// Attacks actions used by the scenario
attacks_used: i8,
/// Resulting damage
damage_done: f64,
/// Remaining actions that need to be used to finish reload
reload_remaining: i8,
/// A debug value, should be taken down in final builds
// TODO[6]: Remove debug once the tests are done
depth: u8,
}
impl Add for BestDamageScenarios {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self {
actions_used: self.actions_used + rhs.actions_used,
attacks_used: self.attacks_used + rhs.attacks_used,
damage_done: self.damage_done + rhs.damage_done,
reload_remaining: self.reload_remaining + rhs.reload_remaining,
depth: self.depth + rhs.depth,
}
}
/// The "unsage" damage, as in, full dice, 2 attacks
// TODO: This damages does max(Max dices * 1, 5 dices * 2), which might not be optimal
pub fn get_unsafe_dmg(&self, attack_cost: i8) -> f64 {
f64::max(
self.get_safe_dmg(attack_cost) * 2.,
(self.get_damage(FixedPrecision::Low, FixedDiceNumber::Many)
+ self.get_damage(FixedPrecision::Medium, FixedDiceNumber::Many)
+ self.get_damage(FixedPrecision::High, FixedDiceNumber::Many))
/ 3.,
}
impl Deref for BestDamageScenarios {
type Target = f64;
fn deref(&self) -> &Self::Target {
&self.damage_done
}
}
// TODO[!!]: Add a lot of testing
impl BestDamageScenarios {
/// Calculate the best alternative with a set of contraints
///
/// Returns None if the scenario cant exist with the current conditions (too few actions for an attack to be launched)
fn from_action_constraints(
value: &InnerEquipementStats,
actions_allowed: i8,
attacks_allowed: i8,
dices_allowed: Dices,
precision: Precision,
) -> Option<Self> {
Self::from_action_constraints_recursive(
value,
actions_allowed,
attacks_allowed,
dices_allowed,
precision,
0,
0,
)
}
}
impl Serialize for DamageMatrix {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
// TODO: Not sure of the right way to do this
// serializer.serialize_str(&format!("[{:?}]", self.damage_matrix))
serializer.serialize_str(&format!(
"{:?}",
self.damage_matrix.iter().sum::<f64>() / self.damage_matrix.len() as f64
))
}
}
impl Display for DamageMatrix {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut table = Table::new();
table.apply_modifier(UTF8_ROUND_CORNERS);
let mut headers = vec![String::from("D\\P")];
headers.append(
&mut FixedPrecision::iter()
.map(|e| format!("{:.3}", e))
.collect::<Vec<String>>(),
);
table.set_header(headers);
table.add_rows(FixedDiceNumber::iter().map(|dices| {
vec![format!("{:.3}", dices)].into_iter().chain(
FixedPrecision::iter()
.map(move |precision| format!("{:5.2}", self.get_damage(precision, dices))),
)
}));
write!(f, "{}", table)
}
}
impl DamageMatrix {
/// Calculate the DamageMatrix for a given InnerEquipementStats
fn calculate_for(value: &InnerEquipementStats) -> Self {
DamageMatrix {
damage_matrix: (FixedDiceNumber::iter()
.flat_map(|dices| {
FixedPrecision::iter()
.map(move |prec| {
binomial_dice_distribution(value, prec.value(), dices.value())
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>()),
/// Recursive part of the from_action_constraints call
///
/// This algorithm takes a recursive approact to avoid too much forward complexity
fn from_action_constraints_recursive(
value: &InnerEquipementStats,
actions_allowed: i8,
attacks_allowed: i8,
dices_allowed: Dices,
precision: Precision,
reload_remaining: i8,
depth: u8,
) -> Option<Self> {
// If we can't attack return early
if value.action_cost > actions_allowed || attacks_allowed == 0 || reload_remaining != 0 {
return None;
}
let atkreload_cost = value.reload_cost.unwrap_or_default() + value.action_cost;
// We create our first contender, One attack only
let one_attack = Self {
// No matter what we try to reload, even if we overcap the attack was still valid
actions_used: (atkreload_cost).clamp(0, actions_allowed),
attacks_used: 1,
damage_done: binomial_dice_distribution(value, precision, dices_allowed),
// If the reload+attack exceed the actions, we must bookkeep it
// as a reminder that we have leftover actions to spend next turn
reload_remaining: (atkreload_cost - actions_allowed).clamp(0, actions_allowed),
depth,
};
println!(
"[{depth}] > One attack ({}): {one_attack:?}",
Dices(*dices_allowed)
);
// We can only try two attacks if two attack would be valid aka:
// - We can spend: 2 attacks and (at least) 1 reload (as actions)
// - : 2 attacks (as attacks)
if atkreload_cost + value.action_cost < actions_allowed && attacks_allowed > 1 {
// Cumbersome because of rounding errors
if let (Some(a), Some(b)) = (
(Self::from_action_constraints_recursive(
value,
actions_allowed - atkreload_cost,
attacks_allowed - 1,
Dices(dices_allowed.div_floor(2)),
precision,
reload_remaining,
depth + 1,
)),
(Self::from_action_constraints_recursive(
value,
actions_allowed - atkreload_cost,
attacks_allowed - 1,
Dices(dices_allowed.div_ceil(2)),
precision,
reload_remaining,
depth + 1,
)),
) {
let sum_sub_attacks = a + b;
println!(
"[{depth}] > Two attacks ({} & {}) : {sum_sub_attacks:?}",
Dices(dices_allowed.div_floor(2)),
Dices(dices_allowed.div_ceil(2))
);
// The alternative was better
if one_attack.damage_done < sum_sub_attacks.damage_done {
return Some(sum_sub_attacks);
}
}
}
// The alternative didn't exist or was worse
Some(one_attack)
}
}
// TODO: Consider implementing something else instead ?
impl InnerEquipementStats {
/// Calculate the average damage expected for a set of precisions and dices
fn average_damage(&self, precisions: &[Precision], list_dices: &[Dices]) -> f64 {
precisions
.iter()
.map(|precision| {
list_dices
.iter()
.map(|dices| binomial_dice_distribution(self, *precision, *dices))
.sum::<f64>()
})
.sum::<f64>()
/ (precisions.len() as f64 * list_dices.len() as f64)
}
}
@ -380,6 +496,7 @@ pub enum FixedDiceNumber {
Few,
}
// TODO[9] These implementations date back to the matrix code, rewriting them would be for the best
impl FixedPrecision {
#[inline]
/// Associate a value to the different values
@ -396,9 +513,9 @@ impl FixedDiceNumber {
/// Associate a value to the different values
fn value(&self) -> Dices {
match self {
FixedDiceNumber::Many => Dices(7),
FixedDiceNumber::Average => Dices(5),
FixedDiceNumber::Few => Dices(3),
FixedDiceNumber::Many => Dices(8),
FixedDiceNumber::Average => Dices(6),
FixedDiceNumber::Few => Dices(4),
}
}
}
@ -406,18 +523,10 @@ impl FixedDiceNumber {
#[cfg(test)]
mod test {
use crate::weaponry_structs::{
equipement_advanced_repr::{DamageMatrix, FixedDiceNumber, FixedPrecision},
equipement_advanced_repr::{FixedDiceNumber, FixedPrecision},
equipement_structs::InnerEquipementStats,
};
#[test]
fn test_binomial() {
let damage = new_inner_eq();
let mat: DamageMatrix = DamageMatrix::calculate_for(&damage);
println!("{:#?}", damage);
println!("{:#?}", mat);
}
fn new_inner_eq() -> InnerEquipementStats {
InnerEquipementStats {
damage: 10,
@ -430,13 +539,23 @@ mod test {
}
#[test]
fn test_creation() {
let mat = DamageMatrix::calculate_for(&new_inner_eq());
println!("{}", mat);
println!(
"(High,Many): {}, (Low,Few): {}",
mat.get_damage(FixedPrecision::High, FixedDiceNumber::Many),
mat.get_damage(FixedPrecision::Low, FixedDiceNumber::Few)
fn basic_binomial() {
let eq = new_inner_eq();
assert!(
(eq.average_damage(
&[FixedPrecision::High.value()],
&[FixedDiceNumber::Many.value()]
) - 13.99995162)
.abs()
< 1E-2
);
assert!(
(eq.average_damage(
&[FixedPrecision::Low.value()],
&[FixedDiceNumber::Few.value()]
) - 10.1119999)
.abs()
< 1E-2
);
}
}