1
#[warn(missing_docs)]
2

            
3
use crate::Craft;
4
use clap::Parser;
5
use core::fmt::Display;
6

            
7
// #[cfg(not(feature = "no_python"))]
8
use pyo3::prelude::*;
9

            
10
1
#[derive(Debug, Clone, Copy)]
11
pub struct Parameters {
12
    pub threads: usize,
13
    pub verbose: u8,
14
    pub depth: u32,
15
    pub desperate: bool,
16
    pub byregot_step: u8,
17
}
18

            
19
8
#[derive(Parser, Debug, Clone)]
20
#[command(author, version, about, long_about = None)]
21
pub struct Args {
22
    /// Name of the receipe
23
1
    #[arg(short, long, default_value_t = String::from("default_recipe"))]
24
    pub recipe_name: String,
25

            
26
    /// Name of the character
27
1
    #[arg(short, long, default_value_t = String::from("default_character"))]
28
    pub character_name: String,
29

            
30
    /// The ml file name
31
1
    #[arg(short, long, default_value_t = String::from("craft.toml"))]
32
    pub file_name: String,
33

            
34
    /// The verbose flag
35
    #[arg(short, long, action = clap::ArgAction::Count)]
36
    pub verbose: u8,
37

            
38
    /// The depth of the first pass
39
1
    #[arg(short, long, default_value_t = 8)]
40
    pub depth: u32,
41

            
42
    /// Thread counts, default is 4
43
1
    #[arg(short, long, default_value_t = 4)]
44
    pub threads: usize,
45

            
46
    /// Desperate mode, will try to finish the craft above all
47
1
    #[arg(short = 'D', long, default_value_t = false)]
48
    pub desperate: bool,
49

            
50
    /// Long mode, will try to find more solutions, at the expense of time
51
1
    #[arg(short = 'l', long, default_value_t = false)]
52
    pub long: bool,
53
}
54

            
55
/// A final stripped down version of a craft
56
/// used for final print and talking with python
57
1
#[derive(Debug)]
58
#[pyclass]
59
pub struct SolverResult {
60
    #[pyo3(get)]
61
    pub steps: u32,
62
    #[pyo3(get)]
63
    pub quality: u32,
64
    #[pyo3(get)]
65
    pub progression: u32,
66
    #[pyo3(get)]
67
    pub durability: i32,
68
    #[pyo3(get)]
69
    pub cp: i32,
70
    #[pyo3(get)]
71
    pub total_cp: u32,
72
    #[pyo3(get)]
73
    pub total_progression: u32,
74
    #[pyo3(get)]
75
    pub total_quality: u32,
76
    #[pyo3(get)]
77
    pub total_durability: u32,
78
    #[pyo3(get)]
79
    pub actions: Vec<String>,
80
    #[pyo3(get)]
81
    pub step1_solutions: usize,
82
    #[pyo3(get)]
83
    pub step2_solutions: usize,
84
    #[pyo3(get)]
85
    pub found_100_percent: bool,
86
}
87

            
88
/// Pretty display for SolverResult
89
impl Display for SolverResult {
90
2
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
91
2
        write!(f, "{:?}", self.actions)
92
2
    }
93
}
94

            
95
//#[pymethods]
96
impl SolverResult {
97
    pub fn from_craft(
98
        craft: &Craft,
99
        step1_solutions: usize,
100
        step2_solutions: usize,
101
        found_100_percent: bool,
102
    ) -> SolverResult {
103
        let mut actions = craft
104
            .actions
105
            .iter()
106
            .map(|action| format!("{}", action.short_name))
107
            .collect::<Vec<String>>();
108
        let arg = (craft.recipe.progress as f32 - craft.progression as f32)
109
            / craft.get_base_progression() as f32;
110
        if 0.0 < arg && arg < 1.2 {
111
            actions.push("basicSynth2".to_string());
112
        }
113
        if 1.2 <= arg && arg < 1.8 {
114
            actions.push("carefulSynthesis".to_string());
115
        }
116
        if 1.8 <= arg && arg < 2.0 {
117
            actions.push("observe".to_string());
118
            actions.push("focusedSynthesis".to_string());
119
        }
120
        SolverResult {
121
            steps: craft.step_count,
122
            progression: craft.progression,
123
            quality: craft.quality,
124
            durability: craft.durability,
125
            actions: actions,
126
            step1_solutions,
127
            step2_solutions,
128
            found_100_percent,
129
            total_progression: craft.recipe.progress,
130
            total_quality: craft.recipe.quality,
131
            total_durability: craft.recipe.durability,
132
            cp: craft.cp,
133
            total_cp: craft.stats.max_cp,
134
        }
135
    }
136
}
137

            
138
#[pymethods]
139
impl SolverResult {
140
    #[staticmethod]
141
2
    pub fn default() -> Self {
142
2
        Self {
143
2
            steps: 0,
144
2
            progression: 0,
145
2
            quality: 0,
146
2
            durability: 0,
147
2
            total_progression: 0,
148
2
            total_quality: 0,
149
2
            total_durability: 0,
150
2
            actions: vec!["Act1".to_string(), "Act2".to_string()],
151
2
            step1_solutions: 0,
152
2
            step2_solutions: 0,
153
2
            found_100_percent: false,
154
2
            cp: 0,
155
2
            total_cp: 0,
156
2
        }
157
2
    }
158

            
159
1
    pub fn pretty_print(&self) {
160
1
        println!(
161
1
            "Quality: [{}/{}] | Durability: [{}/{}] | Cp : [{}/{}] | Steps : {}",
162
1
            self.quality,
163
1
            self.total_quality,
164
1
            self.durability,
165
1
            self.total_durability,
166
1
            self.cp,
167
1
            self.total_cp,
168
1
            self.steps
169
1
        );
170
1
        println!("{:?}", self.actions);
171
1
    }
172
}
173

            
174
impl Parameters {
175
    pub fn from_args(args: &Args) -> Self {
176
        Self {
177
            depth: if args.desperate { 11 } else { 8 },
178
            threads: args.threads,
179
            verbose: args.verbose,
180
            desperate: args.desperate,
181
            byregot_step: if args.long { 6 } else { 8 },
182
        }
183
    }
184
}
185

            
186
////// Python Bindings //////
187

            
188
/// A Python module implemented in Rust.
189
#[cfg(not(feature = "no_python"))]
190
#[pymodule]
191
fn xiv_csolver_lib(_py: Python, m: &PyModule) -> PyResult<()> {
192
    m.add_function(wrap_pyfunction!(test_result, m)?)?;
193
    m.add_function(wrap_pyfunction!(solve_from_python, m)?)?;
194
    Ok(())
195
}
196

            
197
///
198
#[cfg(not(feature = "no_python"))]
199
#[pyfunction]
200
pub fn test_result() -> SolverResult {
201
    SolverResult::default()
202
}
203

            
204
/// Create a stat struct stats with the base values
205
#[cfg(not(feature = "no_python"))]
206
use crate::{solve_craft, Recipe, Stats};
207

            
208
#[cfg(not(feature = "no_python"))]
209
#[pyfunction]
210
pub fn solve_from_python(values: &PyAny) -> PyResult<Option<Vec<SolverResult>>> {
211
    // // Create Recipe
212
    let recipe = Recipe {
213
        durability: values.getattr("durability")?.extract()?,
214
        progress: values.getattr("progress")?.extract()?,
215
        progress_divider: values.getattr("progress_divider")?.extract()?,
216
        progress_modifier: values.getattr("progress_modifier")?.extract()?,
217
        quality: values.getattr("quality")?.extract()?,
218
        quality_divider: values.getattr("quality_divider")?.extract()?,
219
        quality_modifier: values.getattr("quality_modifier")?.extract()?,
220
    };
221

            
222
    // Create Stats
223
    let stats = Stats {
224
        craftsmanship: values.getattr("craftsmanship")?.extract()?,
225
        control: values.getattr("control")?.extract()?,
226
        max_cp: values.getattr("max_cp")?.extract()?,
227
    };
228

            
229
    // Create parameters
230
    let param = Parameters {
231
        depth: values.getattr("depth")?.extract()?,
232
        byregot_step: values.getattr("byregot_step")?.extract()?,
233
        desperate: values.getattr("desperate")?.extract()?,
234
        threads: values.getattr("threads")?.extract()?,
235
        verbose: values.getattr("verbose")?.extract()?,
236
    };
237

            
238
    // println!("{:?} len: {:?} ",values,values.getattr("len()"));
239
    let res = solve_craft(recipe, stats, param);
240
    Ok(res)
241
}
242

            
243
#[cfg(test)]
244
mod tests {
245
    use crate::io::Args;
246
    use crate::{Parameters, SolverResult};
247
    use pretty_assertions::{assert_eq, assert_ne};
248
    use clap::Parser;
249

            
250
    impl PartialEq for Parameters {
251
1
        fn eq(&self, rhs: &Parameters) -> bool {
252
1
            (self.byregot_step == rhs.byregot_step)
253
1
                & (self.depth == rhs.depth)
254
1
                & (self.desperate == rhs.desperate)
255
1
                & (self.threads == rhs.threads)
256
1
        }
257
    }
258

            
259
1
    #[test]
260
1
    pub fn test_parameters_derived_attributes() {
261
1
        let def = Parameters {
262
1
            byregot_step: 0,
263
1
            depth: 0,
264
1
            desperate: false,
265
1
            threads: 42,
266
1
            verbose: 1,
267
1
        };
268
1
        let def2 = def;
269
1
        let def3 = def2.clone();
270
1

            
271
1
        assert_eq!(def2, def3);
272
1
    }
273

            
274
1
    #[test]
275
1
    pub fn test_display() {
276
1
        let def = SolverResult::default();
277
1
        assert_ne!(def.to_string(), "");
278
1
        assert_eq!(def.to_string(), "[\"Act1\", \"Act2\"]");
279
1
        def.pretty_print();
280
1
    }
281

            
282
1
    #[test]
283
1
    pub fn test_debug() {
284
1
        let def = SolverResult::default();
285
1
        assert_eq!(format!("{:?}", def),"SolverResult { steps: 0, quality: 0, progression: 0, durability: 0, cp: 0, total_cp: 0, total_progression: 0, total_quality: 0, total_durability: 0, actions: [\"Act1\", \"Act2\"], step1_solutions: 0, step2_solutions: 0, found_100_percent: false }");
286
1
    }
287

            
288
1
    #[test]
289
1
    pub fn test_arguments() {
290
1
        // Create false argument parameter
291
1
        let a = Args {
292
1
            character_name: "Bob GZ".to_string(),
293
1
            depth: 77,
294
1
            desperate: false,
295
1
            file_name: "test.toml".to_string(),
296
1
            long: false,
297
1
            recipe_name: "Belladone".to_string(),
298
1
            threads: 11,
299
1
            verbose: 1,
300
1
        };
301
1
        let a2 = a.clone();
302
1
        println!("{:?}",a2);
303
1
        // Test Custom recipe
304
1
        let a3 = Args::parse_from(["ultraman","-r", "recipe","-c","dan","-f","bigfile.toml","-d","45","-t","4","-D","-l","-vvv"]);
305
1
        let _ = Args::parse_from(["-V"]);
306
1
        let _ = Args::parse_from(["-H"]);
307
1
        assert_eq!(a3.recipe_name,"recipe");
308
1
        assert_eq!(a3.character_name,"dan");
309
1
        assert_eq!(a3.file_name,"bigfile.toml");
310
1
        assert_eq!(a3.verbose,3);
311
1
        assert_eq!(a3.depth,45);
312
1
        assert_eq!(a3.threads,4);
313
1
        assert_eq!(a3.desperate,true);
314
1
        assert_eq!(a3.long,true);
315

            
316
        // Test default parameters
317
1
        let a4 = Args::parse_from(["bobGZ"]); 
318
1
        assert_eq!(a4.recipe_name,"default_recipe");
319
1
        assert_eq!(a4.character_name,"default_character");
320
1
        assert_eq!(a4.file_name,"craft.toml");
321
1
        assert_eq!(a4.verbose,0);
322
1
        assert_eq!(a4.depth,8);
323
1
        assert_eq!(a4.threads,4);
324
1
        assert_eq!(a4.desperate,false);
325
1
        assert_eq!(a4.long,false);
326
1
    }
327

            
328
1
    #[test]
329
1
    pub fn test_parameters() {}
330
}