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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
use rosu_map::section::general::GameMode;

use self::calculator::ManiaPerformanceCalculator;

pub use self::inspect::InspectManiaPerformance;

use crate::{
    Performance,
    any::{
        CalculateError, Difficulty, HitResultGenerator, HitResultPriority, InspectablePerformance,
        IntoModePerformance, IntoPerformance, hitresult_generator::Fast,
    },
    mania::ManiaHitResults,
    model::{mode::ConvertError, mods::GameMods},
    osu::OsuPerformance,
    util::map_or_attrs::MapOrAttrs,
};

use super::{Mania, attributes::ManiaPerformanceAttributes, score_state::ManiaScoreState};

mod calculator;
pub mod gradual;
mod hitresult_generator;
mod inspect;

/// Performance calculator on osu!mania maps.
#[derive(Clone, Debug)]
#[must_use]
pub struct ManiaPerformance<'map> {
    map_or_attrs: MapOrAttrs<'map, Mania>,
    difficulty: Difficulty,
    n320: Option<u32>,
    n300: Option<u32>,
    n200: Option<u32>,
    n100: Option<u32>,
    n50: Option<u32>,
    misses: Option<u32>,
    acc: Option<f64>,
    hitresult_priority: HitResultPriority,
    hitresult_generator: Option<fn(InspectManiaPerformance<'_>) -> ManiaHitResults>,
}

// Manual implementation because of the `hitresult_generator` function pointer
impl PartialEq for ManiaPerformance<'_> {
    fn eq(&self, other: &Self) -> bool {
        let Self {
            map_or_attrs,
            difficulty,
            n320,
            n300,
            n200,
            n100,
            n50,
            misses,
            acc,
            hitresult_priority,
            hitresult_generator: _,
        } = self;

        map_or_attrs == &other.map_or_attrs
            && difficulty == &other.difficulty
            && n320 == &other.n320
            && n300 == &other.n300
            && n200 == &other.n200
            && n100 == &other.n100
            && n50 == &other.n50
            && misses == &other.misses
            && acc == &other.acc
            && hitresult_priority == &other.hitresult_priority
    }
}

impl<'map> ManiaPerformance<'map> {
    /// Create a new performance calculator for osu!mania maps.
    ///
    /// The argument `map_or_attrs` must be either
    /// - previously calculated attributes ([`ManiaDifficultyAttributes`]
    ///   or [`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
    /// [`ManiaDifficultyAttributes`]: crate::mania::ManiaDifficultyAttributes
    pub fn new(map_or_attrs: impl IntoModePerformance<'map, Mania>) -> Self {
        map_or_attrs.into_performance()
    }

    /// Try to create a new performance calculator for osu!mania maps.
    ///
    /// Returns `None` if `map_or_attrs` does not belong to osu!mania i.e.
    /// a [`DifficultyAttributes`] or [`PerformanceAttributes`] of a different
    /// mode.
    ///
    /// See [`ManiaPerformance::new`] for more information.
    ///
    /// [`DifficultyAttributes`]: crate::any::DifficultyAttributes
    /// [`PerformanceAttributes`]: crate::any::PerformanceAttributes
    pub fn try_new(map_or_attrs: impl IntoPerformance<'map>) -> Option<Self> {
        if let Performance::Mania(calc) = map_or_attrs.into_performance() {
            Some(calc)
        } else {
            None
        }
    }

    /// 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(mut self, mods: impl Into<GameMods>) -> Self {
        self.difficulty = self.difficulty.mods(mods);

        self
    }

    /// Use the specified settings of the given [`Difficulty`].
    pub fn difficulty(mut self, difficulty: Difficulty) -> Self {
        self.difficulty = difficulty;

        self
    }

    /// 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 [`ManiaPerformance`] multiple times with different
    /// `passed_objects`, you should use [`ManiaGradualPerformance`].
    ///
    /// [`ManiaGradualPerformance`]: crate::mania::ManiaGradualPerformance
    pub fn passed_objects(mut self, passed_objects: u32) -> Self {
        self.difficulty = self.difficulty.passed_objects(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.
    ///
    /// | Minimum | Maximum |
    /// | :-----: | :-----: |
    /// | 0.01    | 100     |
    pub fn clock_rate(mut self, clock_rate: f64) -> Self {
        self.difficulty = self.difficulty.clock_rate(clock_rate);

        self
    }

    /// Override a beatmap's set HP.
    ///
    /// `with_mods` 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(mut self, hp: f32, with_mods: bool) -> Self {
        self.difficulty = self.difficulty.hp(hp, with_mods);

        self
    }

    /// Override a beatmap's set OD.
    ///
    /// `with_mods` 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(mut self, od: f32, with_mods: bool) -> Self {
        self.difficulty = self.difficulty.od(od, with_mods);

        self
    }

    /// Specify the accuracy of a play between `0.0` and `100.0`.
    /// This will be used to generate matching hitresults.
    pub fn accuracy(mut self, acc: f64) -> Self {
        self.acc = Some(acc.clamp(0.0, 100.0) / 100.0);

        self
    }

    /// Specify the priority of hitresults.
    pub const fn hitresult_priority(mut self, priority: HitResultPriority) -> Self {
        self.hitresult_priority = priority;

        self
    }

    /// Specify how hitresults should be generated.
    pub fn hitresult_generator<H: HitResultGenerator<Mania>>(self) -> ManiaPerformance<'map> {
        ManiaPerformance {
            map_or_attrs: self.map_or_attrs,
            difficulty: self.difficulty,
            n320: self.n320,
            n300: self.n300,
            n200: self.n200,
            n100: self.n100,
            n50: self.n50,
            misses: self.misses,
            acc: self.acc,
            hitresult_priority: self.hitresult_priority,
            hitresult_generator: Some(H::generate_hitresults),
        }
    }

    /// Whether the calculated attributes belong to an osu!lazer or osu!stable
    /// score.
    ///
    /// Defaults to `true`.
    ///
    /// This affects internal hitresult generation because lazer (without `CL`
    /// mod) gives two hitresults per hold note whereas stable only gives one.
    /// It also affect accuracy calculation because stable makes no difference
    /// between perfect (n320) and great (n300) hitresults but lazer (without
    /// `CL` mod) rewards slightly more for perfect hitresults.
    pub fn lazer(mut self, lazer: bool) -> Self {
        self.difficulty = self.difficulty.lazer(lazer);

        self
    }

    /// Specify the amount of 320s of a play.
    pub const fn n320(mut self, n320: u32) -> Self {
        self.n320 = Some(n320);

        self
    }

    /// Specify the amount of 300s of a play.
    pub const fn n300(mut self, n300: u32) -> Self {
        self.n300 = Some(n300);

        self
    }

    /// Specify the amount of 200s of a play.
    pub const fn n200(mut self, n200: u32) -> Self {
        self.n200 = Some(n200);

        self
    }

    /// Specify the amount of 100s of a play.
    pub const fn n100(mut self, n100: u32) -> Self {
        self.n100 = Some(n100);

        self
    }

    /// Specify the amount of 50s of a play.
    pub const fn n50(mut self, n50: u32) -> Self {
        self.n50 = Some(n50);

        self
    }

    /// Specify the amount of misses of a play.
    pub const fn misses(mut self, n_misses: u32) -> Self {
        self.misses = Some(n_misses);

        self
    }

    /// Provide parameters through an [`ManiaScoreState`].
    #[expect(clippy::needless_pass_by_value, reason = "more sensible")]
    pub const fn state(mut self, state: ManiaScoreState) -> Self {
        let ManiaScoreState {
            n320,
            n300,
            n200,
            n100,
            n50,
            misses,
        } = state;

        self.n320 = Some(n320);
        self.n300 = Some(n300);
        self.n200 = Some(n200);
        self.n100 = Some(n100);
        self.n50 = Some(n50);
        self.misses = Some(misses);

        self
    }

    /// Create the [`ManiaScoreState`] that will be used for performance
    /// calculation.
    ///
    /// If this [`ManiaPerformance`] contained a [`Beatmap`], it will be
    /// replaced by [`ManiaDifficultyAttributes`].
    ///
    /// [`Beatmap`]: crate::Beatmap
    /// [`ManiaDifficultyAttributes`]: crate::mania::ManiaDifficultyAttributes
    pub fn generate_state(&mut self) -> Result<ManiaScoreState, ConvertError> {
        self.map_or_attrs.insert_attrs(&self.difficulty)?;

        // SAFETY: We just calculated and inserted the attributes.
        let state = unsafe { generate_state(self) };

        Ok(state)
    }

    /// Same as [`ManiaPerformance::generate_state`] but verifies that the map
    /// was not suspicious.
    pub fn checked_generate_state(&mut self) -> Result<ManiaScoreState, CalculateError> {
        self.map_or_attrs.checked_insert_attrs(&self.difficulty)?;

        // SAFETY: We just calculated and inserted the attributes.
        let state = unsafe { generate_state(self) };

        Ok(state)
    }

    /// Calculate all performance related values, including pp and stars.
    pub fn calculate(mut self) -> Result<ManiaPerformanceAttributes, ConvertError> {
        let state = self.generate_state()?;

        // SAFETY: Attributes are calculated in `generate_state`.
        let attrs = unsafe { self.map_or_attrs.into_attrs() };

        Ok(ManiaPerformanceCalculator::new(attrs, self.difficulty.get_mods(), state).calculate())
    }

    /// Same as [`ManiaPerformance::calculate`] but verifies that the map was
    /// not suspicious.
    pub fn checked_calculate(mut self) -> Result<ManiaPerformanceAttributes, CalculateError> {
        let state = self.checked_generate_state()?;

        // SAFETY: Attributes are calculated in `checked_generate_state`.
        let attrs = unsafe { self.map_or_attrs.into_attrs() };

        Ok(ManiaPerformanceCalculator::new(attrs, self.difficulty.get_mods(), state).calculate())
    }

    pub(crate) const fn from_map_or_attrs(map_or_attrs: MapOrAttrs<'map, Mania>) -> Self {
        Self {
            map_or_attrs,
            difficulty: Difficulty::new(),
            n320: None,
            n300: None,
            n200: None,
            n100: None,
            n50: None,
            misses: None,
            acc: None,
            hitresult_priority: HitResultPriority::DEFAULT,
            hitresult_generator: None,
        }
    }
}

impl<'map> TryFrom<OsuPerformance<'map>> for ManiaPerformance<'map> {
    type Error = OsuPerformance<'map>;

    /// Try to create [`ManiaPerformance`] through [`OsuPerformance`].
    ///
    /// Returns `None` if [`OsuPerformance`] does not contain a beatmap, i.e.
    /// if it was constructed through attributes or
    /// [`OsuPerformance::generate_state`] was called.
    fn try_from(mut osu: OsuPerformance<'map>) -> Result<Self, Self::Error> {
        let mods = osu.difficulty.get_mods();

        let map = match OsuPerformance::try_convert_map(osu.map_or_attrs, GameMode::Mania, mods) {
            Ok(map) => map,
            Err(map_or_attrs) => {
                osu.map_or_attrs = map_or_attrs;

                return Err(osu);
            }
        };

        let OsuPerformance {
            map_or_attrs: _,
            difficulty,
            acc,
            combo: _,
            large_tick_hits: _,
            small_tick_hits: _,
            slider_end_hits: _,
            n300,
            n100,
            n50,
            misses,
            hitresult_priority,
            hitresult_generator: _,
            legacy_total_score: _,
        } = osu;

        Ok(Self {
            map_or_attrs: MapOrAttrs::Map(map),
            difficulty,
            n320: None,
            n300,
            n200: None,
            n100,
            n50,
            misses,
            acc,
            hitresult_priority,
            hitresult_generator: None,
        })
    }
}

impl<'map, T: IntoModePerformance<'map, Mania>> From<T> for ManiaPerformance<'map> {
    fn from(into: T) -> Self {
        into.into_performance()
    }
}

/// # Safety
/// Caller must ensure that the internal [`MapOrAttrs`] contains attributes.
unsafe fn generate_state(perf: &mut ManiaPerformance) -> ManiaScoreState {
    // SAFETY: Ensured by caller
    let attrs = unsafe { perf.map_or_attrs.get_attrs() };

    let inspect = Mania::inspect_performance(perf, attrs);

    let total_hits = inspect.total_hits();

    let mut hitresults = match perf.hitresult_generator {
        Some(generator) => generator(inspect),
        // TODO: use Statistical(?)
        None => <Fast as HitResultGenerator<Mania>>::generate_hitresults(inspect),
    };

    let remain = total_hits.saturating_sub(hitresults.total_hits());

    match perf.hitresult_priority {
        HitResultPriority::BestCase => {
            match (perf.n320, perf.n300, perf.n200, perf.n100, perf.n50) {
                (None, ..) => hitresults.n320 += remain,
                (_, None, ..) => hitresults.n300 += remain,
                (_, _, None, ..) => hitresults.n200 += remain,
                (.., None, _) => hitresults.n100 += remain,
                _ => hitresults.n50 += remain,
            }
        }
        HitResultPriority::WorstCase => {
            match (perf.n50, perf.n100, perf.n200, perf.n300, perf.n320) {
                (None, ..) => hitresults.n50 += remain,
                (_, None, ..) => hitresults.n100 += remain,
                (_, _, None, ..) => hitresults.n200 += remain,
                (.., None, _) => hitresults.n300 += remain,
                _ => hitresults.n320 += remain,
            }
        }
    }

    let ManiaHitResults {
        n320,
        n300,
        n200,
        n100,
        n50,
        misses,
    } = &hitresults;

    perf.n320 = Some(*n320);
    perf.n300 = Some(*n300);
    perf.n200 = Some(*n200);
    perf.n100 = Some(*n100);
    perf.n50 = Some(*n50);
    perf.misses = Some(*misses);

    hitresults
}

#[cfg(test)]
mod tests {
    use std::sync::OnceLock;

    use rosu_map::section::general::GameMode;
    use rosu_mods::{GameMod, generated_mods::ClassicMania};

    use crate::{
        Beatmap,
        any::{DifficultyAttributes, PerformanceAttributes},
        mania::ManiaDifficultyAttributes,
        osu::{OsuDifficultyAttributes, OsuPerformanceAttributes},
    };

    use super::*;

    static ATTRS: OnceLock<ManiaDifficultyAttributes> = OnceLock::new();

    const N_OBJECTS: u32 = 594;
    const N_HOLD_NOTES: u32 = 121;

    fn beatmap() -> Beatmap {
        Beatmap::from_path("./resources/1638954.osu").unwrap()
    }

    fn attrs() -> ManiaDifficultyAttributes {
        ATTRS
            .get_or_init(|| {
                let map = beatmap();
                let attrs = Difficulty::new().calculate_for_mode::<Mania>(&map).unwrap();

                assert_eq!(N_OBJECTS, map.hit_objects.len() as u32);
                assert_eq!(
                    N_HOLD_NOTES,
                    map.hit_objects.iter().filter(|h| !h.is_circle()).count() as u32
                );

                attrs
            })
            .to_owned()
    }

    /// Creates a [`rosu_mods::GameMods`] instance and inserts `CL` if `classic`
    /// is true.
    fn mods(classic: bool) -> rosu_mods::GameMods {
        if classic {
            let mut mods = rosu_mods::GameMods::new();
            mods.insert(GameMod::ClassicMania(ClassicMania::default()));

            mods
        } else {
            rosu_mods::GameMods::new()
        }
    }

    #[test]
    fn hitresults_n320_misses_best() {
        let classic = true;

        let state = ManiaPerformance::from(attrs())
            .lazer(!classic)
            .mods(mods(classic))
            .n320(500)
            .misses(2)
            .hitresult_priority(HitResultPriority::BestCase)
            .generate_state()
            .unwrap();

        let expected = ManiaScoreState {
            n320: 500,
            n300: 92,
            n200: 0,
            n100: 0,
            n50: 0,
            misses: 2,
        };

        assert_eq!(state, expected);
    }

    #[test]
    fn hitresults_n100_n50_misses_worst() {
        let classic = true;

        let state = ManiaPerformance::from(attrs())
            .lazer(!classic)
            .mods(mods(classic))
            .n100(200)
            .n50(50)
            .misses(2)
            .hitresult_priority(HitResultPriority::WorstCase)
            .generate_state()
            .unwrap();

        let expected = ManiaScoreState {
            n320: 0,
            n300: 0,
            n200: 342,
            n100: 200,
            n50: 50,
            misses: 2,
        };

        assert_eq!(state, expected);
    }

    #[test]
    fn create() {
        let mut map = beatmap();

        let _ = ManiaPerformance::new(ManiaDifficultyAttributes::default());
        let _ = ManiaPerformance::new(ManiaPerformanceAttributes::default());
        let _ = ManiaPerformance::new(&map);
        let _ = ManiaPerformance::new(map.clone());

        let _ = ManiaPerformance::try_new(ManiaDifficultyAttributes::default()).unwrap();
        let _ = ManiaPerformance::try_new(ManiaPerformanceAttributes::default()).unwrap();
        let _ = ManiaPerformance::try_new(DifficultyAttributes::Mania(
            ManiaDifficultyAttributes::default(),
        ))
        .unwrap();
        let _ = ManiaPerformance::try_new(PerformanceAttributes::Mania(
            ManiaPerformanceAttributes::default(),
        ))
        .unwrap();
        let _ = ManiaPerformance::try_new(&map).unwrap();
        let _ = ManiaPerformance::try_new(map.clone()).unwrap();

        let _ = ManiaPerformance::from(ManiaDifficultyAttributes::default());
        let _ = ManiaPerformance::from(ManiaPerformanceAttributes::default());
        let _ = ManiaPerformance::from(&map);
        let _ = ManiaPerformance::from(map.clone());

        let _ = ManiaDifficultyAttributes::default().performance();
        let _ = ManiaPerformanceAttributes::default().performance();

        assert!(
            map.convert_mut(GameMode::Osu, &GameMods::default())
                .is_err()
        );

        assert!(ManiaPerformance::try_new(OsuDifficultyAttributes::default()).is_none());
        assert!(ManiaPerformance::try_new(OsuPerformanceAttributes::default()).is_none());
        assert!(
            ManiaPerformance::try_new(
                DifficultyAttributes::Osu(OsuDifficultyAttributes::default())
            )
            .is_none()
        );
        assert!(
            ManiaPerformance::try_new(PerformanceAttributes::Osu(
                OsuPerformanceAttributes::default()
            ))
            .is_none()
        );
    }
}