diff --git a/.gitignore b/.gitignore index c7d61f4..87e0fb6 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ *.iml /bin.py python/dontlook.py +expected_values.md # Byte-compiled / optimized / DLL files __pycache__/ diff --git a/Cargo.toml b/Cargo.toml index cc49e95..a1ced99 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "xiv_craft_solver" version = "0.1.2" edition = "2021" -authors = ["谭俊健","Dandaedre"] +authors = ["谭俊健","Dandaedre","Vkyfox"] 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 @@ -17,6 +17,9 @@ threadpool = "1.8.1" # For python bindings TODO: make it optionnal pyo3 = { version = "0.18.0", features = ["extension-module"] } +# [target.'cfg(not(no_python))'.dependencies] +# pyo3 = { version = "0.18.0", features = ["extension-module"] } + # [build] # target = ["x86_64-unknown-linux-gnu", "x86_64-unknown-windows-gnu"] @@ -24,11 +27,12 @@ pyo3 = { version = "0.18.0", features = ["extension-module"] } panic = 'abort' opt-level = 3 lto = true -vere0 = false [features] default = [] verbose = [] +no_python = [] # Removes the python bindings +fast = [] # Remove some under optimisations that try to find other routes [lib] name = "xiv_craft_solver" diff --git a/README.md b/README.md index 4d20cc2..7737c21 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,71 @@ # xiv_craft_solver -A rust program for solving FFXIV craft recipe. **Only normal lv90 recipes with stars and 70/80 dur works.** +A rust program for solving FFXIV craft recipe. -## Usage +Originaly written by [RikaKagurasaka](https://github.com/RikaKagurasaka/xiv_craft_solver), +it now is widely improved and provides python bindings for a GUI (or anything else really) + +### Basic RUST CLI Usage +Everything is done through the regular cargo interface 1. Download the latest release. 2. Unzip the file. 3. Edit the `craft.toml` file. 4. Run the program. -5. Wait for about 1 minute. +5. Wait for about 1-3 seconds. 6. Copy the output. 7. Import to other simulators. -#### Example -Note: The recipe data can be retrieved from [FFXIV Crafting Optimizer](https://yyyy.games/crafter/#/simulator) +## CLI +When building the CLI invocation is done with the following parameters +``` +Small XIV solver library in rust, with python and rust bindings + +Usage: ffcraft [OPTIONS] + +Options: + -r, --recipe-name + Name of the receipe [default: default_recipe] + -c, --character-name + Name of the character [default: default_character] + -f, --file-name + The ml file name [default: craft.toml] + -v, --verbose... + The verbose flag + -d, --depth + The depth of the first pass [default: 8] + -t, --threads + Thread counts, default is 4 [default: 4] + -D, --desperate + Desperate mode, will try to finish the craft above all + -l, --long + Long mode, will try to find more solutions, at the expense of time + -h, --help + Print help + -V, --version + Print version +``` +## Developpement +### Rust +Everything is located in the root & src. +You can build the program (CLI) with cargo build the following features are available +``cargo build --features=["fast","no_python","verbose"]`` +- The ``no_python`` will not build the lib (WIP, not fully implemented) +- The ``fast`` feature will not allow some under-optimisation to run (saving global run-time) +- The ``verbose`` feature will allow even more debug messages (They might not be shown depending on the verbosity level hoever) +#### Maturin +To build the python module, run ``maturin develop`` or ``maturin build`` then ``maturin install`` + +### Python +#### Developping the GUI +0. Activate the venv ``source .venv/bin/activate`` +1. Go to the ``python`` directory +2. Install the dev dependencies ``pip install -r requirements_dev.txt`` +3. Install the project (in editable mode) ``pip install -e .`` +4. Invoke the project (from anywhere) ``python -m ffcraft_solver`` +5. Edit the project and re-invoke it (no need to install / compile again) + + +#### Rust CLI Example +Note: The recipe data can be retrieved from a [FFXIV Crafting Optimizer](https://yyyy.games/crafter/#/simulator) with checking of **Custom Recipe** after selecting the recipe. ![img.png](img.png) ```toml @@ -43,9 +97,19 @@ max_cp = 602 ``` Solving... -Quality: 11126/12628 - ["muscleMemory", "manipulation", "veneration", "groundwork2", "basicSynth2", "prudentSynthesis", "prudentSynthesis", "prudentSynthesis", "prudentTouch", "prudentTouch", "manipulation", "innovation", "prudentTouch", "basicTouch", "standardTouch", "advancedTouch", "innovation", "prudentTouch", "basicTouch", "standardTouch", "advancedTouch", "innovation", "trainedFinesse", "trainedFinesse", "greatStrides", "byregotsBlessing", "basicSynth2"] + > SOLUTION [Least steps] < +Quality: [10941/10920] | Durability: [0/70] | Cp : [14/602] | Steps : 18 +["muscleMemory", "manipulation", "veneration", "wasteNot2", "groundwork", "delicateSynthesis", "basicSynth", "innovation", "preparatoryTouch", "preparatoryTouch", "preparatoryTouch", "preparatoryTouch", "greatStrides", "innovation", "basicTouch", "standardTouch", "greatStrides", "byregotsBlessing", "basicSynth2"] + > SOLUTION [Most durability] < +Quality: [10923/10920] | Durability: [15/70] | Cp : [4/602] | Steps : 22 +["muscleMemory", "manipulation", "veneration", "groundwork", "carefulSynthesis", "prudentTouch", "innovation", "prudentTouch", "prudentTouch", "prudentTouch", "prudentTouch", "manipulation", "innovation", "prudentTouch", "basicTouch", "standardTouch", "advancedTouch", "innovation", "prudentTouch", "basicTouch", "greatStrides", "byregotsBlessing", "basicSynth2"] + + > SOLUTION [Most quality] < +Quality: [12142/10920] | Durability: [-5/70] | Cp : [1/602] | Steps : 22 +["muscleMemory", "manipulation", "veneration", "wasteNot2", "groundwork", "carefulSynthesis", "basicTouch", "innovation", "preparatoryTouch", "basicTouch", "standardTouch", "advancedTouch", "innovation", "prudentTouch", "basicTouch", "standardTouch", "advancedTouch", "innovation", "prudentTouch", "trainedFinesse", "greatStrides", "byregotsBlessing", "basicSynth2"] + +Program finished successfully in 954ms Press enter to exit... ``` diff --git a/pyproject.toml b/pyproject.toml index e75ad35..e26bb76 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,13 +2,12 @@ requires = ["maturin>=0.14,<0.15"] build-backend = "maturin" -[project] +[project] # The rust bindings name = "xiv_craft_solver" requires-python = ">=3.7" +version = "0.0.4" classifiers = [ "Programming Language :: Rust", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", -] - - +] \ No newline at end of file diff --git a/python/__ignore_setup.cfg b/python/__ignore_setup.cfg new file mode 100644 index 0000000..5681c80 --- /dev/null +++ b/python/__ignore_setup.cfg @@ -0,0 +1,39 @@ +[metadata] +platforms = unix, linux, cygwin, win32 +classifiers = + Programming Language :: Python :: 3 + Programming Language :: Python :: 3 :: Only + Programming Language :: Python :: 3.10 + Programming Language :: Python :: 3.9 + +[options] +packages = + ffcraft_solver + ffcraft_solver.modules +install_requires = + pyyaml>=6.0 +python_requires = >=3.9 +package_dir = + =src + +zip_safe = no + +[options.packages.find] +where = + = src + = src/ffcraft_solver + +[options.extras_require] +testing = + flake8>=4.0.1 + tox>=3.24.3 + pytest>=6.2.5 + pytest-cov>=2.12.1 + mypy>=0.910 + pyyaml>=6.0 + +[options.package_data] +slapping = py.typed + +[flake8] +max-line-length = 160 \ No newline at end of file diff --git a/python/pyproject.toml b/python/pyproject.toml new file mode 100644 index 0000000..0e3f93e --- /dev/null +++ b/python/pyproject.toml @@ -0,0 +1,38 @@ +[build-system] +requires = ["setuptools>=42.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] # The Python GUI +name = "ffcraft_solver" +authors = [ + {name="Vkyfox"}, + {name="Dandaedre"}, +] +requires-python = ">=3.7" +version = "0.0.4" +license = {text="Mozilla Public License Version 2.0"} +classifiers = [ + "Programming Language :: Rust", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", +] + +[tool.pytest.ini_options] +addopts = "--cov=ffcraft_solver" +testpaths = [ + "tests", +] + +[tool.mypy] +mypy_path = "python" +check_untyped_defs = true +disallow_any_generics = true +ignore_missing_imports = true +no_implicit_optional = true +show_error_codes = true +strict_equality = true +warn_redundant_casts = true +warn_return_any = true +warn_unreachable = true +warn_unused_configs = true +no_implicit_reexport = true \ No newline at end of file diff --git a/python/requirements.txt b/python/requirements.txt new file mode 100644 index 0000000..d2a5867 --- /dev/null +++ b/python/requirements.txt @@ -0,0 +1,3 @@ +dearpygui==1.8.0 +PyYAML==6.0 +rich==13.3.1 diff --git a/python/requirements_dev.txt b/python/requirements_dev.txt new file mode 100644 index 0000000..a8b4c81 --- /dev/null +++ b/python/requirements_dev.txt @@ -0,0 +1,8 @@ +flake8==4.0.1 +tox==3.24.5 +pytest==7.1.1 +pytest-cov==3.0.0 +mypy==0.941 +dearpygui==1.8.0 +PyYAML==6.0 +rich==13.3.1 \ No newline at end of file diff --git a/python/src/ffcraft_solver/__init__.py b/python/src/ffcraft_solver/__init__.py new file mode 100644 index 0000000..8925872 --- /dev/null +++ b/python/src/ffcraft_solver/__init__.py @@ -0,0 +1,4 @@ +""" +A rust program for solving FFXIV craft recipe. + - ffcraft_solver +""" diff --git a/python/main.py b/python/src/ffcraft_solver/__main__.py similarity index 99% rename from python/main.py rename to python/src/ffcraft_solver/__main__.py index bdb884f..41485a2 100644 --- a/python/main.py +++ b/python/src/ffcraft_solver/__main__.py @@ -1,13 +1,12 @@ import dearpygui.dearpygui as dpg -import loader -import rich import xiv_craft_solver as xcs +from ffcraft_solver.modules import loader +import rich dpg.create_context() dpg.configure_app(manual_callback_management=True) dpg.create_viewport(title='XIV Solver', width=500, height=700) - class User: name = 'NEW' food = '' diff --git a/configs/consumables.yaml b/python/src/ffcraft_solver/configs/consumables.yaml similarity index 100% rename from configs/consumables.yaml rename to python/src/ffcraft_solver/configs/consumables.yaml diff --git a/configs/recipes.yaml b/python/src/ffcraft_solver/configs/recipes.yaml similarity index 100% rename from configs/recipes.yaml rename to python/src/ffcraft_solver/configs/recipes.yaml diff --git a/configs/users.yaml b/python/src/ffcraft_solver/configs/users.yaml similarity index 100% rename from configs/users.yaml rename to python/src/ffcraft_solver/configs/users.yaml diff --git a/python/src/ffcraft_solver/example.py b/python/src/ffcraft_solver/example.py new file mode 100644 index 0000000..a9c19ec --- /dev/null +++ b/python/src/ffcraft_solver/example.py @@ -0,0 +1,32 @@ +import xiv_craft_solver +import rich + +rich.inspect(xiv_craft_solver) +rich.inspect(xiv_craft_solver.test_result) +rich.inspect(xiv_craft_solver.test_result()) +rich.inspect(xiv_craft_solver.test_result()) + + +class feedMeDaddy: + durability = 70 + progress = 3900 + quality = 10920 + progress_divider = 130 + quality_divider = 115 + progress_modifier = 80 + quality_modifier = 70 + craftsmanship = 4041 + control = 3959 + max_cp = 602 + + # Config + depth = 10 + byregot_step = 10 + desperate = False + threads = 8 + verbose = 0 + + +el_daddy=feedMeDaddy() +rich.inspect(xiv_craft_solver.solve_from_python(el_daddy)) + diff --git a/python/example_dearpygui.py b/python/src/ffcraft_solver/example_dearpygui.py similarity index 100% rename from python/example_dearpygui.py rename to python/src/ffcraft_solver/example_dearpygui.py diff --git a/python/src/ffcraft_solver/modules/__init__.py b/python/src/ffcraft_solver/modules/__init__.py new file mode 100644 index 0000000..746130e --- /dev/null +++ b/python/src/ffcraft_solver/modules/__init__.py @@ -0,0 +1,3 @@ +""" +The modules in this folder are used to generate the GUI and parse the results +""" diff --git a/python/loader.py b/python/src/ffcraft_solver/modules/loader.py similarity index 74% rename from python/loader.py rename to python/src/ffcraft_solver/modules/loader.py index 3c9ea60..f847083 100644 --- a/python/loader.py +++ b/python/src/ffcraft_solver/modules/loader.py @@ -1,5 +1,13 @@ import rich import yaml +import os + +class DefaultConfig: + yaml_user = 'configs/users.yaml' + yaml_consumable = 'configs/consumables.yaml' + yaml_recipes = 'configs/recipes.yaml' + + class Loader: @@ -10,24 +18,29 @@ class Loader: self.foods_list = {' ': [[0, 0], [0, 0], [0, 0]]} self.pots_list = {' ': [[0, 0], [0, 0], [0, 0]]} self.recipes_list = {'NEW': [0, 0, 0]} + self.config = DefaultConfig() + try: - with open('../configs/users.yaml', 'r') as file: + with open(self.relative_import(self.config.yaml_user), 'r') as file: self.user_list.update(yaml.safe_load(file)) except FileNotFoundError as e: print(e) try: - with open('../configs/consumables.yaml', 'r') as file: + with open(self.relative_import(self.config.yaml_consumable), 'r') as file: loaded_file = yaml.safe_load(file) self.foods_list.update(loaded_file['Foods']) self.pots_list.update(loaded_file['Pots']) except FileNotFoundError as e: print(e) try: - with open('../configs/recipes.yaml', 'r') as file: + with open(self.relative_import(self.config.yaml_recipes), 'r') as file: self.recipes_list.update(yaml.safe_load(file)) - except FileNotFoundError as e: + except (FileNotFoundError,IsADirectoryError) as e: print(e) + def relative_import(self, path): + return (os.path.normpath(os.path.join(__file__,"../..",path))) + def get_users_dict(self) -> dict: return self.user_list diff --git a/python/src/ffcraft_solver/resources/ffcraft_solver.ico b/python/src/ffcraft_solver/resources/ffcraft_solver.ico new file mode 100644 index 0000000..3b9f0cf Binary files /dev/null and b/python/src/ffcraft_solver/resources/ffcraft_solver.ico differ diff --git a/python/src/ffcraft_solver/resources/ffcraft_solver.png b/python/src/ffcraft_solver/resources/ffcraft_solver.png new file mode 100644 index 0000000..60a51ef Binary files /dev/null and b/python/src/ffcraft_solver/resources/ffcraft_solver.png differ diff --git a/python/tox.ini b/python/tox.ini new file mode 100644 index 0000000..7fb9316 --- /dev/null +++ b/python/tox.ini @@ -0,0 +1,29 @@ +[tox] +minversion = 3.8.0 +envlist = py37, py38, py39, flake8, mypy +isolated_build = true + +[gh-actions] +python = + 3.7: py36, mypy, flake8 + 3.8: py38 + 3.9: py39 + +[testenv] +setenv = + PYTHONPATH = {toxinidir} +deps = + -r{toxinidir}/requirements_dev.txt +commands = + pytest --basetemp={envtmpdir} + +[testenv:flake8] +basepython = python3.10 +deps = flake8 +commands = flake8 src tests + +[testenv:mypy] +basepython = python3.10 +deps = + -r{toxinidir}/requirements_dev.txt +commands = mypy src diff --git a/src/action.rs b/src/action.rs index 84c6d1a..513927c 100644 --- a/src/action.rs +++ b/src/action.rs @@ -179,6 +179,8 @@ pub struct ActionList { pub veneration: Action, pub great_strides: Action, pub innovation: Action, + //pub observe: Action, + //pub focused_synthesis: Action, } impl Default for ActionList { @@ -208,6 +210,10 @@ impl Default for ActionList { veneration: ActionBuilder::new("Veneration").cp(18).buff(Some((Buff::Veneration, 4))).build(), great_strides: ActionBuilder::new("Great Strides").cp(32).buff(Some((Buff::GreatStrides, 3))).build(), innovation: ActionBuilder::new("Innovation").cp(18).buff(Some((Buff::Innovation, 4))).build(), + + // Todo: Add back + //observe: ActionBuilder::new("observe").cp(18).buff(Some((Buff::Observe, 1))).build(), + //focused_synthesis: ActionBuilder::new("focused_synthesis").cp(18).quality(100).build(), } } } diff --git a/src/bin/ffcraft.rs b/src/bin/ffcraft.rs index fe86edc..586749e 100644 --- a/src/bin/ffcraft.rs +++ b/src/bin/ffcraft.rs @@ -1,4 +1,5 @@ // #![warn(missing_docs,unsafe_code,unstable_features,)] +use std::time::{Instant}; use clap::Parser; use xiv_craft_solver; @@ -6,15 +7,53 @@ use xiv_craft_solver; struct CustomError(String); fn main() { - let args = xiv_craft_solver::Args::parse(); - let params = xiv_craft_solver::Parameters{ - depth: args.depth, - threads: args.threads, - verbose: args.verbose, - }; + let args = xiv_craft_solver::io::Args::parse(); + let params = xiv_craft_solver::io::Parameters::from_args(&args); + // Start timer + let now = Instant::now(); + println!("Solving..."); + + // Solve from config let (recipe,stats) = xiv_craft_solver::load_from_config(&args.recipe_name, &args.file_name, &args.character_name); - xiv_craft_solver::solve_craft(recipe,stats,params); + let results = xiv_craft_solver::solve_craft(recipe,stats,params); + // Stop timer + let t_final = now.elapsed().as_millis(); + + + + // Show best result depending on selected value + match results{ + None => { + println!("[Error] No solutions found for craft '{}' with crafter '{}' (ms)", args.recipe_name, args.character_name); + return + } + Some(ref res)=>{ + // Show best results + if args.verbose>0{ + println!("[Final] {} results were found:",res.len()); + #[cfg(feature = "verbose")] + if args.verbose>1{ + xiv_craft_solver::print_routes(&results); + } + } + }, + } + println!("\n > SOLUTION [Least steps] <"); + xiv_craft_solver::find_fast_route(&results).unwrap().pretty_print(); + println!("\n > SOLUTION [Most durability] <"); + xiv_craft_solver::find_safe_route(&results).unwrap().pretty_print(); + println!("\n > SOLUTION [Most quality] < "); + xiv_craft_solver::find_quality_route(&results).unwrap().pretty_print(); + + // #[cfg(feature = "verbose")] + // if params.verbose>2{ + // println!("[F] Top routes {:?}",results); + // } + + // Wait for user input + println!("\nProgram finished successfully in {}ms\nPress enter to exit...", t_final); + let mut input = String::new(); std::io::stdin().read_line(&mut input).unwrap(); () } \ No newline at end of file diff --git a/src/craft.rs b/src/craft.rs index 242d66e..f45a794 100644 --- a/src/craft.rs +++ b/src/craft.rs @@ -3,7 +3,6 @@ use crate::action::Action; use crate::specs::{Buff, BuffState, Recipe, Stats, Success}; use crate::Parameters; - #[derive(Clone)] pub struct Craft<'a> { pub recipe: Recipe, @@ -70,6 +69,20 @@ impl<'a> Craft<'a> { self.actions.push(action); return self; } + + // Assumes the craft is finished and tries to add the last actions + // pub fn add_last_actions(&mut self)->&Self{ + // let arg = (self.recipe.progress as f32 - self.progression as f32) / self.get_base_progression() as f32; + // self.durability+=10; + // if 0.0 < arg && arg < 1.2 { self.run_action(&ACTIONS.basic_synthesis);} + // if 1.2 <= arg && arg < 1.8 { self.cp+=7; self.run_action(&ACTIONS.careful_synthesis); } + // if 1.8 <= arg && arg < 2.0 { + // self.cp+=12; + // self.run_action(&ACTIONS.observe); + // self.run_action(&ACTIONS.focused_synthesis); + // } + // self + // } } impl<'a> Debug for Craft<'a> { diff --git a/src/io.rs b/src/io.rs new file mode 100644 index 0000000..af0c153 --- /dev/null +++ b/src/io.rs @@ -0,0 +1,225 @@ +use crate::Craft; +use core::fmt::Display; +use clap::Parser; + +#[cfg(not(feature="no_python"))] +use pyo3::prelude::*; + +#[derive(Debug, Clone, Copy)] +pub struct Parameters { + pub threads: usize, + pub verbose: u8, + pub depth: u32, + pub desperate:bool, + pub byregot_step: u8, +} + +#[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 + #[arg(short, long, default_value_t = 4)] + pub threads: usize, + + /// Desperate mode, will try to finish the craft above all + #[arg(short='D', long, default_value_t = false)] + pub desperate: bool, + + /// Long mode, will try to find more solutions, at the expense of time + #[arg(short='l', long, default_value_t = false)] + pub long: bool, +} + + +/// A final stripped down version of a craft +/// used for final print and talking with python +#[derive(Debug)] +#[pyclass] +pub struct SolverResult{ + #[pyo3(get)] + pub steps: u32, + #[pyo3(get)] + pub quality: u32, + #[pyo3(get)] + pub progression: u32, + #[pyo3(get)] + pub durability: i32, + #[pyo3(get)] + pub cp:i32, + #[pyo3(get)] + pub total_cp:u32, + #[pyo3(get)] + pub total_progression:u32, + #[pyo3(get)] + pub total_quality:u32, + #[pyo3(get)] + pub total_durability:u32, + #[pyo3(get)] + pub actions: Vec, + #[pyo3(get)] + pub step1_solutions: usize, + #[pyo3(get)] + pub step2_solutions: usize, + #[pyo3(get)] + pub found_100_percent: bool, +} + +/// Pretty display for SolverResult +impl Display for SolverResult{ + fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { + println!("{:?}",self.actions); + Ok(()) + } +} + +//#[pymethods] +impl SolverResult{ + pub fn from_craft(craft: & Craft,step1_solutions : usize,step2_solutions : usize, found_100_percent: bool)->SolverResult{ + // Todo: recreate actions + // Where steps ? + let mut actions = craft.actions.iter().map(|action| + format!("{}",action.short_name) + ).collect::>(); + let arg = (craft.recipe.progress as f32 - craft.progression as f32) / craft.get_base_progression() as f32; + if 0.0 < arg && arg < 1.2 { actions.push("basicSynth2".to_string()); } + if 1.2 <= arg && arg < 1.8 { actions.push("carefulSynthesis".to_string()); } + if 1.8 <= arg && arg < 2.0 { + actions.push("observe".to_string()); + actions.push("focusedSynthesis".to_string()); + } + SolverResult{ + steps:craft.step_count, + progression: craft.progression, + quality:craft.quality, + durability:craft.durability, + actions:actions, + step1_solutions, + step2_solutions, + found_100_percent, + total_progression:craft.recipe.progress, + total_quality:craft.recipe.quality, + total_durability:craft.recipe.durability, + cp: craft.cp, + total_cp : craft.stats.max_cp, + } + + } +} + +#[pymethods] +impl SolverResult{ + #[staticmethod] + pub fn default()->Self{ + Self{ + steps:0, + progression: 0, + quality:0, + durability:0, + total_progression:0, + total_quality:0, + total_durability:0, + actions:vec!["Act1".to_string(),"Act2".to_string()], + step1_solutions:0, + step2_solutions:0, + found_100_percent:false, + cp:0, + total_cp:0, + } + } + + pub fn pretty_print(&self){ + println!("Quality: [{}/{}] | Durability: [{}/{}] | Cp : [{}/{}] | Steps : {}", + self.quality, self.total_quality, self.durability, self.total_durability, self.cp, self.total_cp, self.steps); + println!("{:?}", self.actions); + } +} + +impl Parameters{ + pub fn from_args(args:& Args) -> Self{ + Self{ + depth: if args.desperate{11}else{8}, + threads: args.threads, + verbose: args.verbose, + desperate: args.desperate, + byregot_step: if args.long{6}else{8} + } + } +} + + +////// Python Bindings ////// + +/// A Python module implemented in Rust. +#[cfg(not(feature="no_python"))] +#[pymodule] +fn xiv_craft_solver(_py: Python, m: &PyModule) -> PyResult<()> { + m.add_function(wrap_pyfunction!(test_result, m)?)?; + m.add_function(wrap_pyfunction!(solve_from_python, m)?)?; + Ok(()) +} + +/// +#[cfg(not(feature="no_python"))] +#[pyfunction] +pub fn test_result()-> SolverResult { + SolverResult::default() +} + +/// Create a stat struct stats with the base values +#[cfg(not(feature="no_python"))] +use crate::{Recipe,Stats,solve_craft}; + +#[cfg(not(feature="no_python"))] +#[pyfunction] +pub fn solve_from_python(values : &PyAny)->PyResult>>{ + // // Create Recipe + let recipe = Recipe{ + durability: values.getattr("durability")?.extract()?, + progress: values.getattr("progress")?.extract()?, + progress_divider: values.getattr("progress_divider")?.extract()?, + progress_modifier: values.getattr("progress_modifier")?.extract()?, + quality: values.getattr("quality")?.extract()?, + quality_divider:values.getattr("quality_divider")?.extract()?, + quality_modifier:values.getattr("quality_modifier")?.extract()?, + }; + + // Create Stats + let stats = Stats{ + craftsmanship: values.getattr("craftsmanship")?.extract()?, + control: values.getattr("control")?.extract()?, + max_cp: values.getattr("max_cp")?.extract()?, + }; + + // Create parameters + let param = Parameters{ + depth: values.getattr("depth")?.extract()?, + byregot_step: values.getattr("byregot_step")?.extract()?, + desperate: values.getattr("desperate")?.extract()?, + threads: values.getattr("threads")?.extract()?, + verbose: values.getattr("verbose")?.extract()?, + }; + + // println!("{:?} len: {:?} ",values,values.getattr("len()")); + let res = solve_craft(recipe, stats, param); + Ok(res) +} \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 536c3b6..fdd70c2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,98 +1,42 @@ +use crate::io::SolverResult; use crate::{ craft::Craft, specs::{Recipe,Stats}, + io::Parameters, }; -use std::time::{Instant}; use threadpool::ThreadPool; use std::sync::{Arc,Mutex}; -use clap::Parser; -use pyo3::prelude::*; mod solver; mod specs; pub mod action; pub mod craft; +pub mod io; - -#[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, -} - -#[pyfunction] -pub fn pouet()-> &'static str { - return "pouet"; -} - -/// A Python module implemented in Rust. -#[pymodule] -fn xiv_craft_solver(_py: Python, m: &PyModule) -> PyResult<()> { - m.add_function(wrap_pyfunction!(pouet, m)?)?; - Ok(()) -} - -/// Solve the craft with given arguments -pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Option>>{ +/// Solve the craft with given arguments, this functions calls threads and must own it's values +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); #[cfg(feature = "verbose")] if params.verbose>0{ - println!("Solving...\n"); println!("[P1] Starting phase 1..."); } + let phase1_routes = solver::generate_routes_phase1(craft); - + let nb_p1 = phase1_routes.len(); + #[cfg(feature = "verbose")] 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, - ); - }; - } + if params.verbose>1{ for r in &phase1_routes{ + println!("[P1] {:?} p:{}% q:{}% c:{} d:{}",r.actions,r.progression,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())); @@ -100,92 +44,46 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti let _phase2_routes = Arc::clone(&arc_phase2_routes); pool.execute(move || { - if let Some(_route) = solver::generate_routes_phase2(route){ + if let Some(mut _route) = solver::generate_routes_phase2(route){ let mut shared = _phase2_routes.lock().unwrap(); - shared.push(_route); + shared.append(&mut _route); }; }); } pool.join(); let phase2_routes = arc_phase2_routes.lock().unwrap(); - + let nb_p2 = phase2_routes.len(); + + // Drop on empty results + if phase2_routes.len()==0{ + return None + } + // Print the results if verbose #[cfg(feature = "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); - }; - } + 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![]; + // Prune the results for analysis + // let mut valid_routes : Vec = vec![]; + let mut valid_solutions: Vec = vec![]; for route in phase2_routes.iter(){ if route.quality>=route.recipe.quality{ - valid_routes.push(route.clone()); + // valid_routes.push(route.clone()); + valid_solutions.push(SolverResult::from_craft(route,nb_p1,nb_p2,true)); } } - - if valid_routes.len()==0{ - for route in phase2_routes.iter(){valid_routes.push(route.clone())} // Deep copy through the mutex guard + // If no craft can make it to 100% HQ, fallback to base results + if valid_solutions.len()==0{ + for route in phase2_routes.iter(){valid_solutions.push(SolverResult::from_craft(route,nb_p1,nb_p2,false));} } - - // Select best route TODO: Seperate function - let top_route = match valid_routes.iter().max_by_key(|route| route.quality) { - Some(top) => top, - None => { - #[cfg(feature = "verbose")] - 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()); - } - - #[cfg(feature = "verbose")] - 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) + Some(valid_solutions) } /// Load the config from args and make a craft from it @@ -254,6 +152,49 @@ pub fn load_from_config<'a>(recipe_name: &str, file_name: &str, character_name: (recipe,stats) } -// fn make_craft_from_values(){ +/// Print all routes in the vect, verbose +pub fn print_routes<'a>(routes: & Option>){ + match routes{ + Some(r) => { + println!("Showing {} routes",r.len()); + for c in r.iter(){ + println!("\n[{}¤][{}@][{}#] {:?} ",c.quality,c.durability,c.steps,c.actions) + } + }, + None => println!("No routes to print") + } +} -// } \ No newline at end of file +/// Find the route with the least amount of steps +pub fn find_fast_route(routes: &Option>) -> Option<&SolverResult>{ + match routes { + Some(_routes) => { + if _routes.len()>0{ + _routes.iter().min_by_key(|key| key.steps) + } else { None } + }, + None => None, + } +} + +/// Find the route with the maximum amount of quality +pub fn find_quality_route(routes: &Option>) -> Option<&SolverResult>{ + match routes { + Some(_routes) => _routes.iter().max_by_key(|key| key.quality), + None => None, + } +} + +/// Find the route with the maximum of durability left +pub fn find_safe_route(routes: &Option>) -> Option<&SolverResult>{ + match routes { + Some(_routes) => { + if _routes.len()>0{ + _routes.iter().max_by_key(|key| key.durability) + } else { + None + } + }, + None => None, + } +} \ No newline at end of file diff --git a/src/solver.rs b/src/solver.rs index 2730936..f2b6d0d 100644 --- a/src/solver.rs +++ b/src/solver.rs @@ -8,6 +8,7 @@ macro_rules! action_vec { ($($tt:expr),*) => { vec![ $(Some(&$tt),)*]}; } +/// Find the next authorised action for this step of the craft 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(); @@ -30,8 +31,10 @@ pub fn next_action_picker_1<'a>(craft: & Craft<'a>) -> Vec> { available_actions.append(&mut action_vec![ACTIONS.basic_synthesis,ACTIONS.careful_synthesis,ACTIONS.prudent_synthesis,ACTIONS.delicate_synthesis]); // ACTIONS.groundwork for the --pls - // available_actions.append(&mut action_vec![ACTIONS.groundwork]); - + if craft.args.desperate{ + available_actions.append(&mut action_vec![ACTIONS.groundwork]); + } + // For long first run if craft.step_count > 8 {available_actions.append(&mut action_vec![ACTIONS.waste_not_ii, ACTIONS.waste_not])}; @@ -46,6 +49,8 @@ pub fn next_action_picker_1<'a>(craft: & Craft<'a>) -> Vec> { result_actions } + +/// Find all routes that can finish in one more action pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec> { let mut queue = Vec::new(); queue.push(craft); @@ -80,7 +85,6 @@ pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec> { // 8 Seemed to be a good initial guess with enouth to use a good amount of WN / WNII to get close // 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.args.depth { queue.push(craft); } } } @@ -88,6 +92,7 @@ pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec> { } +/// Find the list of authorised actions for this step 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(); @@ -125,7 +130,7 @@ pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec> { forbidden_actions.push(&ACTIONS.basic_touch); } // Todo, allow earlier byregot if the craft can be finished all the same (useless with always optimize on) - if craft.buffs.inner_quiet >= 8 { // 10 + if craft.buffs.inner_quiet >= craft.args.byregot_step { // 10 available_actions.push(&ACTIONS.trained_finesse); available_actions.push(&ACTIONS.great_strides); } @@ -137,8 +142,7 @@ pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec> { } } let mut final_actions: Vec> = Vec::new(); - //drop duplicates - + for action in available_actions { if !forbidden_actions.contains(&action) && !final_actions.iter().any(|a| a.unwrap() == action) { final_actions.push(Some(action)); @@ -147,12 +151,14 @@ pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec> { final_actions } -pub fn generate_routes_phase2<'a>(craft: Craft<'a>) -> Option> { +/// Apply all actions to the current route +pub fn generate_routes_phase2<'a>(craft: Craft<'a>) -> Option>> { let mut queue = VecDeque::new(); - // println!("{}", ACTIONS.careful_synthesis.can_use(&craft)); - let mut top_route: Option> = Some(craft.clone()); // Default route, no hq on that one - + // Todo: Return a vec of relevant functions, instead of the most quality one + let mut top_route: Craft<'a> = craft.clone(); // Default route, no hq on that one + let mut top_routes: Vec> = vec![]; + queue.push_back(craft); while !queue.is_empty() { @@ -164,18 +170,21 @@ pub fn generate_routes_phase2<'a>(craft: Craft<'a>) -> Option> { let mut craft = _craft.clone(); craft.run_action(action.unwrap()); if action.unwrap() == &ACTIONS.byregot_blessing { - if let Some(top_route) = &mut top_route { - if top_route.quality < craft.quality { - // TODO: Should we erase the craft if the improvement is cosmetic (aka, already finished) - *top_route = craft; - } - } else { - top_route = Some(craft); + #[cfg(not(feature="fast"))] + if top_route.quality>=craft.recipe.quality{ + top_routes.push(craft.clone()); // Me memory + } + if top_route.quality < craft.quality { + #[cfg(feature="fast")] + top_routes.push(craft.clone()); + top_route = craft; } } else { queue.push_back(craft); } } } - top_route + // Let's not forget the best result + top_routes.push(top_route); + Some(top_routes) } \ No newline at end of file diff --git a/src/specs.rs b/src/specs.rs index cf5454e..8379d5f 100644 --- a/src/specs.rs +++ b/src/specs.rs @@ -33,7 +33,7 @@ pub enum Buff { // v Hidden v BasicTouch, StandardTouch, - // Observe, + Observe, } #[derive(Debug, Clone, Copy)] @@ -47,6 +47,7 @@ pub struct BuffState { pub muscle_memory: u8, pub basic_touch: u8, pub standard_touch: u8, + pub observe: u8, } impl BuffState { @@ -61,6 +62,7 @@ impl BuffState { muscle_memory: 0, basic_touch: 0, standard_touch: 0, + observe: 0, } } @@ -75,6 +77,7 @@ impl BuffState { Buff::MuscleMemory => self.muscle_memory = 0, Buff::BasicTouch => self.basic_touch = 0, Buff::StandardTouch => self.standard_touch = 0, + Buff::Observe => self.observe = 0, } } @@ -95,11 +98,11 @@ impl BuffState { Buff::MuscleMemory => self.muscle_memory = value, Buff::BasicTouch => self.basic_touch = value, Buff::StandardTouch => self.standard_touch = value, + Buff::Observe => self.standard_touch = value, } } pub fn tick(&mut self) { - if self.waste_not > 0 { self.waste_not -= 1; } if self.great_strides > 0 { self.great_strides -= 1; } if self.innovation > 0 { self.innovation -= 1; }