rosu-pp 4.0.1

Difficulty and performance calculation for osu!
Documentation
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
use rosu_map::section::general::GameMode;

use crate::{
    Difficulty, GameMods,
    any::{CalculateError, HitResultGenerator},
    catch::{Catch, CatchPerformance},
    mania::{Mania, ManiaPerformance},
    model::beatmap::TooSuspicious,
    osu::{Osu, OsuPerformance},
    taiko::{Taiko, TaikoPerformance},
};

use self::into::IntoPerformance;

use super::{attributes::PerformanceAttributes, score_state::ScoreState};

pub mod gradual;
pub mod inspectable;
pub mod into;

const NO_CONVERSION_REQUIRED: &str = "no conversion required";

macro_rules! forward_to_variants {
    ( $self:ident => |$perf:ident| $enum:ident($expr:expr) ) => {
        match $self {
            Self::Osu($perf) => $enum::Osu($expr),
            Self::Taiko($perf) => $enum::Taiko($expr),
            Self::Catch($perf) => $enum::Catch($expr),
            Self::Mania($perf) => $enum::Mania($expr),
        }
    };
}

/// Performance calculator on maps of any mode.
#[derive(Clone, Debug, PartialEq)]
#[must_use]
pub enum Performance<'map> {
    Osu(OsuPerformance<'map>),
    Taiko(TaikoPerformance<'map>),
    Catch(CatchPerformance<'map>),
    Mania(ManiaPerformance<'map>),
}

impl<'map> Performance<'map> {
    /// Create a new performance calculator for any mode.
    ///
    /// The argument `map_or_attrs` must be either
    /// - previously calculated attributes ([`DifficultyAttributes`],
    ///   [`PerformanceAttributes`], or mode-specific attributes like
    ///   [`TaikoDifficultyAttributes`], [`ManiaPerformanceAttributes`], ...)
    /// - a [`Beatmap`] (by reference or value)
    ///
    /// If a map is given, difficulty attributes will need to be calculated
    /// internally which is a costly operation. Hence, passing attributes
    /// should be prefered.
    ///
    /// However, when passing previously calculated attributes, make sure they
    /// have been calculated for the same map and [`Difficulty`] settings.
    /// Otherwise, the final attributes will be incorrect.
    ///
    /// [`Beatmap`]: crate::model::beatmap::Beatmap
    /// [`DifficultyAttributes`]: crate::any::DifficultyAttributes
    /// [`TaikoDifficultyAttributes`]: crate::taiko::TaikoDifficultyAttributes
    /// [`ManiaPerformanceAttributes`]: crate::mania::ManiaPerformanceAttributes
    pub fn new(map_or_attrs: impl IntoPerformance<'map>) -> Self {
        map_or_attrs.into_performance()
    }

    /// Consume the performance calculator and calculate
    /// performance attributes for the given parameters.
    #[expect(clippy::missing_panics_doc, reason = "unreachable")]
    pub fn calculate(self) -> PerformanceAttributes {
        forward_to_variants!(self => |perf| PerformanceAttributes(
            perf.calculate().expect(NO_CONVERSION_REQUIRED)
        ))
    }

    /// Same as [`Performance::calculate`] but verifies that the map is not too
    /// suspicious.
    pub fn checked_calculate(self) -> Result<PerformanceAttributes, TooSuspicious> {
        let map_err = |err| match err {
            CalculateError::Suspicion(err) => err,
            CalculateError::Convert(_) => unreachable!("{}", NO_CONVERSION_REQUIRED),
        };

        let this = match self {
            Self::Osu(o) => PerformanceAttributes::Osu(o.checked_calculate().map_err(map_err)?),
            Self::Taiko(t) => PerformanceAttributes::Taiko(t.checked_calculate().map_err(map_err)?),
            Self::Catch(f) => PerformanceAttributes::Catch(f.checked_calculate().map_err(map_err)?),
            Self::Mania(m) => PerformanceAttributes::Mania(m.checked_calculate().map_err(map_err)?),
        };

        Ok(this)
    }

    /// Attempt to convert the map to the specified mode.
    ///
    /// Returns `Err(self)` if the conversion is incompatible or no beatmap is
    /// contained, i.e. if this [`Performance`] was created through attributes
    /// or [`Performance::generate_state`] was called.
    ///
    /// If the given mode should be ignored in case of an error, use
    /// [`mode_or_ignore`] instead.
    ///
    /// [`mode_or_ignore`]: Self::mode_or_ignore
    #[expect(clippy::result_large_err, reason = "both variants have the same size")]
    pub fn try_mode(self, mode: GameMode) -> Result<Self, Self> {
        match (self, mode) {
            (Self::Osu(o), _) => o.try_mode(mode).map_err(Self::Osu),
            (this @ Self::Taiko(_), GameMode::Taiko)
            | (this @ Self::Catch(_), GameMode::Catch)
            | (this @ Self::Mania(_), GameMode::Mania) => Ok(this),
            (this, _) => Err(this),
        }
    }

    /// Attempt to convert the map to the specified mode.
    ///
    /// If the conversion is incompatible or if the internal beatmap was
    /// already replaced with difficulty attributes, the map won't be modified.
    ///
    /// To see whether the given mode is incompatible or the internal beatmap
    /// was replaced, use [`try_mode`] instead.
    ///
    /// [`try_mode`]: Self::try_mode
    pub fn mode_or_ignore(self, mode: GameMode) -> Self {
        if let Self::Osu(osu) = self {
            osu.mode_or_ignore(mode)
        } else {
            self
        }
    }

    /// Specify mods.
    ///
    /// Accepted types are
    /// - `u32`
    /// - [`rosu_mods::GameModsLegacy`]
    /// - [`rosu_mods::GameMods`]
    /// - [`rosu_mods::GameModsIntermode`]
    /// - [`&rosu_mods::GameModsIntermode`](rosu_mods::GameModsIntermode)
    ///
    /// See <https://github.com/ppy/osu-api/wiki#mods>
    pub fn mods(self, mods: impl Into<GameMods>) -> Self {
        forward_to_variants!(self => |perf| Self(perf.mods(mods)))
    }

    /// Use the specified settings of the given [`Difficulty`].
    pub fn difficulty(self, difficulty: Difficulty) -> Self {
        forward_to_variants!(self => |perf| Self(perf.difficulty(difficulty)))
    }

    /// Amount of passed objects for partial plays, e.g. a fail.
    ///
    /// If you want to calculate the performance after every few objects,
    /// instead of using [`Performance`] multiple times with different
    /// `passed_objects`, you should use [`GradualPerformance`].
    ///
    /// [`GradualPerformance`]: crate::GradualPerformance
    pub fn passed_objects(self, passed_objects: u32) -> Self {
        forward_to_variants!(self => |perf| Self(perf.passed_objects(passed_objects)))
    }

    /// 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.
    ///
    /// | Minimum | Maximum |
    /// | :-----: | :-----: |
    /// | 0.01    | 100     |
    pub fn clock_rate(self, clock_rate: f64) -> Self {
        forward_to_variants!(self => |perf| Self(perf.clock_rate(clock_rate)))
    }

    /// Override a beatmap's set AR.
    ///
    /// Only relevant for osu! and osu!catch.
    ///
    /// `fixed` determines if the given value should be used before
    /// or after accounting for mods, e.g. on `true` the value will be
    /// used as is and on `false` it will be modified based on the mods.
    ///
    /// | Minimum | Maximum |
    /// | :-----: | :-----: |
    /// | -20     | 20      |
    pub fn ar(self, ar: f32, fixed: bool) -> Self {
        match self {
            Self::Osu(o) => Self::Osu(o.ar(ar, fixed)),
            Self::Catch(c) => Self::Catch(c.ar(ar, fixed)),
            Self::Taiko(_) | Self::Mania(_) => self,
        }
    }

    /// Override a beatmap's set CS.
    ///
    /// Only relevant for osu! and osu!catch.
    ///
    /// `fixed` determines if the given value should be used before
    /// or after accounting for mods, e.g. on `true` the value will be
    /// used as is and on `false` it will be modified based on the mods.
    ///
    /// | Minimum | Maximum |
    /// | :-----: | :-----: |
    /// | -20     | 20      |
    pub fn cs(self, cs: f32, fixed: bool) -> Self {
        match self {
            Self::Osu(o) => Self::Osu(o.cs(cs, fixed)),
            Self::Catch(c) => Self::Catch(c.cs(cs, fixed)),
            Self::Taiko(_) | Self::Mania(_) => self,
        }
    }

    /// Override a beatmap's set HP.
    ///
    /// `fixed` determines if the given value should be used before
    /// or after accounting for mods, e.g. on `true` the value will be
    /// used as is and on `false` it will be modified based on the mods.
    ///
    /// | Minimum | Maximum |
    /// | :-----: | :-----: |
    /// | -20     | 20      |
    pub fn hp(self, hp: f32, fixed: bool) -> Self {
        forward_to_variants!(self => |perf| Self(perf.hp(hp, fixed)))
    }

    /// Override a beatmap's set OD.
    ///
    /// `fixed` determines if the given value should be used before
    /// or after accounting for mods, e.g. on `true` the value will be
    /// used as is and on `false` it will be modified based on the mods.
    ///
    /// | Minimum | Maximum |
    /// | :-----: | :-----: |
    /// | -20     | 20      |
    pub fn od(self, od: f32, fixed: bool) -> Self {
        forward_to_variants!(self => |perf| Self(perf.od(od, fixed)))
    }

    /// Adjust patterns as if the HR mod is enabled.
    ///
    /// Only relevant for osu!catch.
    pub fn hardrock_offsets(self, hardrock_offsets: bool) -> Self {
        if let Self::Catch(catch) = self {
            Self::Catch(catch.hardrock_offsets(hardrock_offsets))
        } else {
            self
        }
    }

    /// Provide parameters through a [`ScoreState`].
    pub fn state(self, state: ScoreState) -> Self {
        forward_to_variants!(self => |perf| Self(perf.state(state.into())))
    }

    /// Set the accuracy between `0.0` and `100.0`.
    pub fn accuracy(self, acc: f64) -> Self {
        forward_to_variants!(self => |perf| Self(perf.accuracy(acc)))
    }

    /// Specify the amount of misses of a play.
    pub fn misses(self, n_misses: u32) -> Self {
        forward_to_variants!(self => |perf| Self(perf.misses(n_misses)))
    }

    /// Specify the max combo of the play.
    ///
    /// Irrelevant for osu!mania.
    pub fn combo(self, combo: u32) -> Self {
        match self {
            Self::Osu(o) => Self::Osu(o.combo(combo)),
            Self::Taiko(t) => Self::Taiko(t.combo(combo)),
            Self::Catch(f) => Self::Catch(f.combo(combo)),
            Self::Mania(_) => self,
        }
    }

    /// Specify the priority of hitresults.
    pub fn hitresult_priority(self, priority: HitResultPriority) -> Self {
        match self {
            Self::Osu(o) => Self::Osu(o.hitresult_priority(priority)),
            Self::Taiko(t) => Self::Taiko(t.hitresult_priority(priority)),
            Self::Catch(_) => self,
            Self::Mania(m) => Self::Mania(m.hitresult_priority(priority)),
        }
    }

    /// Specify how hitresults should be generated.
    ///
    /// # Example
    /// ```rust
    /// use rosu_pp::any::hitresult_generator::{Closest, Composable, Fast};
    /// # use rosu_pp::Performance;
    ///
    /// # let map = rosu_pp::catch::CatchDifficultyAttributes::default();
    /// let attrs = Performance::new(map)
    ///     // Use `Closest` for osu!, taiko, and catch, and `Fast` for mania
    ///     .hitresult_generator::<Composable<Closest, Closest, Closest, Fast>>()
    ///     .calculate();
    /// ```
    pub fn hitresult_generator<H>(self) -> Self
    where
        H: HitResultGenerator<Osu>
            + HitResultGenerator<Taiko>
            + HitResultGenerator<Catch>
            + HitResultGenerator<Mania>,
    {
        forward_to_variants!(self => |perf| Self(perf.hitresult_generator::<H>()))
    }

    /// Whether the calculated attributes belong to an osu!lazer or osu!stable
    /// score.
    ///
    /// Defaults to `true`.
    ///
    /// This affects internal accuracy calculation because lazer considers
    /// slider heads for accuracy whereas stable does not.
    ///
    /// Only relevant for osu!standard and osu!mania.
    pub fn lazer(self, lazer: bool) -> Self {
        match self {
            Self::Osu(o) => Self::Osu(o.lazer(lazer)),
            Self::Taiko(_) | Self::Catch(_) => self,
            Self::Mania(m) => Self::Mania(m.lazer(lazer)),
        }
    }

    /// Specify the amount of "large tick" hits.
    ///
    /// Only relevant for osu!standard.
    ///
    /// The meaning depends on the kind of score:
    /// - if set on osu!stable, this value is irrelevant and can be `0`
    /// - if set on osu!lazer *with* slider accuracy, this value is the amount
    ///   of hit slider ticks and repeats
    /// - if set on osu!lazer *without* slider accuracy, this value is the
    ///   amount of hit slider heads, ticks, and repeats
    pub fn large_tick_hits(self, large_tick_hits: u32) -> Self {
        if let Self::Osu(osu) = self {
            Self::Osu(osu.large_tick_hits(large_tick_hits))
        } else {
            self
        }
    }

    /// Specify the amount of "small tick" hits.
    ///
    /// Only relevant for osu!standard lazer scores without slider accuracy. In
    /// that case, this value is the amount of slider tail hits.
    pub fn small_tick_hits(self, small_tick_hits: u32) -> Self {
        if let Self::Osu(osu) = self {
            Self::Osu(osu.small_tick_hits(small_tick_hits))
        } else {
            self
        }
    }

    /// Specify the amount of hit slider ends.
    ///
    /// Only relevant for osu!standard lazer scores with slider accuracy.
    pub fn slider_end_hits(self, slider_end_hits: u32) -> Self {
        if let Self::Osu(osu) = self {
            Self::Osu(osu.slider_end_hits(slider_end_hits))
        } else {
            self
        }
    }

    /// Specify the amount of 300s of a play.
    pub fn n300(self, n300: u32) -> Self {
        match self {
            Self::Osu(o) => Self::Osu(o.n300(n300)),
            Self::Taiko(t) => Self::Taiko(t.n300(n300)),
            Self::Catch(f) => Self::Catch(f.fruits(n300)),
            Self::Mania(m) => Self::Mania(m.n300(n300)),
        }
    }

    /// Specify the amount of 100s of a play.
    pub fn n100(self, n100: u32) -> Self {
        match self {
            Self::Osu(o) => Self::Osu(o.n100(n100)),
            Self::Taiko(t) => Self::Taiko(t.n100(n100)),
            Self::Catch(f) => Self::Catch(f.droplets(n100)),
            Self::Mania(m) => Self::Mania(m.n100(n100)),
        }
    }

    /// Specify the amount of 50s of a play.
    ///
    /// Irrelevant for osu!taiko.
    pub fn n50(self, n50: u32) -> Self {
        match self {
            Self::Osu(o) => Self::Osu(o.n50(n50)),
            Self::Taiko(_) => self,
            Self::Catch(f) => Self::Catch(f.tiny_droplets(n50)),
            Self::Mania(m) => Self::Mania(m.n50(n50)),
        }
    }

    /// Specify the amount of katus of a play.
    ///
    /// Only relevant for osu!catch for which it represents the amount of tiny
    /// droplet misses and osu!mania for which it repesents the amount of n200.
    pub fn n_katu(self, n_katu: u32) -> Self {
        match self {
            Self::Osu(_) | Self::Taiko(_) => self,
            Self::Catch(f) => Self::Catch(f.tiny_droplet_misses(n_katu)),
            Self::Mania(m) => Self::Mania(m.n200(n_katu)),
        }
    }

    /// Specify the amount of gekis of a play.
    ///
    /// Only relevant for osu!mania for which it repesents the
    /// amount of n320.
    pub fn n_geki(self, n_geki: u32) -> Self {
        match self {
            Self::Osu(_) | Self::Taiko(_) | Self::Catch(_) => self,
            Self::Mania(m) => Self::Mania(m.n320(n_geki)),
        }
    }

    /// Specify the legacy total score.
    ///
    /// Only relevant for osu!standard.
    pub fn legacy_total_score(self, legacy_total_score: u32) -> Self {
        match self {
            Self::Osu(o) => Self::Osu(o.legacy_total_score(legacy_total_score)),
            _ => self,
        }
    }

    /// Create the [`ScoreState`] that will be used for performance calculation.
    ///
    /// If this [`Performance`] contained a [`Beatmap`], it will be replaced
    /// by the difficulty attributes of the mode.
    ///
    /// [`Beatmap`]: crate::Beatmap
    #[expect(clippy::missing_panics_doc, reason = "unreachable")]
    pub fn generate_state(&mut self) -> ScoreState {
        match self {
            Self::Osu(o) => o.generate_state().expect(NO_CONVERSION_REQUIRED).into(),
            Self::Taiko(t) => t.generate_state().expect(NO_CONVERSION_REQUIRED).into(),
            Self::Catch(f) => f.generate_state().expect(NO_CONVERSION_REQUIRED).into(),
            Self::Mania(m) => m.generate_state().expect(NO_CONVERSION_REQUIRED).into(),
        }
    }

    /// Same as [`Performance::generate_state`] but verifies that the map was
    /// not suspicious.
    pub fn checked_generate_state(&mut self) -> Result<ScoreState, TooSuspicious> {
        let map_err = |err| match err {
            CalculateError::Suspicion(err) => err,
            CalculateError::Convert(_) => unreachable!("{}", NO_CONVERSION_REQUIRED),
        };

        match self {
            Self::Osu(o) => o.checked_generate_state().map(From::from).map_err(map_err),
            Self::Taiko(t) => t.checked_generate_state().map(From::from).map_err(map_err),
            Self::Catch(f) => f.checked_generate_state().map(From::from).map_err(map_err),
            Self::Mania(m) => m.checked_generate_state().map(From::from).map_err(map_err),
        }
    }
}

/// While generating remaining hitresults, decide how they should be distributed.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum HitResultPriority {
    /// Prioritize good hitresults over bad ones
    BestCase,
    /// Prioritize bad hitresults over good ones
    WorstCase,
}

impl HitResultPriority {
    pub(crate) const DEFAULT: Self = Self::BestCase;
}

impl Default for HitResultPriority {
    fn default() -> Self {
        Self::DEFAULT
    }
}

impl<'a, T: IntoPerformance<'a>> From<T> for Performance<'a> {
    fn from(into: T) -> Self {
        into.into_performance()
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        Beatmap,
        any::DifficultyAttributes,
        catch::{CatchDifficultyAttributes, CatchPerformanceAttributes},
        mania::{ManiaDifficultyAttributes, ManiaPerformanceAttributes},
        osu::{OsuDifficultyAttributes, OsuPerformanceAttributes},
        taiko::{TaikoDifficultyAttributes, TaikoPerformanceAttributes},
    };

    use super::*;

    #[test]
    fn create() {
        let map = Beatmap::from_path("./resources/1028484.osu").unwrap();

        let _ = Performance::new(&map);
        let _ = Performance::new(map.clone());

        let _ = Performance::new(OsuDifficultyAttributes::default());
        let _ = Performance::new(TaikoDifficultyAttributes::default());
        let _ = Performance::new(CatchDifficultyAttributes::default());
        let _ = Performance::new(ManiaDifficultyAttributes::default());

        let _ = Performance::new(OsuPerformanceAttributes::default());
        let _ = Performance::new(TaikoPerformanceAttributes::default());
        let _ = Performance::new(CatchPerformanceAttributes::default());
        let _ = Performance::new(ManiaPerformanceAttributes::default());

        let _ = Performance::new(DifficultyAttributes::Osu(OsuDifficultyAttributes::default()));
        let _ = Performance::new(PerformanceAttributes::Taiko(
            TaikoPerformanceAttributes::default(),
        ));

        let _ = Performance::from(&map);
        let _ = Performance::from(map);

        let _ = Performance::from(OsuDifficultyAttributes::default());
        let _ = Performance::from(TaikoDifficultyAttributes::default());
        let _ = Performance::from(CatchDifficultyAttributes::default());
        let _ = Performance::from(ManiaDifficultyAttributes::default());

        let _ = Performance::from(OsuPerformanceAttributes::default());
        let _ = Performance::from(TaikoPerformanceAttributes::default());
        let _ = Performance::from(CatchPerformanceAttributes::default());
        let _ = Performance::from(ManiaPerformanceAttributes::default());

        let _ = Performance::from(DifficultyAttributes::Osu(OsuDifficultyAttributes::default()));
        let _ = Performance::from(PerformanceAttributes::Taiko(
            TaikoPerformanceAttributes::default(),
        ));

        let _ = DifficultyAttributes::Osu(OsuDifficultyAttributes::default()).performance();
        let _ = PerformanceAttributes::Taiko(TaikoPerformanceAttributes::default()).performance();
    }
}