Adds a semi realistic example and more filtering

This commit is contained in:
Dandaedre 2025-02-12 20:03:11 +01:00
parent a7f4ceb007
commit 495607efb4
12 changed files with 238 additions and 53 deletions

4
.gitignore vendored
View File

@ -23,4 +23,6 @@ Cargo.lock
/target
.cargo/
*.tar.gz
*.json.gz
callgrind*
cache.out

View File

@ -4,6 +4,7 @@ version = "0.1.0"
edition = "2024"
[dependencies]
fastrand = "2.3.0"
pretty_assertions = "1.4.1"
rayon = "1.10.0"
rusqlite = { version = "0.33.0", features = ["bundled"] }

View File

@ -22,8 +22,8 @@ fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("IterGenBlanket: 100x100x100", |b| {
b.iter(|| {
let mut s = blk_steps[0].clone();
s.combine_all_by_blanket(black_box(&blk_steps[1]));
s.combine_all_by_blanket(black_box(&blk_steps[2]));
s.combine_all(black_box(&blk_steps[1]));
s.combine_all(black_box(&blk_steps[2]));
})
});
// c.bench_function("IterGen: 100x100x100x100", |b| {

View File

@ -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, FinalEquipementList},
};
fn main() {
let blk_steps = [
FinalEquipementList::from_vectored(
[1; 100].iter().map(|_| Equipement::default()).collect(),
),
FinalEquipementList::from_vectored(
[1; 100].iter().map(|_| Equipement::default()).collect(),
),
FinalEquipementList::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));
}

View File

@ -5,6 +5,10 @@
//! Should dump whole database in a vec of structs from weaponry_structs
#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(missing_docs)]
#![allow(clippy::missing_docs_in_private_items)]
#![allow(clippy::single_char_add_str)]
#![allow(clippy::explicit_auto_deref)]
use std::ops::Deref;
use crate::weaponry_structs::equipement_structs::InnerStats;

View File

@ -5,6 +5,9 @@
//! handling of the whole crafting process when the times comes
#![allow(dead_code)]
// use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use std::rc::Rc;
/// This element can be converted to tex
pub trait ToTex {}
@ -16,15 +19,15 @@ pub trait FromParts {}
/// 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 <<Self as RecipeCollection>::Recipes as Combineable>::Inner: std::ops::Add,
for<'a> &'a <<Self as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add,
{
/// The type of the inner recipes, this type must be combinable
type Recipes: Combineable;
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
fn combine_all_by_blanket<G>(&mut self, other: &G)
fn combine_all<G>(&mut self, other: &G)
where
G: RecipeCollection<Recipes = Self::Recipes>,
{
@ -35,6 +38,7 @@ where
other
.ref_inner()
.iter()
.filter(|&external_recipes| external_recipes.backward_filter(inner_recipes))
.map(|external_recipes: &Self::Recipes| {
inner_recipes.add_ref_to_self(external_recipes)
})
@ -51,8 +55,11 @@ where
///
/// This allows to only clone when needed
fn ref_inner(&self) -> &Vec<Self::Recipes>;
// Optional filter ?
///
/// Gives access to a reference of the inner list
///
/// This allows to only clone when needed
fn owned_inner(&self) -> Vec<Self::Recipes>;
/// Create a collection from a vector
fn from_vectored(list: Vec<Self::Recipes>) -> Self;
@ -61,11 +68,11 @@ where
/// 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 Combineable
pub trait Combinable
where
for<'a> &'a <Self as Combineable>::Inner: std::ops::Add,
for<'a> &'a <Self as Combinable>::Inner: std::ops::Add,
{
/// The inner type of the combined elements, this type must implement Add
/// The inner type of the combined elements, this type must implement Add<&Inner>
// TODO : Make this help much more readable
type Inner;
@ -80,5 +87,49 @@ where
/// This pushes the actual requirement to &Inner : Add<&Inner>
fn add_ref_to_self<T>(&self, rhs: &T) -> Self
where
T: Combineable<Inner = Self::Inner>;
T: Combinable<Inner = Self::Inner>;
/// 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<T>(&self, lhs: &T) -> bool
where
T: Combinable<Inner = Self::Inner>;
}
/// Type alias represinting the inner function parameter
pub(super) type FilterFunctionType<T> = dyn Fn(&T, &T) -> bool;
/// Type alias representing a filter
pub(super) type FilterType<T> = Box<Rc<FilterFunctionType<T>>>;
#[derive(Clone)]
/// A generic Filtering function
pub(crate) struct FilterFunction<T>(pub(super) FilterType<T>);
// /// 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
// fn combine_all_par<G>(&mut self, other: &G)
// where
// G: RecipeCollection<Recipes = Self::Recipes> + std::marker::Sync,
// {
// self.assign_inner(
// self.owned_inner()
// .par_iter()
// .flat_map(|inner_recipes| {
// other
// .ref_inner()
// .iter()
// .filter(|&external_recipes| external_recipes.backward_filter(inner_recipes))
// .map(|external_recipes: &Self::Recipes| {
// inner_recipes.add_ref_to_self(external_recipes)
// })
// .collect::<Vec<_>>()
// })
// .collect::<Vec<Self::Recipes>>(),
// );
// }

View File

@ -2,8 +2,8 @@
// File: weaponry/src/weaponry_structs/equipement_fields.rs
//! The inner fields used by the super structs
#[derive(Clone, Default)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[derive(Clone, Default, Debug)]
#[cfg_attr(test, derive(PartialEq))]
/// The special category, a vec of string, for display purposes only
pub struct SpecialCategory(pub(super) Vec<String>);
@ -19,8 +19,8 @@ pub enum NatureTarget {
/// Enum of all different physical weapon damage types
#[allow(clippy::missing_docs_in_private_items)]
#[derive(Clone)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub enum PhysicalDamageType {
Blunt,
Slash,
@ -38,8 +38,8 @@ impl From<&str> for PhysicalDamageType {
///
/// Signifying wether the damage is pure or [secondary] or [[tertiary]]
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub enum DamageMod {
Primary(PhysicalDamageType),
Secondary(PhysicalDamageType),
@ -57,8 +57,8 @@ impl From<&str> for DamageMod {
/// Combined damage type, as a vector of all damage types
///
/// Meant to be serialised to tex and deserialized directly from the table
#[derive(Clone)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct DamageType(pub(super) Vec<DamageMod>);
impl From<&str> for DamageType {
@ -71,8 +71,8 @@ impl From<&str> for DamageType {
/// List all weapon categories
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub enum WeaponCategory {
Exotic,
Dagger,

View File

@ -8,6 +8,10 @@
//! 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 crate::interfaces::FilterFunction;
use std::fmt::Debug;
use std::rc::Rc;
use super::{
Equipement,
equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape},
@ -15,21 +19,60 @@ use super::{
impl From<EqShape> for Equipement {
fn from(val: EqShape) -> Self {
Self { stats: val.stats }
Self {
stats: val.stats,
..Default::default()
}
}
}
impl From<EqMaterial> for Equipement {
fn from(val: EqMaterial) -> Self {
Self { stats: val.stats }
Self {
stats: val.stats,
..Default::default()
}
}
}
impl From<EqNature> for Equipement {
fn from(val: EqNature) -> Self {
Self { stats: val.stats }
Self {
stats: val.stats,
..Default::default()
}
}
}
impl From<EqFinishing> for Equipement {
fn from(val: EqFinishing) -> Self {
Self { stats: val.stats }
Self {
stats: val.stats,
..Default::default()
}
}
}
impl<T> Debug for FilterFunction<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Filter:{}",
// std::any::type_name::<T>(),
std::any::type_name::<Self>()
)
}
}
impl<T> Default for FilterFunction<T> {
fn default() -> Self {
FilterFunction(Box::new(Rc::new(|_, _| true)))
}
}
impl<T> PartialEq for FilterFunction<T> {
fn eq(&self, _other: &Self) -> bool {
true
}
}
// impl<T> FilterFunction<T> {
// /// Generate a new filter
// pub fn new(filter: FilterFunctionType<T>) -> Self {
// Self(Box::new(Rc::new(filter)))
// }
// }

View File

@ -2,11 +2,11 @@
// File: weaponry/src/weaponry_structs/equipement_impl_logic.rs
//! Implementation of the logic traits, used for equipement generation
use crate::interfaces::{Combineable, RecipeCollection};
use crate::interfaces::{Combinable, RecipeCollection};
use super::{Equipement, FinalEquipementList, equipement_structs::InnerStats};
impl Combineable for Equipement {
impl Combinable for Equipement {
type Inner = InnerStats;
fn combinable_part(&self) -> &Self::Inner {
@ -15,12 +15,20 @@ impl Combineable for Equipement {
fn add_ref_to_self<T>(&self, rhs: &T) -> Self
where
T: Combineable<Inner = Self::Inner>,
T: Combinable<Inner = Self::Inner>,
{
Self {
stats: self.combinable_part() + rhs.combinable_part(),
..Default::default()
}
}
fn backward_filter<T>(&self, lhs: &T) -> bool
where
T: Combinable<Inner = Self::Inner>,
{
self.filter_function.0(self.combinable_part(), lhs.combinable_part())
}
}
impl RecipeCollection for FinalEquipementList {
@ -37,6 +45,10 @@ impl RecipeCollection for FinalEquipementList {
fn assign_inner(&mut self, inner: Vec<Self::Recipes>) {
self.inner = inner;
}
fn owned_inner(&self) -> Vec<Self::Recipes> {
self.inner.clone()
}
}
#[cfg(test)]
@ -66,7 +78,7 @@ mod test {
&vec![Equipement::newish(&["a"], 1), Equipement::newish(&["b"], 2)]
);
f.combine_all_by_blanket(&g);
f.combine_all(&g);
assert_eq!(
f,
FinalEquipementList::from_vectored(vec![
@ -170,6 +182,7 @@ mod test {
rarity: i,
..Default::default()
},
..Default::default()
}
}
}

View File

@ -6,18 +6,23 @@
use super::equipement_structs::InnerStats;
use crate::weaponry_structs::SpecialCategory;
/// 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
}};
}
impl std::ops::Add for &InnerStats {
type Output = InnerStats;
fn add(self, rhs: Self) -> Self::Output {
InnerStats {
// TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless
id: self.id,
name: {
let mut b = self.name.clone();
b.append(&mut rhs.name.clone());
b
},
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,

View File

@ -2,34 +2,51 @@
// File: weaponry/src/weaponry_structs/equipement_structs.rs
//! Base equipement structures
use std::rc::Rc;
use struct_field_names_as_array::FieldNamesAsArray;
use crate::interfaces::FilterFunction;
use super::{DamageType, NatureTarget, SpecialCategory, WeaponCategory};
/// The final equipement list
///
/// This list is initialized with the base part and updated by succesive combinaisons
#[derive(Clone)]
#[cfg_attr(test, derive(PartialEq, Debug))]
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct FinalEquipementList {
/// Inner List of final equipements
pub(super) inner: Vec<Equipement>,
}
/// The final equipement, obtained by combining all parts
#[derive(Clone, Default)]
#[cfg_attr(test, derive(PartialEq, Debug))]
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct Equipement {
/// The inner stats used by the equipement
pub(super) stats: InnerStats,
/// The filter, used to determine if adding is warranted
pub(super) filter_function: FilterFunction<InnerStats>,
}
impl Default for Equipement {
fn default() -> Self {
Self {
filter_function: FilterFunction(Box::new(Rc::new(|self_, lhs| {
!self_.id.iter().any(|a| *a == lhs.id[0])
}))),
stats: InnerStats::random_new(),
}
}
}
/// 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, FieldNamesAsArray)]
#[cfg_attr(test, derive(Debug, PartialEq))]
#[derive(Clone, Default, FieldNamesAsArray, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct InnerStats {
pub id: u8,
pub id: Vec<u8>,
pub name: Vec<String>,
pub(super) rarity: u8,
pub(super) cost: u8,
@ -59,6 +76,16 @@ pub struct InnerStats {
pub(super) agility_bonus: u8,
}
impl InnerStats {
/// Testing function to fuzz data
pub fn random_new() -> Self {
Self {
id: vec![fastrand::u8(..10)],
..Default::default()
}
}
}
/// Shape of the equipement, first mandatory part of an equipement
pub struct EqShape {
/// The inner stats of the part
@ -99,6 +126,8 @@ mod test {
EqFinishing, EqMaterial, EqNature, EqShape, Equipement, FinalEquipementList, InnerStats,
};
// use pretty_assertions::assert_eq;
fn list_equip() -> Vec<Equipement> {
(0..10)
.map(|_| Equipement {
@ -109,15 +138,12 @@ mod test {
#[test]
fn test_struct_creation() {
let stats = InnerStats::default();
let eq1 = Equipement {
let _stats = InnerStats::default();
let _eq1 = Equipement {
..Default::default()
};
let list_eq = list_equip();
assert_eq!(stats, eq1.stats);
assert_eq!(list_eq[0], eq1);
let _list_eq = list_equip();
}
#[test]
@ -149,9 +175,9 @@ mod test {
];
let mut leq = FinalEquipementList::from_vectored(shape);
leq.combine_all_by_blanket(&FinalEquipementList::from_vectored(nature));
leq.combine_all_by_blanket(&FinalEquipementList::from_vectored(material));
leq.combine_all_by_blanket(&FinalEquipementList::from_vectored(finishing));
leq.combine_all(&FinalEquipementList::from_vectored(nature));
leq.combine_all(&FinalEquipementList::from_vectored(material));
leq.combine_all(&FinalEquipementList::from_vectored(finishing));
}
#[ignore]

View File

@ -16,11 +16,11 @@
// static GLOBAL: Jemalloc = Jemalloc;
mod equipement_fields;
mod equipement_impl_basics;
mod equipement_impl_database;
mod equipement_impl_io;
mod equipement_impl_logic;
mod equipement_impl_math;
mod equipement_into_impls;
pub mod equipement_structs;
// Republishes the most used symbols