-
Notifications
You must be signed in to change notification settings - Fork 8
/
pyttanko.py
executable file
·1384 lines (1046 loc) · 37.5 KB
/
pyttanko.py
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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
osu! pp and difficulty calculator.
pure python implementation of oppai-ng
this is meant to be used as a completely standalone python module,
more portable and easier to use than bindings.
this is over 10 times slower than the C version, so if you need to
calculate hundreds or thousands of scores you should consider
using the C version or making python bindings for it.
for comparison, the C version runs through the test suite (~12k
unique scores) in ~9-10 seconds on my i7-4790k while pyttanko takes
100+ seconds
if you want a command line interface, check out
https://github.com/Francesco149/oppai-ng
-------------------------------------------------------------------
usage:
put pyttanko.py in your project's folder and import pyttanko
for example usage, check out the __main__ at the bottom of the file
you can run it like:
cat /path/to/map.osu | ./pyttanko.py +HDDT 200x 1m 95%
also, check out "pydoc pyttanko" for full documentation
-------------------------------------------------------------------
this is free and unencumbered software released into the public
domain. check the attached UNLICENSE or http://unlicense.org/
"""
__author__ = "Franc[e]sco <lolisamurai@tfwno.gf>"
__version__ = "2.1.0"
import sys
import math
if sys.version_info[0] < 3:
# hack to force utf-8
reload(sys)
sys.setdefaultencoding("utf-8")
info = sys.stderr.write
class v2f:
"""2D vector with float values"""
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
def __sub__(self, other):
return v2f(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return v2f(self.x * other, self.y * other)
def len(self):
return math.sqrt(self.x * self.x + self.y * self.y)
def __str__(self):
return str(self.__dict__)
def __repr__(self):
return str(self)
def dot(self, other):
return self.x * other.x + self.y * other.y
# -------------------------------------------------------------------------
# beatmap utils
MODE_STD = 0
class circle:
def __init__(self, pos=None):
"""
initializes a circle object.
if pos is None, it will be set to v2f()
"""
if pos == None:
pos = v2f()
self.pos = pos
def __str__(self):
return str(self.__dict__)
def __repr__(self):
return str(self)
class slider:
def __init__(self, pos=None, distance=0.0, repetitions=0):
"""
initializes a slider object.
distance: distance travelled by one repetition (float)
pos: instance of v2f. if None, it will be set to v2f()
"""
if pos == None:
pos = v2f()
self.pos = pos
self.distance = distance
self.repetitions = repetitions
def __str__(self):
return str(self.__dict__)
def __repr__(self):
return str(self)
OBJ_CIRCLE = 1<<0
OBJ_SLIDER = 1<<1
OBJ_SPINNER = 1<<3
class hitobject:
def __init__(self, time=0.0, objtype=OBJ_CIRCLE, data=None):
"""
initializes a new hitobject.
time: start time in milliseconds (float)
data: an instance of circle, slider or None
"""
self.time = time
self.objtype = objtype
self.data = data
self.normpos = v2f()
self.angle = 0.0
self.strains = [ 0.0, 0.0 ]
self.is_single = False
self.delta_time = 0.0
self.d_distance = 0.0
def typestr(self):
res = ""
if self.objtype & OBJ_CIRCLE != 0:
res += "circle | "
if self.objtype & OBJ_SLIDER != 0:
res += "slider | "
if self.objtype & OBJ_SPINNER != 0:
res += "spinner | "
return res[0:-3]
def __str__(self):
return (
"""hitobject(time=%g, objtype=%s, data=%s,
normpos=%s, strains=%s, is_single=%s)""" % (
self.time, self.typestr(), str(self.data),
str(self.normpos), str(self.strains),
str(self.is_single)
)
)
def __repr__(self):
return str(self)
class timing:
def __init__(self, time=0.0, ms_per_beat=-100.0, change=False):
"""
initializes a timing point
time: start time in milliseconds (float)
ms_per_beat: float
change: if False, ms_per_beat is -100.0 * bpm_multiplier
"""
self.time = time
self.ms_per_beat = ms_per_beat
self.change = change
def __str__(self):
return str(self.__dict__)
def __repr__(self):
return str(self)
class beatmap:
"""
the bare minimum amount of data about a beatmap to perform
difficulty and pp calculation
fields:
mode: gamemode, see MODE_* constants (integer)
title title_unicode artist artist_unicode
creator: mapper name
version: difficulty name
ncircles, nsliders, nspinners
hp cs od ar (float)
sv tick_rate (float)
hitobjects: list (hitobject)
timing_points: list (timing)
"""
def __init__(self):
# i tried pre-allocating hitobjects and timing_points
# as well as object data.
# it didn't show any appreciable performance improvement
self.format_version = 1
self.hitobjects = []
self.timing_points = []
# these are assumed to be ordered by time low to high
self.reset()
def reset(self):
"""
resets fields to prepare the object to store a new
beatmap. used internally by the parser
"""
self.mode = MODE_STD
self.title = ""
self.title_unicode = ""
self.artist = ""
self.artist_unicode = ""
self.creator = ""
self.version = ""
self.ncircles = self.nsliders = self.nspinners = 0
self.hp = self.cs = self.od = 5
self.ar = None
self.sv = self.tick_rate = 1.0
self.hitobjects[:] = []
self.timing_points[:] = []
def __str__(self):
s = self
return """beatmap(
title="%s", title_unicode="%s"
artist="%s", artist_unicode="%s",
creator="%s", version="%s",
hitobjects=[ %s ],
timing_points=[ %s ],
ncircles=%d, nsliders=%d, nspinners=%d,
hp=%g, cs=%g, od=%g, ar=%g,
sv=%g, tick_rate=%g\n)""" % (
s.title, s.title_unicode, s.artist, s.artist_unicode,
s.creator, s.version,
",\n ".join([str(x) for x in s.hitobjects]),
",\n ".join([str(x) for x in s.timing_points]),
s.ncircles, s.nsliders, s.nspinners, s.hp, s.cs, s.od,
s.ar, s.sv, s.tick_rate
)
def __repr__(self):
return str(self)
def max_combo(self):
res = 0
points = self.timing_points
tindex = -1
tnext = -float("inf")
px_per_beat = None
for obj in self.hitobjects:
if obj.objtype & OBJ_SLIDER == 0:
res += 1
continue
# keep track of the current timing point without
# looping through all of the timing points for every
# object
while tnext != None and obj.time >= tnext:
tindex += 1
if len(points) > tindex + 1:
tnext = points[tindex + 1].time
else:
tnext = None
t = points[tindex]
sv_multiplier = 1.0
if not t.change and t.ms_per_beat < 0:
sv_multiplier = (-100.0 / t.ms_per_beat)
px_per_beat = self.sv * 100.0 * sv_multiplier
if self.format_version < 8:
px_per_beat /= sv_multiplier
# slider ticks
sl = obj.data
num_beats = (
(sl.distance * sl.repetitions) / px_per_beat
)
ticks = int(
math.ceil(
(num_beats - 0.1) /
sl.repetitions * self.tick_rate
)
)
ticks -= 1
ticks *= sl.repetitions
ticks += sl.repetitions + 1
res += max(0, ticks)
return res
# -------------------------------------------------------------------------
# beatmap parser
class parser:
"""
beatmap parser.
fields:
lastline lastpos: last line and token touched (strings)
nline: last line number touched
done: True if the parsing completed successfully
"""
def __init__(self):
self.lastline = ""
self.lastpos = ""
self.nline = 0
self.done = False
def __str__(self):
"""formats parser status if the parsing failed"""
if self.done:
return "parsing successful"
return (
"in line %d\n%s\n> %s\n" % (
self.nline, self.lastline, self.lastpos
)
)
def __repr__(self):
return str(self)
def setlastpos(self, v):
# sets lastpos to v and returns v
# should be used to access any string that can make the
# parser fail
self.lastpos = v
return v
def property(self, line):
# parses PropertyName:Value into a tuple
s = line.split(":")
if len(s) < 2:
raise SyntaxError(
"property must be a pair of ':'-separated values"
)
return (s[0], "".join(s[1:]))
def metadata(self, b, line):
p = self.property(line)
if p[0] == "Title":
b.title = p[1]
elif p[0] == "TitleUnicode":
b.title_unicode = p[1]
elif p[0] == "Artist":
b.artist = p[1]
elif p[0] == "ArtistUnicode":
b.artist_unicode = p[1]
elif p[0] == "Creator":
b.creator = p[1]
elif p[0] == "Version":
b.version = p[1]
def general(self, b, line):
p = self.property(line)
if p[0] == "Mode":
b.mode = int(self.setlastpos(p[1]))
def difficulty(self, b, line):
p = self.property(line)
if p[0] == "CircleSize":
b.cs = float(self.setlastpos(p[1]))
elif p[0] == "OverallDifficulty":
b.od = float(self.setlastpos(p[1]))
elif p[0] == "ApproachRate":
b.ar = float(self.setlastpos(p[1]))
elif p[0] == "HPDrainRate":
b.hp = float(self.setlastpos(p[1]))
elif p[0] == "SliderMultiplier":
b.sv = float(self.setlastpos(p[1]))
elif p[0] == "SliderTickRate":
b.tick_rate = float(self.setlastpos(p[1]))
def timing(self, b, line):
s = line.split(",")
if len(s) > 8:
info("W: timing point with trailing values\n")
elif len(s) < 2:
raise SyntaxError(
"timing point must have at least two fields"
)
t = timing(
time=float(self.setlastpos(s[0])),
ms_per_beat=float(self.setlastpos(s[1]))
)
if len(s) >= 7:
t.change = int(s[6]) != 0
b.timing_points.append(t)
def objects_std(self, b, line):
s = line.split(",")
if len(s) > 11:
info("W: object with trailing values\n")
if len(s) < 5:
raise SyntaxError(
"hitobject must have at least 5 fields"
)
# I already tried calling the constructor with all of the
# values on the fly and it wasn't any faster, don't bother
obj = hitobject()
obj.time = float(self.setlastpos(s[2]))
obj.objtype = int(self.setlastpos(s[3]))
if obj.objtype < 0 or obj.objtype > 255:
raise SyntaxError("invalid hitobject type")
# x,y,...
if obj.objtype & OBJ_CIRCLE != 0:
b.ncircles += 1
c = circle()
c.pos.x = float(self.setlastpos(s[0]))
c.pos.y = float(self.setlastpos(s[1]))
obj.data = c
# ?,?,?,?,?,end_time,custom_sample_banks
elif obj.objtype & OBJ_SPINNER != 0:
b.nspinners += 1
# x,y,time,type,sound_type,points,repetitions,distance,
# per_node_sounds,per_node_samples,custom_sample_banks
elif obj.objtype & OBJ_SLIDER != 0:
if len(s) < 7:
raise SyntaxError(
"slider must have at least 7 fields"
)
b.nsliders += 1
sli = slider()
sli.pos.x = float(self.setlastpos(s[0]))
sli.pos.y = float(self.setlastpos(s[1]))
sli.repetitions = int(self.setlastpos(s[6]))
sli.distance = float(self.setlastpos(s[7]))
obj.data = sli
b.hitobjects.append(obj)
def objects(self, b, line):
if b.mode == MODE_STD:
self.objects_std(b, line)
# TODO: other modes
else:
raise NotImplementedError
def map(self, osu_file, bmap = None):
"""
reads a file object and parses it into a beatmap object
which is then returned.
if bmap is specified, it will be reused as a pre-allocated
beatmap object instead of building a new one, speeding
up parsing slightly because of less allocations
"""
f = osu_file
self.done = False
section = ""
b = bmap
if b == None:
b = beatmap()
else:
b.reset()
for line in osu_file:
self.nline += 1
self.lastline = line
# comments (according to lazer)
if line.startswith(" ") or line.startswith("_"):
continue
line = line.strip()
if line == "":
continue
# c++ style comments
if line.startswith("//"):
continue
# [SectionName]
if line.startswith("["):
section = line[1:-1]
continue
try:
if section == "Metadata":
self.metadata(b, line)
elif section == "General":
self.general(b, line)
elif section == "Difficulty":
self.difficulty(b, line)
elif section == "TimingPoints":
self.timing(b, line)
elif section == "HitObjects":
self.objects(b, line)
else:
OSU_MAGIC = "file format v"
findres = line.strip().find(OSU_MAGIC)
if findres > 0:
b.format_version = int(
line[findres+len(OSU_MAGIC):]
)
except (ValueError, SyntaxError) as e:
info("W: %s\n%s\n" % (e, self))
if b.ar is None:
b.ar = b.od
self.done = True
return b
# -------------------------------------------------------------------------
# mods utils
MODS_NOMOD = 0
MODS_NF = 1<<0
MODS_EZ = 1<<1
MODS_TD = MODS_TOUCH_DEVICE = 1<<2
MODS_HD = 1<<3
MODS_HR = 1<<4
MODS_DT = 1<<6
MODS_HT = 1<<8
MODS_NC = 1<<9
MODS_FL = 1<<10
MODS_SO = 1<<12
def mods_str(mods):
"""
gets string representation of mods, such as HDDT.
returns "nomod" for nomod
"""
if mods == 0:
return "nomod"
res = ""
if mods & MODS_HD != 0: res += "HD"
if mods & MODS_HT != 0: res += "HT"
if mods & MODS_HR != 0: res += "HR"
if mods & MODS_EZ != 0: res += "EZ"
if mods & MODS_TOUCH_DEVICE != 0: res += "TD"
if mods & MODS_NC != 0: res += "NC"
elif mods & MODS_DT != 0: res += "DT"
if mods & MODS_FL != 0: res += "FL"
if mods & MODS_SO != 0: res += "SO"
if mods & MODS_NF != 0: res += "NF"
return res
def mods_from_str(string):
"""
get mods bitmask from their string representation
(touch device is TD)
"""
res = 0
while string != "":
if string.startswith("HD"): res |= MODS_HD
elif string.startswith("HT"): res |= MODS_HT
elif string.startswith("HR"): res |= MODS_HR
elif string.startswith("EZ"): res |= MODS_EZ
elif string.startswith("TD"): res |= MODS_TOUCH_DEVICE
elif string.startswith("NC"): res |= MODS_NC
elif string.startswith("DT"): res |= MODS_DT
elif string.startswith("FL"): res |= MODS_FL
elif string.startswith("SO"): res |= MODS_SO
elif string.startswith("NF"): res |= MODS_NF
else:
string = string[1:]
continue
string = string[2:]
return res
def mods_apply(mods, ar = None, od = None, cs = None, hp = None):
"""
calculates speed multiplier, ar, od, cs, hp with the given
mods applied. returns (speed_mul, ar, od, cs, hp).
the base stats are all optional and default to None. if a base
stat is None, then it won't be calculated and will also be
returned as None.
"""
OD0_MS = 80
OD10_MS = 20
AR0_MS = 1800
AR5_MS = 1200
AR10_MS = 450
OD_MS_STEP = (OD0_MS - OD10_MS) / 10.0
AR_MS_STEP1 = (AR0_MS - AR5_MS) / 5.0
AR_MS_STEP2 = (AR5_MS - AR10_MS) / 5.0
MODS_SPEED_CHANGING = MODS_DT | MODS_HT | MODS_NC
MODS_MAP_CHANGING = MODS_HR | MODS_EZ | MODS_SPEED_CHANGING
if mods & MODS_MAP_CHANGING == 0:
return (1.0, ar, od, cs, hp)
speed_mul = 1.0
if mods & (MODS_DT | MODS_NC) != 0:
speed_mul = 1.5
if mods & MODS_HT != 0:
speed_mul *= 0.75
od_ar_hp_multiplier = 1.0
if mods & MODS_HR != 0:
od_ar_hp_multiplier = 1.4
if mods & MODS_EZ:
od_ar_hp_multiplier *= 0.5
if ar != None:
ar *= od_ar_hp_multiplier
# convert AR into milliseconds
arms = AR5_MS
if ar < 5.0:
arms = AR0_MS - AR_MS_STEP1 * ar
else:
arms = AR5_MS - AR_MS_STEP2 * (ar - 5)
# stats must be capped to 0-10 before HT/DT which brings
# them to a range of -4.42-11.08 for OD and -5-11 for AR
arms = min(AR0_MS, max(AR10_MS, arms))
arms /= speed_mul
# convert back to AR
if arms > AR5_MS:
ar = (AR0_MS - arms) / AR_MS_STEP1
else:
ar = 5.0 + (AR5_MS - arms) / AR_MS_STEP2
if od != None:
od *= od_ar_hp_multiplier
odms = OD0_MS - math.ceil(OD_MS_STEP * od)
odms = min(OD0_MS, max(OD10_MS, odms))
odms /= speed_mul
od = (OD0_MS - odms) / OD_MS_STEP
if cs != None:
if mods & MODS_HR != 0:
cs *= 1.3
if mods & MODS_EZ != 0:
cs *= 0.5
cs = min(10.0, cs)
if hp != None:
hp = min(10.0, hp * od_ar_hp_multiplier)
return (speed_mul, ar, od, cs, hp)
# -------------------------------------------------------------------------
# difficulty calculator
DIFF_SPEED = 0
DIFF_AIM = 1
def d_spacing_weight(difftype, distance, delta_time, prev_distance,
prev_delta_time, angle):
# calculates spacing weight and returns (weight, is_single)
# NOTE: is_single is only computed for DIFF_SPEED
MIN_SPEED_BONUS = 75.0 # ~200BPM 1/4 streams
MAX_SPEED_BONUS = 45.0 # ~330BPM 1/4 streams
ANGLE_BONUS_SCALE = 90
AIM_TIMING_THRESHOLD = 107
SPEED_ANGLE_BONUS_BEGIN = 5 * math.pi / 6
AIM_ANGLE_BONUS_BEGIN = math.pi / 3
# arbitrary thresholds to determine when a stream is spaced
# enough that it becomes hard to alternate
SINGLE_SPACING = 125.0
strain_time = max(delta_time, 50.0)
prev_strain_time = max(prev_delta_time, 50.0)
if difftype == DIFF_AIM:
result = 0.0
if angle is not None and angle > AIM_ANGLE_BONUS_BEGIN:
angle_bonus = math.sqrt(
max(prev_distance - ANGLE_BONUS_SCALE, 0.0) *
pow(math.sin(angle - AIM_ANGLE_BONUS_BEGIN), 2.0) *
max(distance - ANGLE_BONUS_SCALE, 0.0)
)
result = (
1.5 * pow(max(0.0, angle_bonus), 0.99) /
max(AIM_TIMING_THRESHOLD, prev_strain_time)
)
weighted_distance = pow(distance, 0.99)
res = max(result +
weighted_distance / max(AIM_TIMING_THRESHOLD, strain_time),
weighted_distance / strain_time)
return (res, False)
elif difftype == DIFF_SPEED:
is_single = distance > SINGLE_SPACING
distance = min(distance, SINGLE_SPACING)
delta_time = max(delta_time, MAX_SPEED_BONUS)
speed_bonus = 1.0
if delta_time < MIN_SPEED_BONUS:
speed_bonus += pow((MIN_SPEED_BONUS - delta_time) / 40.0, 2)
angle_bonus = 1.0
if angle is not None and angle < SPEED_ANGLE_BONUS_BEGIN:
s = math.sin(1.5 * (SPEED_ANGLE_BONUS_BEGIN - angle))
angle_bonus += s * s / 3.57
if angle < math.pi / 2.0:
angle_bonus = 1.28
if distance < ANGLE_BONUS_SCALE and angle < math.pi / 4.0:
angle_bonus += (
(1.0 - angle_bonus) *
min((ANGLE_BONUS_SCALE - distance) / 10.0, 1.0)
)
elif distance < ANGLE_BONUS_SCALE:
angle_bonus += (
(1.0 - angle_bonus) *
min((ANGLE_BONUS_SCALE - distance) / 10.0, 1.0) *
math.sin((math.pi / 2.0 - angle) * 4.0 / math.pi)
)
res = (
(1 + (speed_bonus - 1) * 0.75) * angle_bonus *
(0.95 + speed_bonus * pow(distance / SINGLE_SPACING, 3.5))
) / strain_time
return (res, is_single)
raise NotImplementedError
DECAY_BASE = [ 0.3, 0.15 ] # strain decay per interval
def d_strain(difftype, obj, prevobj, speed_mul):
# calculates the difftype strain value for a hitobject. stores
# the result in obj.strains[difftype]
# this assumes that normpos is already computed
WEIGHT_SCALING = [ 1400.0, 26.25 ] # balances speed and aim
t = difftype
value = 0.0
time_elapsed = (obj.time - prevobj.time) / speed_mul
obj.delta_time = time_elapsed
decay = pow(DECAY_BASE[t], time_elapsed / 1000.0)
# this implementation doesn't account for sliders
if obj.objtype & (OBJ_SLIDER | OBJ_CIRCLE) != 0:
distance = (obj.normpos - prevobj.normpos).len()
obj.d_distance = distance
value, is_single = d_spacing_weight(t, distance, time_elapsed,
prevobj.d_distance, prevobj.delta_time, obj.angle)
value *= WEIGHT_SCALING[t]
if t == DIFF_SPEED:
obj.is_single = is_single
obj.strains[t] = prevobj.strains[t] * decay + value
class diff_calc:
"""
difficulty calculator.
fields:
total: star rating
aim: aim stars
speed: speed stars
nsingles: number of notes that are considered singletaps by
the difficulty calculator
nsingles_threshold: number of taps slower or equal to the
singletap threshold value
"""
def __init__(self):
self.strains = []
# NOTE: i tried pre-allocating this to 600 elements or so
# and it didn't show appreciable performance improvements
self.reset()
def reset(self):
self.total = 0.0
self.aim = self.aim_difficulty = self.aim_length_bonus = 0.0
self.speed = self.speed_difficulty = self.speed_length_bonus = 0.0
self.nsingles = self.nsingles_threshold = 0
def __str__(self):
return """%g stars (%g aim, %g speed)
%d spacing singletaps
%d taps within singletap threshold""" % (
self.total, self.aim, self.speed, self.nsingles,
self.nsingles_threshold
)
def calc_individual(self, difftype, bmap, speed_mul):
# calculates total strain for difftype. this assumes the
# normalized positions for hitobjects are already present
# max strains are weighted from highest to lowest.
# this is how much the weight decays
DECAY_WEIGHT = 0.9
# strains are calculated by analyzing the map in chunks
# and taking the peak strains in each chunk. this is the
# length of a strain interval in milliseconds
strain_step = 400.0 * speed_mul
objs = bmap.hitobjects
self.strains[:] = []
# first object doesn't generate a strain so we begin with
# an incremented interval end
interval_end = (
math.ceil(objs[0].time / strain_step) * strain_step
)
max_strain = 0.0
t = difftype
for i, obj in enumerate(objs[1:]):
prev = objs[i]
d_strain(difftype, obj, prev, speed_mul)
while obj.time > interval_end:
# add max strain for this interval
self.strains.append(max_strain)
# decay last object's strains until the next
# interval and use that as the initial max strain
decay = pow(
DECAY_BASE[t],
(interval_end - prev.time) / 1000.0
)
max_strain = prev.strains[t] * decay
interval_end += strain_step
max_strain = max(max_strain, obj.strains[t])
# don't forget to add the last strain
self.strains.append(max_strain)
# weight the top strains sorted from highest to lowest
weight = 1.0
total = 0.0
difficulty = 0.0
strains = self.strains
strains.sort(reverse=True)
for strain in strains:
total += pow(strain, 1.2)
difficulty += strain * weight
weight *= DECAY_WEIGHT
return ( difficulty, total )
def calc(self, bmap, mods=MODS_NOMOD, singletap_threshold=125):
"""
calculates difficulty and stores results in self.total,
self.aim, self.speed, self.nsingles,
self.nsingles_threshold.
returns self.
singletap_threshold is the smallest milliseconds interval
that will be considered singletappable, defaults to 125ms
which is 240 bpm 1/2 ((60000 / 240) / 2)
"""
# non-normalized diameter where the small circle size buff
# starts
CIRCLESIZE_BUFF_THRESHOLD = 30.0
STAR_SCALING_FACTOR = 0.0675 # global stars multiplier
# 50% of the difference between aim and speed is added to
# star rating to compensate aim only or speed only maps
EXTREME_SCALING_FACTOR = 0.5
PLAYFIELD_WIDTH = 512.0 # in osu!pixels
playfield_center = v2f(
PLAYFIELD_WIDTH / 2, PLAYFIELD_WIDTH / 2
)
if bmap.mode != MODE_STD:
raise NotImplementedError
self.reset()
# calculate CS with mods
speed_mul, _, _, cs, _ = mods_apply(mods, cs=bmap.cs)
# circle radius
radius = (
(PLAYFIELD_WIDTH / 16.0) *
(1.0 - 0.7 * (cs - 5.0) / 5.0)
)
# positions are normalized on circle radius so that we can
# calc as if everything was the same circlesize
scaling_factor = 52.0 / radius
# low cs buff (credits to osuElements)
if radius < CIRCLESIZE_BUFF_THRESHOLD:
scaling_factor *= (
1.0 + min(CIRCLESIZE_BUFF_THRESHOLD - radius, 5.0) / 50.0
)
playfield_center *= scaling_factor
# calculate normalized positions
objs = bmap.hitobjects
prev1 = None
prev2 = None
i = 0
for obj in objs: