-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetatiled.py
More file actions
1382 lines (1095 loc) · 50.7 KB
/
Copy pathmetatiled.py
File metadata and controls
1382 lines (1095 loc) · 50.7 KB
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 os
import shutil
import colorsys
import argparse
from PIL import Image, ImageOps, ImageDraw
# COLOR -----------------------------------------------------------------------
palettes = {
"morn": {
"GRAY": [(28, 31, 16), (21, 21, 21), (13, 13, 13), (7, 7, 7)],
"RED": [(28, 31, 16), (31, 19, 24), (30, 10, 6), (7, 7, 7)],
"GREEN": [(22, 31, 10), (12, 25, 1), (5, 14, 0), (7, 7, 7)],
"WATER": [(23, 23, 31), (18, 19, 31), (13, 12, 31), (7, 7, 7)],
"YELLOW": [(28, 31, 16), (31, 31, 7), (31, 16, 1), (7, 7, 7)],
"BROWN": [(28, 31, 16), (24, 18, 7), (20, 15, 3), (7, 7, 7)],
"ROOF": [(28, 31, 16), (15, 31, 31), (5, 17, 31), (7, 7, 7)],
"TEXT": [(31, 31, 16), (31, 31, 16), (14, 9, 0), (0, 0, 0)]
},
"day": {
"GRAY": [(27, 31, 27), (21, 21, 21), (13, 13, 13), (7, 7, 7)],
"RED": [(27, 31, 27), (31, 19, 24), (30, 10, 6), (7, 7, 7)],
"GREEN": [(22, 31, 10), (12, 25, 1), (5, 14, 0), (7, 7, 7)],
"WATER": [(23, 23, 31), (18, 19, 31), (13, 12, 31), (7, 7, 7)],
"YELLOW": [(27, 31, 27), (31, 31, 7), (31, 16, 1), (7, 7, 7)],
"BROWN": [(27, 31, 27), (24, 18, 7), (20, 15, 3), (7, 7, 7)],
"ROOF": [(27, 31, 27), (15, 31, 31), (5, 17, 31), (7, 7, 7)],
"TEXT": [(31, 31, 16), (31, 31, 16), (14, 9, 0), (0, 0, 0)]
},
"nite": {
"GRAY": [(15, 14, 24), (11, 11, 19), (7, 7, 12), (0, 0, 0)],
"RED": [(15, 14, 24), (14, 7, 17), (13, 0, 8), (0, 0, 0)],
"GREEN": [(15, 14, 24), (8, 13, 19), (0, 11, 13), (0, 0, 0)],
"WATER": [(15, 13, 27), (10, 9, 20), (4, 3, 18), (0, 0, 0)],
"YELLOW": [(30, 30, 11), (16, 14, 18), (16, 14, 10), (0, 0, 0)],
"BROWN": [(15, 14, 24), (12, 9, 15), (8, 4, 5), (0, 0, 0)],
"ROOF": [(15, 14, 24), (13, 12, 23), (11, 9, 20), (0, 0, 0)],
"TEXT": [(31, 31, 16), (31, 31, 16), (14, 9, 0), (0, 0, 0)]
},
"dark": {
"GRAY": [(1, 1, 2), (0, 0, 0), (0, 0, 0), (0, 0, 0)],
"RED": [(1, 1, 2), (0, 0, 0), (0, 0, 0), (0, 0, 0)],
"GREEN": [(1, 1, 2), (0, 0, 0), (0, 0, 0), (0, 0, 0)],
"WATER": [(1, 1, 2), (0, 0, 0), (0, 0, 0), (0, 0, 0)],
"YELLOW": [(30, 30, 11), (0, 0, 0), (0, 0, 0), (0, 0, 0)],
"BROWN": [(1, 1, 2), (0, 0, 0), (0, 0, 0), (0, 0, 0)],
"ROOF": [(1, 1, 2), (0, 0, 0), (0, 0, 0), (0, 0, 0)],
"TEXT": [(31, 31, 16), (31, 31, 16), (14, 9, 0), (0, 0, 0)]
},
"indoor": {
"GRAY": [(30, 28, 26), (19, 19, 19), (13, 13, 13), (7, 7, 7)],
"RED": [(30, 28, 26), (31, 19, 24), (30, 10, 6), (7, 7, 7)],
"GREEN": [(18, 24, 9), (15, 20, 1), (9, 13, 0), (7, 7, 7)],
"WATER": [(30, 28, 26), (15, 16, 31), (9, 9, 31), (7, 7, 7)],
"YELLOW": [(30, 28, 26), (31, 31, 7), (31, 16, 1), (7, 7, 7)],
"BROWN": [(26, 24, 17), (21, 17, 7), (16, 13, 3), (7, 7, 7)],
"ROOF": [(30, 28, 26), (17, 19, 31), (14, 16, 31), (7, 7, 7)],
"TEXT": [(31, 31, 16), (31, 31, 16), (14, 9, 0), (0, 0, 0)]
}
}
def is_same_tone(tile_tone, palette_tone, tolerance=1):
match = all([abs(tile_tone[i] - palette_tone[i])
<= tolerance for i in range(3)])
return match
def is_same_color(tile_tones, palette_tones):
match = all([any(is_same_tone(tile_tone, palette_tone)
for palette_tone in palette_tones) for tile_tone in tile_tones])
return match
def convert_to_5bit_rgb(color):
return tuple((c * 31) // 255 for c in color)
def convert_to_8bit_rgb(color):
return tuple((c * 255) // 31 for c in color)
def rgb_to_hex(rgb):
return ''.join(f'{value:02X}' for value in rgb)
def hex_to_rgb(hex_color):
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
def palettes_to_8bit_rgb(palettes):
palettes_8bit = {
palette_name: {
color_name: [convert_to_8bit_rgb(c) for c in tones]
for color_name, tones in colors.items()
}
for palette_name, colors in palettes.items()
}
return palettes_8bit
def sort_color(tones):
'''Sort using luminance formula'''
return sorted(tones, key=lambda c: (
0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]), reverse=True)
def is_tile_white(tile):
white_pixel = (255, 255, 255)
for pixel in tile.getdata():
if pixel != white_pixel:
return False
return True
def tile_to_grayscale(tile, color_to_grays):
grayscale = {
0: (255, 255, 255),
1: (170, 170, 170),
2: (85, 85, 85),
3: (0, 0, 0)
}
grays = {gray: grayscale[position]
for gray, position in color_to_grays.items()}
new_tile = Image.new('RGB', (8, 8))
for y in range(8):
for x in range(8):
pixel = tile.getpixel((x, y))
new_tile.putpixel(
(x, y), grays.get(pixel, (255, 255, 255)))
return new_tile
def tile_to_color(tile, color_to_grays):
grayscale = {
(255, 255, 255): 0,
(170, 170, 170): 1,
(85, 85, 85): 2,
(0, 0, 0): 3
}
color_tile = Image.new('RGB', (8, 8))
for y in range(8):
for x in range(8):
gray_pixel = tile.getpixel((x, y))
gray_index = grayscale.get(gray_pixel, 0)
tone = next(key for key, value in color_to_grays.items()
if value == gray_index)
color_tile.putpixel((x, y), tone)
return color_tile
def get_tile_tones(tile):
tile_tones = set(tile.getpixel((i % 8, i // 8)) for i in range(64))
tile_tones = sort_color(tile_tones)
return tile_tones
def process_partial_colors(lst):
lst_sorted = sorted(lst, key=len, reverse=True)
unique_list = []
for sublist in lst_sorted:
sublist_set = set(sublist)
if not any(sublist_set.issubset(set(existing_sublist)) for existing_sublist in unique_list):
unique_list.append(sublist)
return unique_list
def identify_palette(tile_color_tones, palettes):
palette_scores = {palette_name: 0 for palette_name in palettes}
for tile_tones in tile_color_tones:
for palette_name, colors in palettes.items():
for color_name, palette_tones in colors.items():
if is_same_color(tile_tones, palette_tones):
palette_scores[palette_name] += 1
break
total_score = sum(palette_scores.values())
if total_score == 0:
print('Palette: monochrome')
return 'monochrome'
palette_name = max(palette_scores, key=palette_scores.get)
print(f'Palette: {palette_name}')
return palette_name
def get_roof_colors(unique_tiles, palette):
'''For monochrome maps and roof tiles.'''
if not palette.get('ROOF'):
return
def is_roof(tile_tones, palette):
for color_name, palette_tones in palette.items():
if all(any(is_same_tone(tile_tone, palette_tone) for palette_tone in palette_tones) for tile_tone in tile_tones):
return False
return True
roof_tones = []
for tile in unique_tiles:
tile_tones = set(tile.getpixel((i % 8, i // 8)) for i in range(64))
tile_tones = sort_color(tile_tones)
if is_roof(tile_tones, palette):
roof_tones.append(tile_tones)
palette['ROOF'] = process_partial_colors(roof_tones)[0] if process_partial_colors(
roof_tones) else palette['ROOF']
def get_tile_palette_color(tile_tones, palette):
matching_positions = {}
for color_name, palette_tones in palette.items():
positions = {}
match = True
for i, tile_tone in enumerate(tile_tones):
found = False
for j, palette_tone in enumerate(palette_tones):
if is_same_tone(tile_tone, palette_tone):
positions[tile_tone] = j
found = True
break
if not found:
match = False
break
if match:
matching_positions[color_name] = positions
color_name = next(iter(matching_positions))
return color_name, matching_positions[color_name]
def load_info(image_path):
txt_path = image_path.replace('.png', '.txt')
if not os.path.exists(txt_path):
return None
with open(txt_path, 'r') as f:
lines = f.read().strip().split('\n')
custom_palette = {}
collision_colors = {}
in_palette_section = False
in_collision_section = False
current_color_name = None
for line in lines:
line = line.strip()
if line == '[PALETTE]':
in_palette_section = True
in_collision_section = False
print('Custom palette found!')
continue
elif line == '[COLLISIONS]':
in_palette_section = False
in_collision_section = True
if os.path.exists(image_path.replace('.png', '_coll.png')):
print('Collision info and mask found!')
continue
if in_palette_section:
if line and not line.startswith('['):
if len(line) == 6 and all(c in '0123456789ABCDEFabcdef' for c in line):
if current_color_name:
custom_palette[current_color_name].append(
hex_to_rgb(line))
else:
current_color_name = line
custom_palette[current_color_name] = []
if in_collision_section:
if line and not line.startswith('['):
parts = line.split(',')
if len(parts) == 2:
collision_name = parts[0].strip()
collision_color = f'#{parts[1].strip()}'
collision_colors[collision_color] = collision_name
return custom_palette, collision_colors
# ANALYZE ---------------------------------------------------------------------
def get_palette_color(tile, palette_colors):
'''Used when you don't know the name of the color'''
def fits_color(tile, color):
unique_tones = {tile.getpixel((x, y))
for x in range(8) for y in range(8)}
return len(unique_tones) <= 4 and all(tone in color for tone in unique_tones)
for index, color in enumerate(palette_colors):
if fits_color(tile, color):
return index, color
return None, None
def generate_distinct_colors(n):
colors = []
for i in range(n):
hue = i / n
lightness = 0.5
saturation = 0.9
rgb = colorsys.hls_to_rgb(hue, lightness, saturation)
colors.append(tuple(int(c * 255) for c in rgb))
return colors
def analyze(image_path):
image = Image.open(image_path)
width, height = image.size
if width % 32 != 0 or height % 32 != 0:
raise ValueError("Image dimensions must be multiples of 32")
tiles = []
for y in range(0, height, 8):
for x in range(0, width, 8):
tile = image.crop((x, y, x + 8, y + 8))
tiles.append((x, y, tile))
tile_color_tones = []
wrong_tiles = 0
for _, _, tile in tiles:
tile_tones = get_tile_tones(tile)
if len(tile_tones) <= 4:
tile_color_tones.append(tile_tones)
else:
wrong_tiles += 1
palette_colors = process_partial_colors(tile_color_tones)
print("Colors found:", len(palette_colors),
"(> 7)" if len(palette_colors) > 7 else "")
print("Tiles with more than 4 tones:", wrong_tiles)
if len(palette_colors) <= 7 and wrong_tiles == 0:
print("The palette is valid!")
else:
print("The palette is invalid! The output image will help you fix the errors.")
mode = "fill"
output_image = Image.new("RGB", (width, height))
draw = ImageDraw.Draw(output_image)
display_colors = generate_distinct_colors(len(palette_colors))
for x, y, tile in tiles:
color_index, color = get_palette_color(tile, palette_colors)
if (color_index, color) != (None, None):
sorted_color = sort_color(color)
for i, tone in enumerate(sorted_color):
for dx in range(4):
for dy in range(4):
tile.putpixel((4*(i % 2) + dx, 4*(i//2) + dy), tone)
if len(sorted_color) < 4:
missing_index = len(sorted_color)
for dx in range(4):
for dy in range(4):
tile.putpixel((4*(missing_index % 2) + dx,
4*(missing_index//2) + dy), (0, 255, 0))
output_image.paste(tile, (x, y))
if (color_index, color) != (None, None):
if mode == "fill":
draw.rectangle([x, y, x + 8, y + 8],
fill=display_colors[color_index])
else:
center_x = x + 3
center_y = y + 3
draw.rectangle([center_x, center_y, center_x + 1,
center_y + 1], fill=display_colors[color_index])
draw.rectangle([x, y, x + 7, y + 7], outline=(0, 0, 0))
output_image.save(image_path.replace(".png", "_analysis.png"))
# PROCESS ---------------------------------------------------------------------
def divide_into_metatiles(image):
width, height = image.size
metatiles = []
positions = []
for y in range(0, height, 32):
for x in range(0, width, 32):
metatile = image.crop((x, y, x + 32, y + 32))
metatiles.append(metatile)
positions.append((x // 32 + 1, y // 32 + 1))
return metatiles, positions
def identify_unique_metatiles(metatiles, positions, darkest_tone):
unique_metatiles = []
metatile_positions = []
metatile_indexes = []
border_metatile = Image.new('RGB', (32, 32), color=darkest_tone)
unique_metatiles.append(border_metatile)
metatile_positions.append((0, 0))
for i, metatile in enumerate(metatiles):
if metatile not in unique_metatiles:
unique_metatiles.append(metatile)
metatile_positions.append(positions[i])
metatile_indexes.append(unique_metatiles.index(metatile))
print('Unique metatiles:', len(unique_metatiles))
return unique_metatiles, metatile_positions, metatile_indexes
def identify_unique_tiles(unique_metatiles, metatile_positions, palettes, palette=None):
monocrhome = False
unique_tiles = []
tile_color_tones = []
tile_color_names = []
color_to_grays = []
for i, metatile in enumerate(unique_metatiles):
for y in range(0, 32, 8):
for x in range(0, 32, 8):
tile = metatile.crop((x, y, x + 8, y + 8))
if tile not in unique_tiles:
unique_tiles.append(tile)
tile_tones = get_tile_tones(tile)
if len(tile_tones) > 4:
raise SystemExit(
f'[Error] Tile ({x // 8 + 1}, {y // 8 + 1}) in metatile {metatile_positions[i]} has more than 4 colors. Analyze the map first.')
if tile_tones not in tile_color_tones:
tile_color_tones.append(tile_tones)
print(f'Unique tiles: {len(unique_tiles)}',
'(> 192)' if len(unique_tiles) > 192 else '')
palette_colors = process_partial_colors(tile_color_tones)
if palette == 'extract':
if len(palette_colors) > 7:
raise SystemExit(
f'[Error] {len(palette_colors)} colors found. Limit is 7. Analyze the map first.')
print(f'Unique colors: {len(palette_colors)}')
return palette_colors, None, None, None
if not palette:
print(f'Unique colors: {len(palette_colors)}')
palette_name = identify_palette(palette_colors, palettes)
if palette_name == 'monochrome':
monocrhome = True
palette_name = 'morn'
palette = palettes[palette_name]
get_roof_colors(unique_tiles, palette)
for tile in unique_tiles:
tile_tones = get_tile_tones(tile)
color, positions = get_tile_palette_color(tile_tones, palette)
tile_color_names.append(color)
color_to_grays.append(positions)
# print(color, positions)
# ? Tile $7F (128) is reserved for the space character
if len(unique_tiles) > 192:
space_tile = Image.new('RGB', (8, 8), color=(0, 255, 255))
unique_tiles.insert(127, space_tile)
tile_color_names.insert(127, 'TEXT')
color_to_grays.insert(127, {(0, 255, 255): 0})
return unique_tiles, tile_color_names, color_to_grays, monocrhome
def compress_tiles(tiles, tile_color_names, color_to_grays):
compressed_tiles = []
transformations = []
for i, tile in enumerate(tiles):
# ? Tile $7F (128) is reserved for the space character
if len(tiles) <= 192 or (len(tiles) > 192 and i != 127):
gray_tile = tile_to_grayscale(tile, color_to_grays[i])
color = tile_color_names[i]
variants = {
'original': gray_tile,
'flip_x': ImageOps.mirror(gray_tile),
'flip_y': ImageOps.flip(gray_tile),
'flip_xy': ImageOps.flip(ImageOps.mirror(gray_tile))
}
found = False
for variant_name, variant_tile in variants.items():
for j, comp_tile in enumerate(compressed_tiles):
if variant_tile.tobytes() == comp_tile.tobytes():
flip_x = 'flip_x' in variant_name or 'flip_xy' in variant_name
flip_y = 'flip_y' in variant_name or 'flip_xy' in variant_name
transformations.append((j, flip_x, flip_y, color))
# Reapply transformations to original tile
retransformed_tile = reapply_transformations(
comp_tile, flip_x, flip_y, color_to_grays[i])
# Debugging
# tile.save(f"debug/{i}_original_tile.png")
# gray_tile.save(f"debug/{i}_gray_tile.png")
# retransformed_tile.save(f"debug/{i}_retransformed_tile_{variant_name}.png")
assert retransformed_tile.tobytes() == tile.tobytes(), \
f"Transformation error: tile {i}, variant {variant_name}, flip_x={flip_x}, flip_y={flip_y}, color={color}"
found = True
break
if found:
break
if not found:
compressed_tiles.append(gray_tile)
transformations.append(
(len(compressed_tiles) - 1, False, False, color))
# ? It seems Polished crystal always uses tile $7F for the space character
if len(compressed_tiles) > 127:
space_tile = Image.new('RGB', (8, 8), color=(0, 255, 255))
compressed_tiles.insert(127, space_tile)
# Adjust indices in transformations
for idx, (j, flip_x, flip_y, color) in enumerate(transformations):
if j >= 127:
transformations[idx] = (j + 1, flip_x, flip_y, color)
print(
f'Compressed tiles: {len(tiles)} to {len(compressed_tiles)} ({len(tiles) - len(compressed_tiles)})')
return compressed_tiles, transformations
def reapply_transformations(tile, flip_x, flip_y, color_to_grays):
if flip_x:
tile = ImageOps.mirror(tile)
if flip_y:
tile = ImageOps.flip(tile)
recolored_tile = tile_to_color(tile, color_to_grays)
return recolored_tile
def get_attr_metatiles(metatiles, compressed_tiles, transformations, color_to_grays):
if len(color_to_grays) > 192:
del color_to_grays[127]
attr_metatiles = []
for metatile in metatiles:
metatile_info = []
for y in range(0, 32, 8):
for x in range(0, 32, 8):
tile = metatile.crop((x, y, x + 8, y + 8))
for i, (compressed_index, flip_x, flip_y, color) in enumerate(transformations):
retransformed_tile = reapply_transformations(
compressed_tiles[compressed_index], flip_x, flip_y, color_to_grays[i])
if tile.tobytes() == retransformed_tile.tobytes():
metatile_info.append(
(compressed_index, color, flip_x, flip_y))
break
attr_metatiles.append(metatile_info)
return attr_metatiles
# MERGE -----------------------------------------------------------------------
def read_bin_file(file_path):
with open(file_path, 'rb') as f:
content = f.read()
return [list(content[i:i+16]) for i in range(0, len(content), 16)]
def process_tileset(image_path):
tileset_image = Image.open(image_path).convert("RGB")
width, height = tileset_image.size
tiles = []
for y in range(0, height, 8):
for x in range(0, width, 8):
tile = tileset_image.crop((x, y, x + 8, y + 8))
if is_tile_white(tile):
# Check if last tile is white
if x + 8 >= width and y + 8 >= height:
# ! Fringe case: last tile is really white
break
# Check if next tile is white
next_x = x + 8
next_y = y
if next_x >= width:
next_x = 0
next_y = y + 8
if next_y < height:
next_tile = tileset_image.crop(
(next_x, next_y, next_x + 8, next_y + 8))
if is_tile_white(next_tile):
break
tiles.append(tile)
return tiles
def merge_maps(map_dir, base_tileset_index, metatiles_index_mappings, ablk=False):
map_files = os.listdir(map_dir)
base_map_file = os.path.join(map_dir, map_files[base_tileset_index])
base_map = read_bin_file(base_map_file)
base_map_count = len(base_map)
for map_file in map_files:
if map_file != os.path.basename(base_map_file):
file_path = os.path.join(map_dir, map_file)
map = read_bin_file(file_path)
new_map = []
for line in map:
line_length = len(line)
for i in range(line_length):
mapped = False
for mapping in metatiles_index_mappings:
if line[i] in mapping:
line[i] = mapping[line[i]]
mapped = True
break
if not mapped:
new_metatile_index = base_map_count + len(base_map)
line[i] = new_metatile_index
new_map.append(line)
extension = 'ablk' if ablk else 'blk'
output_file_path = os.path.join(
map_dir, f"{os.path.splitext(map_file)[0]}Merged.{extension}")
with open(output_file_path, 'wb') as f:
for metatile in new_map:
f.write(bytes(metatile))
# blk -------------------------------------------------------------------------
def merge_blk_tilesets(gfx_dir):
tilesets = []
palette_maps = []
found_pal_file = False
for filename in os.listdir(gfx_dir):
if filename.endswith('.png'):
tileset_path = os.path.join(gfx_dir, filename)
tiles = process_tileset(tileset_path)
tilesets.append(tiles)
elif filename.endswith('.asm'):
palette_map_path = os.path.join(gfx_dir, filename)
palette_map = []
with open(palette_map_path, 'r') as f:
lines = f.read().strip().split('\n')
for line in lines:
if line.startswith('\ttilepal'):
colors = line.split(', ')[1:]
palette_map.extend(colors)
palette_maps.append(palette_map)
elif filename.endswith('.pal') and not found_pal_file:
pal_file_path = os.path.join(gfx_dir, filename)
shutil.copy(pal_file_path, os.path.join(gfx_dir, 'merged.pal'))
found_pal_file = True
base_tileset = max(tilesets, key=len)
base_tileset_index = tilesets.index(base_tileset)
base_palette_map = palette_maps[base_tileset_index]
tiles_index_mappings = [{} for _ in range(len(tilesets))]
for i, tileset in enumerate(tilesets):
if i == base_tileset_index:
continue
for tile_index, tile in enumerate(tileset):
for base_tile_index, base_tile in enumerate(base_tileset):
if tile.tobytes() == base_tile.tobytes():
if palette_maps[i][tile_index] == base_palette_map[base_tile_index]:
tiles_index_mappings[i][tile_index] = base_tile_index
# debug_dir = os.path.join(gfx_dir, 'debug')
# os.makedirs(debug_dir, exist_ok=True)
# debug_image = Image.new('RGB', (8, 16))
# debug_image.paste(tile, (0, 0))
# debug_image.paste(base_tile, (0, 8))
# debug_image_path = os.path.join(debug_dir, f'match_{i}_{tile_index}_{base_tile_index}.png')
# debug_image.save(debug_image_path)
break
tile_width, tile_height = base_tileset[0].size
merged_tiles = base_tileset[:]
merged_palette_map = base_palette_map[:len(base_tileset)]
for i, tileset in enumerate(tilesets):
if i == base_tileset_index:
continue
for tile_index, tile in enumerate(tileset):
if tile_index not in tiles_index_mappings[i]:
tiles_index_mappings[i][tile_index] = len(merged_tiles)
merged_tiles.append(tile)
merged_palette_map.append(palette_maps[i][tile_index])
merged_width = tile_width * 16
merged_height = tile_height * ((len(merged_tiles) + 15) // 16)
merged_image = Image.new(
'RGB', (merged_width, merged_height), (255, 255, 255))
for idx, tile in enumerate(merged_tiles):
x = (idx % 16) * tile_width
y = (idx // 16) * tile_height
merged_image.paste(tile, (x, y))
merged_image_path = os.path.join(gfx_dir, 'merged.png')
merged_image.save(merged_image_path)
save_palette_map_asm_file(merged_palette_map, os.path.join(
gfx_dir, 'merged_palette_map.asm'))
tiles_index_mappings = [mapping for i, mapping in enumerate(
tiles_index_mappings) if i != base_tileset_index]
return base_tileset_index, tiles_index_mappings
def merge_blk_metatiles(data_dir, base_tileset_index, tiles_index_mappings):
bin_files = [f for f in os.listdir(data_dir) if f.endswith('.bin')]
base_metatiles_file = os.path.join(data_dir, bin_files[base_tileset_index])
base_metatiles = read_bin_file(base_metatiles_file)
base_metatiles_count = len(base_metatiles)
collision_files = [f for f in os.listdir(
data_dir) if f.endswith('collision.asm')]
if len(collision_files) == 0 or len(collision_files) != len(bin_files):
raise SystemExit('[Error] Some collision files are missing.')
base_collision_file = os.path.join(
data_dir, collision_files[base_tileset_index])
with open(base_collision_file, 'r') as f:
base_collision_lines = [
line for line in f if line.startswith('\ttilecoll')]
new_collision_lines = base_collision_lines[:]
metatiles_index_mappings = []
for filename in bin_files:
if filename != os.path.basename(base_metatiles_file):
file_path = os.path.join(data_dir, filename)
metatiles = read_bin_file(file_path)
collision_file_path = file_path.replace(
'metatiles.bin', 'collision.asm')
with open(collision_file_path, 'r') as f:
collision_lines = [
line for line in f if line.startswith('\ttilecoll')]
file_index_mapping = {}
for metatile_index, metatile in enumerate(metatiles):
for i in range(16):
tile_index = metatile[i]
for mapping in tiles_index_mappings:
if tile_index in mapping:
metatile[i] = mapping[tile_index]
break
match_found = False
for base_metatile_index, base_metatile in enumerate(base_metatiles[:base_metatiles_count]):
if metatile == base_metatile:
file_index_mapping[metatile_index] = base_metatile_index
match_found = True
break
if not match_found:
file_index_mapping[metatile_index] = len(base_metatiles)
base_metatiles.append(metatile)
new_collision_lines.append(collision_lines[metatile_index])
if file_index_mapping:
metatiles_index_mappings.append(file_index_mapping)
output_file_path = os.path.join(data_dir, 'merged_metatiles.bin')
with open(output_file_path, 'wb') as f:
for metatile in base_metatiles:
f.write(bytes(metatile))
output_file_path = os.path.join(data_dir, 'merged_collision.asm')
with open(output_file_path, 'w') as f:
for line in new_collision_lines:
f.write(line)
return metatiles_index_mappings
# ablk ------------------------------------------------------------------------
def merge_ablk_tilesets(gfx_dir):
tilesets = []
found_pal_file = False
for filename in os.listdir(gfx_dir):
if filename.endswith('.png'):
tileset_path = os.path.join(gfx_dir, filename)
tiles = process_tileset(tileset_path)
tilesets.append(tiles)
elif filename.endswith('.pal') and not found_pal_file:
pal_file_path = os.path.join(gfx_dir, filename)
shutil.copy(pal_file_path, os.path.join(gfx_dir, 'merged.pal'))
found_pal_file = True
base_tileset = max(tilesets, key=len)
base_tileset_index = tilesets.index(base_tileset)
tiles_index_mappings = [{} for _ in range(len(tilesets))]
for i, tileset in enumerate(tilesets):
if i == base_tileset_index:
continue
for tile_index, tile in enumerate(tileset):
for base_tile_index, base_tile in enumerate(base_tileset):
# Compare the original tile
if tile.tobytes() == base_tile.tobytes():
tiles_index_mappings[i][tile_index] = (
base_tile_index, False, False)
break
# Compare the tile with flip x
tile_flipped_x = ImageOps.mirror(tile)
if tile_flipped_x.tobytes() == base_tile.tobytes():
tiles_index_mappings[i][tile_index] = (
base_tile_index, True, False)
break
# Comparar the tile with flip y
tile_flipped_y = ImageOps.flip(tile)
if tile_flipped_y.tobytes() == base_tile.tobytes():
tiles_index_mappings[i][tile_index] = (
base_tile_index, False, True)
break
# Comparar the tile with flip x and y
tile_flipped_xy = ImageOps.mirror(tile_flipped_y)
if tile_flipped_xy.tobytes() == base_tile.tobytes():
tiles_index_mappings[i][tile_index] = (
base_tile_index, True, True)
break
tile_width, tile_height = base_tileset[0].size
merged_tiles = base_tileset[:]
for i, tileset in enumerate(tilesets):
if i == base_tileset_index:
continue
for tile_index, tile in enumerate(tileset):
if tile_index not in tiles_index_mappings[i]:
tiles_index_mappings[i][tile_index] = (
len(merged_tiles), False, False)
merged_tiles.append(tile)
merged_width = tile_width * 16
merged_height = tile_height * ((len(merged_tiles) + 15) // 16)
merged_image = Image.new(
'RGB', (merged_width, merged_height), (255, 255, 255))
for idx, tile in enumerate(merged_tiles):
x = (idx % 16) * tile_width
y = (idx // 16) * tile_height
merged_image.paste(tile, (x, y))
merged_image_path = os.path.join(gfx_dir, 'merged.png')
merged_image.save(merged_image_path)
tiles_index_mappings = [mapping for i, mapping in enumerate(
tiles_index_mappings) if i != base_tileset_index]
return base_tileset_index, tiles_index_mappings
def merge_ablk_metatiles(data_dir, base_tileset_index, tiles_index_mappings):
def get_tile_index_real(tile_index, tile_info):
tile_bank = (tile_info >> 3) & 1
if tile_bank == 1:
tile_index += 128 # $80 = 128
return tile_index
def set_tile(tile_index_mapping, tile_attrs):
tile_index_real, flip_x, flip_y = tile_index_mapping
if tile_index_real >= 128:
tile_bank = 1
tile_index = tile_index_real - 128
else:
tile_bank = 0
tile_index = tile_index_real
if tile_bank == 1:
tile_attrs |= (1 << 3)
else:
tile_attrs &= ~(1 << 3)
# Invert bits 5 and 6
if flip_x:
tile_attrs ^= (1 << 5)
if flip_y:
tile_attrs ^= (1 << 6)
return tile_index, tile_attrs
metatiles_files = [f for f in os.listdir(
data_dir) if f.endswith('metatiles.bin')]
base_metatiles_file = os.path.join(
data_dir, metatiles_files[base_tileset_index])
base_metatiles = read_bin_file(base_metatiles_file)
base_metatiles_count = len(base_metatiles)
attributes_files = [f for f in os.listdir(
data_dir) if f.endswith('attributes.bin')]
base_attributes_file = os.path.join(
data_dir, attributes_files[base_tileset_index])
base_attributes = read_bin_file(base_attributes_file)
collision_files = [f for f in os.listdir(
data_dir) if f.endswith('collision.asm')]
if len(collision_files) == 0 or len(collision_files) != len(metatiles_files):
raise SystemExit('[Error] Some collision files are missing.')
base_collision_file = os.path.join(
data_dir, collision_files[base_tileset_index])
with open(base_collision_file, 'r') as f:
base_collision_lines = [
line for line in f if line.startswith('\ttilecoll')]
new_collision_lines = base_collision_lines[:]
metatiles_index_mappings = []
for filename in metatiles_files:
if filename != os.path.basename(base_metatiles_file):
file_path = os.path.join(data_dir, filename)
metatiles = read_bin_file(file_path)
attributes = read_bin_file(file_path.replace(
'metatiles.bin', 'attributes.bin'))
collision_file_path = file_path.replace(
'metatiles.bin', 'collision.asm')
with open(collision_file_path, 'r') as f:
collision_lines = [
line for line in f if line.startswith('\ttilecoll')]
file_index_mapping = {}
for metatile_index, metatile in enumerate(metatiles):
metatile_attrs = attributes[metatile_index]
for i in range(16):
tile_index = metatile[i]
tile_attrs = metatile_attrs[i]
tile_index_real = get_tile_index_real(
tile_index, tile_attrs)
for mapping in tiles_index_mappings:
if tile_index_real in mapping:
tile_info = set_tile(
mapping[tile_index_real], tile_attrs)
metatile[i] = tile_info[0]
metatile_attrs[i] = tile_info[1]
break
match_found = False
for base_metatile_index, base_metatile in enumerate(base_metatiles[:base_metatiles_count]):
if metatile == base_metatile and metatile_attrs == base_attributes[base_metatile_index]:
file_index_mapping[metatile_index] = base_metatile_index
match_found = True
break
if not match_found:
file_index_mapping[metatile_index] = len(base_metatiles)
base_metatiles.append(metatile)
base_attributes.append(metatile_attrs)
new_collision_lines.append(collision_lines[metatile_index])
if file_index_mapping:
metatiles_index_mappings.append(file_index_mapping)
output_file_path = os.path.join(data_dir, 'merged_metatiles.bin')
with open(output_file_path, 'wb') as f:
for metatile in base_metatiles:
f.write(bytes(metatile))
output_file_path = os.path.join(data_dir, 'merged_attributes.bin')
with open(output_file_path, 'wb') as f:
for attrs in base_attributes:
f.write(bytes(attrs))
output_file_path = os.path.join(data_dir, 'merged_collision.asm')
with open(output_file_path, 'w') as f:
for line in new_collision_lines:
f.write(line)
return metatiles_index_mappings