1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
mod difficulty_object;
mod gradual_difficulty;
mod gradual_performance;
mod mania_object;
mod pp;
mod skills;

use std::borrow::Cow;

use crate::{beatmap::BeatmapHitWindows, util::FloatExt, Beatmap, GameMode, Mods, OsuStars};

pub use self::{gradual_difficulty::*, gradual_performance::*, mania_object::ManiaObject, pp::*};

pub(crate) use self::mania_object::ObjectParameters;

use self::{
    difficulty_object::ManiaDifficultyObject,
    skills::{Skill, Strain},
};

const SECTION_LEN: f64 = 400.0;
const STAR_SCALING_FACTOR: f64 = 0.018;

/// Difficulty calculator on osu!mania maps.
///
/// # Example
///
/// ```
/// use rosu_pp::{ManiaStars, Beatmap};
///
/// # /*
/// let map: Beatmap = ...
/// # */
/// # let map = Beatmap::default();
///
/// let difficulty_attrs = ManiaStars::new(&map)
///     .mods(8 + 64) // HDDT
///     .calculate();
///
/// println!("Stars: {}", difficulty_attrs.stars);
/// ```
#[derive(Clone, Debug)]
pub struct ManiaStars<'map> {
    map: Cow<'map, Beatmap>,
    mods: u32,
    passed_objects: Option<usize>,
    clock_rate: Option<f64>,
    is_convert: bool,
}

impl<'map> ManiaStars<'map> {
    /// Create a new difficulty calculator for osu!mania maps.
    #[inline]
    pub fn new(map: &'map Beatmap) -> Self {
        let map = map.convert_mode(GameMode::Mania);
        let is_convert = matches!(map, Cow::Owned(_));

        Self {
            map,
            mods: 0,
            passed_objects: None,
            clock_rate: None,
            is_convert,
        }
    }

    /// Specify mods through their bit values.
    ///
    /// See [https://github.com/ppy/osu-api/wiki#mods](https://github.com/ppy/osu-api/wiki#mods)
    #[inline]
    pub fn mods(mut self, mods: u32) -> Self {
        self.mods = mods;

        self
    }

    /// Amount of passed objects for partial plays, e.g. a fail.
    ///
    /// If you want to calculate the difficulty after every few objects, instead of
    /// using [`ManiaStars`] multiple times with different `passed_objects`, you should use
    /// [`ManiaGradualDifficultyAttributes`](crate::mania::ManiaGradualDifficultyAttributes).
    #[inline]
    pub fn passed_objects(mut self, passed_objects: usize) -> Self {
        self.passed_objects = Some(passed_objects);

        self
    }

    /// Adjust the clock rate used in the calculation.
    /// If none is specified, it will take the clock rate based on the mods
    /// i.e. 1.5 for DT, 0.75 for HT and 1.0 otherwise.
    ///
    /// The value cannot go below 0.001.
    #[inline]
    pub fn clock_rate(mut self, clock_rate: f64) -> Self {
        self.clock_rate = Some(clock_rate.max(0.001));

        self
    }

    /// Specify whether the map is a convert i.e. an osu!standard map.
    ///
    /// This only needs to be specified if the map was converted manually beforehand.
    #[inline]
    pub fn is_convert(mut self, is_convert: bool) -> Self {
        self.is_convert = is_convert;

        self
    }

    /// Calculate all difficulty related values, including stars.
    #[inline]
    pub fn calculate(self) -> ManiaDifficultyAttributes {
        let is_convert = self.is_convert || matches!(self.map, Cow::Owned(_));

        let clock_rate = self.clock_rate.unwrap_or_else(|| self.mods.clock_rate());

        let BeatmapHitWindows { od: hit_window, .. } = self
            .map
            .attributes()
            .mods(self.mods)
            .converted(is_convert)
            .clock_rate(clock_rate)
            .hit_windows();

        let ManiaResult { strain, max_combo } = calculate_result(self);

        ManiaDifficultyAttributes {
            stars: strain.difficulty_value() * STAR_SCALING_FACTOR,
            hit_window,
            max_combo,
        }
    }

    /// Calculate the skill strains.
    ///
    /// Suitable to plot the difficulty of a map over time.
    #[inline]
    pub fn strains(self) -> ManiaStrains {
        let ManiaResult { strain, .. } = calculate_result(self);

        ManiaStrains {
            section_len: SECTION_LEN,
            strains: strain.strain_peaks,
        }
    }
}

/// The result of calculating the strains on a osu!taiko map.
/// Suitable to plot the difficulty of a map over time.
#[derive(Clone, Debug)]
pub struct ManiaStrains {
    /// Time in ms inbetween two strains.
    pub section_len: f64,
    /// Strain peaks of the strain skill.
    pub strains: Vec<f64>,
}

impl ManiaStrains {
    /// Returns the number of strain peaks per skill.
    #[inline]
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        self.strains.len()
    }
}

fn calculate_result(params: ManiaStars<'_>) -> ManiaResult {
    let ManiaStars {
        map,
        mods,
        passed_objects,
        clock_rate,
        is_convert: _,
    } = params;

    let take = passed_objects.unwrap_or(map.hit_objects.len());
    let total_columns = map.cs.round_even().max(1.0);

    let clock_rate = clock_rate.unwrap_or_else(|| mods.clock_rate());
    let mut strain = Strain::new(total_columns as usize);
    let mut params = ObjectParameters::new(map.as_ref());
    let mut hit_objects = map.hit_objects.iter().take(take);

    let first = match hit_objects.next() {
        Some(h) => ManiaObject::new(h, total_columns, &mut params),
        None => {
            return ManiaResult {
                strain,
                max_combo: 0,
            }
        }
    };

    let diff_objects_iter = hit_objects.enumerate().scan(first, |last, (i, h)| {
        let base = ManiaObject::new(h, total_columns, &mut params);
        let diff_object = ManiaDifficultyObject::new(&base, &*last, clock_rate, i);
        *last = base;

        Some(diff_object)
    });

    let mut diff_objects = Vec::with_capacity(map.hit_objects.len().min(take).saturating_sub(1));
    diff_objects.extend(diff_objects_iter);

    for curr in diff_objects.iter() {
        strain.process(curr, &diff_objects);
    }

    ManiaResult {
        strain,
        max_combo: params.max_combo,
    }
}

struct ManiaResult {
    strain: Strain,
    max_combo: usize,
}

/// The result of a difficulty calculation on an osu!mania map.
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct ManiaDifficultyAttributes {
    /// The final star rating.
    pub stars: f64,
    /// The perceived hit window for an n300 inclusive of rate-adjusting mods (DT/HT/etc).
    pub hit_window: f64,
    /// The maximum achievable combo.
    pub max_combo: usize,
}

impl ManiaDifficultyAttributes {
    /// Return the maximum combo.
    #[inline]
    pub fn max_combo(&self) -> usize {
        self.max_combo
    }
}

/// The result of a performance calculation on an osu!mania map.
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct ManiaPerformanceAttributes {
    /// The difficulty attributes that were used for the performance calculation.
    pub difficulty: ManiaDifficultyAttributes,
    /// The final performance points.
    pub pp: f64,
    /// The difficulty portion of the final pp.
    pub pp_difficulty: f64,
}

impl ManiaPerformanceAttributes {
    /// Return the star value.
    #[inline]
    pub fn stars(&self) -> f64 {
        self.difficulty.stars
    }

    /// Return the performance point value.
    #[inline]
    pub fn pp(&self) -> f64 {
        self.pp
    }

    /// Return the maximum combo of the map.
    #[inline]
    pub fn max_combo(&self) -> usize {
        self.difficulty.max_combo
    }
}

impl From<ManiaPerformanceAttributes> for ManiaDifficultyAttributes {
    #[inline]
    fn from(attributes: ManiaPerformanceAttributes) -> Self {
        attributes.difficulty
    }
}

impl<'map> From<OsuStars<'map>> for ManiaStars<'map> {
    #[inline]
    fn from(osu: OsuStars<'map>) -> Self {
        let OsuStars {
            map,
            mods,
            passed_objects,
            clock_rate,
        } = osu;

        Self {
            map: map.convert_mode(GameMode::Mania),
            mods,
            passed_objects,
            clock_rate,
            is_convert: true,
        }
    }
}