-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtoolkit_functions.py
4121 lines (3816 loc) · 191 KB
/
toolkit_functions.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
import io
import sys
import os
import random
import re
import mido
import CRC
import numpy as np
import struct
import configparser
root_folder = os.path.realpath(os.path.dirname(__file__))
sys.path.append(os.path.join(root_folder, "pak_extract"))
sys.path.append(os.path.join(root_folder, "midqb_gen"))
sys.path.append(os.path.join(root_folder, "ska_converter"))
sys.path.append(os.path.join(root_folder, "create_audio"))
from pak_extract import PAKExtract, QB2Text, Text2QB
from midqb_gen import MidQbGen as mid_qb
from ska_converter.ska_functions import make_modern_ska, make_gh3_ska
from ska_converter.ska_classes import ska_bytes, lipsync_dict
from gh_sections import gh_sections
from toolkit_variables import *
from io import StringIO, BytesIO
from debug_qs import qs_debug
from copy import deepcopy
from CRC import qbkey_hex, QBKey
from dbg import checksum_dbg
from mido import MidiFile, MidiTrack, second2tick as s2t, Message, MetaMessage
orig_std = sys.stdout
round_time = PAKExtract.round_time
def set_std_out(loc):
sys.stdout = loc
def cam_len_check(cam_len):
if str(cam_len).endswith("34"):
cam_len -= 1
elif str(cam_len).endswith("66"):
cam_len += 1
return cam_len
def get_rhythm_headers(song_name):
rhythm_parts = []
rhythm_dict = {}
for x in PAKExtract.charts:
for y in PAKExtract.difficulties:
if x == "song":
rhythm_parts.append(f"{song_name}_{x}_aux_{y}")
else:
rhythm_parts.append(f"{song_name}_aux_{y}_{x}")
for x in rhythm_parts:
rhythm_dict[x] = int(PAKExtract.QBKey(x), 16)
return rhythm_parts, rhythm_dict
def get_qs_strings(qs_bytes):
qs_dict = {}
qs_split = qs_bytes[2:].decode('utf-16-le').split("\n")
for count, item in enumerate(qs_split):
if item == "":
continue
qs_line = item.split(maxsplit=1)
qs_line[1] = qs_line[1][1:-1].replace("\\L", "")
qs_dict[int(qs_line[0], 16)] = qs_line[1]
return qs_dict
def get_track_type(track_name):
diffs = ["Easy", "Medium", "Hard", "Expert"]
instrument = ["guitarcoop", "rhythmcoop", "rhythm"]
if (any(x in track_name for x in diffs)):
for x in diffs:
if x in track_name:
if "Battle" in track_name:
track_type = "Battle"
elif "Star" in track_name:
track_type = "Star"
else:
track_type = "Notes"
track_diff = x
for y in instrument:
if y in track_name:
track_play = y
break
else:
track_play = "song"
return {"instrument": track_play, "track_type": track_type, "difficulty": track_diff}
else:
return {"track_type": track_name[track_name.find("_") + 1:]}
def pak2mid(pakmid, song_name):
if type(pakmid) == bytes or type(pakmid) == bytearray:
mid_bytes = pakmid
elif pakmid.lower().endswith(".mid"):
with open(os.devnull, "w") as fake:
set_std_out(fake)
mid_bytes, song_name = output_mid_gh3(pakmid, 170)
set_std_out(orig_std)
else:
with open(pakmid, 'rb') as pak:
mid_bytes = pak.read()
mid_bytes = PAKExtract.check_decomp(mid_bytes, output_decomp=False)
song_files = PAKExtract.main(mid_bytes, f"{song_name}_song.pak", toolkit_mode=True)
song_names = [song_name]
starts = ["a", "b", "c"]
if song_name[0] in starts:
song_names.append(song_name[1:])
for x in song_files:
if "0x" in x['file_name']:
file_name_scrubbed = x['file_name'].replace("\\", "")
if file_name_scrubbed.endswith(".qb"):
qb_string = f'songs/{song_name}.mid.qb'
crc_name = int(PAKExtract.QBKey(f'songs/{song_name}.mid.qb'), 16)
try:
hex_name = int(file_name_scrubbed[:-3], 16)
except:
continue
if crc_name == hex_name:
mid_qb = qb_string
mid_data_bytes = x['file_data']
elif ".mid.qb" in x['file_name']:
mid_qb = x['file_name'].replace("\\", "")
mid_data_bytes = x['file_data']
if "mid_data_bytes" in locals():
file_headers = {}
for s_name in song_names:
file_headers |= QB2Text.createHeaderDict(s_name)
file_headers_hex = QB2Text.create_hex_headers(file_headers)
qb_sections = QB2Text.convert_qb_file(QB2Text.qb_bytes(mid_data_bytes), song_name, file_headers)
else:
qb_sections = 0
file_headers = 0
file_headers_hex = 0
return qb_sections, file_headers, file_headers_hex, song_files
'''def swap_checksums(filepath,):
for y in os.listdir(f"{filepath}"):
if os.path.isfile(f"{filepath}\\{y}"):
# continue
if "_song.pak.xen" in y.lower():
pak_data = f"{filepath}\\{y}"
old_name = y.split("_")[0]
old_ids = generate_ids(old_name)
# raise Exception
elif "_anim" in y.lower():
pak_anim = f"{filepath}\\{y}"
elif ".mid" in y.lower():
override_mid = f"{filepath}\\{y}"
print(f"MIDI File: {y} found.")
else:
print(f"Unknown file {y} found. Skipping...")
""" Only for BH/GH5 style PAKs
with open(f"{filepath}\\{y}", 'rb') as f:
decomp_pak = f.read()
if decomp_pak[:4] == b"CHNK":
decomp_pak = decompress_pak(decomp_pak)
for i, z in enumerate(old_ids):
decomp_pak = decomp_pak.replace(z, dlc_ids[i])
"""
else:
folderpath = f"{filepath}\\{y}"
foldersavepath = f"{savepath}\\{y}"
for z in os.listdir(f"{folderpath}"):
file_console = file_renamer(os.path.basename(z[-3:]).lower())
if file_console != console:
continue
no_ext = file_renamer(os.path.basename(z[:-8]).lower())
key = generate_fsb_key(no_ext)
print(f"Processing {z}")
with open(f"{folderpath}\\{z}", 'rb') as f:
audio = f.read()
if audio[:3] != b'FSB':
audio = decrypt_fsb4(audio, key)
if audio[:3] != b'FSB':
raise Exception("Error Decrypting. Please check your song name.")
print("Successfully Decrypted")
new_id = f"a{x[0]}{z[z.find('_'):z.find('.')]}"
no_ext = file_renamer(new_id.lower())
key = generate_fsb_key(no_ext)
print(f"Re-encrypting with id {no_ext}")
audio = encrypt_fsb4(audio, key)
print("Successfully Encrypted")
try:
os.makedirs(foldersavepath)
except:
pass
file_name = f"{foldersavepath}\\a{no_ext}.fsb.{console}"
if console == "ps3":
file_name = file_name.upper()
with open(file_name, 'wb') as f:
f.write(audio)
# raise Exception
'''
def qb_2_sections(qb_sections):
qb_array = []
for x in qb_sections.keys():
qb_array.append(qb_sections[x])
result = StringIO()
orig_stdout = sys.stdout
sys.stdout = result
QB2Text.print_qb_text_file(qb_array)
sys.stdout = orig_stdout
qb_text = result.getvalue()
return qb_text
def sections_2_qb(qb_sections, console="PC", endian="big", game="GH3"):
qb_text = qb_2_sections(qb_sections)
qb_file = Text2QB.main(qb_text, console, endian, game)
return qb_file
def add_to_dict(p_dict, t, entry):
if t in p_dict:
p_dict[t].append(entry)
else:
p_dict[t] = [entry] if type(entry) != list else entry
return
def convert_to_gh3(pakmid, output=f'{os.getcwd()}', singer="gh3_singer"):
if not "_song.pak" in pakmid:
warning = input(
"WARNING: File does not appear to be a validly named mid PAK file. Do you want to continue? (Y/N): ")
if not warning.lower().startswith("y"):
return -1
song_name = pakmid[len(os.path.dirname(pakmid)) + 1:pakmid.find("_song")].lower()
track_types = []
qb_sections, file_headers, file_headers_hex, song_files = pak2mid(pakmid, song_name)
rhythm_sections, rhythm_dict = get_rhythm_headers(song_name)
ska_dict = {}
for file in song_files:
if file["file_name"].lower().endswith(".ska"):
file["file_data"] = ska_bytes(file["file_data"])
ska_dict[file["file_name"]] = file["file_data"]
sections_dict = {}
for x in qb_sections:
if x.section_id in file_headers_hex.keys():
x.set_new_id(file_headers_hex[x.section_id])
if x.section_id not in rhythm_sections:
sections_dict[x.section_id] = x
new_cams = []
# Swap camera cuts
for x in sections_dict[f"{song_name}_cameras_notes"].section_data:
try:
if type(gha_to_gh3[x[1]]) == list:
raise Exception("Fatal error when processing camera swaps.")
else:
x[1] = gha_to_gh3[x[1]]
new_cams.append(x)
except:
print(f"Bad Camera Cut {x[1]} found. Skipping")
# Remove Rhythm left-hand anims
new_anims = []
new_anims_type = []
for x in sections_dict[f"{song_name}_anim_notes"].section_data:
if x[1] > 94:
new_anims.append(x)
new_anims_type.append("ArrayInteger")
sections_dict[f"{song_name}_anim_notes"].section_data = new_anims
sections_dict[f"{song_name}_anim_notes"].subarray_types = new_anims_type
for x in sections_dict[f"{song_name}_markers"].section_data:
if x.data_value[1].data_type == "StructItemQbKeyString":
x.data_value[1].data_type = "StructItemStringW"
marker_hex = x.data_value[1].data_value
if "markers_text" in marker_hex:
new_marker = gh_sections[int(marker_hex[-8:], 16)]
else:
new_marker = "No Section Name"
x.data_value[1].set_string_w(new_marker)
x.data_value[1].data_value = new_marker
# Delete GH:A Exclusive events (special mocap, Rhythm events, etc)
perf_to_ignore = ['dummy_function', 'ChangeNodeFlag'.lower(), 'super_airbag_hide', "SpecialCamera_PlayAnim".lower(),
"Band_PlaySimpleAnim".lower(), "super_Shakin_guitar_unhide".lower(),
"super_Shakin_guitar_hide".lower()]
to_ignore_start = ["Z_".lower()]
new_perf = []
stances = {"guitarist": [],
"bassist": [],
"vocalist": []}
for x in sections_dict[f"{song_name}_performance"].section_data:
if x.data_value[1].data_value.lower() in perf_to_ignore:
continue
elif x.data_value[1].data_value.lower() in allowed_anims_gha:
continue
elif x.data_value[1].data_value == 'Band_ChangeStance':
stance = x.data_dict["params"]["stance"].lower()
player = x.data_dict["params"]["name"]
if player.lower() == "rhythm":
continue
if stance == "stance_d":
# print()
try:
if stances[player][-1].lower().endswith("a"):
x.data_dict["params"]["stance"] = "stance_b"
elif stances[player][-1].lower().endswith("b"):
x.data_dict["params"]["stance"] = "stance_c"
else:
x.data_dict["params"]["stance"] = "stance_a"
except:
x.data_dict["params"]["stance"] = "stance_a"
x.reprocess_dict()
if player in stances:
stances[player].append(stance)
elif x.data_value[1].data_value == 'Band_PlayAnim':
if x.data_value[2].struct_data_struct[0].data_value.lower() == "rhythm":
continue
anim = x.data_dict["params"]["anim"]
player = x.data_dict["params"]["name"]
if anim.lower() in gha_anim_swaps:
x.data_dict["params"]["anim"] = gha_anim_swaps[x.data_dict["params"]["anim"].lower()]
x.reprocess_dict()
elif x.data_value[1].data_value.lower() in allowed_anims_gh3:
pass
else:
for a_check in to_ignore_start:
if not x.data_value[1].data_value.lower().startswith(a_check):
print(x.data_value[1].data_value)
continue
# else:
new_perf.append(x)
if not stances["vocalist"]:
vox_stances = {}
a_stances = []
b_stances = [0]
perf_dict = {}
for x in new_perf:
t = x.data_dict["time"]
add_to_dict(perf_dict, t, x)
if x.data_dict["scr"] == "Band_PlayFacialAnim":
if x.data_dict["params"]["name"] == "vocalist":
a_time = t - 5000 if t > 5000 else 0
stance_a = PAKExtract.new_stance_gh3(a_time, "vocalist", "stance_b")
ska_length = round(ska_dict[f'{x.data_dict["params"]["anim"]}.ska'].duration * 1000)
b_time = t + ska_length + 1000
stance_b = PAKExtract.new_stance_gh3(b_time, "vocalist", "stance_a")
add_to_dict(vox_stances, a_time, stance_a)
a_stances.append(a_time)
add_to_dict(vox_stances, b_time, stance_b)
b_stances.append(b_time)
# print()
if a_stances:
for a, b in zip(a_stances, b_stances):
if b == 0:
add_to_dict(perf_dict, a, vox_stances[a])
elif a < b:
continue
else:
add_to_dict(perf_dict, b, vox_stances[b])
add_to_dict(perf_dict, a, vox_stances[a])
add_to_dict(perf_dict, b_stances[-1], vox_stances[b_stances[-1]])
new_perf = []
for perfs in sorted(list(perf_dict.keys())):
for perf in perf_dict[perfs]:
new_perf.append(perf)
sections_dict[f"{song_name}_performance"].set_data(new_perf)
gh3_qb_sections = []
for x in sections_dict.keys():
gh3_qb_sections.append(sections_dict[x])
result = StringIO()
orig_stdout = sys.stdout
sys.stdout = result
QB2Text.print_qb_text_file(gh3_qb_sections)
sys.stdout = orig_stdout
gh3_text = result.getvalue()
gh3_qb = Text2QB.main(gh3_text, "PC", "big")
for x in song_files:
x['file_name'] = x['file_name'].replace("\\", "")
if x['file_name'] == f'songs/{song_name}.mid.qb':
x["file_data"] = gh3_qb
if ".ska" in x['file_name']:
x["file_data"] = make_gh3_ska(x["file_data"], ska_switch=singer, quats_mult=0.5)
gh3_array = []
for x in song_files:
gh3_array.append([x["file_data"], x['file_name']])
# Create the song PAK file
song_pak = mid_qb.pakMaker(gh3_array)
# raise Exception
return song_name, song_pak
def convert_to_gha(pakmid, output=f'{os.getcwd()}', singer="gha_singer"):
if "_song.pak" in pakmid:
song_name = pakmid[len(os.path.dirname(pakmid)) + 1:pakmid.find("_song")]
elif ".mid" in pakmid:
print("MIDI file found for GHA conversion.")
print("This tool cannot convert directly to GHA yet.")
print("Converting to GH3 first.")
song_name = pakmid[len(os.path.dirname(pakmid)) + 1:pakmid.find(".mid")]
track_types = []
qb_sections, file_headers, file_headers_hex, song_files = pak2mid(pakmid, song_name)
rhythm_sections, rhythm_dict = get_rhythm_headers(song_name)
rhythm_parts = []
sections_dict = {}
for x in qb_sections:
if x.section_id in file_headers_hex.keys():
x.set_new_id(file_headers_hex[x.section_id])
sections_dict[x.section_id] = x
for x in rhythm_sections:
if x != f"{song_name}_song_aux_Expert":
fake_section = PAKExtract.qb_section("SectionArray")
fake_section.make_empty()
fake_section.set_new_id(x)
fake_section.set_pak_name(sections_dict[f"{song_name}_song_Expert"].section_pak_name)
rhythm_parts.append(fake_section)
else:
rhythm_section = PAKExtract.qb_section("SectionArray")
rhythm_section.set_new_id(x)
rhythm_section.set_array_node_type("ArrayInteger")
rhythm_section.set_data(sections_dict[f"{song_name}_song_Expert"].section_data)
rhythm_section.set_pak_name(sections_dict[f"{song_name}_song_Expert"].section_pak_name)
rhythm_parts.append(rhythm_section)
# Swap camera cuts
if not sections_dict[f"{song_name}_cameras_notes"].is_empty():
for x in sections_dict[f"{song_name}_cameras_notes"].section_data:
if type(gh3_to_gha[x[1]]) == list:
x[1] = random.choice(gh3_to_gha[x[1]])
else:
x[1] = gh3_to_gha[x[1]]
# Add left-hand anims to rhythm player
if sections_dict[f"{song_name}_anim_notes"].section_data != [0, 0]:
new_anims = []
new_anims_type = []
for x in sections_dict[f"{song_name}_anim_notes"].section_data:
if x[1] in range(118, 128):
new_anims.append([x[0], x[1] - 34, x[2]])
new_anims_type.append("ArrayInteger")
new_anims.append(x)
new_anims_type.append("ArrayInteger")
sections_dict[f"{song_name}_anim_notes"].section_data = new_anims
sections_dict[f"{song_name}_anim_notes"].subarray_types = new_anims_type
if not sections_dict[f"{song_name}_markers"].is_empty():
for x in sections_dict[f"{song_name}_markers"].section_data:
if x.data_value[1].data_type == "StructItemQbKeyString":
x.data_value[1].data_type = "StructItemStringW"
marker_hex = x.data_value[1].data_value
if "markers_text" in marker_hex:
new_marker = gh_sections[int(marker_hex[-8:], 16)]
else:
new_marker = "No Section Name"
x.data_value[1].set_string_w(new_marker)
x.data_value[1].data_value = new_marker
# Add rhythm notes to total package
gha_dict = {}
for x in sections_dict.keys():
if x != f"{song_name}_rhythm_Expert_StarBattleMode":
gha_dict[x] = sections_dict[x]
else:
gha_dict[x] = sections_dict[x]
for y in rhythm_parts:
gha_dict[y.section_id] = y
gha_qb_sections = []
for x in gha_dict.keys():
gha_qb_sections.append(gha_dict[x])
result = StringIO()
orig_stdout = sys.stdout
sys.stdout = result
QB2Text.print_qb_text_file(gha_qb_sections)
sys.stdout = orig_stdout
gha_text = result.getvalue()
gha_qb = Text2QB.main(gha_text, "PC", "big")
# QB2Text.output_qb_file(gha_qb_sections, output+f'\\{song_name}.txt')
for x in song_files:
x['file_name'] = x['file_name'].replace("\\", "")
if x['file_name'] == f'songs/{song_name}.mid.qb':
x["file_data"] = gha_qb
if ".ska" in x['file_name']:
if re.search("[0-9][bB]\.ska", x['file_name'].lower()):
# raise Exception
x["file_data"] = make_gh3_ska(ska_bytes(x["file_data"]), ska_switch="gha_guitarist",
quats_mult=2)
else:
x["file_data"] = make_gh3_ska(ska_bytes(x["file_data"]), ska_switch=singer, quats_mult=2)
# raise Exception
# Convert dict to array of arrays
gha_array = []
for x in song_files:
gha_array.append([x["file_data"], x['file_name']])
# Create the song PAK file
song_pak = mid_qb.pakMaker(gha_array)
return song_name, song_pak
# raise Exception
def process_base_gh5(data_array, gh5_name, gh5_entry, size, modulo=1):
gh5_base = mid_qb.gh5_base_entry()
if data_array == [0, 0]:
data_array = []
elif data_array == [0] and gh5_name == "gh5_vocal_phrase":
data_array = []
gh5_base.process_vox(data_array, gh5_name, gh5_entry, size, modulo)
return gh5_base
def read_qs_debug():
qs_debug_qb = {}
qs_vals = {}
for x in qs_debug.keys():
qs_debug_qb[int(CRC.QBKey(x), 16)] = qs_debug[x]
# curr_folder = os.getcwd()
file_path = os.path.join(root_folder, "conversion_files", "qs_e.txt")
with open(file_path, encoding="utf-16-le") as f:
qs_text = f.readlines()
for x in qs_text:
quoted_text = ""
quote_mode = False
for char in x:
if char == "\"":
quote_mode = not quote_mode
continue
if quote_mode:
quoted_text += char
if not quoted_text:
continue
placeholder = "zxcvasdfqwer"
split_line = x.replace(quoted_text, placeholder)
split_line = " ".join(split_line.split()).split(maxsplit=1)
if len(split_line) == 2:
new_text = split_line[1].replace(placeholder, quoted_text).replace("\"", "")
qs_test = CRC.QBKey_qs(new_text)
if int(qs_test, 16) == int(split_line[0], 16):
qs_vals[int(split_line[0], 16)] = new_text
else:
print(f"Invalid qb key {split_line[0]} to {split_line[1]}")
return qs_vals, qs_debug_qb
def note_2_bin(raw_file):
n_info = bytearray()
for note_item in raw_file.keys():
item = raw_file[note_item]
n_info += qbkey_hex(item.name) # QB key of item type (hard drums, easy guitar, etc.)
n_info += int.to_bytes(round(len(item.entries) / item.modulo), 4, "big")
n_info += qbkey_hex(item.qb_string) # QB key of entry type (instrument_note)
n_info += int.to_bytes(item.size, 4, "big")
if len(item.entries) != 0:
if type(item) != mid_qb.gh5_base_entry:
for enum, notes in enumerate(item.entries):
if type(item) == mid_qb.gh5_star_note:
n_info += int.to_bytes(notes, 4 if enum % 2 == 0 else 2, "big")
elif type(item) == mid_qb.gh5_instrument_note:
if item.qb_string == 'gh6_expert_drum_note':
n_info += int.to_bytes(notes, 1 if enum % 3 == 2 else 4, "big")
else:
n_info += int.to_bytes(notes, 4, "big")
elif type(item) == mid_qb.gh5_special_note:
n_info += int.to_bytes(notes, 4, "big")
else:
for enum, notes in enumerate(item.entries):
if item.name == "timesig":
n_info += int.to_bytes(notes, 4 if enum % 3 == 0 else 1, "big")
elif item.name == "fretbar":
n_info += int.to_bytes(notes, 4, "big")
elif item.name == "guitarmarkers":
n_info += int.to_bytes(notes if enum % 2 == 0 else int(notes, 16), 4, "big")
elif item.name == "vocals":
n_info += int.to_bytes(notes, 4 if enum % 3 == 0 else 2 if enum % 3 == 1 else 1, "big")
elif item.name == "vocalfreeform":
n_info += int.to_bytes(notes, 4 if enum % 3 != 2 else 2, "big")
elif item.name == "vocalphrase":
n_info += int.to_bytes(notes, 4, "big")
elif item.name == "vocallyrics" or item.name == "vocalsmarkers":
if enum % 2 == 0:
n_info += int.to_bytes(notes, 4, "big")
else:
utf_16 = b''
for letter in notes:
utf_16 += ord(letter).to_bytes(2, "big")
if len(utf_16) > item.size - 4:
print(
f"{'Lyric' if item.name == 'vocallyrics' else 'Phrase'} \'{notes}\' is longer than {int((item.size - 4) / 2)} characters long.")
utf_16 = utf_16[:(item.size - 4)]
print(f"Truncating to {int((item.size - 4) / 2)} characters.")
print(
f"{'Lyric' if item.name == 'vocallyrics' else 'Phrase'} is now {utf_16.decode('utf-16-be')}")
utf_16 += b'\x00' * ((item.size - 4) - len(utf_16))
# print(len(utf_16))
n_info += utf_16
elif item.name == "bandmoment":
n_info += int.to_bytes(notes, 4, "big")
return n_info
def perf_2_bin(perf_file, song_name, loop_anims):
p_info = bytearray()
for x in ["autocutcameras", "momentcameras"]:
item = perf_file[x]
p_info += qbkey_hex(x) # QB key of camera type
p_info += int.to_bytes(round(len(item) / 3), 4, "big")
p_info += qbkey_hex("gh5_camera_note")
for enum, camera_cut in enumerate(item):
p_info += int.to_bytes(camera_cut, 4 if enum % 3 == 0 else 2 if enum % 3 == 1 else 1, "big")
if loop_anims:
for x in ["Female", "Male"]:
item = loop_anims[x]
loop_bytes = b''
for player in ["guitarist", "bassist", "vocalist"]:
player_loops = b''
for loop in item[player]:
player_loops += qbkey_hex(loop)
if len(player_loops) > 200:
raise Exception(f"Player {player} has more than 50 anim and camera loops")
player_loops += b'\x00' * (200 - len(player_loops))
loop_bytes += player_loops
loop_bytes += b'\x00' * 400
for y in ["", "_alt"]:
p_info += qbkey_hex(f"car_{x}{y}_anim_struct_{song_name}")
p_info += int.to_bytes(1, 4, "big")
p_info += qbkey_hex("gh6_actor_loops")
p_info += loop_bytes
else:
for x in ["female", "male"]:
item = perf_file[x]
for y in ["", "_alt"]:
p_info += qbkey_hex(f"car_{x}{y}_anim_struct_{song_name}")
p_info += int.to_bytes(1, 4, "big")
p_info += qbkey_hex("gh5_actor_loops")
for anim_loop in item:
p_info += qbkey_hex(anim_loop)
return p_info
def convert_to_gh5_bin(raw_file, file_type, song_name="", *args, **kwargs):
if file_type == "note" or file_type == "perf":
header = bytearray()
header += b'\x40\xa0\x00\xd2' if file_type == "note" else b'\x40\xa0\x01\xa3' # Game id
header += qbkey_hex(song_name) # DLC_id
header += int.to_bytes(len(raw_file) if file_type == "note" else 6, 4, "big") # Number of entries
header += qbkey_hex(file_type) # "Note" or "Perf" to hex
header += b'\x00' * 12 # Padding
if file_type == "note":
return header + note_2_bin(raw_file)
else:
loop_anims = 0
if args:
if args[0]["Male"]["vocalist"]:
loop_anims = args[0]
return header + perf_2_bin(raw_file, song_name, loop_anims)
elif file_type == "qs":
qs_bin = bytearray()
qs_bin += b'\xFF\xFE'
for qs in raw_file:
qs_key = CRC.QBKey_qs(qs)
for char in qs_key:
qs_bin += ord(char).to_bytes(2, "little")
qs_bin += ord(" ").to_bytes(2, "little")
qs_bin += ord("\"").to_bytes(2, "little")
for char in qs:
qs_bin += ord(char).to_bytes(2, "little")
qs_bin += ord("\"").to_bytes(2, "little")
qs_bin += b'\x0A\x00' # new line
qs_bin += b'\x0A\x00\x0A\x00'
return qs_bin
elif file_type in ["qb", "perf_xml"]:
if "console" in kwargs and "endian" in kwargs:
return sections_2_qb(raw_file, kwargs["console"], kwargs["endian"], game="GH5")
else:
raise Exception(f"Unknown file type {file_type} found")
return
def reorg_qb(qb_file, song_name):
new_qb = {}
for x in ["_anim_notes", "_anim", "_drums_notes", "_scripts", "_cameras_notes", "_cameras", "_performance",
"_crowd_notes", "_crowd", "_lightshow_notes", "_lightshow", "_facial", "_localized_strings"]:
new_qb[f"{song_name}{x}"] = qb_file[f"{song_name}{x}"]
return new_qb
def reorg_perfqb(qb_file):
scripty = 0
new_perf = {}
for x in qb_file.keys():
if x.endswith("scriptevents"):
scripty = qb_file[x]
else:
new_perf[x] = qb_file[x]
new_perf[scripty.section_id] = scripty
return new_perf
def grab_debug_2(string, dbg_dict):
if string.startswith("0x"):
string = dbg_dict[f"0x{hex(int(string, 16))[2:].zfill(8)}"]
return string
def gen_wt_anim_dict(song_name, file_headers):
anim_data_dict = {}
to_open = ["ghwt", "ghm", "ghsh", "ghvh"]
for game in to_open: # Grab all the animation structs to convert potentially
with open(f"{root_folder}/conversion_files/{game}_guitar_animation_data.txt") as f:
anim_data = Text2QB.main(f.read())
anim_data = QB2Text.convert_qb_file(QB2Text.qb_bytes(anim_data), song_name, file_headers)
for x in anim_data:
if x.section_type == "SectionStruct":
if x.section_id not in anim_data_dict:
anim_data_dict[x.section_id] = x
return anim_data_dict
def gen_wor_anim_sets():
root_folder = os.path.realpath(os.path.dirname(__file__))
wor_anim = {}
anims = []
anim_nogen = []
with open(f"{root_folder}/conversion_files/wor_anim_sets.txt") as f:
anim_data = Text2QB.main(f.read())
anim_data = QB2Text.convert_qb_file(QB2Text.qb_bytes(anim_data), "0", {"0": "0"})
for x in anim_data[0].data_dict.keys():
anims.append(x.lower())
return anims
def default_anim_structs():
female_struct = {
"guitar": {
"pak": "L_GUIT_JeffS_LowKey_anims",
"anim_set": "L_GUIT_JeffS_Lowkey_anims_set",
"finger_anims": "guitarist_finger_anims_car_female",
"fret_anims": "fret_anims_rocker",
"strum_anims": "CAR_Female_Normal",
"facial_anims": "facial_anims_female_rocker"
},
"bass": {
"pak": "L_GUIT_JeffS_LowKey_anims",
"anim_set": "L_GUIT_JeffS_Lowkey_anims_set",
"finger_anims": "guitarist_finger_anims_car_female",
"fret_anims": "fret_anims_rocker",
"strum_anims": "CAR_Female_Normal",
"facial_anims": "facial_anims_female_rocker"
},
"drum": {
"pak": "L_DRUM_Loops_Standard_anims",
"anim_set": "L_DRUM_Loops_standard_anims_set",
"facial_anims": "facial_anims_female_rocker"
},
"vocals": {
"pak": "L_SING_JeffS_LowKey_anims",
"anim_set": "L_SING_JeffS_Lowkey_anims_set",
"facial_anims": "facial_anims_female_rocker"
}
}
male_struct = {
"guitar": {
"pak": "L_GUIT_JeffS_LowKey_anims",
"anim_set": "L_GUIT_JeffS_Lowkey_anims_set",
"finger_anims": "guitarist_finger_anims_car_male",
"fret_anims": "fret_anims_rocker",
"strum_anims": "CAR_male_Normal",
"facial_anims": "facial_anims_male_rocker"
},
"bass": {
"pak": "L_GUIT_JeffS_LowKey_anims",
"anim_set": "L_GUIT_JeffS_Lowkey_anims_set",
"finger_anims": "guitarist_finger_anims_car_male",
"fret_anims": "fret_anims_rocker",
"strum_anims": "CAR_male_Normal",
"facial_anims": "facial_anims_male_rocker"
},
"drum": {
"pak": "L_DRUM_Loops_Standard_anims",
"anim_set": "L_DRUM_Loops_standard_anims_set",
"facial_anims": "facial_anims_male_rocker"
},
"vocals": {
"pak": "L_SING_JeffS_LowKey_anims",
"anim_set": "L_SING_JeffS_Lowkey_anims_set",
"facial_anims": "facial_anims_male_rocker"
}
}
return female_struct, male_struct
def get_song_file_dict(song_files):
song_files_dict = {}
for key in song_files:
song_files_dict[key["file_name"]] = key
return song_files_dict
def get_section_dict(qb_sections, file_headers_hex):
sections_dict = {}
if not qb_sections:
return sections_dict
for x in qb_sections:
if x.section_id in file_headers_hex.keys():
x.set_new_id(file_headers_hex[x.section_id])
sections_dict[x.section_id] = x
return sections_dict
def perf_struct(female_struct, male_struct):
wor_anims = gen_wor_anim_sets()
for enum, struct in enumerate([female_struct, male_struct]):
struct_perf = []
for instrument in ["guitar", "bass"]:
for perf_type in ["pak", "anim_set", "finger_anims", "fret_anims", "strum_anims", "facial_anims"]:
if perf_type == "pak":
if struct[instrument]["pak"].lower() not in wor_anims:
input(f"{struct[instrument]['pak']} is not a WOR anim, please check")
struct_perf.append(struct[instrument][perf_type])
# Vocals anims in GH5/6 use 3 exclusive values, and 3 the same
try:
if struct["vocals"]["pak"].lower() not in wor_anims:
input(f"{struct['vocals']['pak']} is not a WOR anim, please check")
except:
struct["vocals"] = {'pak': "L_SING_JeffS_LowKey_anims",'anim_set': "L_SING_JeffS_Lowkey_anims_set", 'facial_anims': f"facial_anims_{'fe' if enum == 0 else ''}male_rocker"}
struct_perf += [struct["vocals"]["pak"], struct["vocals"]["anim_set"], "guitarist_finger_anims_car_female",
"fret_anims_rocker", "car_female_normal", struct["vocals"]["facial_anims"]]
# Drums are all default
struct_perf += ["L_GUIT_Jeffs_LowKey_anims", "L_GUIT_Jeffs_LowKey_anims_set",
"guitarist_finger_anims_car_female", "fret_anims_rocker", "car_female_normal",
"facial_anims_female_rocker"]
for perf_type in ["L_DRUM_Loops_Standard_anims",
"l_drum_loops_standard_anims_set"]: # GHM songs have custom drum loops. Don't use
struct_perf.append(perf_type)
struct_perf.append(struct["drum"]["facial_anims"])
struct["perf"] = struct_perf.copy()
return female_struct, male_struct
def compile_perf_anims(script_sections, anim_data_dict, use_anims=1, *args, **kwargs):
perf_file = {}
if not use_anims:
female_struct, male_struct = default_anim_structs()
else:
male_struct = deepcopy(anim_struct)
female_struct = deepcopy(anim_struct)
female_anims = ["judita", "ginger", "morgan", "amanda", "debbie", "natalie", "haley"]
special_anim_names = {
"l_guit_chrisvance_bulls_anims": "L_GUIT_ChrisV_Bulls_F_anims",
"l_guit_chrisvance_damnit_anims": "L_GUIT_ChrisV_Damnit_F_anims",
"l_guit_chrisvance_joker_anims": "L_GUIT_ChrisV_Joker_F_anims",
"l_guit_davidicus_bulls_anims": "L_GUIT_Davdics_Bulls_F_anims",
"l_guit_davidicus_damnit2_anims": "L_GUIT_Davdics_Damnit2_F_anims",
"l_guit_davidicus_damnit_anims": "L_GUIT_Davdics_Damnit_F_anims",
"l_guit_davidicus_joker_anims": "L_GUIT_Davdics_Joker_F_anims",
"l_guit_morgan_4horsemen_anims": "L_GUIT_Morgan_4Horse_M_anims",
"l_guit_morgan_bleedingme_anims": "L_GUIT_Morgan_BleedMe_M_anims",
"l_sing_morgan_bleedingns_anims": "L_SING_Morgan_BleedNS_M_anims",
"l_guit_chrisvance_bulls_anims_set": "L_GUIT_ChrisV_Bulls_F_anims_set",
"l_guit_chrisvance_damnit_anims_set": "L_GUIT_ChrisV_Damnit_F_anims_set",
"l_guit_chrisvance_joker_anims_set": "L_GUIT_ChrisV_Joker_F_anims_set",
"l_guit_davidicus_bulls_anims_set": "L_GUIT_Davdics_Bulls_F_anims_set",
"l_guit_davidicus_damnit2_anims_set": "L_GUIT_Davdics_Damnit2_F_anims_set",
"l_guit_davidicus_damnit_anims_set": "L_GUIT_Davdics_Damnit_F_anims_set",
"l_guit_davidicus_joker_anims_set": "L_GUIT_Davdics_Joker_F_anims_set",
"l_guit_morgan_4horsemen_anims_set": "L_GUIT_Morgan_4Horse_M_anims_set",
"l_guit_morgan_bleedingme_anims_set": "L_GUIT_Morgan_BleedMe_M_anims_set",
"l_sing_morgan_bleedingns_anims_set": "L_SING_Morgan_BleedNS_M_anims_set",
"l_guit_joes_hot_150_anims": "L_GUIT_JoeS_Hot_150_anims",
"l_guit_joes_hot_150_anims_set": "L_GUIT_JoeS_Hot_150_anims_set",
"l_guit_dvdicus_bulls_150_anims": "L_GUIT_Dvdicus_Bulls_150_anims",
"l_guit_dvdicus_bulls_150_anims_set": "L_GUIT_Dvdicus_Bulls_150_anims_set",
}
wt_anim_swap = {
"l_sing_haley_joker_anims": "L_SING_Amanda_Joker_anims",
"l_sing_haley_bulls_anims": "L_SING_Amanda_Bulls_anims",
"l_sing_haley_dammit_anims": "L_SING_Amanda_Dammit_anims",
"l_guit_jimi_joker_anims": "l_guit_dan_joker_anims",
"l_sing_haley_joker_anims_set": "L_SING_Amanda_Joker_anims_set",
"l_sing_haley_bulls_anims_set": "L_SING_Amanda_Bulls_anims_set",
"l_sing_haley_dammit_anims_set": "L_SING_Amanda_Dammit_anims_set",
"l_guit_jimi_joker_anims_set": "l_guit_dan_joker_anims_set",
"l_guit_zakk_stillborn_anims": "L_GUIT_Sonny_Stillborn_anims",
"l_guit_zakk_stillborn_anims_set": "L_GUIT_Sonny_Stillborn_anims_set",
"l_guit_sting_demolition_anims": "L_GUIT_Dan_Joker_anims",
"l_guit_sting_demolition_anims_set": "L_GUIT_Dan_Joker_anims_set"
}
no_swap = []
for section in script_sections:
if section.section_id == "0x6c8d898f":
print("Found odd animation structs. Changing...")
section.section_id = "car_male_anim_struct_dlc35"
section.section_data[1].struct_data_struct[1].data_value = "L_GUIT_JoeS_AreYou_anims_set"
if re.search(r"^(car_female|car_male)_anim", section.section_id, flags=re.IGNORECASE):
if not use_anims:
continue
if re.search(r"(purplehaze|windcriesmary|dlc22|dlc23|dlc24|dlc92|dlc96|dlc97)$", section.section_id,
flags=re.IGNORECASE):
for anims in section.section_data:
if anims.data_type == "StructItemStruct":
if anims.data_id.lower() == "vocalist":
anims.data_id = "vocals"
if anims.data_id.lower() == "vocals":
anims.struct_data_struct[0].data_value = "L_SING_JeffS_LowKey_anims"
anims.struct_data_struct[1].data_value = "L_SING_JeffS_LowKey_anims_set"
for anims in section.section_data:
if anims.data_dict["pak"] == "anim_loops":
female_struct, male_struct = default_anim_structs()
use_anims = 0
break
anims.data_id = grab_debug_2(anims.data_id, checksum_dbg)
if anims.data_id == "drum":
anims.struct_data_struct[0].data_value = "L_DRUM_Loops_Standard_anims"
anims.struct_data_struct[1].data_value = "l_drum_loops_standard_anims_set"
if anims.data_id.lower() in anim_struct:
for anim_types in anims.struct_data_struct:
if anim_types.data_id == '0x0':
continue
anim_types.data_id = grab_debug_2(anim_types.data_id, checksum_dbg)
try:
anim_types.data_value = grab_debug_2(anim_types.data_value, checksum_dbg)
except:
if anim_types.data_id == "facial_anims":
anim_types.data_value = f"facial_anims_{'fe' if 'female' in section.section_id else ''}male_rocker"
car_name = anim_types.data_value
if car_name.lower() in wt_anim_swap:
car_name = wt_anim_swap[car_name.lower()]
car_animator = car_name.split("_")[2].lower()
if car_animator in female_anims:
if "car_male" in section.section_id:
if re.search(r"^L_", car_name, flags=re.IGNORECASE):
if car_name.lower() in special_anim_names:
car_name = special_anim_names[car_name.lower()]
elif not re.search(r"^L_drum", car_name, flags=re.IGNORECASE):
if not re.search(r"_M_", car_name, flags=re.IGNORECASE):
f_pos = car_name.rfind("_anim")
car_name = f"{car_name[:f_pos]}_M{car_name[f_pos:]}"
# print()
male_struct[anims.data_id.lower()][anim_types.data_id] = car_name
else:
female_struct[anims.data_id.lower()][anim_types.data_id] = car_name
else:
if "car_female" in section.section_id:
if re.search(r"^L_", car_name, flags=re.IGNORECASE):
if car_name.lower() in special_anim_names:
car_name = special_anim_names[car_name.lower()]
elif not re.search(r"^L_drum", car_name, flags=re.IGNORECASE):
if not re.search(r"_F_", car_name, flags=re.IGNORECASE):
f_pos = car_name.rfind("_anim")
car_name = f"{car_name[:f_pos]}_F{car_name[f_pos:]}"
# print()
female_struct[anims.data_id.lower()][anim_types.data_id] = car_name
else:
male_struct[anims.data_id.lower()][anim_types.data_id] = car_name
elif "Struct" in section.section_type:
if section.section_id not in anim_data_dict:
anim_data_dict[section.section_id] = section
else:
pass
female_struct, male_struct = perf_struct(female_struct, male_struct)