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/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 new file mode 100644 index 0000000..abc1b32 --- /dev/null +++ b/src/libs.rs @@ -0,0 +1,236 @@ +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, Copy)] +pub struct Parameters { + pub threads: usize, + pub verbose: u8, + pub depth: u32, +} + +#[derive(Parser, Debug, Clone)] +#[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>(recipe: Recipe, stats: Stats, params: Parameters) -> Option>>{ + // Load the craft with given arguments + let craft = Craft::new(recipe,stats,params); + // Start timer + let now = Instant::now(); + + // Start a threadpool + let pool = ThreadPool::new(params.threads); + + if params.verbose>0{ + println!("Solving...\n"); + println!("[P1] Starting phase 1..."); + } + let phase1_routes = generate_routes_phase1(craft); + + if params.verbose>0{ + println!("[P1] Found {} routes, testing them all...",phase1_routes.len()); + if params.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, + ); + }; + } + } + // 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::clone(&arc_phase2_routes); + + 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 params.verbose>0{ + println!("[P2] Found {} solutions, sorting",phase2_routes.len()); + + if params.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); + }; + } + } + + // 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()); + return None; + }, + }; + + // 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()); } + if 1.8 <= arg && arg < 2.0 { + content.push("\"observe\"".to_string()); + content.push("\"focusedSynthesis\"".to_string()); + } + + if params.verbose>2{ + println!("[F] Top route {:?}",top_route); + } + + println!("Quality: {}/{}", top_route.quality, top_route.recipe.quality); + println!("\t[{}]", content.join(", ")); + + // Wait for enter TODO: Remove + 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(); + Some(valid_routes) +} + +/// Load the config from args and make a craft from it +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) + .expect(&format!("Can't open {}",file_name)) + ).unwrap(); + + let recp = match config.get(recipe_name){ + Some(r) => r, + 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 '{}'", + 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 '{}'", + 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 '{}'", + 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 '{}'", + 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 '{}'", + 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 '{}'", + 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 '{}'", + recipe_name,file_name)) + .as_integer().expect("Can't convert quality_modifier as an integer") as u32, + }; + + let cfg = match config.get(character_name){ + Some(c) => c, + 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 '{}'", + 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 '{}'", + 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 '{}'", + character_name,file_name)) + .as_integer().expect("Can't convert max_cp as an integer") as u32, + }; + (recipe,stats) +} + +// fn make_craft_from_values(){ + +// } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index bfdb41a..bbf090c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,293 +1,31 @@ -use crate::craft::Craft; -use crate::solver::{generate_routes_phase1, generate_routes_phase2}; -use crate::specs::{Recipe, Stats}; - +// #![warn(missing_docs,unsafe_code,unstable_features,)] +use crate::libs::Parameters; +use crate::libs::load_from_config; use clap::Parser; -use std::sync::{Arc,Mutex}; -use std::time::{Instant}; -use threadpool::ThreadPool; +use crate::libs::Args; +use crate::craft::Craft; +use crate::specs::{Recipe, Stats}; 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) + let params = Parameters{ + depth: args.depth, + threads: args.threads, + verbose: args.verbose, }; - // 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); + let (recipe,stats) = load_from_config(&args.recipe_name, &args.file_name, &args.character_name); + libs::solve_craft(recipe,stats,params); - 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(); () } diff --git a/src/solver.rs b/src/solver.rs index 7989697..2730936 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,24 +38,23 @@ 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); } } - // println!("Av: {:?}",result_actions); 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); 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) { let mut craft = craft.clone(); + match action{ Some(a) => craft.run_action(a), None => break, @@ -82,16 +81,14 @@ pub fn generate_routes_phase1(craft: Craft) -> 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 } -pub fn next_action_phase_2<'a>(craft: &Craft) -> Vec> { - // println!("State of craft {:}",craft); - +pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec> { 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]; }