Not fearless refactoring of Categories

This commit is contained in:
Dandaedre 2025-02-25 18:27:00 +01:00
parent 9cbdc25df4
commit e99d723e5d
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
9 changed files with 171 additions and 156 deletions

Binary file not shown.

View File

@ -38,9 +38,9 @@ fn main() {
.unwrap()
// .inner_filter(|e| (e.advanced.max_damage_per_attack > 0.))
.inner_filter(|e| {
e.inner.macro_category.as_ref().is_some_and(|v| {
!matches!(v, weaponry::weaponry_structs::WeaponMacroCategory::Shields)
&& !matches!(v, weaponry::weaponry_structs::WeaponMacroCategory::Armor)
e.inner.category_base.as_ref().is_some_and(|v| {
!matches!(v, weaponry::weaponry_structs::WeaponBaseShape::Shields)
&& !matches!(v, weaponry::weaponry_structs::WeaponBaseShape::Armors)
})
});

View File

@ -29,8 +29,8 @@ pub enum NatureTarget {
/// Enum of all different physical weapon damage types
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
// #[cfg_attr(test, derive(PartialEq))]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
pub enum PhysicalDamageType {
Blunt,
Slash,
@ -77,53 +77,27 @@ impl Add for DamageType {
}
}
// TODO: Convert into this category at the end, depending on all important factors
/// List all the final weapon categories, this enum should be infered from <Size> and <BaseShape> if they were defined
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone, Debug, PartialEq, Display, Deserialize, Serialize, strum::EnumString)]
// #[cfg_attr(test, derive(PartialEq))]
pub enum WeaponCategory {
Exotic,
// HeavyExotic ?
Dagger, // Light sword ? Kill it tbh
Claws,
Blade,
Haroth,
Axe,
Kahml,
Hammer,
Rhodarak,
Staff,
Lance,
Landscapper,
Bow,
Crossbow,
Cannon,
// Armor,
// Shield,
}
// TODO[!]: This is only needed as long as we dont have a special category for the target
// TODO[!]: This part should be handled by a category filter instead, filtering Shape on Shape
impl PartialEq for WeaponMacroCategory {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(&Self::None, _) => false,
(_, Self::None) => false,
(&Self::Armor, &Self::Armor) => true,
(&Self::Armor, _) => false,
(_, &Self::Armor) => false,
(&Self::Weapons, _) => true,
(_, &Self::Weapons) => true,
(&Self::Staves, &Self::Staves) => true,
(&Self::Blunt, &Self::Blunt) => true,
(&Self::Slash, &Self::Slash) => true,
(&Self::Ranged, &Self::Ranged) => true,
(&Self::Exotic, &Self::Exotic) => true,
_ => false,
}
}
}
// // TODO[!]: This is only needed as long as we dont have a special category for the target
// // TODO[!]: This part should be handled by a category filter instead, filtering Shape on Shape
// impl PartialEq for EquipementSerializedCategory {
// fn eq(&self, other: &Self) -> bool {
// match (self, other) {
// (&Self::None, _) => false,
// (_, Self::None) => false,
// (&Self::Armors, &Self::Armors) => true,
// (&Self::Armors, _) => false,
// (_, &Self::Armors) => false,
// (&Self::Weapons, _) => true,
// (_, &Self::Weapons) => true,
// (&Self::Staves, &Self::Staves) => true,
// (&Self::Blunt, &Self::Blunt) => true,
// (&Self::Slash, &Self::Slash) => true,
// (&Self::Ranged, &Self::Ranged) => true,
// (&Self::Exotic, &Self::Exotic) => true,
// _ => false,
// }
// }
// }
#[cfg(test)]
mod test {
@ -217,20 +191,27 @@ pub enum ThrowSpecialties {
// TODO[!]: This enum should only include Weapons, Shields, Armors and no <BaseShape>
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)]
pub enum WeaponMacroCategory {
pub enum EquipementSerializedCategory {
Staves,
Blunt,
Slash,
Ranged,
Armor,
Shields,
Exotic,
/// A custom weapon category, only used by the target
// TODO: Get rid of this category and make a custom category for target
Weapons,
/// A custom none category, used to forbid a part to be cast upon of from
/// 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
// TODO: Check the soundness of this implementation
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
@ -238,49 +219,73 @@ pub enum WeaponMacroCategory {
/// 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,
Armor,
Armors,
Shields,
Exotic,
// TODO[!]: Check the soundness of this
// TODO[!]: Check the soundness of this, as it is not used currently
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 EquipementSection {
Weapon,
Armor,
Shield,
pub enum EquipementTargets {
Weapons,
Armors,
Shields,
Ranged,
}
// TODO[!]: Add this as a target and nature instead of the old Type
// : Remember it's the applied into that specify wether they can be applied not the other way around
/// Specifies the exact nature of the target this element can be applied to
#[allow(dead_code, clippy::missing_docs_in_private_items, missing_docs)]
pub enum EquipementFilter {
/// This element can only be applied to a specific category
Target(EquipementSection),
/// This element exists only for recipes or for export to tex, it cannot be auto-applied
NoTarget,
/// This element can be applied to any target
AnyTarget,
// /// This element can only be applied to a specific base shape
// TargetShape(WeaponBaseShape)
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, Debug, Display, Deserialize, Serialize, strum::EnumString)]
#[cfg_attr(test, derive(PartialEq))]
pub enum WeaponBaseSize {
Light,
Medium,
Heavy,
SuperHeavy,
}
// // TODO[!]: Add this as a target and nature instead of the old Type
// // : Remember it's the applied into that specify wether they can be applied not the other way around
// /// Specifies the exact nature of the target this element can be applied to
// #[allow(dead_code, clippy::missing_docs_in_private_items, missing_docs)]
// pub enum EquipementFilter {
// /// This element can only be applied to a specific category
// Target(EquipementSection),
// /// This element exists only for recipes or for export to tex, it cannot be auto-applied
// NoTarget,
// /// This element can be applied to any target
// AnyTarget,
// // /// This element can only be applied to a specific base shape
// // TargetShape(WeaponBaseShape)
// }

View File

@ -76,12 +76,15 @@ impl Display for InnerEquipementStats {
self.name.join(" & ")
)]);
table.add_row(vec![format!(
"Rarity: {}, Cost {}, Difficulty: {}, Tier: {} [{}]",
"Rarity: {}, Cost {}, Difficulty: {}, Tier: {} [{}+{}]",
self.rarity,
self.cost,
self.difficulty,
self.tier,
self.macro_category
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())
)]);

View File

@ -12,6 +12,8 @@ use crate::interfaces::{FixedRecipe, RecipeDatabase};
use rusqlite::Connection;
use serde::de::DeserializeOwned;
use super::EquipementSerializedCategory;
use super::equipement_fields::{WeaponBaseShape, WeaponBaseSize};
use super::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats};
/// Struct for database connection.
@ -92,6 +94,8 @@ impl TryFrom<DatabaseEquipementStats> for InnerEquipementStats {
type Error = FatalEquipementError;
fn try_from(value: DatabaseEquipementStats) -> Result<Self, Self::Error> {
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],
@ -116,13 +120,42 @@ impl TryFrom<DatabaseEquipementStats> for InnerEquipementStats {
parry: value.parry,
speed: value.speed,
stealth: value.stealth,
macro_category: from_serde!(&value.category)?,
target: from_serde!(&value.target)?,
// 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<WeaponBaseShape>, Option<WeaponBaseSize>);
/// Infer all subcategories from a deserialized DatabaseCategory
fn get_sub_categories_from_serde(category: &str) -> Result<SubCategories, FatalEquipementError> {
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::Weapons => todo!(),
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)
})
}

View File

@ -53,7 +53,7 @@ mod test {
interfaces::RecipeCollection,
weaponry_structs::{
DamageMod, DamageType, Equipement, InitialEquipementList, SpecialField,
equipement_fields::{PhysicalDamageType, WeaponMacroCategory},
equipement_fields::{PhysicalDamageType, WeaponBaseShape},
equipement_structs::InnerEquipementStats,
},
};
@ -94,7 +94,7 @@ mod test {
integrity: 2,
range: 3,
agility_bonus: 4.,
macro_category: Some(WeaponMacroCategory::Staves),
category_base: Some(WeaponBaseShape::Staves),
special: SpecialField(vec!["zero".into()]),
damage_type: Some(DamageType(vec![DamageMod::Secondary(
PhysicalDamageType::Slash,
@ -119,7 +119,7 @@ mod test {
agility_bonus: 9.,
damage: 10,
range: 3,
macro_category: Some(WeaponMacroCategory::Staves),
category_base: Some(WeaponBaseShape::Staves),
special: SpecialField(vec!["zero".into(), "one".into(), "two".into()]),
damage_type: Some(DamageType(vec![
DamageMod::Secondary(PhysicalDamageType::Slash,),

View File

@ -18,15 +18,26 @@ macro_rules! add_to_vec {
/// Adds either of the vectors or merge them
macro_rules! add_two_options {
($self: expr, $rhs: expr) => {{
match ($self.clone(), $rhs.clone()) {
match ($self.as_ref(), $rhs.as_ref()) {
(None, None) => None,
(None, Some(a)) => Some(a),
(Some(a), None) => Some(a),
(Some(a), Some(b)) => Some(a + b),
(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;
@ -55,13 +66,16 @@ impl std::ops::Add for &InnerEquipementStats {
parry: self.parry + rhs.parry,
speed: self.speed + rhs.speed,
stealth: self.stealth + rhs.stealth,
macro_category: self.macro_category.clone().or(rhs.macro_category.clone()), // Can be further optimized
target: self.target.clone().or(rhs.target.clone()), // Can be further optimized
// macro_category: self.macro_category.clone().or(rhs.macro_category.clone()), // Can be further optimized
// target: self.target.clone().or(rhs.target.clone()), // Can be further optimized
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),
}
}
}
@ -76,46 +90,3 @@ impl std::ops::Add for SpecialField {
c
}
}
// impl std::ops::AddAssign for SpecialCategory {
// fn add_assign(&mut self, rhs: Self) {
// todo!()
// }
// }
// impl std::ops::Add for OptionnalReloadType {
// type Output = OptionnalReloadType;
// fn add(self, rhs: Self) -> Self::Output {
// todo!()
// }
// }
// impl std::ops::AddAssign for OptionnalReloadType {
// fn add_assign(&mut self, rhs: Self) {
// todo!()
// }
// }
// impl std::ops::Add for OptionnalWeaponCategory {
// type Output = OptionnalWeaponCategory;
// fn add(self, rhs: Self) -> Self::Output {
// todo!()
// }
// }
// impl std::ops::AddAssign for OptionnalWeaponCategory {
// fn add_assign(&mut self, rhs: Self) {
// todo!()
// }
// }
// impl std::ops::Add for OptionnalDamageType {
// type Output = OptionnalDamageType;
// fn add(self, rhs: Self) -> Self::Output {
// todo!()
// }
// }
// impl std::ops::AddAssign for OptionnalDamageType {
// fn add_assign(&mut self, rhs: Self) {
// todo!()
// }
// }

View File

@ -8,7 +8,12 @@ use crate::interfaces::{FilterFunction, FilterFunctionType};
use more_fields::FieldsAsSlice;
use serde::{Deserialize, Serialize};
use super::{DamageType, SpecialField, WeaponCategory, equipement_fields::WeaponMacroCategory};
use super::{
DamageType, SpecialField,
equipement_fields::{
EquipementSerializedCategory, EquipementTargets, WeaponBaseShape, WeaponBaseSize,
},
};
/// The final equipement list
///
@ -46,29 +51,18 @@ pub(crate) fn filter_id_unique()
}
/// 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| {
// println!(
// "Trying to match {:?} with {:?}. {:?} {:?}",
// sel.name, lhs.name, sel.target, lhs.macro_category
// );
lhs.id.iter().all(|a| *a != sel.id[0])
& match (&sel.target, &lhs.macro_category) {
& 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)) => {
// println!("{} {}", a, b);
a == b
}
// There is no target and the part about to be added is generic
(Some(a), Some(b)) => a.can_apply_onto(b),
// TODO: Unsound to have a generic nature, this should be caught at serialisation
// TODO: Testing a generic anyway
// There is no target and the part about to be added is generic
(None, _) => true, // panic!("The EqNature about to be added cannot be generic"),
// There is a specific target but the part about to be added is generic
// TODO: Impossible
(Some(_), None) => panic!("The part about to be added unto cannot be generic"),
// // There is restriction on the target and the recipient
// (None, Some(_)) => true,
}
}
}
@ -106,9 +100,17 @@ pub struct InnerEquipementStats {
pub(super) parry: i8,
pub(super) speed: i8,
pub(super) stealth: i8,
/// The initial macro category, in turn combined with other stats it will describe a final category
pub macro_category: Option<WeaponMacroCategory>, // TODO : This initial macro category fill as a final stat feed the final category
pub(super) target: Option<WeaponMacroCategory>, // TODO: This might be incorrect, to check
/// 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<WeaponBaseShape>,
/// The category size as [WeaponBaseSize]
///
/// Categories are : (Light, Medium, Heavy and SuperHeavy)
pub category_size: Option<WeaponBaseSize>,
/// The section of an equipement (Weapon, Shield, Armor)
/// The Section the target applies to
pub target_category: Option<EquipementTargets>,
pub(super) special: SpecialField,
pub(super) action_cost: i8,
pub(super) reload_cost: Option<i8>, // Shouldn't it be Option ?
@ -184,8 +186,8 @@ impl Default for DatabaseEquipementStats {
meta_category: "EqShape".to_string(),
name: String::new(),
damage_type: serde_json::to_string(&None::<DamageType>).unwrap(),
category: serde_json::to_string(&None::<WeaponMacroCategory>).unwrap(),
target: serde_json::to_string(&None::<WeaponCategory>).unwrap(),
category: serde_json::to_string(&None::<EquipementSerializedCategory>).unwrap(),
target: serde_json::to_string(&None::<EquipementTargets>).unwrap(),
special: serde_json::to_string(&SpecialField::default()).unwrap(),
reload_cost: serde_json::to_string(&None::<u8>).unwrap(),
rarity: 0,

View File

@ -39,7 +39,8 @@ pub use crate::weaponry_structs::equipement_advanced_repr::RefinedEquipementList
pub use equipement_advanced_repr::RefinedEquipement;
pub use equipement_fields::PhysicalDamageType;
pub use equipement_fields::{
DamageMod, DamageType, NatureTarget, SpecialField, WeaponCategory, WeaponMacroCategory,
DamageMod, DamageType, EquipementSerializedCategory, NatureTarget, SpecialField,
WeaponBaseShape,
};
// Likely ? Final Re-Exports
pub use equipement_scenario::CrossRecipeScenario;