forked from sylverb/game-and-watch-retro-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse_roms.py
1753 lines (1555 loc) · 63 KB
/
parse_roms.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 python3
import argparse
import hashlib
import os
import shutil
import struct
import subprocess
import sys
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import List
try:
from tqdm import tqdm
except ImportError:
tqdm = None
ROM_ENTRIES_TEMPLATE = """
const retro_emulator_file_t {name}[] EMU_DATA = {{
{body}
}};
const uint32_t {name}_count = {rom_count};
"""
# Note: this value is not easily changed as it's assumed in some memory optimizations
MAX_CHEAT_CODES = 16
ROM_ENTRY_TEMPLATE = """\t{{
#if CHEAT_CODES == 1
\t\t.id = {rom_id},
#endif
\t\t.name = "{name}",
\t\t.ext = "{extension}",
\t\t.address = {rom_entry},
\t\t.size = {size},
\t\t#if COVERFLOW != 0
\t\t.img_address = {img_entry},
\t\t.img_size = {img_size},
\t\t#endif
\t\t.save_address = {save_entry},
\t\t.save_size = {save_size},
\t\t.system = &{system},
\t\t.region = {region},
\t\t.mapper = {mapper},
\t\t.game_config = {game_config},
#if CHEAT_CODES == 1
\t\t.cheat_codes = {cheat_codes},
\t\t.cheat_descs = {cheat_descs},
\t\t.cheat_count = {cheat_count},
#endif
\t}},"""
SYSTEM_PROTO_TEMPLATE = """
#if !defined (COVERFLOW)
#define COVERFLOW 0
#endif /* COVERFLOW */
#if !defined (BIG_BANK)
#define BIG_BANK 1
#endif
#if (BIG_BANK == 1) && (EXTFLASH_SIZE <= 128*1024*1024)
#define EMU_DATA
#else
#define EMU_DATA __attribute__((section(".extflash_emu_data")))
#endif
extern const rom_system_t {name};
"""
SYSTEM_TEMPLATE = """
const rom_system_t {name} EMU_DATA = {{
\t.system_name = "{system_name}",
\t.roms = {variable_name},
\t.extension = "{extension}",
\t#if COVERFLOW != 0
\t.cover_width = {cover_width},
\t.cover_height = {cover_height},
\t#endif
\t.roms_count = {roms_count},
}};
"""
SAVE_SIZES = {
"nes": 24 * 1024, # only when using nofrendo, elseway it's given by nesmapper script
"sms": 60 * 1024,
"gg": 60 * 1024,
"col": 60 * 1024,
"sg": 60 * 1024,
"pce": 76 * 1024,
"msx": 272 * 1024,
"gw": 4 * 1024,
"wsv": 28 * 1024,
"md": 144 * 1024,
"a7800": 36 * 1024,
"amstrad": 132 * 1024,
"zelda3": 272 * 1024,
"smw": 264 * 1024,
"tama": 8 * 1024,
}
# TODO: Find a better way to find this before building
MAX_COMPRESSED_NES_SIZE = 0x00080010 #512kB + 16 bytes header
MAX_COMPRESSED_PCE_SIZE = 0x00049000
MAX_COMPRESSED_WSV_SIZE = 0x00080000
MAX_COMPRESSED_SG_COL_SIZE = 60 * 1024
MAX_COMPRESSED_A7800_SIZE = 131200
MAX_COMPRESSED_MSX_SIZE = 136*1024
"""
All ``compress_*`` functions must be decorated ``@COMPRESSIONS`` and have the
following signature:
Positional argument:
data : bytes
Optional argument:
level : ``None`` for default value, depends on compression algorithm.
Can be the special ``DONT_COMPRESS`` sentinel value, in which the
returned uncompressed data is properly framed to be handled by the
decompressor.
And return compressed bytes.
"""
DONT_COMPRESS = object()
class CompressionRegistry(dict):
prefix = "compress_"
def __call__(self, f):
name = f.__name__
assert name.startswith(self.prefix)
key = name[len(self.prefix) :]
self[key] = f
self["." + key] = f
return f
COMPRESSIONS = CompressionRegistry()
@COMPRESSIONS
def compress_lzma(data, level=None):
if level == DONT_COMPRESS:
if args.compress_gb_speed:
raise NotImplementedError
# This currently assumes this will only be applied to GB Bank 0
return data
import lzma
compressed_data = lzma.compress(
data,
format=lzma.FORMAT_ALONE,
filters=[
{
"id": lzma.FILTER_LZMA1,
"preset": 6,
"dict_size": 16 * 1024,
}
],
)
compressed_data = compressed_data[13:]
return compressed_data
def sha1_for_file(filename):
sha1 = hashlib.sha1()
if os.path.exists(filename):
with open(filename, 'rb') as f:
while True:
data = f.read(16*1024)
if not data:
break
sha1.update(data)
return sha1.hexdigest()
else:
return ""
def parse_msx_bios_files():
#check that required MSX bios files are present
if (sha1_for_file("roms/msx_bios/MSX2P.rom") != "e90f80a61d94c617850c415e12ad70ac41e66bb7"):
print("Bad or missing roms/msx_bios/MSX2P.rom, check roms/msx_bios/README.md for info")
return 0
if (sha1_for_file("roms/msx_bios/MSX2PEXT.rom") != "fe0254cbfc11405b79e7c86c7769bd6322b04995"):
print("Bad or missing roms/msx_bios/MSX2PEXT.rom, check roms/msx_bios/README.md for info")
return 0
if (sha1_for_file("roms/msx_bios/MSX2PMUS.rom") != "6354ccc5c100b1c558c9395fa8c00784d2e9b0a3"):
print("Bad or missing roms/msx_bios/MSX2PMUS.rom, check roms/msx_bios/README.md for info")
return 0
if (sha1_for_file("roms/msx_bios/MSX2.rom") != "6103b39f1e38d1aa2d84b1c3219c44f1abb5436e"):
print("Bad or missing roms/msx_bios/MSX2.rom, check roms/msx_bios/README.md for info")
return 0
if (sha1_for_file("roms/msx_bios/MSX2EXT.rom") != "5c1f9c7fb655e43d38e5dd1fcc6b942b2ff68b02"):
print("Bad or missing roms/msx_bios/MSX2EXT.rom, check roms/msx_bios/README.md for info")
return 0
if (sha1_for_file("roms/msx_bios/MSX.rom") != "e998f0c441f4f1800ef44e42cd1659150206cf79"):
print("Bad or missing roms/msx_bios/MSX.rom, check roms/msx_bios/README.md for info")
return 0
# We revert previously patched PANASONICDISK if needed as we changed how it is done
if (sha1_for_file("roms/msx_bios/PANASONICDISK.rom") == "b9bce28fb74223ea902f82ebd107279624cf2aba"):
print("Reverting patch on roms/msx_bios/PANASONICDISK.rom")
with open("roms/msx_bios/PANASONICDISK.rom", 'rb+') as f:
f.seek(0x17ec)
f.write(b'\x02')
if (sha1_for_file("roms/msx_bios/PANASONICDISK.rom") != "7ed7c55e0359737ac5e68d38cb6903f9e5d7c2b6"):
print("Bad or missing roms/msx_bios/PANASONICDISK.rom, check roms/msx_bios/README.md for info")
return 0
# PANASONICDISK_.rom is a patched version of PANASONICDISK.rom to disable the 2nd FDD
# this is allowing to free some ram, which is needed for some games. It could be done by pressing
# ctrl key at boot using original bios, but using this patched version, the user will have nothing
# to do. Unfortunately this version can't be used in all cases because some games (from Micro Cabin)
# like Fray, XAK III,
if (sha1_for_file("roms/msx_bios/PANASONICDISK_.rom") != "b9bce28fb74223ea902f82ebd107279624cf2aba"):
shutil.copy("roms/msx_bios/PANASONICDISK.rom","roms/msx_bios/PANASONICDISK_.rom")
if (sha1_for_file("roms/msx_bios/PANASONICDISK_.rom") == "7ed7c55e0359737ac5e68d38cb6903f9e5d7c2b6"):
print("Patching roms/msx_bios/PANASONICDISK_.rom to disable 2nd FDD controller (= more free RAM)")
with open("roms/msx_bios/PANASONICDISK_.rom", 'rb+') as f:
f.seek(0x17ec)
f.write(b'\x00')
else:
print("Bad or missing roms/msx_bios/PANASONICDISK.rom, check roms/msx_bios/README.md for info")
return 0
return 1
def compare_versions(version1, version2):
"""
Compare two versions represented as strings.
Returns:
-1 if version1 < version2
0 if version1 == version2
1 if version1 > version2
"""
v1_parts = [int(part) for part in version1.split('.')]
v2_parts = [int(part) for part in version2.split('.')]
for v1, v2 in zip(v1_parts, v2_parts):
if v1 < v2:
return -1
elif v1 > v2:
return 1
# If all parts are equal, compare the lengths
if len(v1_parts) < len(v2_parts):
return -1
elif len(v1_parts) > len(v2_parts):
return 1
else:
return 0
def write_covart(srcfile, fn, w, h, jpg_quality):
from PIL import Image, ImageOps
if compare_versions(Image.__version__, '7.0') >= 0:
dither = Image.Resampling.LANCZOS
else:
dither = Image.ANTIALIAS
img = Image.open(srcfile).convert(mode="RGB").resize((w, h), dither)
img.save(fn,format="JPEG",optimize=True,quality=jpg_quality)
# def write_rgb565(srcfile, fn, v):
# from PIL import Image, ImageOps
# #print(srcfile)
# img = Image.open(srcfile).convert(mode="RGB")
# img = img.resize((w, h), Image.ANTIALIAS)
# pixels = list(img.getdata())
# with open(fn, "wb") as f:
# #no file header
# for pix in pixels:
# r = (pix[0] >> 3) & 0x1F
# g = (pix[1] >> 2) & 0x3F
# b = (pix[2] >> 3) & 0x1F
# f.write(struct.pack("H", (r << 11) + (g << 5) + b))
class NoArtworkError(Exception):
"""No artwork found for this ROM"""
class ROM:
def __init__(self, system_name: str, filepath: str, extension: str, romdefs: dict):
filepath = Path(filepath)
self.rom_id = 0
self.path = filepath
self.filename = filepath
# Remove compression extension from the name in case it ends with that
if filepath.suffix in COMPRESSIONS or filepath.suffix == '.cdk':
self.filename = filepath.with_suffix("").stem
else :
self.filename = filepath.stem
romdefs.setdefault(self.filename, {})
self.romdef = romdefs[self.filename]
self.romdef.setdefault('name', self.filename)
self.romdef.setdefault('publish', '1')
self.romdef.setdefault('embed', '1')
self.romdef.setdefault('enable_save', '0')
self.publish = (self.romdef['publish'] == '1')
self.embed = (self.romdef['embed'] == '1')
self.enable_save = (self.romdef['enable_save'] == '1') or args.save
self.system_name = system_name
self.name = self.romdef['name']
print("Found rom " + self.filename +" will display name as: " + self.romdef['name'])
if not (self.publish):
print("& will not Publish !")
if not (self.embed):
print("& will not embed !")
self.symbol = "0";
obj_name = "".join([i if i.isalnum() else "_" for i in self.path.name])
self.obj_path = "build/roms/" + obj_name + ".o"
symbol_path = str(self.path.parent) + "/" + obj_name
if (self.embed):
self.symbol = (
"_binary_"
+ "".join([i if i.isalnum() else "_" for i in symbol_path])
+ "_start"
)
self.img_path = self.path.parent / (self.filename + ".img")
obj_name = "".join([i if i.isalnum() else "_" for i in self.img_path.name])
symbol_path = str(self.path.parent) + "/" + obj_name
self.obj_img = "build/roms/" + obj_name + "_" + extension + ".o"
self.img_symbol = (
"_binary_"
+ "".join([i if i.isalnum() else "_" for i in symbol_path])
+ "_start"
)
def __str__(self) -> str:
return f"id: {self.rom_id} name: {self.name} size: {self.size} ext: {self.ext}"
def __repr__(self):
return str(self)
def read(self):
return self.path.read_bytes()
def get_rom_patchs(self):
#get pce rompatchs files
pceplus = Path(self.path.parent, self.filename + ".pceplus")
if not os.path.exists(pceplus):
return []
codes_and_descs = []
for line in pceplus.read_text().splitlines():
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
parts = line.split(',')
cmd_count = 0
cmd_str = ""
for i in range(len(parts) - 1):
part = parts[i].strip()
#get cmd byte count
x_str = part[0:2]
x = (int(x_str, 16) >> 4) + 1
one_cmd = ""
for y in range(3):
one_cmd = one_cmd + "\\x" + part[y * 2: y * 2 + 2]
for y in range(x):
one_cmd = one_cmd + "\\x" + part[y * 2 + 6: y * 2 + 8]
#got one cmd
cmd_count += 1
cmd_str = cmd_str + one_cmd
cmd_str = "\\x%x" % (cmd_count) + cmd_str
desc = parts[len(parts) - 1]
if desc is not None:
desc = desc[:40]
desc = desc.replace('\\', r'\\\\')
desc = desc.replace('"', r'\"')
desc = desc.strip()
codes_and_descs.append((cmd_str, desc))
if len(codes_and_descs) > MAX_CHEAT_CODES:
print(
f"INFO: {self.name} has more than {MAX_CHEAT_CODES} cheat codes. Truncating..."
)
codes_and_descs = codes_and_descs[:MAX_CHEAT_CODES]
return codes_and_descs
def get_cheat_codes(self):
# Get game genie code file path
gg_path = Path(self.path.parent, self.filename + ".ggcodes")
if os.path.exists(gg_path):
codes_and_descs = []
for line in gg_path.read_text().splitlines():
line = line.strip()
if not line:
continue
parts = line.split(',', 1)
code = parts[0]
desc = None
if len(parts)>1:
desc = parts[1]
# Remove whitespace
code = "".join(code.split())
# Remove empty lines
if code == "":
continue
# Capitalize letters
code = code.upper()
# Shorten description
if desc is not None:
desc = desc[:40]
desc = desc.replace('\\', r'\\\\')
desc = desc.replace('"', r'\"')
desc = desc.strip()
codes_and_descs.append((code, desc))
if len(codes_and_descs) > MAX_CHEAT_CODES:
print(
f"INFO: {self.name} has more than {MAX_CHEAT_CODES} cheat codes. Truncating..."
)
codes_and_descs = codes_and_descs[:MAX_CHEAT_CODES]
return codes_and_descs
pceplus = Path(self.path.parent, self.filename + ".pceplus")
if os.path.exists(pceplus):
return self.get_rom_patchs()
mfc_path = Path(self.path.parent, self.filename + ".mcf")
if os.path.exists(mfc_path):
codes_and_descs = []
for line in mfc_path.read_text(encoding="cp1252").splitlines():
line = line.strip()
if not line:
continue
# Check if it's a comment
if line[0] == '!':
continue
parts = line.split(',', 4)
if len(parts) == 5:
length = 1
if int(parts[2]) > 0xff:
length = 2
elif int(parts[2]) > 0xffff:
length = 4
code = parts[1]+','+parts[2]+','+str(length)
desc = None
if len(parts)>4:
desc = parts[4]
# Remove whitespace
code = "".join(code.split())
# Remove empty lines
if code == "":
continue
# Capitalize letters
code = code.upper()
# Shorten description
if desc is not None:
desc = desc[:40]
desc = desc.replace('\\', r'\\\\')
desc = desc.replace('"', r'\"')
desc = desc.strip()
codes_and_descs.append((code, desc))
elif len(parts) == 1:
parts = line.split(':', 4)
if int(parts[2]) == 0:
length = 1
elif int(parts[2]) == 1:
length = 2
elif int(parts[2]) == 2:
length = 4
code = str(int(parts[0], base=16))+','+str(int(parts[1], base=16))+','+str(length)
desc = None
if len(parts)>4:
desc = parts[4]
# Remove whitespace
code = "".join(code.split())
# Remove empty lines
if code == "":
continue
# Capitalize letters
code = code.upper()
# Shorten description
if desc is not None:
desc = desc[:40]
desc = desc.replace('\\', r'\\\\')
desc = desc.replace('"', r'\"')
desc = desc.strip()
codes_and_descs.append((code, desc))
if len(codes_and_descs) > MAX_CHEAT_CODES:
print(
f"INFO: {self.name} has more than {MAX_CHEAT_CODES} cheat codes. Truncating..."
)
codes_and_descs = codes_and_descs[:MAX_CHEAT_CODES]
return codes_and_descs
# No cheat file found
return []
@property
def ext(self):
return self.path.suffix[1:].lower()
@property
def size(self):
return self.path.stat().st_size
@property
def mapper(self):
mapper = 0
if self.system_name == "MSX":
mapper = int(subprocess.check_output([sys.executable, "./tools/findblueMsxMapper.py", "roms/msx_bios/msxromdb.xml", str(self.path).replace('.dsk.cdk','.dsk').replace('.lzma','')]))
if self.system_name == "Nintendo Entertainment System":
mapper = int(subprocess.check_output([sys.executable, "./fceumm-go/nesmapper.py", "mapper", str(self.path).replace('.lzma','')]))
return mapper
@property
def game_config(self):
value = 0xff
if self.system_name == "MSX":
# MSX game_config structure :
# b7-b0 : Controls profile
# b8 : Does the game require to press ctrl at boot ?
sp_output = subprocess.check_output([sys.executable, "./tools/findblueMsxControls.py", "roms/msx_bios/msxromdb.xml", str(self.path).replace('.dsk.cdk','.dsk').replace('.lzma','')]).splitlines()
value = int(sp_output[0]) + (int(sp_output[1]) << 8)
if int(sp_output[0]) == 0xff :
print(f"Warning : {self.name} has no controls configuration in roms/msx_bios/msxromdb.xml, default controls will be used")
return value
@property
def img_size(self):
try:
return self.img_path.stat().st_size
except FileNotFoundError:
return 0
class ROMParser:
global sms_reserved_flash_size
def find_roms(self, system_name: str, folder: str, extension: str, romdefs: dict) -> [ROM]:
extension = extension.lower()
ext = extension
if not extension.startswith("."):
extension = "." + extension
script_path = Path(__file__).parent
roms_folder = script_path / "roms" / folder
# find all files that end with extension (case-insensitive)
rom_files = list(roms_folder.iterdir())
rom_files = [r for r in rom_files if r.name.lower().endswith(extension)]
rom_files.sort()
found_roms = [ROM(system_name, rom_file, ext, romdefs) for rom_file in rom_files]
for rom in found_roms:
suffix = "_no_save"
if rom.name.endswith(suffix) :
rom.name = rom.name[:-len(suffix)]
rom.enable_save = False
return found_roms
def generate_rom_entries(
self, name: str, roms: [ROM], save_prefix: str, system: str, cheat_codes_prefix: str
) -> str:
body = ""
pubcount = 0
for i in range(len(roms)):
rom = roms[i]
if not (rom.publish):
continue
is_pal = any(
substring in rom.filename
for substring in [
"(E)",
"(Europe)",
"(Sweden)",
"(Germany)",
"(Italy)",
"(France)",
"(A)",
"(Australia)",
]
)
region = "REGION_PAL" if is_pal else "REGION_NTSC"
gg_count_name = "%s%s_COUNT" % (cheat_codes_prefix, i)
gg_code_array_name = "%sCODE_%s" % (cheat_codes_prefix, i)
gg_desc_array_name = "%sDESC_%s" % (cheat_codes_prefix, i)
body += ROM_ENTRY_TEMPLATE.format(
rom_id=rom.rom_id,
name=str(rom.name),
size=rom.size,
rom_entry=rom.symbol,
img_size=rom.img_size,
img_entry=rom.img_symbol if rom.img_size else "NULL",
save_entry=(save_prefix + str(i)) if rom.enable_save else "NULL",
save_size=("sizeof(" + save_prefix + str(i) + ")") if rom.enable_save else "0",
region=region,
extension=rom.ext,
system=system,
cheat_codes=gg_code_array_name if cheat_codes_prefix else "NULL",
cheat_descs=gg_desc_array_name if cheat_codes_prefix else 0,
cheat_count=gg_count_name if cheat_codes_prefix else 0,
mapper=rom.mapper,
game_config=rom.game_config,
)
body += "\n"
pubcount += 1
return ROM_ENTRIES_TEMPLATE.format(name=name, body=body, rom_count=pubcount)
def generate_object_file(self, rom: ROM,system_name) -> str:
# convert rom to an .o file and place the data in the .extflash_game_rom section
prefix = ""
if "GCC_PATH" in os.environ:
prefix = os.environ["GCC_PATH"]
prefix = Path(prefix)
if system_name == "Sega Genesis":
subprocess.check_output(
[
prefix / "arm-none-eabi-objcopy",
"--rename-section",
".data=.extflash_game_rom,alloc,load,readonly,data,contents",
"-I",
"binary",
"-O",
"elf32-littlearm",
"-B",
"armv7e-m",
"--reverse-bytes=2",
rom.path,
rom.obj_path,
]
)
else:
subprocess.check_output(
[
prefix / "arm-none-eabi-objcopy",
"--rename-section",
".data=.extflash_game_rom,alloc,load,readonly,data,contents",
"-I",
"binary",
"-O",
"elf32-littlearm",
"-B",
"armv7e-m",
rom.path,
rom.obj_path,
]
)
subprocess.check_output(
[
prefix / "arm-none-eabi-ar",
"-cr",
"build/roms.a",
rom.obj_path,
]
)
template = "extern const uint8_t {name}[];\n"
return template.format(name=rom.symbol)
def generate_img_object_file(self, rom: ROM, w, h) -> str:
# convert rom_img to an .o file and place the data in the .extflash_game_rom section
prefix = ""
if "GCC_PATH" in os.environ:
prefix = os.environ["GCC_PATH"]
prefix = Path(prefix)
imgs = []
imgs.append(str(rom.img_path.with_suffix(".png")))
imgs.append(str(rom.img_path.with_suffix(".PNG")))
imgs.append(str(rom.img_path.with_suffix(".Png")))
imgs.append(str(rom.img_path.with_suffix(".jpg")))
imgs.append(str(rom.img_path.with_suffix(".JPG")))
imgs.append(str(rom.img_path.with_suffix(".Jpg")))
imgs.append(str(rom.img_path.with_suffix(".jpeg")))
imgs.append(str(rom.img_path.with_suffix(".JPEG")))
imgs.append(str(rom.img_path.with_suffix(".Jpeg")))
imgs.append(str(rom.img_path.with_suffix(".bmp")))
imgs.append(str(rom.img_path.with_suffix(".BMP")))
imgs.append(str(rom.img_path.with_suffix(".Bmp")))
for img in imgs:
if Path(img).exists():
write_covart(Path(img), rom.img_path, w, h, args.jpg_quality)
break
if not rom.img_path.exists():
raise NoArtworkError
print(f"INFO: Packing {rom.name} Cover> {rom.img_path} ...")
subprocess.check_output(
[
prefix / "arm-none-eabi-objcopy",
"--rename-section",
".data=.extflash_game_rom,alloc,load,readonly,data,contents",
"-I",
"binary",
"-O",
"elf32-littlearm",
"-B",
"armv7e-m",
rom.img_path,
rom.obj_img,
]
)
subprocess.check_output(
[
prefix / "arm-none-eabi-ar",
"-cru",
"build/roms.a",
rom.obj_img,
]
)
template = "extern const uint8_t {name}[];\n"
return template.format(name=rom.img_symbol)
def generate_save_entry(self, name: str, save_size: int) -> str:
return f'uint8_t {name}[{save_size}] __attribute__((section (".saveflash"))) __attribute__((aligned(4096)));\n'
def generate_cheat_entry(self, name: str, num: int, cheat_codes_and_descs: []) -> str:
str = ""
codes = "{%s}" % ",".join(f'"{c}"' for (c,d) in cheat_codes_and_descs)
descs = "{%s}" % ",".join(f'NULL' if d is None else f'"{d}"' for (c,d) in cheat_codes_and_descs)
number_of_codes = len(cheat_codes_and_descs)
count_name = "%s%s_COUNT" % (name, num)
code_array_name = "%sCODE_%s" % (name, num)
desc_array_name = "%sDESC_%s" % (name, num)
str += f'#if CHEAT_CODES == 1\n'
str += f'const char* {code_array_name}[{number_of_codes}] = {codes};\n'
str += f'const char* {desc_array_name}[{number_of_codes}] = {descs};\n'
str += f'const int {count_name} = {number_of_codes};\n'
str += f'#endif\n'
return str
def get_gameboy_save_size(self, file: Path):
total_size = 4096
file = Path(file)
if file.suffix in COMPRESSIONS:
file = file.with_suffix("") # Remove compression suffix
with open(file, "rb") as f:
# cgb
f.seek(0x143)
cgb = ord(f.read(1))
# 0x80 = Gameboy color but supports old gameboy
# 0xc0 = Gameboy color only
if cgb & 0x80 or cgb == 0xC0:
# Bank 0 + 1-7 for gameboy color work ram
total_size += 8 * 4096 # irl
# Bank 0 + 1 for gameboy color video ram, 2*8KiB
total_size += 4 * 4096 # vrl
else:
# Bank 0 + 1 for gameboy classic work ram
total_size += 2 * 4096 # irl
# Bank 0 only for gameboy classic video ram, 1*8KiB
total_size += 2 * 4096 # vrl
# Cartridge ram size
f.seek(0x149)
total_size += [1, 1, 1, 4, 16, 8][ord(f.read(1))] * 8 * 1024
return total_size
return 0
def get_nes_save_size(self, file: Path):
file = Path(file)
if file.suffix in COMPRESSIONS:
file = file.with_suffix("") # Remove compression suffix
total_size = int(subprocess.check_output([sys.executable, "./fceumm-go/nesmapper.py", "savesize", file]))
return total_size
return 0
def _compress_rom(self, variable_name, rom, compress_gb_speed=False, compress=None):
"""This will create a compressed rom file next to the original rom."""
global sms_reserved_flash_size
if not (rom.publish):
return
if compress is None:
compress = "lz4"
if compress not in COMPRESSIONS:
raise ValueError(f'Unknown compression method: "{compress}"')
if compress[0] != ".":
compress = "." + compress
output_file = Path(str(rom.path) + compress)
compress = COMPRESSIONS[compress]
data = rom.read()
if "nes_system" in variable_name: # NES
if rom.path.stat().st_size > MAX_COMPRESSED_NES_SIZE:
print(
f"INFO: {rom.name} is too large to compress, skipping compression!"
)
return
compressed_data = compress(data)
output_file.write_bytes(compressed_data)
elif "pce_system" in variable_name: # PCE
if rom.path.stat().st_size > MAX_COMPRESSED_PCE_SIZE:
print(
f"INFO: {rom.name} is too large to compress, skipping compression!"
)
return
compressed_data = compress(data)
output_file.write_bytes(compressed_data)
elif "msx_system" in variable_name: # MSX
if rom.path.stat().st_size > MAX_COMPRESSED_MSX_SIZE:
print(
f"INFO: {rom.name} is too large to compress, skipping compression!"
)
return
compressed_data = compress(data)
output_file.write_bytes(compressed_data)
elif "wsv_system" in variable_name: # WSV
if rom.path.stat().st_size > MAX_COMPRESSED_WSV_SIZE:
print(
f"INFO: {rom.name} is too large to compress, skipping compression!"
)
return
compressed_data = compress(data)
output_file.write_bytes(compressed_data)
elif "a7800_system" in variable_name: # Atari 7800
if rom.path.stat().st_size > MAX_COMPRESSED_A7800_SIZE:
print(
f"INFO: {rom.name} is too large to compress, skipping compression!"
)
return
compressed_data = compress(data)
output_file.write_bytes(compressed_data)
elif variable_name in ["col_system","sg1000_system"] : # COL or SG
if rom.path.stat().st_size > MAX_COMPRESSED_SG_COL_SIZE:
print(
f"INFO: {rom.name} is too large to compress, skipping compression!"
)
return
compressed_data = compress(data)
output_file.write_bytes(compressed_data)
elif variable_name in ["sms_system","gg_system","md_system"]: # GG or SMS or MD
BANK_SIZE = 128*1024
banks = [data[i : i + BANK_SIZE] for i in range(0, len(data), BANK_SIZE)]
compressed_banks = [compress(bank) for bank in banks]
# add header + number of banks + banks(offset)
output_data=[]
output_data.append( b'SMS+')
output_data.append(pack("<l", len(compressed_banks)))
for compressed_bank in compressed_banks:
output_data.append(pack("<l", len(compressed_bank)))
# Reassemble all banks back into one file
for compressed_bank in compressed_banks:
output_data.append(compressed_bank)
output_data = b"".join(output_data)
output_file.write_bytes(output_data)
elif "gb_system" in variable_name: # GB/GBC
BANK_SIZE = 16384
banks = [data[i : i + BANK_SIZE] for i in range(0, len(data), BANK_SIZE)]
compressed_banks = [compress(bank) for bank in banks]
# For ROM having continous bank switching we can use 'partial' compression
# a mix of comcompressed and uncompress
# compress empty banks and the bigger compress ratio
compress_its = [True] * len(banks)
compress_its[0] = False # keep bank0 uncompressed
# START : ALTERNATIVE COMPRESSION STRATEGY
if compress_gb_speed:
# the larger banks only are compressed.
# It shoul fit exactly in the cache reducing the SWAP cache feequency to 0.
# any empty bank is compressed (=98bytes). considered never used by MBC.
# Ths is the cache size used as a compression credit
# TODO : can we the value from the linker ?
compression_credit = 26
compress_size = [len(bank) for bank in compressed_banks[1:]]
# to keep empty banks compressed (size=98)
compress_size = [i for i in compress_size if i > 98]
ordered_size = sorted(compress_size)
if compression_credit > len(ordered_size):
compression_credit = len(ordered_size) - 1
compress_threshold = ordered_size[int(compression_credit)]
for i, bank in enumerate(compressed_banks):
if len(bank) >= compress_threshold:
# Don't compress banks with poor compression
compress_its[i] = False
# END : ALTERNATIVE COMPRESSION STRATEGY
# Reassemble all banks back into one file
output_banks = []
for bank, compressed_bank, compress_it in zip(
banks, compressed_banks, compress_its
):
if compress_it:
output_banks.append(compressed_bank)
else:
output_banks.append(compress(bank, level=DONT_COMPRESS))
output_data = b"".join(output_banks)
output_file.write_bytes(output_data)
def _convert_dsk(self, variable_name, dsk, compress):
"""This will convert dsk image to cdk."""
if not (dsk.publish):
return
if compress is None:
compress="none"
if "msx_system" in variable_name: # MSX disk compression
subprocess.check_output("python3 tools/dsk2lzma.py \""+str(dsk.path)+"\" "+compress, shell=True)
if "amstrad_system" in variable_name: # Amstrad disk compression
subprocess.check_output("python3 tools/amdsk2lzma.py \""+str(dsk.path)+"\" "+compress, shell=True)
def generate_system(
self,
file: str,
system_name: str,
variable_name: str,
folder: str,
extensions: List[str],
save_prefix: str,
romdefs: dict,
cheat_codes_prefix: str,
current_id: int,
compress: str = None,
compress_gb_speed: bool = False,
) -> int:
import json;
script_path = Path(__file__).parent
json_file = script_path / "roms" / str(folder + ".json")
print(json_file)
if Path(json_file).exists():
with open(json_file,'r') as load_f:
try:
romdef = json.load(load_f)
load_f.close()
romdefs = romdef
except:
load_f.close()
roms_raw = []
for e in extensions:
roms_raw += self.find_roms(system_name, folder, e, romdefs)
roms_uncompressed = roms_raw
def find_compressed_roms():
if not compress:
return []
roms = []
for e in extensions:
roms += self.find_roms(system_name, folder, e + "." + compress, romdefs)
return roms
def find_disks():
disks = self.find_roms(system_name, folder, "dsk", romdefs)
# If a disk name ends with _no_save then it means that we shouldn't
# allocate save space for this disk (to use with multi disks games