forked from pret/pokeyellow
-
Notifications
You must be signed in to change notification settings - Fork 2
/
gfx.py
1931 lines (1552 loc) · 57.3 KB
/
gfx.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
# -*- coding: utf-8 -*-
import os
import sys
sys.path.insert(0,(os.path.abspath(os.path.dirname(__file__) + 'extras/pokemontools'))) # correct module path to pokemontools
import png
from math import sqrt, floor, ceil
import argparse
import configuration
config = configuration.Config()
import pokemon_constants
import trainers
import romstr
def load_rom():
rom = romstr.RomStr.load(filename=config.rom_path)
return rom
def split(list_, interval):
"""
Split a list by length.
"""
for i in xrange(0, len(list_), interval):
j = min(i + interval, len(list_))
yield list_[i:j]
def hex_dump(data, length=0x10):
"""
just use hexdump -C
"""
margin = len('%x' % len(data))
output = []
address = 0
for line in split(data, length):
output += [
hex(address)[2:].zfill(margin) +
' | ' +
' '.join('%.2x' % byte for byte in line)
]
address += length
return '\n'.join(output)
def get_tiles(image):
"""
Split a 2bpp image into 8x8 tiles.
"""
return list(split(image, 0x10))
def connect(tiles):
"""
Combine 8x8 tiles into a 2bpp image.
"""
return [byte for tile in tiles for byte in tile]
def transpose(tiles, width=None):
"""
Transpose a tile arrangement along line y=-x.
00 01 02 03 04 05 00 06 0c 12 18 1e
06 07 08 09 0a 0b 01 07 0d 13 19 1f
0c 0d 0e 0f 10 11 <-> 02 08 0e 14 1a 20
12 13 14 15 16 17 03 09 0f 15 1b 21
18 19 1a 1b 1c 1d 04 0a 10 16 1c 22
1e 1f 20 21 22 23 05 0b 11 17 1d 23
"""
if width == None:
width = int(sqrt(len(tiles))) # assume square image
tiles = sorted(enumerate(tiles), key= lambda (i, tile): i % width)
return [tile for i, tile in tiles]
def transpose_tiles(image, width=None):
return connect(transpose(get_tiles(image), width))
def interleave(tiles, width):
"""
00 01 02 03 04 05 00 02 04 06 08 0a
06 07 08 09 0a 0b 01 03 05 07 09 0b
0c 0d 0e 0f 10 11 --> 0c 0e 10 12 14 16
12 13 14 15 16 17 0d 0f 11 13 15 17
18 19 1a 1b 1c 1d 18 1a 1c 1e 20 22
1e 1f 20 21 22 23 19 1b 1d 1f 21 23
"""
interleaved = []
left, right = split(tiles[::2], width), split(tiles[1::2], width)
for l, r in zip(left, right):
interleaved += l + r
return interleaved
def deinterleave(tiles, width):
"""
00 02 04 06 08 0a 00 01 02 03 04 05
01 03 05 07 09 0b 06 07 08 09 0a 0b
0c 0e 10 12 14 16 --> 0c 0d 0e 0f 10 11
0d 0f 11 13 15 17 12 13 14 15 16 17
18 1a 1c 1e 20 22 18 19 1a 1b 1c 1d
19 1b 1d 1f 21 23 1e 1f 20 21 22 23
"""
deinterleaved = []
rows = list(split(tiles, width))
for left, right in zip(rows[::2], rows[1::2]):
for l, r in zip(left, right):
deinterleaved += [l, r]
return deinterleaved
def interleave_tiles(image, width):
return connect(interleave(get_tiles(image), width))
def deinterleave_tiles(image, width):
return connect(deinterleave(get_tiles(image), width))
def condense_tiles_to_map(image):
tiles = get_tiles(image)
new_tiles = []
tilemap = []
for tile in tiles:
if tile not in new_tiles:
new_tiles += [tile]
tilemap += [new_tiles.index(tile)]
new_image = connect(new_tiles)
return new_image, tilemap
def to_file(filename, data):
file = open(filename, 'wb')
for byte in data:
file.write('%c' % byte)
file.close()
"""
A rundown of Pokemon Crystal's compression scheme:
Control commands occupy bits 5-7.
Bits 0-4 serve as the first parameter <n> for each command.
"""
lz_commands = {
'literal': 0, # n values for n bytes
'iterate': 1, # one value for n bytes
'alternate': 2, # alternate two values for n bytes
'blank': 3, # zero for n bytes
}
"""
Repeater commands repeat any data that was just decompressed.
They take an additional signed parameter <s> to mark a relative starting point.
These wrap around (positive from the start, negative from the current position).
"""
lz_commands.update({
'repeat': 4, # n bytes starting from s
'flip': 5, # n bytes in reverse bit order starting from s
'reverse': 6, # n bytes backwards starting from s
})
"""
The long command is used when 5 bits aren't enough. Bits 2-4 contain a new control code.
Bits 0-1 are appended to a new byte as 8-9, allowing a 10-bit parameter.
"""
lz_commands.update({
'long': 7, # n is now 10 bits for a new control code
})
max_length = 1 << 10 # can't go higher than 10 bits
lowmax = 1 << 5 # standard 5-bit param
"""
If 0xff is encountered instead of a command, decompression ends.
"""
lz_end = 0xff
class Compressed:
"""
Compress arbitrary data, usually 2bpp.
"""
def __init__(self, image=None, mode='horiz', size=None):
assert image, 'need something to compress!'
image = list(image)
self.image = image
self.pic = []
self.animtiles = []
# only transpose pic (animtiles were never transposed in decompression)
if size != None:
for byte in range((size*size)*16):
self.pic += image[byte]
for byte in range(((size*size)*16),len(image)):
self.animtiles += image[byte]
else:
self.pic = image
if mode == 'vert':
self.tiles = get_tiles(self.pic)
self.tiles = transpose(self.tiles)
self.pic = connect(self.tiles)
self.image = self.pic + self.animtiles
self.end = len(self.image)
self.byte = None
self.address = 0
self.stream = []
self.zeros = []
self.alts = []
self.iters = []
self.repeats = []
self.flips = []
self.reverses = []
self.literals = []
self.output = []
self.compress()
def compress(self):
"""
Incomplete, but outputs working compressed data.
"""
self.address = 0
# todo
#self.scanRepeats()
while ( self.address < self.end ):
#if (self.repeats):
# self.doRepeats()
#if (self.flips):
# self.doFlips()
#if (self.reverses):
# self.doReverses
if (self.checkWhitespace()):
self.doLiterals()
self.doWhitespace()
elif (self.checkIter()):
self.doLiterals()
self.doIter()
elif (self.checkAlts()):
self.doLiterals()
self.doAlts()
else: # doesn't fit any pattern -> literal
self.addLiteral()
self.next()
self.doStream()
# add any literals we've been sitting on
self.doLiterals()
# done
self.output.append(lz_end)
def getCurByte(self):
if self.address < self.end:
self.byte = ord(self.image[self.address])
else: self.byte = None
def next(self):
self.address += 1
self.getCurByte()
def addLiteral(self):
self.getCurByte()
self.literals.append(self.byte)
if len(self.literals) > max_length:
raise Exception, "literals exceeded max length and the compressor didn't catch it"
elif len(self.literals) == max_length:
self.doLiterals()
def doLiterals(self):
if len(self.literals) > lowmax:
self.output.append( (lz_commands['long'] << 5) | (lz_commands['literal'] << 2) | ((len(self.literals) - 1) >> 8) )
self.output.append( (len(self.literals) - 1) & 0xff )
elif len(self.literals) > 0:
self.output.append( (lz_commands['literal'] << 5) | (len(self.literals) - 1) )
for byte in self.literals:
self.output.append(byte)
self.literals = []
def doStream(self):
for byte in self.stream:
self.output.append(byte)
self.stream = []
def scanRepeats(self):
"""
Works, but doesn't do flipped/reversed streams yet.
This takes up most of the compress time and only saves a few bytes.
It might be more effective to exclude it entirely.
"""
self.repeats = []
self.flips = []
self.reverses = []
# make a 5-letter word list of the sequence
letters = 5 # how many bytes it costs to use a repeat over a literal
# any shorter and it's not worth the trouble
num_words = len(self.image) - letters
words = []
for i in range(self.address,num_words):
word = []
for j in range(letters):
word.append( ord(self.image[i+j]) )
words.append((word, i))
zeros = []
for zero in range(letters):
zeros.append( 0 )
# check for matches
def get_matches():
# TODO:
# append to 3 different match lists instead of yielding to one
#
#flipped = []
#for byte in enumerate(this[0]):
# flipped.append( sum(1<<(7-i) for i in range(8) if (this[0][byte])>>i&1) )
#reversed = this[0][::-1]
#
for whereabout, this in enumerate(words):
for that in range(whereabout+1,len(words)):
if words[that][0] == this[0]:
if words[that][1] - this[1] >= letters:
# remove zeros
if this[0] != zeros:
yield [this[0], this[1], words[that][1]]
matches = list(get_matches())
# remove more zeros
buffer = []
for match in matches:
# count consecutive zeros in a word
num_zeros = 0
highest = 0
for j in range(letters):
if match[0][j] == 0:
num_zeros += 1
else:
if highest < num_zeros: highest = num_zeros
num_zeros = 0
if highest < 4:
# any more than 3 zeros in a row isn't worth it
# (and likely to already be accounted for)
buffer.append(match)
matches = buffer
# combine overlapping matches
buffer = []
for this, match in enumerate(matches):
if this < len(matches) - 1: # special case for the last match
if matches[this+1][1] <= (match[1] + len(match[0])): # check overlap
if match[1] + len(match[0]) < match[2]:
# next match now contains this match's bytes too
# this only appends the last byte (assumes overlaps are +1
match[0].append(matches[this+1][0][-1])
matches[this+1] = match
elif match[1] + len(match[0]) == match[2]:
# we've run into the thing we matched
buffer.append(match)
# else we've gone past it and we can ignore it
else: # no more overlaps
buffer.append(match)
else: # last match, so there's nothing to check
buffer.append(match)
matches = buffer
# remove alternating sequences
buffer = []
for match in matches:
for i in range(6 if letters > 6 else letters):
if match[0][i] != match[0][i&1]:
buffer.append(match)
break
matches = buffer
self.repeats = matches
def doRepeats(self):
"""doesn't output the right values yet"""
unusedrepeats = []
for repeat in self.repeats:
if self.address >= repeat[2]:
# how far in we are
length = (len(repeat[0]) - (self.address - repeat[2]))
# decide which side we're copying from
if (self.address - repeat[1]) <= 0x80:
self.doLiterals()
self.stream.append( (lz_commands['repeat'] << 5) | length - 1 )
# wrong?
self.stream.append( (((self.address - repeat[1])^0xff)+1)&0xff )
else:
self.doLiterals()
self.stream.append( (lz_commands['repeat'] << 5) | length - 1 )
# wrong?
self.stream.append(repeat[1]>>8)
self.stream.append(repeat[1]&0xff)
#print hex(self.address) + ': ' + hex(len(self.output)) + ' ' + hex(length)
self.address += length
else: unusedrepeats.append(repeat)
self.repeats = unusedrepeats
def checkWhitespace(self):
self.zeros = []
self.getCurByte()
original_address = self.address
if ( self.byte == 0 ):
while ( self.byte == 0 ) & ( len(self.zeros) <= max_length ):
self.zeros.append(self.byte)
self.next()
if len(self.zeros) > 1:
return True
self.address = original_address
return False
def doWhitespace(self):
if (len(self.zeros) + 1) >= lowmax:
self.stream.append( (lz_commands['long'] << 5) | (lz_commands['blank'] << 2) | ((len(self.zeros) - 1) >> 8) )
self.stream.append( (len(self.zeros) - 1) & 0xff )
elif len(self.zeros) > 1:
self.stream.append( lz_commands['blank'] << 5 | (len(self.zeros) - 1) )
else:
raise Exception, "checkWhitespace() should prevent this from happening"
def checkAlts(self):
self.alts = []
self.getCurByte()
original_address = self.address
num_alts = 0
# make sure we don't check for alts at the end of the file
if self.address+3 >= self.end: return False
self.alts.append(self.byte)
self.alts.append(ord(self.image[self.address+1]))
# are we onto smething?
if ( ord(self.image[self.address+2]) == self.alts[0] ):
cur_alt = 0
while (ord(self.image[(self.address)+1]) == self.alts[num_alts&1]) & (num_alts <= max_length):
num_alts += 1
self.next()
# include the last alternated byte
num_alts += 1
self.address = original_address
if num_alts > lowmax:
return True
elif num_alts > 2:
return True
return False
def doAlts(self):
original_address = self.address
self.getCurByte()
#self.alts = []
#num_alts = 0
#self.alts.append(self.byte)
#self.alts.append(ord(self.image[self.address+1]))
#i = 0
#while (ord(self.image[self.address+1]) == self.alts[i^1]) & (num_alts <= max_length):
# num_alts += 1
# i ^=1
# self.next()
## include the last alternated byte
#num_alts += 1
num_alts = len(self.iters) + 1
if num_alts > lowmax:
self.stream.append( (lz_commands['long'] << 5) | (lz_commands['alternate'] << 2) | ((num_alts - 1) >> 8) )
self.stream.append( num_alts & 0xff )
self.stream.append( self.alts[0] )
self.stream.append( self.alts[1] )
elif num_alts > 2:
self.stream.append( (lz_commands['alternate'] << 5) | (num_alts - 1) )
self.stream.append( self.alts[0] )
self.stream.append( self.alts[1] )
else:
raise Exception, "checkAlts() should prevent this from happening"
self.address = original_address
self.address += num_alts
def checkIter(self):
self.iters = []
self.getCurByte()
iter = self.byte
original_address = self.address
while (self.byte == iter) & (len(self.iters) < max_length):
self.iters.append(self.byte)
self.next()
self.address = original_address
if len(self.iters) > 3:
# 3 or fewer isn't worth the trouble and actually longer
# if part of a larger literal set
return True
return False
def doIter(self):
self.getCurByte()
iter = self.byte
original_address = self.address
self.iters = []
while (self.byte == iter) & (len(self.iters) < max_length):
self.iters.append(self.byte)
self.next()
if (len(self.iters) - 1) >= lowmax:
self.stream.append( (lz_commands['long'] << 5) | (lz_commands['iterate'] << 2) | ((len(self.iters)-1) >> 8) )
self.stream.append( (len(self.iters) - 1) & 0xff )
self.stream.append( iter )
elif len(self.iters) > 3:
# 3 or fewer isn't worth the trouble and actually longer
# if part of a larger literal set
self.stream.append( (lz_commands['iterate'] << 5) | (len(self.iters) - 1) )
self.stream.append( iter )
else:
self.address = original_address
raise Exception, "checkIter() should prevent this from happening"
class Decompressed:
"""
Parse compressed data, usually 2bpp.
parameters:
[compressed data]
[tile arrangement] default: 'vert'
[size of pic] default: None
[start] (optional)
splits output into pic [size] and animation tiles if applicable
data can be fed in from rom if [start] is specified
"""
def __init__(self, lz=None, mode=None, size=None, start=0):
# todo: play nice with Compressed
assert lz, 'need something to compress!'
self.lz = lz
self.byte = None
self.address = 0
self.start = start
self.output = []
self.decompress()
debug = False
# print tuple containing start and end address
if debug: print '(' + hex(self.start) + ', ' + hex(self.start + self.address+1) + '),'
# only transpose pic
self.pic = []
self.animtiles = []
if size != None:
self.tiles = get_tiles(self.output)
self.pic = connect(self.tiles[:(size*size)])
self.animtiles = connect(self.tiles[(size*size):])
else: self.pic = self.output
if mode == 'vert':
self.tiles = get_tiles(self.pic)
self.tiles = transpose(self.tiles)
self.pic = connect(self.tiles)
self.output = self.pic + self.animtiles
def decompress(self):
"""
Replica of crystal's decompression.
"""
self.output = []
while True:
self.getCurByte()
if (self.byte == lz_end):
break
self.cmd = (self.byte & 0b11100000) >> 5
if self.cmd == lz_commands['long']: # 10-bit param
self.cmd = (self.byte & 0b00011100) >> 2
self.length = (self.byte & 0b00000011) << 8
self.next()
self.length += self.byte + 1
else: # 5-bit param
self.length = (self.byte & 0b00011111) + 1
# literals
if self.cmd == lz_commands['literal']:
self.doLiteral()
elif self.cmd == lz_commands['iterate']:
self.doIter()
elif self.cmd == lz_commands['alternate']:
self.doAlt()
elif self.cmd == lz_commands['blank']:
self.doZeros()
else: # repeaters
self.next()
if self.byte > 0x7f: # negative
self.displacement = self.byte & 0x7f
self.displacement = len(self.output) - self.displacement - 1
else: # positive
self.displacement = self.byte * 0x100
self.next()
self.displacement += self.byte
if self.cmd == lz_commands['flip']:
self.doFlip()
elif self.cmd == lz_commands['reverse']:
self.doReverse()
else: # lz_commands['repeat']
self.doRepeat()
self.address += 1
#self.next() # somewhat of a hack
def getCurByte(self):
self.byte = ord(self.lz[self.start+self.address])
def next(self):
self.address += 1
self.getCurByte()
def doLiteral(self):
"""
Copy data directly.
"""
for byte in range(self.length):
self.next()
self.output.append(self.byte)
def doIter(self):
"""
Write one byte repeatedly.
"""
self.next()
for byte in range(self.length):
self.output.append(self.byte)
def doAlt(self):
"""
Write alternating bytes.
"""
self.alts = []
self.next()
self.alts.append(self.byte)
self.next()
self.alts.append(self.byte)
for byte in range(self.length):
self.output.append(self.alts[byte&1])
def doZeros(self):
"""
Write zeros.
"""
for byte in range(self.length):
self.output.append(0x00)
def doFlip(self):
"""
Repeat flipped bytes from output.
eg 11100100 -> 00100111
quat 3 2 1 0 -> 0 2 1 3
"""
for byte in range(self.length):
flipped = sum(1<<(7-i) for i in range(8) if self.output[self.displacement+byte]>>i&1)
self.output.append(flipped)
def doReverse(self):
"""
Repeat reversed bytes from output.
"""
for byte in range(self.length):
self.output.append(self.output[self.displacement-byte])
def doRepeat(self):
"""
Repeat bytes from output.
"""
for byte in range(self.length):
self.output.append(self.output[self.displacement+byte])
sizes = [
5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 5, 7, 5, 5, 7, 5,
6, 7, 5, 6, 5, 7, 5, 7, 5, 7, 5, 6, 5, 6, 7, 5,
6, 7, 5, 6, 6, 7, 5, 6, 5, 7, 5, 6, 7, 5, 7, 5,
7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 6, 7, 5, 6,
7, 5, 7, 7, 5, 6, 7, 5, 6, 5, 6, 6, 6, 7, 5, 7,
5, 6, 6, 5, 7, 6, 7, 5, 7, 5, 7, 7, 6, 6, 7, 6,
7, 5, 7, 5, 5, 7, 7, 5, 6, 7, 6, 7, 6, 7, 7, 7,
6, 6, 7, 5, 6, 6, 7, 6, 6, 6, 7, 6, 6, 6, 7, 7,
6, 7, 7, 5, 5, 6, 6, 6, 6, 5, 6, 5, 6, 7, 7, 7,
7, 7, 5, 6, 7, 7, 5, 5, 6, 7, 5, 6, 7, 5, 6, 7,
6, 6, 5, 7, 6, 6, 5, 7, 7, 6, 6, 5, 5, 5, 5, 7,
5, 6, 5, 6, 7, 7, 5, 7, 6, 7, 5, 6, 7, 5, 5, 6,
6, 5, 6, 6, 6, 6, 7, 6, 5, 6, 7, 5, 7, 6, 6, 7,
6, 6, 5, 7, 5, 6, 6, 5, 7, 5, 6, 5, 6, 6, 5, 6,
6, 7, 7, 6, 7, 7, 5, 7, 6, 7, 7, 5, 7, 5, 6, 6,
6, 7, 7, 7, 7, 5, 6, 7, 7, 7, 5,
]
def make_sizes():
"""
Front pics have specified sizes.
"""
rom = load_rom()
top = 251
base_stats = 0x51424
# print monster sizes
address = base_stats + 0x11
output = ''
for id in range(top):
size = (ord(rom[address])) & 0x0f
if id % 16 == 0: output += '\n\t'
output += str(size) + ', '
address += 0x20
print output
def decompress_fx_by_id(id, fxs=0xcfcf6):
rom = load_rom()
address = fxs + id*4 # len_fxptr
# get size
num_tiles = ord(rom[address]) # # tiles
# get pointer
bank = ord(rom[address+1])
address = (ord(rom[address+3]) << 8) + ord(rom[address+2])
address = (bank * 0x4000) + (address & 0x3fff)
# decompress
fx = Decompressed(rom, 'horiz', num_tiles, address)
return fx
def decompress_fx(num_fx=40):
for id in range(num_fx):
fx = decompress_fx_by_id(id)
filename = './gfx/fx/' + str(id).zfill(3) + '.2bpp' # ./gfx/fx/039.2bpp
to_file(filename, fx.pic)
num_pics = 2
front = 0
back = 1
monsters = 0x120000
num_monsters = 251
unowns = 0x124000
num_unowns = 26
unown_dex = 201
def decompress_monster_by_id(id=0, type=front):
rom = load_rom()
# no unowns here
if id + 1 == unown_dex: return None
# get size
if type == front:
size = sizes[id]
else: size = None
# get pointer
address = monsters + (id*2 + type)*3 # bank, address
bank = ord(rom[address]) + 0x36 # crystal
address = (ord(rom[address+2]) << 8) + ord(rom[address+1])
address = (bank * 0x4000) + (address & 0x3fff)
# decompress
monster = Decompressed(rom, 'vert', size, address)
return monster
def decompress_monsters(type=front):
for id in range(num_monsters):
# decompress
monster = decompress_monster_by_id(id, type)
if monster != None: # no unowns here
if not type: # front
filename = 'front.2bpp'
folder = './gfx/pics/' + str(id+1).zfill(3) + '/'
to_file(folder+filename, monster.pic)
filename = 'tiles.2bpp'
folder = './gfx/pics/' + str(id+1).zfill(3) + '/'
to_file(folder+filename, monster.animtiles)
else: # back
filename = 'back.2bpp'
folder = './gfx/pics/' + str(id+1).zfill(3) + '/'
to_file(folder+filename, monster.pic)
def decompress_unown_by_id(letter, type=front):
rom = load_rom()
# get size
if type == front:
size = sizes[unown_dex-1]
else: size = None
# get pointer
address = unowns + (letter*2 + type)*3 # bank, address
bank = ord(rom[address]) + 0x36 # crystal
address = (ord(rom[address+2]) << 8) + ord(rom[address+1])
address = (bank * 0x4000) + (address & 0x3fff)
# decompress
unown = Decompressed(rom, 'vert', size, address)
return unown
def decompress_unowns(type=front):
for letter in range(num_unowns):
# decompress
unown = decompress_unown_by_id(letter, type)
if not type: # front
filename = 'front.2bpp'
folder = './gfx/pics/' + str(unown_dex).zfill(3) + chr(ord('a') + letter) + '/'
to_file(folder+filename, unown.pic)
filename = 'tiles.2bpp'
folder = './gfx/anim/'
to_file(folder+filename, unown.animtiles)
else: # back
filename = 'back.2bpp'
folder = './gfx/pics/' + str(unown_dex).zfill(3) + chr(ord('a') + letter) + '/'
to_file(folder+filename, unown.pic)
trainers = 0x128000
num_trainers = 67
def decompress_trainer_by_id(id):
rom = load_rom()
# get pointer
address = trainers + id*3 # bank, address
bank = ord(rom[address]) + 0x36 # crystal
address = (ord(rom[address+2]) << 8) + ord(rom[address+1])
address = (bank * 0x4000) + (address & 0x3fff)
# decompress
trainer = Decompressed(rom, 'vert', None, address)
return trainer
def decompress_trainers():
for id in range(num_trainers):
# decompress
trainer = decompress_trainer_by_id(id)
filename = './gfx/trainers/' + str(id).zfill(3) + '.2bpp' # ./gfx/trainers/066.2bpp
to_file(filename, trainer.pic)
# in order of use (sans repeats)
intro_gfx = [
('logo', 0x109407),
('001', 0xE641D), # tilemap
('unowns', 0xE5F5D),
('pulse', 0xE634D),
('002', 0xE63DD), # tilemap
('003', 0xE5ECD), # tilemap
('background', 0xE5C7D),
('004', 0xE5E6D), # tilemap
('005', 0xE647D), # tilemap
('006', 0xE642D), # tilemap
('pichu_wooper', 0xE592D),
('suicune_run', 0xE555D),
('007', 0xE655D), # tilemap
('008', 0xE649D), # tilemap
('009', 0xE76AD), # tilemap
('suicune_jump', 0xE6DED),
('unown_back', 0xE785D),
('010', 0xE764D), # tilemap
('011', 0xE6D0D), # tilemap
('suicune_close', 0xE681D),
('012', 0xE6C3D), # tilemap
('013', 0xE778D), # tilemap
('suicune_back', 0xE72AD),
('014', 0xE76BD), # tilemap
('015', 0xE676D), # tilemap
('crystal_unowns', 0xE662D),
('017', 0xE672D), # tilemap
]
def decompress_intro():
rom = load_rom()
for name, address in intro_gfx:
filename = './gfx/intro/' + name + '.2bpp'
gfx = Decompressed( rom, 'horiz', None, address )
to_file(filename, gfx.output)
title_gfx = [
('suicune', 0x10EF46),
('logo', 0x10F326),
('crystal', 0x10FCEE),
]
def decompress_title():
rom = load_rom()
for name, address in title_gfx:
filename = './gfx/title/' + name + '.2bpp'
gfx = Decompressed( rom, 'horiz', None, address )
to_file(filename, gfx.output)
def decompress_tilesets():
rom = load_rom()
tileset_headers = 0x4d596
len_tileset = 15
num_tilesets = 0x25
for tileset in range(num_tilesets):
ptr = tileset*len_tileset + tileset_headers
address = (ord(rom[ptr])*0x4000) + (((ord(rom[ptr+1]))+ord(rom[ptr+2])*0x100)&0x3fff)
tiles = Decompressed( rom, 'horiz', None, address )
filename = './gfx/tilesets/'+str(tileset).zfill(2)+'.2bpp'
to_file( filename, tiles.output )
#print '(' + hex(address) + ', '+ hex(address+tiles.address+1) + '),'
misc = [
('player', 0x2BA1A, 'vert'),
('dude', 0x2BBAA, 'vert'),
('town_map', 0xF8BA0, 'horiz'),
('pokegear', 0x1DE2E4, 'horiz'),
('pokegear_sprites', 0x914DD, 'horiz'),
]
def decompress_misc():
rom = load_rom()
for name, address, mode in misc:
filename = './gfx/misc/' + name + '.2bpp'
gfx = Decompressed( rom, mode, None, address )
to_file(filename, gfx.output)
def decompress_all(debug=False):
"""
Decompress all known compressed data in baserom.
"""
if debug: print 'fronts'
decompress_monsters(front)
if debug: print 'backs'
decompress_monsters(back)
if debug: print 'unown fronts'
decompress_unowns(front)
if debug: print 'unown backs'
decompress_unowns(back)
if debug: print 'trainers'
decompress_trainers()
if debug: print 'fx'
decompress_fx()
if debug: print 'intro'
decompress_intro()