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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
use std::{borrow::Cow, cmp};

use rosu_map::section::general::GameMode;

use self::calculator::OsuPerformanceCalculator;

pub use self::{calculator::PERFORMANCE_BASE_MULTIPLIER, inspect::InspectOsuPerformance};

use crate::{
    Beatmap,
    any::{
        CalculateError, Difficulty, HitResultGenerator, HitResultPriority, InspectablePerformance,
        IntoModePerformance, IntoPerformance, Performance, hitresult_generator::Fast,
    },
    catch::CatchPerformance,
    mania::ManiaPerformance,
    model::{mode::ConvertError, mods::GameMods},
    osu::OsuHitResults,
    taiko::TaikoPerformance,
    util::map_or_attrs::MapOrAttrs,
};

use super::{
    Osu,
    attributes::OsuPerformanceAttributes,
    score_state::{OsuScoreOrigin, OsuScoreState},
};

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

/// Performance calculator on osu!standard maps.
#[derive(Clone, Debug)]
#[must_use]
pub struct OsuPerformance<'map> {
    pub(crate) map_or_attrs: MapOrAttrs<'map, Osu>,
    pub(crate) difficulty: Difficulty,
    pub(crate) acc: Option<f64>,
    pub(crate) combo: Option<u32>,
    pub(crate) large_tick_hits: Option<u32>,
    pub(crate) small_tick_hits: Option<u32>,
    pub(crate) slider_end_hits: Option<u32>,
    pub(crate) n300: Option<u32>,
    pub(crate) n100: Option<u32>,
    pub(crate) n50: Option<u32>,
    pub(crate) misses: Option<u32>,
    pub(crate) legacy_total_score: Option<u32>,
    pub(crate) hitresult_priority: HitResultPriority,
    pub(crate) hitresult_generator: Option<fn(InspectOsuPerformance<'_>) -> OsuHitResults>,
}

// Manual implementation because of the `hitresult_generator` function pointer
impl PartialEq for OsuPerformance<'_> {
    fn eq(&self, other: &Self) -> bool {
        let Self {
            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,
        } = self;

        map_or_attrs == &other.map_or_attrs
            && difficulty == &other.difficulty
            && acc == &other.acc
            && combo == &other.combo
            && large_tick_hits == &other.large_tick_hits
            && small_tick_hits == &other.small_tick_hits
            && slider_end_hits == &other.slider_end_hits
            && n300 == &other.n300
            && n100 == &other.n100
            && n50 == &other.n50
            && misses == &other.misses
            && hitresult_priority == &other.hitresult_priority
            && legacy_total_score == &other.legacy_total_score
    }
}

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

    /// Try to create a new performance calculator for osu! maps.
    ///
    /// Returns `None` if `map_or_attrs` does not belong to osu! i.e.
    /// a [`DifficultyAttributes`] or [`PerformanceAttributes`] of a different
    /// mode.
    ///
    /// See [`OsuPerformance::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::Osu(calc) = map_or_attrs.into_performance() {
            Some(calc)
        } else {
            None
        }
    }

    /// Attempt to convert the map to the specified mode.
    ///
    /// Returns `Err(self)` if no beatmap is contained, i.e. if this
    /// [`OsuPerformance`] was created through attributes or
    /// [`OsuPerformance::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 = "Ok-variant is still larger in size"
    )]
    pub fn try_mode(self, mode: GameMode) -> Result<Performance<'map>, Self> {
        match mode {
            GameMode::Osu => Ok(Performance::Osu(self)),
            GameMode::Taiko => TaikoPerformance::try_from(self).map(Performance::Taiko),
            GameMode::Catch => CatchPerformance::try_from(self).map(Performance::Catch),
            GameMode::Mania => ManiaPerformance::try_from(self).map(Performance::Mania),
        }
    }

    /// Attempt to convert the map to the specified mode.
    ///
    /// If the internal beatmap was already replaced with difficulty
    /// attributes, the map won't be modified.
    ///
    /// To see whether the internal beatmap was replaced, use [`try_mode`]
    /// instead.
    ///
    /// [`try_mode`]: Self::try_mode
    pub fn mode_or_ignore(self, mode: GameMode) -> Performance<'map> {
        match mode {
            GameMode::Osu => Performance::Osu(self),
            GameMode::Taiko => {
                TaikoPerformance::try_from(self).map_or_else(Performance::Osu, Performance::Taiko)
            }
            GameMode::Catch => {
                CatchPerformance::try_from(self).map_or_else(Performance::Osu, Performance::Catch)
            }
            GameMode::Mania => {
                ManiaPerformance::try_from(self).map_or_else(Performance::Osu, Performance::Mania)
            }
        }
    }

    /// 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
    }

    /// Specify the max combo of the play.
    pub const fn combo(mut self, combo: u32) -> Self {
        self.combo = Some(combo);

        self
    }

    /// Specify the priority of hitresults.
    ///
    /// `HitResultPriority::BestCase` sacrifices 300s and n100s to reduce n50s.
    /// `HitResultPriority::WorstCase` does the opposite.
    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<Osu>>(self) -> OsuPerformance<'map> {
        OsuPerformance {
            map_or_attrs: self.map_or_attrs,
            difficulty: self.difficulty,
            acc: self.acc,
            combo: self.combo,
            large_tick_hits: self.large_tick_hits,
            small_tick_hits: self.small_tick_hits,
            slider_end_hits: self.slider_end_hits,
            n300: self.n300,
            n100: self.n100,
            n50: self.n50,
            misses: self.misses,
            hitresult_priority: self.hitresult_priority,
            hitresult_generator: Some(H::generate_hitresults),
            legacy_total_score: self.legacy_total_score,
        }
    }

    /// 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.
    pub fn lazer(mut self, lazer: bool) -> Self {
        self.difficulty = self.difficulty.lazer(lazer);

        self
    }

    /// Specify the amount of "large tick" hits.
    ///
    /// 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 const fn large_tick_hits(mut self, large_tick_hits: u32) -> Self {
        self.large_tick_hits = Some(large_tick_hits);

        self
    }

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

        self
    }

    /// Specify the amount of hit slider ends.
    ///
    /// Only relevant for osu!lazer scores with slider accuracy.
    pub const fn slider_end_hits(mut self, slider_end_hits: u32) -> Self {
        self.slider_end_hits = Some(slider_end_hits);

        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 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
    }

    /// 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 [`OsuPerformance`] multiple times with different
    /// `passed_objects`, you should use [`OsuGradualPerformance`].
    ///
    /// [`OsuGradualPerformance`]: crate::osu::OsuGradualPerformance
    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 AR.
    ///
    /// `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(mut self, ar: f32, fixed: bool) -> Self {
        self.difficulty = self.difficulty.ar(ar, fixed);

        self
    }

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

        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(mut self, hp: f32, fixed: bool) -> Self {
        self.difficulty = self.difficulty.hp(hp, fixed);

        self
    }

    /// 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(mut self, od: f32, fixed: bool) -> Self {
        self.difficulty = self.difficulty.od(od, fixed);

        self
    }

    /// Specify the legacy total score.
    pub const fn legacy_total_score(mut self, legacy_total_score: u32) -> Self {
        self.legacy_total_score = Some(legacy_total_score);

        self
    }

    /// Provide parameters through an [`OsuScoreState`].
    pub const fn state(mut self, state: OsuScoreState) -> Self {
        let OsuScoreState {
            max_combo,
            hitresults,
            legacy_total_score,
        } = state;

        self.combo = Some(max_combo);
        self.legacy_total_score = legacy_total_score;

        self.hitresults(hitresults)
    }

    /// Provide parameters through [`OsuHitResults`].
    #[expect(clippy::needless_pass_by_value, reason = "more convenient")]
    pub const fn hitresults(mut self, hitresults: OsuHitResults) -> Self {
        let OsuHitResults {
            large_tick_hits,
            small_tick_hits,
            slider_end_hits,
            n300,
            n100,
            n50,
            misses,
        } = hitresults;

        self.large_tick_hits = Some(large_tick_hits);
        self.small_tick_hits = Some(small_tick_hits);
        self.slider_end_hits = Some(slider_end_hits);
        self.n300 = Some(n300);
        self.n100 = Some(n100);
        self.n50 = Some(n50);
        self.misses = Some(misses);

        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
    }

    /// Create the [`OsuScoreState`] that will be used for performance
    /// calculation.
    ///
    /// If this [`OsuPerformance`] contained a [`Beatmap`], it will be replaced
    /// by [`OsuDifficultyAttributes`].
    ///
    /// [`Beatmap`]: crate::Beatmap
    /// [`OsuDifficultyAttributes`]: crate::osu::OsuDifficultyAttributes
    pub fn generate_state(&mut self) -> Result<OsuScoreState, 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 [`OsuPerformance::generate_state`] but verifies that the map
    /// was not suspicious.
    pub fn checked_generate_state(&mut self) -> Result<OsuScoreState, 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<OsuPerformanceAttributes, ConvertError> {
        let state = self.generate_state()?;

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

        Ok(attrs)
    }

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

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

        Ok(attrs)
    }

    pub(crate) const fn from_map_or_attrs(map_or_attrs: MapOrAttrs<'map, Osu>) -> Self {
        Self {
            map_or_attrs,
            difficulty: Difficulty::new(),
            acc: None,
            combo: None,
            large_tick_hits: None,
            small_tick_hits: None,
            slider_end_hits: None,
            n300: None,
            n100: None,
            n50: None,
            misses: None,
            hitresult_priority: HitResultPriority::DEFAULT,
            hitresult_generator: None,
            legacy_total_score: None,
        }
    }

    #[expect(
        clippy::result_large_err,
        reason = "Result type serves more as 'Either'"
    )]
    pub(crate) fn try_convert_map(
        map_or_attrs: MapOrAttrs<'map, Osu>,
        mode: GameMode,
        mods: &GameMods,
    ) -> Result<Cow<'map, Beatmap>, MapOrAttrs<'map, Osu>> {
        let MapOrAttrs::Map(map) = map_or_attrs else {
            return Err(map_or_attrs);
        };

        match map {
            Cow::Borrowed(map) => match map.convert_ref(mode, mods) {
                Ok(map) => Ok(map),
                Err(_) => Err(MapOrAttrs::Map(Cow::Borrowed(map))),
            },
            Cow::Owned(mut map) => {
                if map.convert_mut(mode, mods).is_err() {
                    return Err(MapOrAttrs::Map(Cow::Owned(map)));
                }

                Ok(Cow::Owned(map))
            }
        }
    }
}

impl<'map, T: IntoModePerformance<'map, Osu>> From<T> for OsuPerformance<'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 OsuPerformance<'_>) -> OsuScoreState {
    // SAFETY: Ensured by caller
    let attrs = unsafe { perf.map_or_attrs.get_attrs() };

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

    let total_hits = inspect.total_hits();
    let misses = inspect.misses();

    let mut hitresults = match perf.hitresult_generator {
        Some(generator) => generator(inspect),
        None => <Fast as HitResultGenerator<Osu>>::generate_hitresults(inspect),
    };

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

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

    let max_possible_combo = attrs.max_combo.saturating_sub(misses);

    let max_combo = perf.combo.map_or(max_possible_combo, |combo| {
        cmp::min(combo, max_possible_combo)
    });

    perf.combo = Some(max_combo);

    let OsuHitResults {
        large_tick_hits,
        small_tick_hits,
        slider_end_hits,
        n300,
        n100,
        n50,
        misses,
    } = &hitresults;

    perf.slider_end_hits = Some(*slider_end_hits);
    perf.large_tick_hits = Some(*large_tick_hits);
    perf.small_tick_hits = Some(*small_tick_hits);
    perf.n300 = Some(*n300);
    perf.n100 = Some(*n100);
    perf.n50 = Some(*n50);
    perf.misses = Some(*misses);

    OsuScoreState {
        max_combo,
        hitresults,
        legacy_total_score: perf.legacy_total_score,
    }
}

/// # Safety
/// Caller must ensure that the internal [`MapOrAttrs`] contains attributes.
unsafe fn calculate(perf: OsuPerformance<'_>, state: OsuScoreState) -> OsuPerformanceAttributes {
    // SAFETY: Ensured by caller
    let attrs = unsafe { perf.map_or_attrs.into_attrs() };

    let mods = perf.difficulty.get_mods();
    let lazer = perf.difficulty.get_lazer();
    let using_classic_slider_acc = mods.no_slider_head_acc(lazer);

    let origin = match (lazer, using_classic_slider_acc) {
        (false, _) => OsuScoreOrigin::Stable,
        (true, false) => OsuScoreOrigin::WithSliderAcc {
            max_large_ticks: attrs.n_large_ticks,
            max_slider_ends: attrs.n_sliders,
        },
        (true, true) => OsuScoreOrigin::WithoutSliderAcc {
            max_large_ticks: attrs.n_sliders + attrs.n_large_ticks,
            max_small_ticks: attrs.n_sliders,
        },
    };

    let acc = state.hitresults.accuracy(origin);

    let inner = OsuPerformanceCalculator::new(attrs, mods, acc, state, using_classic_slider_acc);

    inner.calculate()
}

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

    use crate::{
        Beatmap,
        any::{DifficultyAttributes, PerformanceAttributes},
        osu::OsuDifficultyAttributes,
        taiko::{TaikoDifficultyAttributes, TaikoPerformanceAttributes},
    };

    use super::*;

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

    const N_OBJECTS: u32 = 601;
    const N_SLIDERS: u32 = 293;
    const N_SLIDER_TICKS: u32 = 15;

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

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

                assert_eq!(
                    (attrs.n_circles, attrs.n_sliders, attrs.n_spinners),
                    (307, 293, 1)
                );
                assert_eq!(
                    attrs.n_circles + attrs.n_sliders + attrs.n_spinners,
                    N_OBJECTS,
                );
                assert_eq!(attrs.n_sliders, N_SLIDERS);
                assert_eq!(attrs.n_large_ticks, N_SLIDER_TICKS);

                attrs
            })
            .to_owned()
    }

    #[test]
    fn hitresults_n300_n100_misses_best() {
        let state = OsuPerformance::from(attrs())
            .combo(500)
            .lazer(true)
            .n300(300)
            .n100(20)
            .misses(2)
            .hitresult_priority(HitResultPriority::BestCase)
            .generate_state()
            .unwrap();

        let expected = OsuHitResults {
            large_tick_hits: N_SLIDER_TICKS,
            small_tick_hits: 0,
            slider_end_hits: N_SLIDERS,
            n300: 300,
            n100: 20,
            n50: 279,
            misses: 2,
        };

        assert_eq!(state.hitresults, expected);
    }

    #[test]
    fn hitresults_n300_n50_misses_best() {
        let state = OsuPerformance::from(attrs())
            .lazer(false)
            .combo(500)
            .n300(300)
            .n50(10)
            .misses(2)
            .hitresult_priority(HitResultPriority::BestCase)
            .generate_state()
            .unwrap();

        let expected = OsuHitResults {
            large_tick_hits: 0,
            small_tick_hits: 0,
            slider_end_hits: 0,
            n300: 300,
            n100: 289,
            n50: 10,
            misses: 2,
        };

        assert_eq!(state.hitresults, expected);
    }

    #[test]
    fn hitresults_n50_misses_worst() {
        let state = OsuPerformance::from(attrs())
            .lazer(true)
            .combo(500)
            .n50(10)
            .misses(2)
            .hitresult_priority(HitResultPriority::WorstCase)
            .generate_state()
            .unwrap();

        let expected = OsuHitResults {
            large_tick_hits: N_SLIDER_TICKS,
            small_tick_hits: 0,
            slider_end_hits: N_SLIDERS,
            n300: 0,
            n100: 589,
            n50: 10,
            misses: 2,
        };

        assert_eq!(state.hitresults, expected);
    }

    #[test]
    fn hitresults_n300_n100_n50_misses_worst() {
        let state = OsuPerformance::from(attrs())
            .lazer(false)
            .combo(500)
            .n300(300)
            .n100(50)
            .n50(10)
            .misses(2)
            .hitresult_priority(HitResultPriority::WorstCase)
            .generate_state()
            .unwrap();

        let expected = OsuHitResults {
            large_tick_hits: 0,
            small_tick_hits: 0,
            slider_end_hits: 0,
            n300: 300,
            n100: 50,
            n50: 249,
            misses: 2,
        };

        assert_eq!(state.hitresults, expected);
    }

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

        let _ = OsuPerformance::new(OsuDifficultyAttributes::default());
        let _ = OsuPerformance::new(OsuPerformanceAttributes::default());
        let _ = OsuPerformance::new(&map);
        let _ = OsuPerformance::new(map.clone());

        let _ = OsuPerformance::try_new(OsuDifficultyAttributes::default()).unwrap();
        let _ = OsuPerformance::try_new(OsuPerformanceAttributes::default()).unwrap();
        let _ =
            OsuPerformance::try_new(DifficultyAttributes::Osu(OsuDifficultyAttributes::default()))
                .unwrap();
        let _ = OsuPerformance::try_new(PerformanceAttributes::Osu(
            OsuPerformanceAttributes::default(),
        ))
        .unwrap();
        let _ = OsuPerformance::try_new(&map).unwrap();
        let _ = OsuPerformance::try_new(map.clone()).unwrap();

        let _ = OsuPerformance::from(OsuDifficultyAttributes::default());
        let _ = OsuPerformance::from(OsuPerformanceAttributes::default());
        let _ = OsuPerformance::from(&map);
        let _ = OsuPerformance::from(map.clone());

        let _ = OsuDifficultyAttributes::default().performance();
        let _ = OsuPerformanceAttributes::default().performance();

        map.convert_mut(GameMode::Taiko, &GameMods::default())
            .unwrap();

        assert!(OsuPerformance::try_new(TaikoDifficultyAttributes::default()).is_none());
        assert!(OsuPerformance::try_new(TaikoPerformanceAttributes::default()).is_none());
        assert!(
            OsuPerformance::try_new(DifficultyAttributes::Taiko(
                TaikoDifficultyAttributes::default()
            ))
            .is_none()
        );
        assert!(
            OsuPerformance::try_new(PerformanceAttributes::Taiko(
                TaikoPerformanceAttributes::default()
            ))
            .is_none()
        );
        assert!(OsuPerformance::try_new(&map).is_none());
        assert!(OsuPerformance::try_new(map).is_none());
    }
}