Clarifies the dependencies and cleanup the text #31

Closed
Dandaedre wants to merge 1 commits from weapons into project_weaponry
14 changed files with 270 additions and 70 deletions

4
.gitignore vendored
View File

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

View File

@ -1,3 +1,8 @@
# ravenous-tools
Set of tools to handle ravenous rulebook creation
Set of tools to handle ravenous rulebook creation
# Installation
Now depends on libsqlite3-dev and sqlite3
A bundled implementation should be added

View File

@ -4,9 +4,10 @@ version = "0.1.0"
edition = "2024"
[dependencies]
fastrand = "2.3.0"
pretty_assertions = "1.4.1"
rayon = "1.10.0"
rusqlite = "0.33.0"
rusqlite = { version = "0.33.0", features = ["bundled"] }
struct-field-names-as-array = "0.3.0"
[dev-dependencies]

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

@ -4,12 +4,9 @@
//! 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)]
#![allow(unused_imports)]
use std::ops::Deref;
use crate::weaponry_structs::equipement_structs::InnerStats;
use rusqlite::{self, Connection, Result, params};
use struct_field_names_as_array::FieldNamesAsArray;
use rusqlite::{self, Connection, Result};
/// Generate a SELECT query with fields generated from a struct. Returns a String
fn generate_query(fields: &[&str], table_name: &str) -> String {
@ -47,9 +44,8 @@ pub fn get_data() -> Vec<InnerStats> {
#[cfg(test)]
mod test {
use std::any::type_name;
use pretty_assertions::assert_eq;
use struct_field_names_as_array::FieldNamesAsArray;
use super::*;
#[derive(FieldNamesAsArray)]
@ -66,16 +62,19 @@ mod test {
)
}
#[ignore]
#[test]
fn test_initialize_database_conn() {
todo!()
}
#[ignore]
#[test]
fn test_generate_table_from_struct() {
todo!()
}
#[ignore]
#[test]
fn test_get_data() {
todo!()

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)
})
@ -52,8 +56,6 @@ where
/// This allows to only clone when needed
fn ref_inner(&self) -> &Vec<Self::Recipes>;
// Optional filter ?
/// Create a collection from a vector
fn from_vectored(list: Vec<Self::Recipes>) -> Self;
}
@ -61,12 +63,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
// TODO : Make this help much more readable
/// 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
@ -80,5 +81,56 @@ 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
// #![feature(trait_alias)]
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>);
// impl<T> FilterFunction<T> {
// fn new_from_closure(m: &FilterFunctionType<T>) -> Self {
// FilterFunction(Box::new(Rc::new(m)))
// }
// }
// /// 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,12 +2,13 @@
// 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>);
/// The kind of target this nature can apply to
#[derive(Clone)]
pub enum NatureTarget {
/// Can apply to a weapon and is unique
WeaponUnique,
@ -19,8 +20,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 +39,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 +58,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 +72,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, PartialEq)]
// #[cfg_attr(test, derive(PartialEq))]
pub enum WeaponCategory {
Exotic,
Dagger,

View File

@ -0,0 +1,24 @@
// Workspace: weaponry
// File: weaponry/src/weaponry_structs/equipement_impl_advanced.rs
//! Advanced implementation, reserved for traits and impls that are implemented only once on the main equipement and it's helper
//!
//! These impls are here to either prettify output, or allow for smoother implementation of other traits and inner workings
use crate::interfaces::FilterFunction;
use std::{fmt::Debug, rc::Rc};
impl<T> Debug for FilterFunction<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Filter:{}", 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
}
}

View File

@ -1,5 +1,5 @@
// Workspace: weaponry
// File: weaponry/src/weaponry_structs/equipement_into_impls.rs
// 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<Combinable> instead
@ -8,6 +8,8 @@
//! 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 super::{
Equipement,
equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape},
@ -15,21 +17,45 @@ 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,
// filter_function: FilterFunction(default_filter_for_equipement()),
filter_function: FilterFunction::new(&|sel, lhs| {
match (&sel.target, &lhs.category) {
(Some(a), Some(b)) => a == b,
(None, None) => true,
_ => false,
}
// if let Some(targ) = &sel.target {
// &lhs.category
// }
// & default_filter()(sel, lhs)
}),
}
}
}
impl From<EqFinishing> for Equipement {
fn from(val: EqFinishing) -> Self {
Self { stats: val.stats }
Self {
stats: val.stats,
..Default::default()
}
}
}

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 {
@ -66,7 +74,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 +178,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,
@ -49,6 +54,7 @@ impl std::ops::Add for &InnerStats {
speed: self.speed + rhs.speed,
stealth: self.stealth + rhs.stealth,
category: self.category.clone().or(rhs.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),

View File

@ -2,34 +2,62 @@
// File: weaponry/src/weaponry_structs/equipement_structs.rs
//! Base equipement structures
use std::rc::Rc;
use struct_field_names_as_array::FieldNamesAsArray;
use super::{DamageType, NatureTarget, SpecialCategory, WeaponCategory};
use crate::interfaces::{FilterFunction, FilterFunctionType};
use super::{DamageType, 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::new(default_filter()),
stats: InnerStats::random_new(),
}
}
}
/// The default filter to use, usefull to implement a new filter function that also uses the default filter
pub(crate) fn default_filter() -> &'static impl Fn(&InnerStats, &InnerStats) -> bool {
&|self_, lhs| !self_.id.iter().any(|a| *a == lhs.id[0])
}
impl<T> FilterFunction<T> {
/// Generate a new filter
// TODO: This static lifetime is basically telling us that an owned value is needed
pub fn new(filter: &'static FilterFunctionType<T>) -> 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, 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,
@ -52,6 +80,7 @@ pub struct InnerStats {
pub(super) speed: u8,
pub(super) stealth: u8,
pub(super) category: Option<WeaponCategory>,
pub(super) target: Option<WeaponCategory>,
pub(super) special: SpecialCategory,
pub(super) action_cost: u8,
pub(super) reload_cost: Option<u8>,
@ -59,6 +88,17 @@ pub struct InnerStats {
pub(super) agility_bonus: u8,
}
// TODO: Make this a test requirement or hide it behind a profile
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
@ -77,10 +117,6 @@ pub struct EqMaterial {
pub struct EqNature {
/// The inner stats of the part
pub(super) stats: InnerStats,
// TODO: Be sure to take this into account
#[allow(dead_code)]
/// Which kind of target this nature applies to
pub(super) target: NatureTarget,
}
/// Finishing touches, since all of them have a cost, they are treated in a special fashion
@ -93,12 +129,14 @@ pub struct EqFinishing {
mod test {
// use super::*;
use crate::{interfaces::RecipeCollection, weaponry_structs::NatureTarget};
use crate::interfaces::RecipeCollection;
use super::{
EqFinishing, EqMaterial, EqNature, EqShape, Equipement, FinalEquipementList, InnerStats,
};
// use pretty_assertions::assert_eq;
fn list_equip() -> Vec<Equipement> {
(0..10)
.map(|_| Equipement {
@ -109,15 +147,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]
@ -131,7 +166,6 @@ mod test {
let nature = vec![
EqNature {
stats: InnerStats::default(),
target: NatureTarget::Armor,
}
.into(),
];
@ -149,9 +183,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,12 @@
// static GLOBAL: Jemalloc = Jemalloc;
mod equipement_fields;
mod equipement_impl_advanced;
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