From 37d22d067415973a9baf47e864d9917cc3f00e0a Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 19 Feb 2023 19:45:31 +0100 Subject: [PATCH 1/5] Solved with static, so...not solved --- src/libs.rs | 219 +++++++++++++++++++++++++++++++++++++++ src/main.rs | 277 +------------------------------------------------- src/solver.rs | 15 ++- 3 files changed, 231 insertions(+), 280 deletions(-) create mode 100644 src/libs.rs diff --git a/src/libs.rs b/src/libs.rs new file mode 100644 index 0000000..67c20cf --- /dev/null +++ b/src/libs.rs @@ -0,0 +1,219 @@ +use std::sync::{Arc,Mutex}; +use crate::solver::{generate_routes_phase1, generate_routes_phase2}; +use std::time::{Instant}; +use threadpool::ThreadPool; +use crate::Recipe; +use crate::Craft; +use crate::Stats; +use clap::Parser; +// use crate::Stats; +// use crate::Recipe; +// use crate::Craft; + +#[derive(Debug, Clone)] +pub struct Config<'a> { + pub craft: Craft<'a>, + // pub recipe: solver::Recipe, + pub depth: usize, +} + +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +pub struct Args { + /// Name of the receipe + #[arg(short, long, default_value_t = String::from("default_recipe"))] + pub recipe_name: String, + + /// Name of the character + #[arg(short, long, default_value_t = String::from("default_character"))] + pub character_name: String, + + /// The ml file name + #[arg(short, long, default_value_t = String::from("craft.toml"))] + pub file_name: String, + + /// The verbose flag + #[arg(short, long, action = clap::ArgAction::Count)] + pub verbose: u8, + + /// The depth of the first pass + #[arg(short, long, default_value_t = 8)] + pub depth: u32, + + /// Thread counts, default is 4 (can you even run ff with less ?) + #[arg(short, long, default_value_t = 4)] + pub threads: usize, +} + +/// Solve the craft with given arguments +pub fn solve_craft<'a>(craft: Craft<'static>, args: &'a Args){ +// Start timer + let now = Instant::now(); + + // Start a threadpool + let pool = ThreadPool::new(args.threads); + + if args.verbose>0{ + println!("Solving...\n"); + println!("[P1] Starting phase 1..."); + } + let phase1_routes = generate_routes_phase1(craft); + + if args.verbose>0{ + println!("[P1] Found {} routes, testing them all...",phase1_routes.len()); + if args.verbose>1{ + for r in &phase1_routes{ + println!("[P1] {:?} p:{}% q:{}% c:{} d:{}", + r.actions, + r.progression * 100 / r.recipe.progress, + r.quality * 100 / r.recipe.quality, + r.cp, + r.durability, + ); + // println!("[P1] {}",r); + }; + } + } + // Core algorithm, fill all found routes with the best route (doesn't branch, just replace) + let arc_phase2_routes = Arc::new(Mutex::new(Vec::::new())); + + for route in phase1_routes { + let _phase2_routes = arc_phase2_routes.clone(); + + pool.execute(move || { + if let Some(_route) = generate_routes_phase2(route){ + let mut shared = _phase2_routes.lock().unwrap(); + shared.push(_route); + }; + }); + } + + pool.join(); + let phase2_routes = arc_phase2_routes.lock().unwrap(); + + // Print the results if verbose + if args.verbose>0{ + println!("[P2] Found {} solutions, sorting",phase2_routes.len()); + + if args.verbose>1{ + for r in phase2_routes.iter(){ + println!("[P2] {:?} p:{}% q:{}% d:{}", + r.actions, + r.progression * 100 / r.recipe.progress, + r.quality * 100 / r.recipe.quality, + r.durability); + }; + } + } + + + let top_route = match phase2_routes.iter().max_by_key(|route| route.quality) { + Some(top) => top, + None => { + println!("[P2] No route could finish the craft.\n[P2] Runtime {}ms. Now exiting...",now.elapsed().as_millis()); + return + }, + }; + + let mut content = (&top_route.actions) + .iter() + .map(|action| { + format!("\"{}\"", action.short_name.clone()) + }) + .collect::>(); + let arg = (top_route.recipe.progress as f32 - top_route.progression as f32) / top_route.get_base_progression() as f32; + if 0.0 < arg && arg < 1.2 { content.push("\"basicSynth2\"".to_string()); } + if 1.2 <= arg && arg < 1.8 { content.push("\"carefulSynthesis\"".to_string()); } + if 1.8 <= arg && arg < 2.0 { + content.push("\"observe\"".to_string()); + content.push("\"focusedSynthesis\"".to_string()); + } + + if args.verbose>2{ + println!("[F] Top route {:?}",top_route); + } + + println!("Quality: {}/{}", top_route.quality, top_route.recipe.quality); + println!("\t[{}]", content.join(", ")); + + // Wait for enter + println!(); + println!("Program finished sucessfuly in {}ms and found {} solutions, [prog:{}]", + now.elapsed().as_millis(), + phase2_routes.len(), + top_route.recipe.progress); + println!("Press enter to exit..."); + let mut input = String::new(); + std::io::stdin().read_line(&mut input).unwrap(); +} + +/// Load the config +pub fn load_config<'a>(args: &Args ) -> Craft<'a> { + //read craft.toml + let config: toml::Value = toml::from_str( + &std::fs::read_to_string(&args.file_name) + .expect(&format!("Can't open {}",&args.file_name)) + ).unwrap(); + + let recp = match config.get(&args.recipe_name){ + Some(r) => r, + None => panic!("Can't find value '{}' in '{}'",&args.recipe_name, &args.file_name) + }; + + // Load receipe values + let recipe = Recipe { + durability: recp + .get("durability").expect(&format!("Can't find 'durability' in recipe '{}' on file '{}'", + &args.recipe_name,&args.file_name)) + .as_integer().expect("Can't convert durability as an integer") as u32, + progress: recp + .get("progress").expect(&format!("Can't find 'progress' in recipe '{}' on '{}'", + &args.recipe_name,&args.file_name)) + .as_integer().expect("Can't convert progress as an integer") as u32, + quality: recp + .get("quality").expect(&format!("Can't find 'quality' in recipe '{}' on '{}'", + &args.recipe_name,&args.file_name)) + .as_integer().expect("Can't convert quality as an integer") as u32, + progress_divider: recp + .get("progress_divider").expect(&format!("Can't find 'progress_divider' in recipe '{}' on '{}'", + &args.recipe_name,&args.file_name)) + .as_integer().expect("Can't convert progress_divider as an integer") as u32, + quality_divider: recp + .get("quality_divider").expect(&format!("Can't find 'quality_divider' in recipe '{}' on '{}'", + &args.recipe_name,&args.file_name)) + .as_integer().expect("Can't convert quality_divider as an integer") as u32, + progress_modifier: recp + .get("progress_modifier").expect(&format!("Can't find 'progress_modifier' in recipe '{}' on '{}'", + &args.recipe_name,&args.file_name)) + .as_integer().expect("Can't convert progress_modifier as an integer") as u32, + quality_modifier: recp + .get("quality_modifier").expect(&format!("Can't find 'quality_modifier' in recipe '{}' on '{}'", + &args.recipe_name,&args.file_name)) + .as_integer().expect("Can't convert quality_modifier as an integer") as u32, + }; + + let cfg = match config.get(&args.character_name){ + Some(c) => c, + None => panic!("Can't find '{}' in file '{}'",&args.character_name,&args.file_name), + }; + let stats = Stats { + craftsmanship: cfg + .get("craftsmanship").expect(&format!("Can't find 'craftsmanship' in character '{}' on file '{}'", + &args.character_name,&args.file_name)) + .as_integer().expect("Can't convert craftsmanship as an integer") as u32, + control: cfg + .get("control").expect(&format!("Can't find 'control' in character '{}' on file '{}'", + &args.character_name,&args.file_name)) + .as_integer().expect("Can't convert control as an integer") as u32, + max_cp: cfg + .get("max_cp").expect(&format!("Can't find 'max_cp' in character '{}' on file '{}'", + &args.character_name,&args.file_name)) + .as_integer().expect("Can't convert max_cp as an integer") as u32, + }; + let craft = Craft::new(recipe, stats, args.depth); + craft +} + +fn make_craft_from_values(){ + +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index bfdb41a..9a78cd8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,293 +1,26 @@ use crate::craft::Craft; -use crate::solver::{generate_routes_phase1, generate_routes_phase2}; +use crate::libs::{Args,}; use crate::specs::{Recipe, Stats}; use clap::Parser; -use std::sync::{Arc,Mutex}; -use std::time::{Instant}; -use threadpool::ThreadPool; - mod specs; pub mod action; pub mod craft; mod solver; - - -#[derive(Debug, Clone)] -pub struct Config<'a> { - pub craft: craft::Craft<'a>, - // pub recipe: solver::Recipe, - pub depth: usize, -} - -#[derive(Parser, Debug)] -#[command(author, version, about, long_about = None)] -struct Args { - /// Name of the receipe - #[arg(short, long, default_value_t = String::from("default_recipe"))] - recipe_name: String, - - /// Name of the character - #[arg(short, long, default_value_t = String::from("default_character"))] - character_name: String, - - /// The ml file name - #[arg(short, long, default_value_t = String::from("craft.toml"))] - file_name: String, - - /// The verbose flag - #[arg(short, long, action = clap::ArgAction::Count)] - verbose: u8, - - /// The depth of the first pass - #[arg(short, long, default_value_t = 8)] - depth: u32, - - /// Thread counts, default is 4 (can you even run ff with less ?) - #[arg(short, long, default_value_t = 4)] - threads: usize, -} +pub mod libs; #[derive(Debug)] struct CustomError(String); -/// -fn load_config<'a>(args: Args ) -> Craft<'a> { - //read craft.toml - let config: toml::Value = toml::from_str( - &std::fs::read_to_string(&args.file_name) - .expect(&format!("Can't open {}",&args.file_name)) - ).unwrap(); - - let recp = match config.get(&args.recipe_name){ - Some(r) => r, - None => panic!("Can't find value '{}' in '{}'",&args.recipe_name, &args.file_name) - }; - - // Load receipe values - let recipe = Recipe { - durability: recp - .get("durability").expect(&format!("Can't find 'durability' in recipe '{}' on file '{}'", - &args.recipe_name,&args.file_name)) - .as_integer().expect("Can't convert durability as an integer") as u32, - progress: recp - .get("progress").expect(&format!("Can't find 'progress' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) - .as_integer().expect("Can't convert progress as an integer") as u32, - quality: recp - .get("quality").expect(&format!("Can't find 'quality' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) - .as_integer().expect("Can't convert quality as an integer") as u32, - progress_divider: recp - .get("progress_divider").expect(&format!("Can't find 'progress_divider' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) - .as_integer().expect("Can't convert progress_divider as an integer") as u32, - quality_divider: recp - .get("quality_divider").expect(&format!("Can't find 'quality_divider' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) - .as_integer().expect("Can't convert quality_divider as an integer") as u32, - progress_modifier: recp - .get("progress_modifier").expect(&format!("Can't find 'progress_modifier' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) - .as_integer().expect("Can't convert progress_modifier as an integer") as u32, - quality_modifier: recp - .get("quality_modifier").expect(&format!("Can't find 'quality_modifier' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) - .as_integer().expect("Can't convert quality_modifier as an integer") as u32, - }; - - let cfg = match config.get(&args.character_name){ - Some(c) => c, - None => panic!("Can't find '{}' in file '{}'",&args.character_name,&args.file_name), - }; - let stats = Stats { - craftsmanship: cfg - .get("craftsmanship").expect(&format!("Can't find 'craftsmanship' in character '{}' on file '{}'", - &args.character_name,&args.file_name)) - .as_integer().expect("Can't convert craftsmanship as an integer") as u32, - control: cfg - .get("control").expect(&format!("Can't find 'control' in character '{}' on file '{}'", - &args.character_name,&args.file_name)) - .as_integer().expect("Can't convert control as an integer") as u32, - max_cp: cfg - .get("max_cp").expect(&format!("Can't find 'max_cp' in character '{}' on file '{}'", - &args.character_name,&args.file_name)) - .as_integer().expect("Can't convert max_cp as an integer") as u32, - }; - let craft = Craft::new(recipe, stats, args.depth); - craft -} - -fn make_craft_from_values(){ - -} - - fn main() { // Get args let args = Args::parse(); - // Start timer - let now = Instant::now(); - - //read craft.toml - let config: toml::Value = toml::from_str( - &std::fs::read_to_string(&args.file_name) - .expect(&format!("Can't open {}",&args.file_name)) - ).unwrap(); - - let recp = match config.get(&args.recipe_name){ - Some(r) => r, - None => panic!("Can't find value '{}' in '{}'",&args.recipe_name, &args.file_name) - }; - - // Load receipe values - let recipe = Recipe { - durability: recp - .get("durability").expect(&format!("Can't find 'durability' in recipe '{}' on file '{}'", - &args.recipe_name,&args.file_name)) - .as_integer().expect("Can't convert durability as an integer") as u32, - progress: recp - .get("progress").expect(&format!("Can't find 'progress' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) - .as_integer().expect("Can't convert progress as an integer") as u32, - quality: recp - .get("quality").expect(&format!("Can't find 'quality' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) - .as_integer().expect("Can't convert quality as an integer") as u32, - progress_divider: recp - .get("progress_divider").expect(&format!("Can't find 'progress_divider' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) - .as_integer().expect("Can't convert progress_divider as an integer") as u32, - quality_divider: recp - .get("quality_divider").expect(&format!("Can't find 'quality_divider' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) - .as_integer().expect("Can't convert quality_divider as an integer") as u32, - progress_modifier: recp - .get("progress_modifier").expect(&format!("Can't find 'progress_modifier' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) - .as_integer().expect("Can't convert progress_modifier as an integer") as u32, - quality_modifier: recp - .get("quality_modifier").expect(&format!("Can't find 'quality_modifier' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) - .as_integer().expect("Can't convert quality_modifier as an integer") as u32, - }; - - let cfg = match config.get(&args.character_name){ - Some(c) => c, - None => panic!("Can't find '{}' in file '{}'",&args.character_name,&args.file_name), - }; - let stats = Stats { - craftsmanship: cfg - .get("craftsmanship").expect(&format!("Can't find 'craftsmanship' in character '{}' on file '{}'", - &args.character_name,&args.file_name)) - .as_integer().expect("Can't convert craftsmanship as an integer") as u32, - control: cfg - .get("control").expect(&format!("Can't find 'control' in character '{}' on file '{}'", - &args.character_name,&args.file_name)) - .as_integer().expect("Can't convert control as an integer") as u32, - max_cp: cfg - .get("max_cp").expect(&format!("Can't find 'max_cp' in character '{}' on file '{}'", - &args.character_name,&args.file_name)) - .as_integer().expect("Can't convert max_cp as an integer") as u32, - }; - let craft = Craft::new(recipe, stats, args.depth); - - // Start a threadpool - let pool = ThreadPool::new(args.threads); - - if args.verbose>0{ - println!("Solving...\n"); - println!("[P1] Starting phase 1..."); - } - let phase1_routes = generate_routes_phase1(craft); + // Load the craft with given arguments + let craft = libs::load_config(&args); - if args.verbose>0{ - println!("[P1] Found {} routes, testing them all...",phase1_routes.len()); - if args.verbose>1{ - for r in &phase1_routes{ - println!("[P1] {:?} p:{}% q:{}% c:{} d:{}", - r.actions, - r.progression * 100 / r.recipe.progress, - r.quality * 100 / r.recipe.quality, - r.cp, - r.durability, - ); - // println!("[P1] {}",r); - }; - } - } + libs::solve_craft(craft,&args); - // Core algorithm, fill all found routes with the best route (doesn't branch, just replace) - let arc_phase2_routes = Arc::new(Mutex::new(Vec::::new())); - - for route in phase1_routes { - let _phase2_routes = arc_phase2_routes.clone(); - pool.execute(move || { - if let Some(_route) = generate_routes_phase2(route){ - let mut shared = _phase2_routes.lock().unwrap(); - shared.push(_route); - }; - }); - } - - pool.join(); - let phase2_routes = arc_phase2_routes.lock().unwrap(); - - // Print the results if verbose - if args.verbose>0{ - println!("[P2] Found {} solutions, sorting",phase2_routes.len()); - - if args.verbose>1{ - for r in phase2_routes.iter(){ - println!("[P2] {:?} p:{}% q:{}% d:{}", - r.actions, - r.progression * 100 / r.recipe.progress, - r.quality * 100 / r.recipe.quality, - r.durability); - }; - } - } - - - let top_route = match phase2_routes.iter().max_by_key(|route| route.quality) { - Some(top) => top, - None => { - println!("[P2] No route could finish the craft.\n[P2] Runtime {}ms. Now exiting...",now.elapsed().as_millis()); - return - }, - }; - - let mut content = (&top_route.actions) - .iter() - .map(|action| { - format!("\"{}\"", action.short_name.clone()) - }) - .collect::>(); - let arg = (top_route.recipe.progress as f32 - top_route.progression as f32) / top_route.get_base_progression() as f32; - if 0.0 < arg && arg < 1.2 { content.push("\"basicSynth2\"".to_string()); } - if 1.2 <= arg && arg < 1.8 { content.push("\"carefulSynthesis\"".to_string()); } - if 1.8 <= arg && arg < 2.0 { - content.push("\"observe\"".to_string()); - content.push("\"focusedSynthesis\"".to_string()); - } - - if args.verbose>2{ - println!("[F] Top route {:?}",top_route); - } - - println!("Quality: {}/{}", top_route.quality, top_route.recipe.quality); - println!("\t[{}]", content.join(", ")); - - // Wait for enter - println!(); - println!("Program finished sucessfuly in {}ms and found {} solutions, [prog:{}]", - now.elapsed().as_millis(), - phase2_routes.len(), - top_route.recipe.progress); - println!("Press enter to exit..."); - let mut input = String::new(); - std::io::stdin().read_line(&mut input).unwrap(); () } diff --git a/src/solver.rs b/src/solver.rs index 7989697..9d31f73 100644 --- a/src/solver.rs +++ b/src/solver.rs @@ -8,7 +8,7 @@ macro_rules! action_vec { ($($tt:expr),*) => { vec![ $(Some(&$tt),)*]}; } -pub fn next_action_picker_1<'a>(craft: &Craft) -> Vec> { +pub fn next_action_picker_1<'a>(craft: Craft<'a>) -> Vec> { if craft.success != Success::Pending { return vec![None]; } let mut available_actions = Vec::>::new(); let mut forbidden_actions = Vec::>::new(); @@ -38,7 +38,7 @@ pub fn next_action_picker_1<'a>(craft: &Craft) -> Vec> { // Pruning the actions with the forbidden ones let mut result_actions = Vec::>::new(); for action in available_actions { - if !forbidden_actions.contains(&action) && action.unwrap().can_use(craft) && result_actions.iter().any(|x| x.unwrap() == action.unwrap()).not() { + if !forbidden_actions.contains(&action) && action.unwrap().can_use(&craft) && result_actions.iter().any(|x| x.unwrap() == action.unwrap()).not() { result_actions.push(action); } } @@ -47,14 +47,13 @@ pub fn next_action_picker_1<'a>(craft: &Craft) -> Vec> { result_actions } -pub fn generate_routes_phase1(craft: Craft) -> Vec { +pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec> { let mut queue = Vec::new(); - // if craft.verbose>2 {print!("#")}; - queue.push(craft); + queue.push(craft.clone()); let mut routes = Vec::new(); while !queue.is_empty() { let craft = queue.pop().unwrap(); - for action in next_action_picker_1(&craft) { + for action in next_action_picker_1(craft.clone()) { let mut craft = craft.clone(); match action{ Some(a) => craft.run_action(a), @@ -89,7 +88,7 @@ pub fn generate_routes_phase1(craft: Craft) -> Vec { } -pub fn next_action_phase_2<'a>(craft: &Craft) -> Vec> { +pub fn next_action_phase_2<'a>(craft: Craft<'a>) -> Vec> { // println!("State of craft {:}",craft); let mut available_actions = vec![&ACTIONS.basic_touch, &ACTIONS.prudent_touch, &ACTIONS.preparatory_touch]; @@ -160,7 +159,7 @@ pub fn generate_routes_phase2<'a>(craft: Craft<'a>) -> Option> { while !queue.is_empty() { let _craft = queue.pop_front().unwrap(); - for action in next_action_phase_2(&_craft) { + for action in next_action_phase_2(_craft.clone()) { if _craft.success != Success::Pending || action.is_none() || !action.unwrap().can_use(&_craft) { continue; } From 35de543b061b7c282d8e5875515c000742d9024d Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 19 Feb 2023 22:08:27 +0100 Subject: [PATCH 2/5] Fix(static) - Solved static problem --- src/craft.rs | 8 +++--- src/libs.rs | 73 +++++++++++++++++++++++++++++---------------------- src/main.rs | 7 +---- src/solver.rs | 2 +- 4 files changed, 48 insertions(+), 42 deletions(-) diff --git a/src/craft.rs b/src/craft.rs index 80a65d1..c4055f3 100644 --- a/src/craft.rs +++ b/src/craft.rs @@ -1,7 +1,7 @@ use std::fmt::{Debug, Formatter,Display}; use crate::action::Action; use crate::specs::{Buff, BuffState, Recipe, Stats, Success}; - +use crate::libs::Parameters; #[derive(Clone)] @@ -16,11 +16,11 @@ pub struct Craft<'a> { pub cp: i32, pub success: Success, pub actions: Vec<&'a Action>, - pub depth: u32, + pub args: Parameters, } impl<'a> Craft<'a> { - pub fn new(recipe: Recipe, stats: Stats, depth: u32) -> Craft<'a> { + pub fn new(recipe: Recipe, stats: Stats, params: Parameters) -> Craft<'a> { Self { recipe, stats, @@ -32,7 +32,7 @@ impl<'a> Craft<'a> { cp: stats.max_cp as i32, success: Success::Pending, actions: Vec::new(), - depth: depth, + args: params, } } diff --git a/src/libs.rs b/src/libs.rs index 67c20cf..256ffd4 100644 --- a/src/libs.rs +++ b/src/libs.rs @@ -10,14 +10,14 @@ use clap::Parser; // use crate::Recipe; // use crate::Craft; -#[derive(Debug, Clone)] -pub struct Config<'a> { - pub craft: Craft<'a>, - // pub recipe: solver::Recipe, - pub depth: usize, +#[derive(Debug, Clone, Copy)] +pub struct Parameters { + pub threads: usize, + pub verbose: u8, + pub depth: u32, } -#[derive(Parser, Debug)] +#[derive(Parser, Debug, Clone)] #[command(author, version, about, long_about = None)] pub struct Args { /// Name of the receipe @@ -46,9 +46,20 @@ pub struct Args { } /// Solve the craft with given arguments -pub fn solve_craft<'a>(craft: Craft<'static>, args: &'a Args){ -// Start timer +pub fn solve_craft<'a>() -> Option>{ + let args = Args::parse(); + let params = Parameters{ + depth: args.depth, + threads: args.threads, + verbose: args.verbose, + }; + + // Load the craft with given arguments + let craft = load_config(&args.recipe_name, &args.file_name, &args.character_name,params); + + // Start timer let now = Instant::now(); + let craft = craft.clone(); // Start a threadpool let pool = ThreadPool::new(args.threads); @@ -57,7 +68,7 @@ pub fn solve_craft<'a>(craft: Craft<'static>, args: &'a Args){ println!("Solving...\n"); println!("[P1] Starting phase 1..."); } - let phase1_routes = generate_routes_phase1(craft); + let phase1_routes = generate_routes_phase1(craft.clone()); if args.verbose>0{ println!("[P1] Found {} routes, testing them all...",phase1_routes.len()); @@ -70,7 +81,6 @@ pub fn solve_craft<'a>(craft: Craft<'static>, args: &'a Args){ r.cp, r.durability, ); - // println!("[P1] {}",r); }; } } @@ -106,12 +116,11 @@ pub fn solve_craft<'a>(craft: Craft<'static>, args: &'a Args){ } } - let top_route = match phase2_routes.iter().max_by_key(|route| route.quality) { Some(top) => top, None => { println!("[P2] No route could finish the craft.\n[P2] Runtime {}ms. Now exiting...",now.elapsed().as_millis()); - return + return None; }, }; @@ -145,72 +154,74 @@ pub fn solve_craft<'a>(craft: Craft<'static>, args: &'a Args){ println!("Press enter to exit..."); let mut input = String::new(); std::io::stdin().read_line(&mut input).unwrap(); + // Some(top_route.clone()) + None } -/// Load the config -pub fn load_config<'a>(args: &Args ) -> Craft<'a> { +/// Load the config from args and make a craft from it +pub fn load_config<'a>(recipe_name: &str, file_name: &str, character_name: &str, params: Parameters) -> Craft<'a> { //read craft.toml let config: toml::Value = toml::from_str( - &std::fs::read_to_string(&args.file_name) - .expect(&format!("Can't open {}",&args.file_name)) + &std::fs::read_to_string(file_name) + .expect(&format!("Can't open {}",file_name)) ).unwrap(); - let recp = match config.get(&args.recipe_name){ + let recp = match config.get(recipe_name){ Some(r) => r, - None => panic!("Can't find value '{}' in '{}'",&args.recipe_name, &args.file_name) + None => panic!("Can't find value '{}' in '{}'",recipe_name, file_name) }; // Load receipe values let recipe = Recipe { durability: recp .get("durability").expect(&format!("Can't find 'durability' in recipe '{}' on file '{}'", - &args.recipe_name,&args.file_name)) + recipe_name,file_name)) .as_integer().expect("Can't convert durability as an integer") as u32, progress: recp .get("progress").expect(&format!("Can't find 'progress' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) + recipe_name,file_name)) .as_integer().expect("Can't convert progress as an integer") as u32, quality: recp .get("quality").expect(&format!("Can't find 'quality' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) + recipe_name,file_name)) .as_integer().expect("Can't convert quality as an integer") as u32, progress_divider: recp .get("progress_divider").expect(&format!("Can't find 'progress_divider' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) + recipe_name,file_name)) .as_integer().expect("Can't convert progress_divider as an integer") as u32, quality_divider: recp .get("quality_divider").expect(&format!("Can't find 'quality_divider' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) + recipe_name,file_name)) .as_integer().expect("Can't convert quality_divider as an integer") as u32, progress_modifier: recp .get("progress_modifier").expect(&format!("Can't find 'progress_modifier' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) + recipe_name,file_name)) .as_integer().expect("Can't convert progress_modifier as an integer") as u32, quality_modifier: recp .get("quality_modifier").expect(&format!("Can't find 'quality_modifier' in recipe '{}' on '{}'", - &args.recipe_name,&args.file_name)) + recipe_name,file_name)) .as_integer().expect("Can't convert quality_modifier as an integer") as u32, }; - let cfg = match config.get(&args.character_name){ + let cfg = match config.get(character_name){ Some(c) => c, - None => panic!("Can't find '{}' in file '{}'",&args.character_name,&args.file_name), + None => panic!("Can't find '{}' in file '{}'",character_name,file_name), }; let stats = Stats { craftsmanship: cfg .get("craftsmanship").expect(&format!("Can't find 'craftsmanship' in character '{}' on file '{}'", - &args.character_name,&args.file_name)) + character_name,file_name)) .as_integer().expect("Can't convert craftsmanship as an integer") as u32, control: cfg .get("control").expect(&format!("Can't find 'control' in character '{}' on file '{}'", - &args.character_name,&args.file_name)) + character_name,file_name)) .as_integer().expect("Can't convert control as an integer") as u32, max_cp: cfg .get("max_cp").expect(&format!("Can't find 'max_cp' in character '{}' on file '{}'", - &args.character_name,&args.file_name)) + character_name,file_name)) .as_integer().expect("Can't convert max_cp as an integer") as u32, }; - let craft = Craft::new(recipe, stats, args.depth); + let craft = Craft::new(recipe, stats, params); craft } diff --git a/src/main.rs b/src/main.rs index 9a78cd8..9edb99c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,13 +14,8 @@ pub mod libs; struct CustomError(String); fn main() { - // Get args - let args = Args::parse(); - - // Load the craft with given arguments - let craft = libs::load_config(&args); - libs::solve_craft(craft,&args); + libs::solve_craft(); () } diff --git a/src/solver.rs b/src/solver.rs index 9d31f73..69774d4 100644 --- a/src/solver.rs +++ b/src/solver.rs @@ -81,7 +81,7 @@ pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec> { // A higher value will yield more initial guesses with minimal benefits // A lover value will yield less initial guesses and might spent too much CP to get to the required progression // TODO: Pass a flag to get more attempts - if craft.step_count < craft.depth { queue.push(craft); } + if craft.step_count < craft.args.depth { queue.push(craft); } } } routes From b1ebe772b95a21d3c963fcfcc63dc3f8b66a2aec Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 19 Feb 2023 22:45:44 +0100 Subject: [PATCH 3/5] Fix(clone) - removed a bunch of clones --- Cargo.toml | 3 ++- src/libs.rs | 45 +++++++++++++++++++++------------------------ src/main.rs | 17 +++++++++++++---- src/solver.rs | 12 ++++++------ 4 files changed, 42 insertions(+), 35 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 02f0ba3..1710e78 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,8 @@ name = "xiv_craft_simulator" version = "0.1.2" edition = "2021" -author = "谭俊健 & Dandaedre" +authors = ["谭俊健","Dandaedre"] +description = "Small XIV solver library in rust, with python and rust bindings" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/src/libs.rs b/src/libs.rs index 256ffd4..5be6876 100644 --- a/src/libs.rs +++ b/src/libs.rs @@ -46,33 +46,31 @@ pub struct Args { } /// Solve the craft with given arguments -pub fn solve_craft<'a>() -> Option>{ - let args = Args::parse(); - let params = Parameters{ - depth: args.depth, - threads: args.threads, - verbose: args.verbose, - }; +pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Option>{ + // let params = Parameters{ + // depth: args.depth, + // threads: args.threads, + // verbose: args.verbose, + // }; - // Load the craft with given arguments - let craft = load_config(&args.recipe_name, &args.file_name, &args.character_name,params); - + // // Load the craft with given arguments + // let craft = make_craft_from_config(&args.recipe_name, &args.file_name, &args.character_name,params); + let craft = Craft::new(recipe,stats,params); // Start timer let now = Instant::now(); - let craft = craft.clone(); // Start a threadpool - let pool = ThreadPool::new(args.threads); + let pool = ThreadPool::new(params.threads); - if args.verbose>0{ + if params.verbose>0{ println!("Solving...\n"); println!("[P1] Starting phase 1..."); } - let phase1_routes = generate_routes_phase1(craft.clone()); + let phase1_routes = generate_routes_phase1(craft); - if args.verbose>0{ + if params.verbose>0{ println!("[P1] Found {} routes, testing them all...",phase1_routes.len()); - if args.verbose>1{ + if params.verbose>1{ for r in &phase1_routes{ println!("[P1] {:?} p:{}% q:{}% c:{} d:{}", r.actions, @@ -102,10 +100,10 @@ pub fn solve_craft<'a>() -> Option>{ let phase2_routes = arc_phase2_routes.lock().unwrap(); // Print the results if verbose - if args.verbose>0{ + if params.verbose>0{ println!("[P2] Found {} solutions, sorting",phase2_routes.len()); - if args.verbose>1{ + if params.verbose>1{ for r in phase2_routes.iter(){ println!("[P2] {:?} p:{}% q:{}% d:{}", r.actions, @@ -138,7 +136,7 @@ pub fn solve_craft<'a>() -> Option>{ content.push("\"focusedSynthesis\"".to_string()); } - if args.verbose>2{ + if params.verbose>2{ println!("[F] Top route {:?}",top_route); } @@ -159,7 +157,7 @@ pub fn solve_craft<'a>() -> Option>{ } /// Load the config from args and make a craft from it -pub fn load_config<'a>(recipe_name: &str, file_name: &str, character_name: &str, params: Parameters) -> Craft<'a> { +pub fn load_from_config<'a>(recipe_name: &str, file_name: &str, character_name: &str) -> (Recipe,Stats) { //read craft.toml let config: toml::Value = toml::from_str( &std::fs::read_to_string(file_name) @@ -221,10 +219,9 @@ pub fn load_config<'a>(recipe_name: &str, file_name: &str, character_name: &str, character_name,file_name)) .as_integer().expect("Can't convert max_cp as an integer") as u32, }; - let craft = Craft::new(recipe, stats, params); - craft + (recipe,stats) } -fn make_craft_from_values(){ +// fn make_craft_from_values(){ -} \ No newline at end of file +// } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 9edb99c..df2426b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,10 @@ +use crate::libs::Parameters; +use crate::libs::load_from_config; +use clap::Parser; +use crate::libs::Args; use crate::craft::Craft; -use crate::libs::{Args,}; use crate::specs::{Recipe, Stats}; -use clap::Parser; mod specs; pub mod action; @@ -14,8 +16,15 @@ pub mod libs; struct CustomError(String); fn main() { - - libs::solve_craft(); + let args = Args::parse(); + let params = Parameters{ + depth: args.depth, + threads: args.threads, + verbose: args.verbose, + }; + + let (recipe,stats) = load_from_config(&args.recipe_name, &args.file_name, &args.character_name); + libs::solve_craft(recipe,stats,params); () } diff --git a/src/solver.rs b/src/solver.rs index 69774d4..3b98b9b 100644 --- a/src/solver.rs +++ b/src/solver.rs @@ -8,7 +8,7 @@ macro_rules! action_vec { ($($tt:expr),*) => { vec![ $(Some(&$tt),)*]}; } -pub fn next_action_picker_1<'a>(craft: Craft<'a>) -> Vec> { +pub fn next_action_picker_1<'a>(craft: & Craft<'a>) -> Vec> { if craft.success != Success::Pending { return vec![None]; } let mut available_actions = Vec::>::new(); let mut forbidden_actions = Vec::>::new(); @@ -43,18 +43,18 @@ pub fn next_action_picker_1<'a>(craft: Craft<'a>) -> Vec> { } } - // println!("Av: {:?}",result_actions); result_actions } pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec> { let mut queue = Vec::new(); - queue.push(craft.clone()); + queue.push(craft); let mut routes = Vec::new(); while !queue.is_empty() { let craft = queue.pop().unwrap(); - for action in next_action_picker_1(craft.clone()) { + for action in next_action_picker_1(& craft) { let mut craft = craft.clone(); + match action{ Some(a) => craft.run_action(a), None => break, @@ -88,7 +88,7 @@ pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec> { } -pub fn next_action_phase_2<'a>(craft: Craft<'a>) -> Vec> { +pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec> { // println!("State of craft {:}",craft); let mut available_actions = vec![&ACTIONS.basic_touch, &ACTIONS.prudent_touch, &ACTIONS.preparatory_touch]; @@ -159,7 +159,7 @@ pub fn generate_routes_phase2<'a>(craft: Craft<'a>) -> Option> { while !queue.is_empty() { let _craft = queue.pop_front().unwrap(); - for action in next_action_phase_2(_craft.clone()) { + for action in next_action_phase_2(&_craft) { if _craft.success != Success::Pending || action.is_none() || !action.unwrap().can_use(&_craft) { continue; } From 4333ee0147da6b5cbc8d19f7b90f4618c88773a8 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 19 Feb 2023 23:00:21 +0100 Subject: [PATCH 4/5] Fix(Misc) - Fixed most clone problems --- src/libs.rs | 15 ++++----------- src/main.rs | 1 + src/solver.rs | 2 -- 3 files changed, 5 insertions(+), 13 deletions(-) diff --git a/src/libs.rs b/src/libs.rs index 5be6876..32bade0 100644 --- a/src/libs.rs +++ b/src/libs.rs @@ -47,14 +47,7 @@ pub struct Args { /// Solve the craft with given arguments pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Option>{ - // let params = Parameters{ - // depth: args.depth, - // threads: args.threads, - // verbose: args.verbose, - // }; - - // // Load the craft with given arguments - // let craft = make_craft_from_config(&args.recipe_name, &args.file_name, &args.character_name,params); + // Load the craft with given arguments let craft = Craft::new(recipe,stats,params); // Start timer let now = Instant::now(); @@ -86,7 +79,7 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti let arc_phase2_routes = Arc::new(Mutex::new(Vec::::new())); for route in phase1_routes { - let _phase2_routes = arc_phase2_routes.clone(); + let _phase2_routes = Arc::clone(&arc_phase2_routes); pool.execute(move || { if let Some(_route) = generate_routes_phase2(route){ @@ -152,8 +145,8 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti println!("Press enter to exit..."); let mut input = String::new(); std::io::stdin().read_line(&mut input).unwrap(); - // Some(top_route.clone()) - None + Some(content) + // None } /// Load the config from args and make a craft from it diff --git a/src/main.rs b/src/main.rs index df2426b..bbf090c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,4 @@ +// #![warn(missing_docs,unsafe_code,unstable_features,)] use crate::libs::Parameters; use crate::libs::load_from_config; use clap::Parser; diff --git a/src/solver.rs b/src/solver.rs index 3b98b9b..2730936 100644 --- a/src/solver.rs +++ b/src/solver.rs @@ -89,8 +89,6 @@ pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec> { pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec> { - // println!("State of craft {:}",craft); - let mut available_actions = vec![&ACTIONS.basic_touch, &ACTIONS.prudent_touch, &ACTIONS.preparatory_touch]; let mut forbidden_actions = Vec::new(); if craft.success != Success::Pending { return vec![None]; } From 2814fbcfec38eeb1039b5319ddbae689b82b5022 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 20 Feb 2023 04:10:41 +0100 Subject: [PATCH 5/5] Fix(return) - Changed the return type --- src/libs.rs | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/src/libs.rs b/src/libs.rs index 32bade0..abc1b32 100644 --- a/src/libs.rs +++ b/src/libs.rs @@ -46,7 +46,7 @@ pub struct Args { } /// Solve the craft with given arguments -pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Option>{ +pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Option>>{ // Load the craft with given arguments let craft = Craft::new(recipe,stats,params); // Start timer @@ -107,7 +107,21 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti } } - let top_route = match phase2_routes.iter().max_by_key(|route| route.quality) { + // Copy the valid results for analysis, by default only the valid one are copied + let mut valid_routes : Vec = vec![]; + for route in phase2_routes.iter(){ + if route.quality>=route.recipe.quality{ + valid_routes.push(route.clone()); + } + } + + if valid_routes.len()==0{ + for route in phase2_routes.iter(){valid_routes.push(route.clone())} // Deep copy through the mutex guard + } + + + // Select best route TODO: Seperate function + let top_route = match valid_routes.iter().max_by_key(|route| route.quality) { Some(top) => top, None => { println!("[P2] No route could finish the craft.\n[P2] Runtime {}ms. Now exiting...",now.elapsed().as_millis()); @@ -115,12 +129,15 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti }, }; + // Print best route TODO: Seperate function let mut content = (&top_route.actions) .iter() .map(|action| { format!("\"{}\"", action.short_name.clone()) }) .collect::>(); + + // Setting something to print, adding the missing actions TODO: Change this behaviour and move to separate function let arg = (top_route.recipe.progress as f32 - top_route.progression as f32) / top_route.get_base_progression() as f32; if 0.0 < arg && arg < 1.2 { content.push("\"basicSynth2\"".to_string()); } if 1.2 <= arg && arg < 1.8 { content.push("\"carefulSynthesis\"".to_string()); } @@ -136,7 +153,7 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti println!("Quality: {}/{}", top_route.quality, top_route.recipe.quality); println!("\t[{}]", content.join(", ")); - // Wait for enter + // Wait for enter TODO: Remove println!(); println!("Program finished sucessfuly in {}ms and found {} solutions, [prog:{}]", now.elapsed().as_millis(), @@ -145,8 +162,7 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti println!("Press enter to exit..."); let mut input = String::new(); std::io::stdin().read_line(&mut input).unwrap(); - Some(content) - // None + Some(valid_routes) } /// Load the config from args and make a craft from it