-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSong.py
4397 lines (3666 loc) · 148 KB
/
Song.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
from __future__ import division
from __future__ import print_function
#####################################################################
# -*- coding: iso-8859-1 -*- #
# #
# Frets on Fire #
# Copyright (C) 2006 Sami Kyöstilä #
# 2008 myfingershurt #
# #
# This program is free software; you can redistribute it and/or #
# modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation; either version 2 #
# of the License, or (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, #
# MA 02110-1301, USA. #
#####################################################################
from past.builtins import cmp
from future import standard_library
from functools import reduce
standard_library.install_aliases()
from builtins import zip
from builtins import str
from builtins import range
from past.utils import old_div
from builtins import object
import midi
import Log
import Audio
from Audio import MusicFinished
import Config
import os
import re
import shutil
import math
import Config
import GameEngine
import Resource
#stump: when we completely drop 2.4 support, change this to just "import hashlib"
try:
import hashlib
except ImportError:
import sha
class hashlib(object):
sha1 = sha.sha
import binascii
import cerealizer
import urllib.request, urllib.parse, urllib.error
import Version
import Theme
import copy
import string
import pickle #stump: cerealizer and sqlite3 don't seem to like each other that much...
from Language import _
DEFAULT_BPM = 120.0
DEFAULT_LIBRARY = "songs"
EXP_DIF = 0
HAR_DIF = 1
MED_DIF = 2
EAS_DIF = 3
#MFH - special / global text-event tracks for the separated text-event list variable
TK_SCRIPT = 0 #script.txt events
TK_SECTIONS = 1 #Section events
TK_GUITAR_SOLOS = 2 #Guitar Solo start/stop events
TK_LYRICS = 3 #RB MIDI Lyric events
TK_UNUSED_TEXT = 4 #Unused / other text events
#code for adding tracks, inside song.py:
#self.song.eventTracks[TK_SCRIPT].addEvent(self.abs_time(), event) #MFH - add an event to the script.txt track
#self.song.eventTracks[TK_SECTIONS].addEvent(self.abs_time(), event) #MFH - add an event to the sections track
#self.song.eventTracks[TK_GUITAR_SOLOS].addEvent(self.abs_time(), event) #MFH - add an event to the guitar solos track
#self.song.eventTracks[TK_LYRICS].addEvent(self.abs_time(), event) #MFH - add an event to the lyrics track
#self.song.eventTracks[TK_UNUSED_TEXT].addEvent(self.abs_time(), event) #MFH - add an event to the unused text track
#code for accessing track objects, outside song.py:
#self.song.eventTracks[Song.TK_SCRIPT]
#self.song.eventTracks[Song.TK_SECTIONS]
#self.song.eventTracks[Song.TK_GUITAR_SOLOS]
#self.song.eventTracks[Song.TK_LYRICS]
#self.song.eventTracks[Song.TK_UNUSED_TEXT]
GUITAR_TRACK = 0
RHYTHM_TRACK = 1
DRUM_TRACK = 2
#FOF_TYPE = 0
#GH1_TYPE = 1
#GH2_TYPE = 2
#MFH
MIDI_TYPE_GH = 0 #GH type MIDIs have starpower phrases marked with a long G8 note on that instrument's track
MIDI_TYPE_RB = 1 #RB type MIDIs have overdrive phrases marked with a long G#9 note on that instrument's track
MIDI_TYPE_WT = 2 #WT type MIDIs have six notes and HOPOs marked on F# of the track
#MFH
EARLY_HIT_WINDOW_NONE = 1 #GH1/RB1/RB2 = NONE
EARLY_HIT_WINDOW_HALF = 2 #GH2/GH3/GHA/GH80's = HALF
EARLY_HIT_WINDOW_FULL = 3 #FoF = FULL
GUITAR_PART = 0
RHYTHM_PART = 1
BASS_PART = 2
LEAD_PART = 3
DRUM_PART = 4
VOCAL_PART = 5
PART_SORT = [0,2,3,1,4,5] # these put Lead before Rhythm in menus.
SORT_PART = [0,3,1,2,4,5]
instrumentDiff = {
0 : (lambda a: a.diffGuitar),
1 : (lambda a: a.diffGuitar),
2 : (lambda a: a.diffBass),
3 : (lambda a: a.diffGuitar),
4 : (lambda a: a.diffDrums),
5 : (lambda a: a.diffVocals)
}
class Part(object):
def __init__(self, id, text):
self.id = id
self.text = text
#self.logClassInits = Config.get("game", "log_class_inits")
#if self.logClassInits == 1:
# Log.debug("Part class init (song.py)...")
def __cmp__(self, other):
if isinstance(other, Part):
return cmp(PART_SORT[self.id], PART_SORT[other.id])
else:
return cmp(self.id, other) #if it's not being compared with a part, we probably want its real ID.
def __str__(self):
return self.text
def __repr__(self):
return self.text
parts = {
GUITAR_PART: Part(GUITAR_PART, _("Guitar")),
RHYTHM_PART: Part(RHYTHM_PART, _("Rhythm")),
BASS_PART: Part(BASS_PART, _("Bass")),
LEAD_PART: Part(LEAD_PART, _("Lead")),
DRUM_PART: Part(DRUM_PART, _("Drums")),
VOCAL_PART: Part(VOCAL_PART, _("Vocals")),
}
class Difficulty(object):
def __init__(self, id, text):
self.id = id
self.text = text
#self.logClassInits = Config.get("game", "log_class_inits")
#if self.logClassInits == 1:
# Log.debug("Difficulty class init (song.py)...")
def __cmp__(self, other):
if isinstance(other, Difficulty):
return cmp(self.id, other.id)
else:
return cmp(self.id, other)
def __str__(self):
return self.text
def __repr__(self):
return self.text
difficulties = {
EAS_DIF: Difficulty(EAS_DIF, _("Easy")),
MED_DIF: Difficulty(MED_DIF, _("Medium")),
HAR_DIF: Difficulty(HAR_DIF, _("Hard")),
EXP_DIF: Difficulty(EXP_DIF, _("Expert")),
}
defaultSections = ["Start","1/4","1/2","3/4"]
class SongInfo(object):
def __init__(self, infoFileName, songLibrary = DEFAULT_LIBRARY, allowCacheUsage = False):
self.songName = os.path.basename(os.path.dirname(infoFileName))
self.fileName = infoFileName
self.libraryNam = songLibrary[songLibrary.find(DEFAULT_LIBRARY):]
self.info = Config.MyConfigParser()
self._partDifficulties = {}
self._parts = None
self._midiStyle = None
self.locked = False
#MFH - want to read valid sections from the MIDI in for practice mode selection here:
self._sections = None
self.name = _("NoName")
try:
self.info.read(infoFileName)
except:
pass
self.logClassInits = Config.get("game", "log_class_inits")
if self.logClassInits == 1:
Log.debug("SongInfo class init (song.py): " + self.name)
self.logSections = Config.get("game", "log_sections")
self.logUneditedMidis = Config.get("log", "log_unedited_midis")
self.useUneditedMidis = Config.get("debug", "use_unedited_midis")
if self.useUneditedMidis == 1: #auto
#if os.path.exists(os.path.join(os.path.dirname(self.fileName), "notes-unedited.mid"))
if os.path.isfile(os.path.join(os.path.dirname(self.fileName), "notes-unedited.mid")):
notefile = "notes-unedited.mid"
if self.logUneditedMidis == 1:
Log.debug("notes-unedited.mid found, using instead of notes.mid! - " + self.name)
else:
notefile = "notes.mid"
if self.logUneditedMidis == 1:
Log.debug("notes-unedited.mid not found, using notes.mid - " + self.name)
else:
notefile = "notes.mid"
if self.logUneditedMidis == 1:
Log.debug("notes-unedited.mid not found, using notes.mid - " + self.name)
self.noteFileName = os.path.join(os.path.dirname(self.fileName), notefile)
if not os.path.exists(self.noteFileName):
# It doesn't exist, which means that it was produced from a writable
# path, we need to get the read-only path in this case...
engine = GameEngine.getEngine()
path = Resource.getWritableResourcePath()
if self.noteFileName[:len(path)] == path:
self.noteFileName = engine.resource.fileName(self.noteFileName[len(path)+1:])
# Read highscores and verify their hashes.
# There ain't no security like security throught obscurity :)
self.highScores = {}
self.handle_scores("scores","scores_ext")
self.highScoresRhythm = {}
self.handle_scores("scores_rhythm","scores_rhythm_ext")
self.highScoresBass = {}
self.handle_scores("scores_bass","scores_bass_ext")
self.highScoresLead = {}
self.handle_scores("scores_lead","scores_lead_ext")
self.highScoresDrum = {}
self.handle_scores("scores_drum","scores_drum_ext")
self.highScoresVocal = {}
self.handle_scores("scores_vocal","scores_vocal_ext")
def handle_scores(self,score1,score2):
scores = self._get(score1, str, "")
scores_ext = self._get(score2, str, "")
if scores:
scores = cerealizer.loads(binascii.unhexlify(scores))
if scores_ext:
scores_ext = cerealizer.loads(binascii.unhexlify(scores_ext))
for difficulty in list(scores.keys()):
try:
difficulty = difficulties[difficulty]
except KeyError:
continue
for i, base_scores in enumerate(scores[difficulty.id]):
score, stars, name, hash = base_scores
if scores_ext != "":
#Someone may have mixed extended and non extended
try:
if len(scores_ext[difficulty.id][i]) < 9:
hash_ext, stars2, notesHit, notesTotal, noteStreak, modVersion, oldInfo, oldInfo2 = scores_ext[difficulty.id][i]
handicapValue = 0
longHandicap = "None"
originalScore = 0
else:
hash_ext, stars2, notesHit, notesTotal, noteStreak, modVersion, handicapValue, longHandicap, originalScore = scores_ext[difficulty.id][i]
scoreExt = (notesHit, notesTotal, noteStreak, modVersion, handicapValue, longHandicap, originalScore)
except:
hash_ext = 0
scoreExt = (0, 0, 0 , "RF-mod", 0, "None", 0)
if self.getScoreHash(difficulty, score, stars, name) == hash:
if scores_ext != "" and hash == hash_ext:
self.addHighscore(difficulty, score, stars, name, part = parts[GUITAR_PART], scoreExt = scoreExt)
else:
self.addHighscore(difficulty, score, stars, name, part = parts[GUITAR_PART])
else:
Log.warn("Weak hack attempt detected. Better luck next time.")
def _set(self, attr, value):
if not self.info.has_section("song"):
self.info.add_section("song")
if type(value) == bytes:
value = value.decode('utf-8')
if type(value) != str:
value = str(value)
self.info.set("song", attr, value)
def getObfuscatedScores(self, part = parts[GUITAR_PART]):
s = {}
if part == parts[GUITAR_PART]:
highScores = self.highScores
elif part == parts[RHYTHM_PART]:
highScores = self.highScoresRhythm
elif part == parts[BASS_PART]:
highScores = self.highScoresBass
elif part == parts[LEAD_PART]:
highScores = self.highScoresLead
elif part == parts[DRUM_PART]:
highScores = self.highScoresDrum
elif part == parts[VOCAL_PART]:
highScores = self.highScoresVocal
else:
highScores = self.highScores
for difficulty in list(highScores.keys()):
if isinstance(difficulty, Difficulty):
diff = diff.id
else:
diff = difficulty
s[diff] = [(score, stars, name, self.getScoreHash(difficulty, score, stars, name)) for score, stars, name, scores_ext in highScores[difficulty]]
return binascii.hexlify(cerealizer.dumps(s))
def getObfuscatedScoresExt(self, part = parts[GUITAR_PART]):
s = {}
if part == parts[GUITAR_PART]:
highScores = self.highScores
elif part == parts[RHYTHM_PART]:
highScores = self.highScoresRhythm
elif part == parts[BASS_PART]:
highScores = self.highScoresBass
elif part == parts[LEAD_PART]:
highScores = self.highScoresLead
elif part == parts[DRUM_PART]:
highScores = self.highScoresDrum
elif part == parts[VOCAL_PART]:
highScores = self.highScoresVocal
else:
highScores = self.highScores
for difficulty in list(highScores.keys()):
if isinstance(difficulty, Difficulty):
diff = diff.id
else:
diff = difficulty
s[diff] = [(self.getScoreHash(difficulty, score, stars, name), stars) + scores_ext for score, stars, name, scores_ext in highScores[difficulty]]
return binascii.hexlify(cerealizer.dumps(s))
def save(self):
if self.highScores != {}:
self._set("scores", self.getObfuscatedScores(part = parts[GUITAR_PART]))
self._set("scores_ext", self.getObfuscatedScoresExt(part = parts[GUITAR_PART]))
if self.highScoresRhythm != {}:
self._set("scores_rhythm", self.getObfuscatedScores(part = parts[RHYTHM_PART]))
self._set("scores_rhythm_ext", self.getObfuscatedScoresExt(part = parts[RHYTHM_PART]))
if self.highScoresBass != {}:
self._set("scores_bass", self.getObfuscatedScores(part = parts[BASS_PART]))
self._set("scores_bass_ext", self.getObfuscatedScoresExt(part = parts[BASS_PART]))
if self.highScoresLead != {}:
self._set("scores_lead", self.getObfuscatedScores(part = parts[LEAD_PART]))
self._set("scores_lead_ext", self.getObfuscatedScoresExt(part = parts[LEAD_PART]))
#myfingershurt: drums :)
if self.highScoresDrum != {}:
self._set("scores_drum", self.getObfuscatedScores(part = parts[DRUM_PART]))
self._set("scores_drum_ext", self.getObfuscatedScoresExt(part = parts[DRUM_PART]))
#akedrou
if self.highScoresVocal != {}:
self._set("scores_vocal", self.getObfuscatedScores(part = parts[VOCAL_PART]))
self._set("scores_vocal_ext", self.getObfuscatedScoresExt(part = parts[VOCAL_PART]))
if os.access(os.path.dirname(self.fileName), os.W_OK) == True:
f = open(self.fileName, "w")
self.info.write(f)
f.close()
def _get(self, attr, type = None, default = ""):
try:
v = self.info.get("song", attr)
except:
v = default
if v == "": #key found, but empty - need to catch as int("") will burn.
v = default
if v is not None and type:
v = type(v)
return v
# def getDifficulties(self):
# # Tutorials only have the medium difficulty
# if self.tutorial:
# return [difficulties[HAR_DIF]]
#
# if self._difficulties is not None:
# return self._difficulties
#
# # See which difficulties are available
# try:
#
# noteFileName = self.noteFileName
#
# Log.debug("Retrieving difficulties from: " + noteFileName)
# info = MidiInfoReaderNoSections()
# midiIn = midi.MidiInFile(info, noteFileName)
# try:
# midiIn.read()
# except MidiInfoReaderNoSections.Done:
# pass
# info.difficulties.sort(lambda a, b: cmp(b.id, a.id))
# self._difficulties = info.difficulties
# except:
# self._difficulties = difficulties.values()
# return self._difficulties
def getPartDifficulties(self):
if self._partDifficulties:
return self._partDifficulties
# parsing this implies opening the midi file, which can take time
# so we cache this in the song.ini
if self._get("diff"):
diff = self._get("diff")
diff = diff.replace("Expert","difficulties[0]")
diff = diff.replace("Hard","difficulties[1]")
diff = diff.replace("Medium","difficulties[2]")
diff = diff.replace("Easy","difficulties[3]")
# Just in case the line was altered, or changed for whatever reason...
try:
self._partDifficulties = eval(diff)
except:
pass
if not self._partDifficulties:
self.getParts()
self._set("diff",self._partDifficulties)
self.save()
return self._partDifficulties
partDifficulties = property(getPartDifficulties)
def getMidiStyle(self):
if self._midiStyle is not None:
return self._midiStyle
self.getParts()
return self._midiStyle
midiStyle = property(getMidiStyle)
def getParts(self):
if self._parts is not None:
return self._parts
# See which parts are available
try:
noteFileName = self.noteFileName
Log.debug("Retrieving parts from: " + noteFileName)
info = MidiPartsDiffReader()
midiIn = midi.MidiInFile(info, noteFileName)
midiIn.read()
if info.parts == []:
Log.debug("Improperly named tracks. Attempting to force first track guitar.")
info = MidiPartsDiffReader(forceGuitar = True)
midiIn = midi.MidiInFile(info, noteFileName)
midiIn.read()
if info.parts == []:
Log.warn("No tracks found!")
raise Exception
self._midiStyle = info.midiStyle
info.parts.sort(key=lambda a: -a.id)
self._parts = info.parts
for part in info.parts:
if self.tutorial:
self._partDifficulties[part.id] = [difficulties[HAR_DIF]]
continue
info.difficulties[part.id].sort(key=lambda a: a.id)
self._partDifficulties[part.id] = info.difficulties[part.id]
except:
Log.warn("Note file not parsed correctly. Selected part and/or difficulty may not be available.")
self._parts = list(parts.values())
for part in self._parts:
self._partDifficulties[part.id] = list(difficulties.values())
return self._parts
def getName(self):
return self._get("name")
def setName(self, value):
self._set("name", value)
def getArtist(self):
return self._get("artist")
def getAlbum(self):
return self._get("album")
def getGenre(self):
return self._get("genre")
def getIcon(self):
return self._get("icon")
def getBossBattle(self):
return self._get("boss_battle")
def getDiffSong(self):
return self._get("diff_band", int, -1)
def getDiffGuitar(self):
return self._get("diff_guitar", int, -1)
def getDiffDrums(self):
return self._get("diff_drums", int, -1)
def getDiffBass(self):
return self._get("diff_bass", int, -1)
def getDiffVocals(self):
return self._get("diff_vocals", int, -1)
def getYear(self):
return self._get("year")
def getLoading(self):
return self._get("loading_phrase")
def getCassetteColor(self):
c = self._get("cassettecolor")
if c:
return Theme.hexToColor(c)
def setCassetteColor(self, color):
self._set("cassettecolor", Theme.colorToHex(color))
def setArtist(self, value):
self._set("artist", value)
def setAlbum(self, value):
self._set("album", value)
def setGenre(self, value):
self._set("genre", value)
def setIcon(self, value):
self._set("icon", value)
def setBossBattle(self, value):
self._set("boss_battle", value)
def setDiffSong(self, value):
self._set("diff_band", value)
def setDiffGuitar(self, value):
self._set("diff_guitar", value)
def setDiffDrums(self, value):
self._set("diff_drums", value)
def setDiffBass(self, value):
self._set("diff_bass", value)
def setDiffVocals(self, value):
self._set("diff_vocals", value)
def setYear(self, value):
self._set("year", value)
def setLoading(self, value):
self._set("loading_phrase", value)
def getScoreHash(self, difficulty, score, stars, name):
if isinstance(difficulty, Difficulty):
difficulty = difficulty.id
return hashlib.sha1(str.encode("%d%d%d%s" % (difficulty, score, stars, name))).hexdigest()
def getDelay(self):
return self._get("delay", int, 0)
def setDelay(self, value):
return self._set("delay", value)
def getFrets(self):
return self._get("frets")
def setFrets(self, value):
self._set("frets", value)
def getVersion(self):
return self._get("version")
def setVersion(self, value):
self._set("version", value)
def getTags(self):
return self._get("tags")
def setTags(self, value):
self._set("tags", value)
def getHopo(self):
return self._get("hopo")
def setHopo(self, value):
self._set("hopo", value)
def getCount(self):
return self._get("count")
def setCount(self, value):
self._set("count", value)
def getEighthNoteHopo(self):
return self._get("eighthnote_hopo")
def setEighthNoteHopo(self, value):
self._set("eighthnote_hopo", value)
def getLyrics(self):
return self._get("lyrics")
def setLyrics(self, value):
self._set("lyrics", value)
def getHighscoresWithPartString(self, difficulty, part = str(parts[GUITAR_PART]) ):
if part == str(parts[GUITAR_PART]):
highScores = self.highScores
elif part == str(parts[RHYTHM_PART]):
highScores = self.highScoresRhythm
elif part == str(parts[BASS_PART]):
highScores = self.highScoresBass
elif part == str(parts[LEAD_PART]):
highScores = self.highScoresLead
#myfingershurt: drums :)
elif part == str(parts[DRUM_PART]):
highScores = self.highScoresDrum
elif part == str(parts[VOCAL_PART]): #akedrou - vocals!
highScores = self.highScoresVocal
else:
highScores = self.highScores
try:
return highScores[difficulty.id]
except KeyError:
return []
def getHighscores(self, difficulty, part = parts[GUITAR_PART]):
if part == parts[GUITAR_PART]:
highScores = self.highScores
elif part == parts[RHYTHM_PART]:
highScores = self.highScoresRhythm
elif part == parts[BASS_PART]:
highScores = self.highScoresBass
elif part == parts[LEAD_PART]:
highScores = self.highScoresLead
#myfingershurt: drums :)
elif part == parts[DRUM_PART]:
highScores = self.highScoresDrum
elif part == parts[VOCAL_PART]: #akedrou - vocals!
highScores = self.highScoresVocal
else:
highScores = self.highScores
try:
return highScores[difficulty.id]
except KeyError:
return []
def uploadHighscores(self, url, songHash, part = parts[GUITAR_PART]):
if part == parts[VOCAL_PART]: #not implemented
return False
try:
d = {
"songName": self.songName,
"songHash": songHash,
"scores": self.getObfuscatedScores(part = part),
"scores_ext": self.getObfuscatedScoresExt(part = part),
"version": "%s-3.100" % Version.appNameSexy(),
"songPart": part
}
data = urllib.request.urlopen(url + "?" + urllib.parse.urlencode(d)).read()
Log.debug("Score upload result: %s" % data)
#return data == "True"
return data #MFH - want to return the actual result data.
except Exception as e:
Log.error("Score upload error: %s" % e)
return False
return True
def addHighscore(self, difficulty, score, stars, name, part = parts[GUITAR_PART], scoreExt = (0, 0, 0, "RF-mod", 0, "None", 0)):
if part == parts[GUITAR_PART]:
highScores = self.highScores
elif part == parts[RHYTHM_PART]:
highScores = self.highScoresRhythm
elif part == parts[BASS_PART]:
highScores = self.highScoresBass
elif part == parts[LEAD_PART]:
highScores = self.highScoresLead
#myfingershurt: drums :)
elif part == parts[DRUM_PART]:
highScores = self.highScoresDrum
elif part == parts[VOCAL_PART]: #akedrou - vocals!
highScores = self.highScoresVocal
else:
highScores = self.highScores
if not difficulty.id in highScores:
highScores[difficulty.id] = []
highScores[difficulty.id].append((score, stars, name, scoreExt))
highScores[difficulty.id].sort(key=lambda element: -element[0])
highScores[difficulty.id] = highScores[difficulty.id][:5]
for i, scores in enumerate(highScores[difficulty.id]):
_score, _stars, _name, _scores_ext = scores
if _score == score and _stars == stars and _name == name:
return i
return -1
def isTutorial(self):
return self._get("tutorial", int, 0) == 1
def findTag(self, find, value = None):
for tag in self.tags.split(','):
temp = tag.split('=')
if find == temp[0]:
if value == None:
return True
elif len(temp) == 2 and value == temp[1]:
return True
return False
def getSections(self): #MFH
if self._sections is not None:
return self._sections
# See which sections are available
try:
noteFileName = self.noteFileName
Log.debug("Retrieving sections from: " + noteFileName)
info = MidiSectionReader()
midiIn = midi.MidiInFile(info, noteFileName)
try:
midiIn.read()
except MidiSectionReader.Done:
pass
self._sections = info.sections
if len(self._sections) <= 1:
self._sections = info.noteCountSections
self._sections.insert(0,["0:00 -> Start", 0.0])
#MFH - only log if enabled
Log.warn("Song.py: Using auto-generated note count sections...")
if self.logSections == 1:
Log.debug("Practice sections: " + str(self._sections))
else:
self._sections.insert(0,["0:00 -> Start", 0.0])
#MFH - only log if enabled
if self.logSections == 1:
Log.debug("Practice sections: " + str(self._sections))
except Exception as e:
Log.warn("Song.py: Unable to retrieve section names for practice mode selection: %s" % e)
self._sections = None
return self._sections
#coolguy567's unlock system
def getUnlockID(self):
return self._get("unlock_id")
def getUnlockRequire(self):
return self._get("unlock_require")
def getUnlockText(self):
return self._get("unlock_text", default = _("This song is locked."))
# This takes True or False, not the value in the ini
def setCompleted(self, value):
if value:
self._set("unlock_completed", len(removeSongOrderPrefixFromName(self.name)) * len(self.artist) + 1)
else:
self._set("unlock_completed", 0)
# This returns True or False, not the value in the ini
def getCompleted(self):
iniValue = self._get("unlock_completed", int, default = 0)
if iniValue == len(removeSongOrderPrefixFromName(self.name)) * len(self.artist) + 1: # yay, security through obscurity!
return True
else:
return False
def setLocked(self, value):
self.locked = value
# WARNING this will only work on a SongInfo loaded via getAvailableSongs
# (yeah, I know)
def getLocked(self):
return self.locked
#MFH - adding song.ini setting to allow fretter to specify early hit window size (none, half, or full)
def getEarlyHitWindowSize(self): #MFH
return self._get("early_hit_window_size", str)
def setEarlyHitWindowSize(self, value): #MFH
self._set("early_hit_window_size", value)
def getHopoFreq(self): #MFH
return self._get("hopofreq")
def setHopoFreq(self, value): #MFH
self._set("hopofreq", value)
name = property(getName, setName)
artist = property(getArtist, setArtist)
year = property(getYear, setYear)
loading = property(getLoading, setLoading)
delay = property(getDelay, setDelay)
tutorial = property(isTutorial)
# difficulties = property(getDifficulties)
cassetteColor = property(getCassetteColor, setCassetteColor)
#New RF-mod Items
parts = property(getParts)
frets = property(getFrets, setFrets)
version = property(getVersion, setVersion)
tags = property(getTags, setTags)
hopo = property(getHopo, setHopo)
count = property(getCount, setCount)
lyrics = property(getLyrics, setLyrics)
EighthNoteHopo = property(getEighthNoteHopo, setEighthNoteHopo)
hopofreq = property(getHopoFreq, setHopoFreq) #MFH
#New rb2 setlist
album = property(getAlbum, setAlbum)
genre = property(getGenre, setGenre)
icon = property(getIcon, setIcon)
diffSong = property(getDiffSong, setDiffSong)
diffGuitar = property(getDiffGuitar, setDiffGuitar)
diffBass = property(getDiffBass, setDiffBass)
diffDrums = property(getDiffDrums, setDiffDrums)
diffVocals = property(getDiffVocals, setDiffVocals)
#boss battles
bossBattle = property(getBossBattle, setBossBattle)
#May no longer be necessary
folder = False
completed = property(getCompleted, setCompleted)
sections = property(getSections) #MFH
early_hit_window_size = property(getEarlyHitWindowSize, setEarlyHitWindowSize) #MFH
class LibraryInfo(object):
def __init__(self, libraryName, infoFileName):
self.libraryName = libraryName
self.fileName = infoFileName
self.info = Config.MyConfigParser()
self.songCount = 0
self.artist = None
self.logClassInits = Config.get("game", "log_class_inits")
if self.logClassInits == 1:
Log.debug("LibraryInfo class init (song.py)...")
try:
self.info.read(infoFileName)
except:
pass
# Set a default name
if not self.name:
self.name = os.path.basename(os.path.dirname(self.fileName))
if Config.get("performance", "disable_libcount") == True:
return
# Count the available songs
libraryRoot = os.path.dirname(self.fileName)
for name in os.listdir(libraryRoot):
if not os.path.isdir(os.path.join(libraryRoot, name)) or name.startswith("."):
#if not os.path.isdir(os.path.join(libraryRoot, name)):
continue
if os.path.isfile(os.path.join(libraryRoot, name, "notes.mid")):
self.songCount += 1
elif os.path.isfile(os.path.join(libraryRoot, name, "notes-unedited.mid")):
self.songCount += 1
def _set(self, attr, value):
if not self.info.has_section("library"):
self.info.add_section("library")
if type(value) == bytes:
value.decode('utf-8')
self.info.set("library", attr, value)
def save(self):
if os.access(os.path.dirname(self.fileName), os.W_OK) == True:
f = open(self.fileName, "w")
self.info.write(f)
f.close()
def _get(self, attr, type = None, default = ""):
try:
v = self.info.get("library", attr)
except:
v = default
if v is not None and type:
v = type(v)
return v
def getName(self):
return self._get("name")
def setName(self, value):
self._set("name", value)
def getColor(self):
c = self._get("color")
if c:
return Theme.hexToColor(c)
def setColor(self, color):
self._set("color", Theme.colorToHex(color))
name = property(getName, setName)
color = property(getColor, setColor)
class BlankSpaceInfo(object): #MFH
#def __init__(self, config, section):
def __init__(self, nameToDisplay = ""):
#self.info = config
#self.section = section
self.nameToDisplay = nameToDisplay
self.logClassInits = Config.get("game", "log_class_inits")
if self.logClassInits == 1:
Log.debug("BlankSpaceInfo class init (song.py)...")
self.artist = None #MFH - prevents search errors
def _set(self, attr, value):
if type(value) == str:
value = value.encode(Config.encoding)
else:
value = str(value)
self.info.set(self.section, attr, value)
def _get(self, attr, type = None, default = ""):
try:
v = self.info.get(self.section, attr)
except:
v = default
if v is not None and type:
v = type(v)
return v
def getName(self):
#return self._get("name")
return self.nameToDisplay
def setName(self, value):
self._set("name", value)
def getColor(self):
c = self._get("color")
if c:
return Theme.hexToColor(c)
def setColor(self, color):
self._set("color", Theme.colorToHex(color))
def getUnlockID(self):
return ""
name = property(getName, setName)
color = property(getColor, setColor)
class CareerResetterInfo(object): #MFH
#def __init__(self, config, section):
def __init__(self):