-
Notifications
You must be signed in to change notification settings - Fork 2
/
replace_files.py
executable file
·1733 lines (1372 loc) · 67 KB
/
replace_files.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/python3
import re
import json
import sys
import random
from enum import Enum, auto
from collections import defaultdict, OrderedDict
if(len(sys.argv) != 2):
print('usage: replace_files.py [path to game decomp folder]')
exit()
class GameVersion(Enum):
FIRERED = 'pokefirered'
RUBY = 'pokeruby'
decomp_folder = sys.argv[1]
version = GameVersion(re.compile(r'.*?/?([a-z]+)/?$').fullmatch(sys.argv[1].strip()).group(1))
class MonContext(Enum):
UNKNOWN = auto()
WILD = auto()
TRAINER = auto()
BOSS = auto()
with open('dex.json') as f:
dex = json.load(f, object_pairs_hook=OrderedDict)
def generate_species_h():
with open(f'templates/{version.value}/species.h_template') as f:
template = f.read()
ndex_list = '\n'.join(f'#define NATIONAL_DEX_{pk} {i}' for i, pk in enumerate(dex['national_dex']))
hdex_list = '\n'.join(f'#define HOENN_DEX_{pk} {i}' for i, pk in enumerate(dex['hoenn_dex']))
template = template.replace('[!NATIONAL_DEX_ORDER!]', ndex_list)
template = template.replace('[!HOENN_DEX_ORDER!]', hdex_list)
with open(decomp_folder + '/include/constants/species.h', 'w') as f:
f.write(template)
print('wrote /include/constants/species.h')
# ruby only: replace pokemon_1.c where hoenn dex order is defined
if version == GameVersion.RUBY:
with open('templates/pokeruby/pokemon_1.c_template') as f:
tmp = f.read()
content = ',\n'.join([ 'NATIONAL_DEX_' + poke for poke in dex['hoenn_dex'][1:] ]) + ','
tmp = tmp.replace('[[!CONTENT!]]', content)
with open(decomp_folder + 'src/pokemon_1.c', 'w') as f:
f.write(tmp)
print('wrote /src/pokemon_1.c')
def generate_base_stats_h():
with open(f'templates/{version.value}/base_stats.h_template') as f:
template = f.read()
poke_start = re.compile('\s\s\s\s\[SPECIES_(.+)\]\s=')
poke_end = re.compile('\s\s\s\s\},')
data = dex['base_stats.h']
current_poke = None
output = []
for line in template.split('\n'):
m = poke_start.search(line)
if m != None and m.group(1) in data:
current_poke = m.group(1)
pkmn = data[current_poke]
if pkmn == 'OLD_UNOWN':
output.append(line)
else:
output.append(line)
output.append(' {')
if version == GameVersion.FIRERED:
output.append(
f""" .baseHP = {pkmn['baseHP']},
.baseAttack = {pkmn['baseAttack']},
.baseDefense = {pkmn['baseDefense']},
.baseSpeed = {pkmn['baseSpeed']},
.baseSpAttack = {pkmn['baseSpAttack']},
.baseSpDefense = {pkmn['baseSpDefense']},
.type1 = TYPE_{pkmn['type1']},
.type2 = TYPE_{pkmn['type2']},
.catchRate = {pkmn['catchRate']},
.expYield = {pkmn['expYield']},
.evYield_HP = {pkmn['evYield_HP']},
.evYield_Attack = {pkmn['evYield_Attack']},
.evYield_Defense = {pkmn['evYield_Defense']},
.evYield_Speed = {pkmn['evYield_Speed']},
.evYield_SpAttack = {pkmn['evYield_SpAttack']},
.evYield_SpDefense = {pkmn['evYield_SpDefense']},
.item1 = ITEM_{pkmn['item1']},
.item2 = ITEM_{pkmn['item2']},
.genderRatio = {pkmn['genderRatio']},
.eggCycles = {pkmn['eggCycles']},
.friendship = {pkmn['friendship']},
.growthRate = GROWTH_{pkmn['growthRate']},
.eggGroup1 = EGG_GROUP_{pkmn['eggGroup1']},
.eggGroup2 = EGG_GROUP_{pkmn['eggGroup2']},
.abilities = {{ ABILITY_{pkmn['abilities'][0]}, ABILITY_{pkmn['abilities'][1]} }},
.safariZoneFleeRate = {pkmn['safariZoneFleeRate']},
.bodyColor = BODY_COLOR_{pkmn['bodyColor']},
.noFlip = TRUE,""")
elif version == GameVersion.RUBY:
output.append(
f""" .baseHP = {pkmn['baseHP']},
.baseAttack = {pkmn['baseAttack']},
.baseDefense = {pkmn['baseDefense']},
.baseSpeed = {pkmn['baseSpeed']},
.baseSpAttack = {pkmn['baseSpAttack']},
.baseSpDefense = {pkmn['baseSpDefense']},
.type1 = TYPE_{pkmn['type1']},
.type2 = TYPE_{pkmn['type2']},
.catchRate = {pkmn['catchRate']},
.expYield = {pkmn['expYield']},
.evYield_HP = {pkmn['evYield_HP']},
.evYield_Attack = {pkmn['evYield_Attack']},
.evYield_Defense = {pkmn['evYield_Defense']},
.evYield_Speed = {pkmn['evYield_Speed']},
.evYield_SpAttack = {pkmn['evYield_SpAttack']},
.evYield_SpDefense = {pkmn['evYield_SpDefense']},
.item1 = ITEM_{pkmn['item1']},
.item2 = ITEM_{pkmn['item2']},
.genderRatio = {pkmn['genderRatio']},
.eggCycles = {pkmn['eggCycles']},
.friendship = {pkmn['friendship']},
.growthRate = GROWTH_{pkmn['growthRate']},
.eggGroup1 = EGG_GROUP_{pkmn['eggGroup1']},
.eggGroup2 = EGG_GROUP_{pkmn['eggGroup2']},
.ability1 = ABILITY_{pkmn['abilities'][0]},
.ability2 = ABILITY_{pkmn['abilities'][1]},
.safariZoneFleeRate = {pkmn['safariZoneFleeRate']},
.bodyColor = BODY_COLOR_{pkmn['bodyColor']},
.noFlip = TRUE,""")
if poke_end.search(line) != None:
current_poke = None
if current_poke == None:
output.append(line)
with open(decomp_folder + '/src/data/pokemon/base_stats.h', 'w') as f:
f.write('\n'.join(output))
print('wrote /src/data/pokemon/base_stats.h')
def generate_names_h_pokefirered():
with open('templates/pokefirered/species_names.h_template') as f:
template = f.read()
names = dex['species_names.h']
names.insert(0, '??????????')
is_name = re.compile('\s\s\s\s_\("(.+)"\)')
output = []
index = 0
for line in template.split('\n'):
m = is_name.search(line)
if m == None:
output.append(line)
else:
if index < len(names):
output.append(f' _("{names[index]}"),')
else:
output.append(line)
index = index + 1
with open(decomp_folder + '/src/data/text/species_names.h', 'w') as f:
f.write('\n'.join(output))
print('wrote /src/data/text/species_names.h')
def generate_names_h_pokeruby():
with open('templates/pokeruby/species_names_en.h_template') as f:
template = f.read()
names = dex['species_names.h']
names.insert(0, '??????????')
is_name = re.compile('_\(.+\)')
output = []
index = 0
for line in template.split('\n'):
if is_name.search(line) != None:
line = re.sub(is_name, f'_("{names[index]}")', line)
index += 1
output.append(line)
with open(decomp_folder + '/src/data/text/species_names_en.h', 'w') as f:
f.write('\n'.join(output))
print('wrote /src/data/text/species_names_en.h')
generate_names_h = {
GameVersion.FIRERED : generate_names_h_pokefirered,
GameVersion.RUBY : generate_names_h_pokeruby
}
def generate_pokemon_h():
with open(f'templates/{version.value}/pokemon.h_template') as f:
template = f.read()
with open('templates/palette_template') as f:
palette_template = f.read()
if version == GameVersion.FIRERED:
get_front_pic = re.compile('const\su32\s(.+)\s=\sINCBIN_U32\("graphics\/pokemon\/(.+)\/front.4bpp.lz"\);')
get_back_pic = re.compile('const\su32\s(.+)\s=\sINCBIN_U32\("graphics\/pokemon\/(.+)\/back.4bpp.lz"\);')
get_icon = re.compile('const\su8\s(.+)\s=\sINCBIN_U8\("graphics\/pokemon\/(.+)\/icon.4bpp"\);')
get_palette = re.compile('const\su32\s.+\s=\sINCBIN_U32\(\"(.+)normal\.gbapal\.lz"\);')
elif version == GameVersion.RUBY:
get_front_pic = re.compile('const\su8\s(.+)\s=\sINCBIN_U8\("graphics\/pokemon\/(.+)\/front.4bpp.lz"\);')
get_back_pic = re.compile('const\su8\s(.+)\s=\sINCBIN_U8\("graphics\/pokemon\/(.+)\/back.4bpp.lz"\);')
get_icon = re.compile('const\su8\s(.+)\s=\sINCBIN_U8\("graphics\/pokemon\/(.+)\/icon.4bpp"\);')
get_palette = re.compile('const\su8\s.+\s=\sINCBIN_U8\(\"(.+)normal\.gbapal\.lz"\);')
output = []
colors = dex['image_colors']
index = 1
for line in template.split('\n'):
m_front = get_front_pic.search(line)
m_back = get_back_pic.search(line)
m_icon = get_icon.search(line)
m_palette = get_palette.search(line)
if '_Egg[]' in line:
m_front = m_palette = m_icon = None
if m_palette != None and index <= len(colors):
palette_file = f'{decomp_folder}{m_palette.group(1)}normal.pal'
while colors[index-1] == 'OLD_UNOWN':
index = index+1
color0 = colors[index-1][0]
color255 = colors[index-1][1]
color205 = (int(205/255*color255[0] + (255-205)/255*color0[0]), int(205/255*color255[1] + (255-205)/255*color0[1]), int(205/255*color255[2] + (255-205)/255*color0[2]))
color172 = (int(172/255*color255[0] + (255-172)/255*color0[0]), int(172/255*color255[1] + (255-172)/255*color0[1]), int(172/255*color255[2] + (255-172)/255*color0[2]))
palette = palette_template
palette = palette.replace('0 0 0', f'{color0[0]} {color0[1]} {color0[2]}')
palette = palette.replace('172 172 172', f'{color172[0]} {color172[1]} {color172[2]}')
palette = palette.replace('205 205 205', f'{color205[0]} {color205[1]} {color205[2]}')
palette = palette.replace('255 255 255', f'{color255[0]} {color255[1]} {color255[2]}')
index = index + 1
with open(palette_file, 'wb') as f:
f.write(str.encode(palette.replace('\n', '\r\n')))
if m_front != None:
if 'Deoxys' in m_front.group(1) and version == GameVersion.FIRERED: # TODO hack, deoxys needs a special sprite file, should make one
output.append(line)
else:
if version == GameVersion.FIRERED:
output.append(f'const u32 {m_front.group(1)} = INCBIN_U32("graphics/pokemon/question_mark/circled/front.4bpp.lz");')
elif version == GameVersion.RUBY:
output.append(f'const u8 {m_front.group(1)} = INCBIN_U8("graphics/pokemon/circled_question_mark/front.4bpp.lz");')
elif m_back != None:
if 'Deoxys' in m_back.group(1) and version == GameVersion.FIRERED:
output.append(line)
else:
if version == GameVersion.FIRERED:
output.append(f'const u32 {m_back.group(1)} = INCBIN_U32("graphics/pokemon/question_mark/circled/back.4bpp.lz");')
elif version == GameVersion.RUBY:
output.append(f'const u8 {m_back.group(1)} = INCBIN_U8("graphics/pokemon/circled_question_mark/back.4bpp.lz");')
elif m_icon != None:
output.append(f'const u8 {m_icon.group(1)} = INCBIN_U8("graphics/pokemon/question_mark/icon.4bpp");')
else:
output.append(line)
with open(decomp_folder + '/src/data/graphics/pokemon.h', 'w') as f:
f.write('\n'.join(output))
print('wrote /src/data/graphics/pokemon.h')
def generate_egg_moves_h():
with open(f'templates/{version.value}/egg_moves.h_template') as f:
template = f.read()
data = dex['egg_moves.h']
output = []
is_start = re.compile('\s\s\s\segg_moves\((.+),')
tmpl_start, tmpl_end = template.split('[!CONTENT!]')
output.append(tmpl_start)
for poke in data.keys():
if len(data[poke]) != 0:
movelist = ', '.join([ '\n MOVE_'+mv for mv in data[poke] ])
output.append(f' egg_moves({poke}, {movelist}),\n')
output.append(tmpl_end)
with open(decomp_folder + '/src/data/pokemon/egg_moves.h', 'w') as f:
f.write('\n'.join(output))
print('wrote /src/data/pokemon/egg_moves.h')
def generate_tmhm_learnsets_h():
with open('archetypes.json') as f:
tm_list = json.load(f)['tm_list']
tms = {}
for i, tm in enumerate(tm_list):
index = i+1
if index <= 50:
start = f'TM{str(index).rjust(2, "0")}'
else:
start = f'HM{str(index-50).rjust(2, "0")}'
if tm == 'SOLAR_BEAM':
tm_str = 'SOLARBEAM'
else:
tm_str = tm
tms[tm] = f'{start}_{tm_str}'
with open(f'templates/{version.value}/tmhm_learnsets.h_template') as f:
template = f.read()
data = dex['tmhm_learnsets.h']
output = []
tmpl_start, tmpl_end = template.split('[!CONTENT!]')
output.append(tmpl_start)
for poke in data.keys():
if len(data[poke]) != 0:
learnset = "\n | ".join([ "TMHM(" + tms[tm] + ")" for tm in data[poke] ])
output.append(f' [SPECIES_{poke}] = TMHM_LEARNSET({learnset}),\n')
output.append(tmpl_end)
with open(decomp_folder + 'src/data/pokemon/tmhm_learnsets.h', 'w') as f:
f.write('\n'.join(output))
print('wrote /src/data/pokemon/tmhm_learnsets.h')
def generate_tutor_learnsets_h_pokefirered():
with open(f'templates/{version.value}/tutor_learnsets.h_template') as f:
template = f.read()
data = dex['tutor_learnsets.h']
output = []
tmpl_start, tmpl_end = template.split('[!CONTENT!]')
output.append(tmpl_start)
for poke in data.keys():
if len(data[poke]) != 0:
learnset = '\n | '.join([ f'TUTOR(MOVE_{mv})' for mv in data[poke] ])
output.append(f' [SPECIES_{poke}] = {learnset},\n')
output.append(tmpl_end)
with open(decomp_folder + 'src/data/pokemon/tutor_learnsets.h', 'w') as f:
f.write('\n'.join(output))
print('wrote /src/data/pokemon/tutor_learnsets.h')
generate_tutor_learnsets_h = {
GameVersion.FIRERED : generate_tutor_learnsets_h_pokefirered,
GameVersion.RUBY : lambda: None
}
def generate_pokedex_entries_h():
with open('templates/pokefirered/pokedex_entries.h_template') as f:
template = f.read()
description_to_entry = {}
species_def = re.compile('DEX_(.+)\]')
get_description = re.compile('=\\s(.+?),')
output = []
current_species = None
for line in template.split('\n'):
m = species_def.search(line)
if m != None:
if m.group(1) in dex['pokedex_entries.h'].keys():
current_species = m.group(1)
else:
current_species = None
if current_species != None:
if 'category' in line:
output.append(f" .categoryName = _(\"{dex['pokedex_entries.h'][current_species]['categoryName']}\"),")
continue
if 'height' in line:
output.append(f" .height = {dex['pokedex_entries.h'][current_species]['height']},")
continue
if 'weight' in line:
output.append(f" .weight = {min(dex['pokedex_entries.h'][current_species]['weight'], 9999)},")
continue
if 'pokemonScale' in line:
output.append(' .pokemonScale = 256,')
continue
if 'pokemonOffset' in line:
output.append(' .pokemonOffset = 0,')
continue
if 'trainerScale' in line:
output.append(' .trainerScale = 256,')
continue
if 'trainerOffset' in line:
output.append(' .trainerOffset = 0,')
continue
if 'description' in line:
description_to_entry[get_description.search(line).group(1)] = dex['pokedex_text_fr.h'][current_species]
output.append(line)
with open(decomp_folder + 'src/data/pokemon/pokedex_entries.h', 'w') as f:
f.write('\n'.join(output))
print('wrote /src/data/pokemon/pokedex_entries.h')
return description_to_entry
def split_dex_entry(entry):
lines = []
i = 0
while i < len(entry):
if i >= 27 and entry[i] == ' ':
lines.append(entry[:i])
entry = entry[i+1:]
i = 0
i = i + 1
if entry != "":
lines.append(entry)
if len(lines) > 3:
print('Overlong pokedex entry:', lines)
lb = "\\n"
lines = [f'"{line + lb}"' for line in lines ]
lines[-1] = lines[-1].replace('\\n', '')
return '\n\t'.join(lines)
def generate_pokedex_text_fr_h(description_to_entry):
with open('templates/pokefirered/pokedex_text_fr.h_template') as f:
template = f.read()
entries = dex['pokedex_text_fr.h']
valid_line = re.compile('const\\su8\\s(.+?)\\[\\]\\s=\\s_\\($')
valid_unused_line = re.compile('const\\su8\\s.+?\\[\\]\\s=\\s_\\(""\\);')
lines = []
for line in template.split('\n'):
is_valid = valid_line.search(line)
if is_valid != None:
if 'Dummy' in line:
lines.append(line + '"");')
else:
desc = is_valid.group(1)
entry = description_to_entry[desc]
lines.append(f'const u8 {desc}[] = _(\n\t{split_dex_entry(entry)});')
elif valid_unused_line.search(line) != None:
lines.append(line)
output = '\n\n'.join(lines)
with open(decomp_folder + 'src/data/pokemon/pokedex_text_fr.h', 'w') as f:
f.write(output)
print('wrote /src/data/pokemon/pokedex_text_fr.h')
def generate_pokedex_pokefirered():
description_to_entry = generate_pokedex_entries_h()
generate_pokedex_text_fr_h(description_to_entry)
def generate_pokedex_pokeruby():
with open('templates/pokeruby/pokedex_entries_en.h_template') as f:
template = f.read()
desc_line_1 = re.compile('_1\[\]\s=\s_\(\n.+\n.+\n?.+\);')
desc_line_2 = re.compile('_2\[\]\s=\s_\(\n.+\n.+\n?.+\);')
desc_1_empty = """_1[] = _(
"This is a newly discovered POKéMON.\\n"
"It is currently under investigation.");"""
desc_2_empty = """_2[] = _(
"No detailed information is available\\n"
"at this time.");"""
template = re.sub(desc_line_1, lambda _: desc_1_empty, template)
template = re.sub(desc_line_2, lambda _: desc_2_empty, template)
dex_data = dex['pokedex_entries.h']
pokelist = list(dex['national_dex'])
output = []
index = -1
for line in template.split('\n'):
if '{ //' in line:
index += 1
pokeid = pokelist[index]
if index >= 0 and '.height' in line:
height = 0
if pokeid != 'NONE':
height = dex_data[pokeid]['height']
output.append(f" .height = {height},")
elif index >= 0 and '.weight' in line:
weight = 0
if pokeid != 'NONE':
weight = dex_data[pokeid]['weight']
output.append(f" .weight = {min(weight, 9999)},")
elif index >= 0 and '.categoryName' in line:
cat_name = 'UNKNOWN'
if pokeid != 'NONE':
cat_name = dex_data[pokeid]['categoryName']
output.append(f' .categoryName = _("{cat_name}"),')
elif '.pokemonScale' in line:
output.append(' .pokemonScale = 256,')
elif '.pokemonOffset' in line:
output.append(' .pokemonOffset = 0,')
elif '.trainerScale' in line:
output.append(' .trainerScale = 256,')
elif '.trainerOffset' in line:
output.append(' .trainerOffset = 0,')
else:
output.append(line)
with open(decomp_folder + 'src/data/pokedex_entries_en.h', 'w') as f:
f.write('\n'.join(output))
print('wrote /src/data/pokedex_entries_en.h')
generate_pokedex = {
GameVersion.FIRERED : generate_pokedex_pokefirered,
GameVersion.RUBY : generate_pokedex_pokeruby
}
def evo_string(evo):
if evo[0] == 'EVO_LEVEL':
return f'{{EVO_LEVEL, {evo[1]}, SPECIES_{evo[2]}}}'
if evo[0] == 'EVO_ITEM':
return f'{{EVO_ITEM, ITEM_{evo[1]}, SPECIES_{evo[2]}}}'
if evo[0] == 'EVO_FRIENDSHIP':
return f'{{EVO_FRIENDSHIP, 0, SPECIES_{evo[2]}}}'
def generate_evolution_h():
with open(f'templates/{version.value}/evolution.h_template') as f:
template = f.read()
data = dex['evolution.h']
output = []
tmpl_start, tmpl_end = template.split('[!CONTENT!]')
output.append(tmpl_start)
for poke in data.keys():
value = '{' + ', '.join([ (evo_string(evo)) for evo in data[poke] ]) + '}'
output.append(f' [SPECIES_{poke}] = {value},\n')
output.append(tmpl_end)
with open(decomp_folder + 'src/data/pokemon/evolution.h', 'w') as f:
f.write('\n'.join(output))
print('wrote /src/data/pokemon/evolution.h')
def generate_level_up_learnsets_h():
with open(f'templates/{version.value}/level_up_learnsets.h_template') as f:
template = f.read()
if version == GameVersion.FIRERED:
poke_start = re.compile('static\sconst\su16\s(.+)\[\]')
elif version == GameVersion.RUBY:
poke_start = re.compile('const\su16\s(.+)\[\]')
output = []
data = dex['level_up_learnsets.h']
current_poke = None
for line in template.split('\n'):
m = poke_start.search(line)
if line == '};':
current_poke = None
elif m != None:
current_poke = m.group(1)
moves_id = m.group(1)
if version == GameVersion.RUBY:
moves_id = 's' + moves_id[1:]
if moves_id in data:
if version == GameVersion.FIRERED:
output.append(f'static const u16 {current_poke}[] = {{')
elif version == GameVersion.RUBY:
output.append(f'const u16 {current_poke}[] = {{')
for mv in data[moves_id]:
output.append(f' LEVEL_UP_MOVE({mv[0]}, MOVE_{mv[1]}),')
output.append(' LEVEL_UP_END')
if current_poke == None or (not moves_id in data):
output.append(line)
with open(decomp_folder + 'src/data/pokemon/level_up_learnsets.h', 'w') as f:
f.write('\n'.join(output))
print('wrote /src/data/pokemon/level_up_learnsets.h')
def generate_sprite_position_files_pokefirered():
with open(decomp_folder + 'src/data/pokemon_graphics/enemy_mon_elevation.h', 'w') as f:
with open('templates/pokefirered/enemy_mon_elevation.h_template') as t:
f.write(t.read())
print('wrote /src/data/pokemon_graphics/enemy_mon_elevation.h')
with open(decomp_folder + 'src/data/pokemon_graphics/back_pic_coordinates.h', 'w') as f:
with open('templates/pokefirered/back_pic_coordinates.h_template') as t:
f.write(t.read())
print('wrote /src/data/pokemon_graphics/back_pic_coordinates.h.h')
with open(decomp_folder + 'src/data/pokemon_graphics/front_pic_coordinates.h', 'w') as f:
with open('templates/pokefirered/front_pic_coordinates.h_template') as t:
f.write(t.read())
print('wrote /src/data/pokemon_graphics/front_pic_coordinates.h')
def generate_sprite_position_files_pokeruby():
with open(decomp_folder + 'src/battle/battle_1.c', 'w') as f:
with open('templates/pokeruby/battle_1.c_template') as t:
f.write(t.read())
print('wrote /src/battle/battle_1.c')
with open(decomp_folder + 'data/graphics/pokemon/front_pic_coords.inc', 'w') as f:
with open('templates/pokeruby/front_pic_coords.inc_template') as t:
f.write(t.read())
print('wrote /data/graphics/pokemon/front_pic_coords.inc')
with open(decomp_folder + 'data/graphics/pokemon/back_pic_coords.inc', 'w') as f:
with open('templates/pokeruby/back_pic_coords.inc_template') as t:
f.write(t.read())
print('wrote /data/graphics/pokemon/back_pic_coords.inc')
generate_sprite_position_files = {
GameVersion.FIRERED : generate_sprite_position_files_pokefirered,
GameVersion.RUBY : generate_sprite_position_files_pokeruby
}
def filter_mons(mons, of_types, of_egg_groups, max_lvl, ctxt=MonContext.UNKNOWN, rarity_max_lvl=50):
choices = []
if len(mons) == 0:
raise BaseException('no mons given')
if of_types == None and of_egg_groups == None:
choices.extend(mons)
else:
for poke_name in mons:
poke = dex['encounter_data'][poke_name]
if poke['types'][0] in of_types or poke['types'][1] in of_types or poke['egg_groups'][0] in of_egg_groups or poke['egg_groups'][1] in of_egg_groups:
choices.append(poke_name)
choices.sort(key=lambda pk: dex['encounter_data'][pk]['bst'])
rarity = max_lvl/rarity_max_lvl
target_len = int(len(choices) * rarity)
rand_max = random.randint(2,4)
if target_len < rand_max:
target_len = rand_max
if target_len > len(choices):
target_len = len(choices)
choices = choices[0:target_len]
random.shuffle(choices)
if ctxt == MonContext.BOSS:
target_len = 6
if(len(choices) > 6):
choices.sort(key=lambda pk: dex['encounter_data'][pk]['bst'])
choices = choices[len(choices)-6:]
else:
target_len = random.randint(3, 5)
if target_len > len(choices):
target_len = len(choices)
choices = choices[0:target_len]
if len(choices) == 0:
raise BaseException(f'no mons for {of_types}, {of_egg_groups}')
return choices
evos_into = {}
evos_from = {}
for evolver in dex['evolution.h'].keys():
evo = dex['evolution.h'][evolver][0]
buffer = 25 #WAS 30
if evolver in evos_from:
buffer = evos_from[evolver]['at'] + 15
if evo[0] == 'EVO_LEVEL':
evos_into[evolver] = { 'at' : evo[1], 'to' : evo[2], 'wild' : True }
evos_from[evo[2]] = { 'at' : evo[1], 'from' : evolver }
elif evo[0] == 'EVO_ITEM':
evos_into[evolver] = { 'at' : buffer, 'to' : evo[2], 'wild' : False }
evos_from[evo[2]] = { 'at' : buffer, 'from' : evolver }
elif evo[0] == 'EVO_FRIENDSHIP':
evos_into[evolver] = { 'at' : buffer, 'to' : evo[2], 'wild' : False }
evos_from[evo[2]] = { 'at' : buffer, 'from' : evolver }
# prevent stage 3 in wild
if evolver in evos_into and evolver in evos_from:
evos_into[evolver]['wild'] = False
def adjust_evo(mon, min_lvl, max_lvl=None, ctxt=None):
if max_lvl == None:
max_lvl = min_lvl
mon_start = mon
while mon in evos_into and max_lvl > evos_into[mon]['at']:
mon = evos_into[mon]['to']
while mon in evos_from and min_lvl < evos_from[mon]['at']:
mon = evos_from[mon]['from']
# prevent illegal wild evolutions
if ctxt == MonContext.WILD and mon in evos_from:
prev_stage = evos_from[mon]['from']
if not evos_into[prev_stage]['wild']:
mon = prev_stage
# randomly devolve trainer pokemon close to evolution level
if ctxt == MonContext.TRAINER and mon in evos_from:
if max_lvl - 5 < evos_from[mon]['at']:
if random.random() > 0.5:
mon = evos_from[mon]['from']
# bosses can cheat a bit and evolve pokemon earlier, as a treat
if ctxt == MonContext.BOSS and mon in evos_into:
if max_lvl + 4 >= evos_into[mon]['at']:
mon = evos_into[mon]['to']
if mon != mon_start:
#print(f'lvl {min_lvl}–{max_lvl}: {mon_start} -> {mon}')
if mon in evos_into:
#print('\t', mon, evos_into[mon])
pass
if mon in evos_from:
#print('\t', mon, evos_from[mon])
pass
return mon
assigned_mons = set()
def assign_wild_mons(mons, wild_mons):
max_lvl = max([ mon['max_level'] for mon in wild_mons['mons'] ])
mons = filter_mons(mons, None, None, max_lvl, rarity_max_lvl = 50 if version == GameVersion.FIRERED else 40)
for mon in wild_mons['mons']:
chosen = adjust_evo(random.choice(mons), mon['min_level'], mon['max_level'], ctxt=MonContext.WILD)
assigned_mons.add(base_form(chosen))
mon['species'] = 'SPECIES_' + chosen
map_cache = {}
def get_map_data(map_name, enc_data):
data = None
map_id = None
for key in enc_data.keys():
if map_name == key:
data = enc_data[key]
map_id = map_name
break
elif key[-1] == '*' and key[0:len(key)-1] == map_name[0:len(key)-1]:
data = enc_data[key]
map_id = key
return (data, map_id)
def set_map_data(map_name, encounters, enc_data, mon_list):
data, map_id = get_map_data(map_name, enc_data)
if data == None:
print('!!!! cant find data:', map_name)
return
if not map_id.startswith('SPECIAL') and not ('habitats' in data and 'motifs' in data):
print('!!!!! incomplete data:', map_name, dict(data))
is_post = 'postgame' in data and data['postgame']
mons = mon_list['post'] if is_post else mon_list['main']
map_id = map_id + ('_post' if is_post else '')
if map_id not in map_cache:
map_cache[map_id] = generate_mons(mons, data['habitats'], data['types'] if 'types' in data else [], data['not_types'] if 'not_types' in data else [], data['motifs'] if 'motifs' in data else [])
try:
assign_wild_mons(map_cache[map_id], encounters)
except BaseException as e:
print(f'cannot assign wild mons for {map_name} {dict(data)}')
print('available:', map_cache[map_id])
raise e
if map_name == 'MAP_ROUTE101' and version == GameVersion.RUBY:
global ROUTE101_WILD_POOCHYENA
ROUTE101_WILD_POOCHYENA = encounters['mons'][0]['species']
def generate_mons(mons, habitats, types, not_types, motifs):
mons = list(mons)
random.shuffle(mons)
mon_values = {}
for m in mons:
mon_values[m] = wild_mon_value(m, habitats, types, not_types, motifs)
mons[:] = [m for m in mons if mon_values[m] > 0]
mons.sort(key=lambda m: -mon_values[m])
target_len = 10# max(10, len(mons)//2)
return mons[0:min(target_len, len(mons))]
def wild_mon_value(mon, habitats, types, not_types, motifs):
val = 0
mon_habitats = dex['encounter_data'][mon]['habitats']
mon_motifs = dex['encounter_data'][mon]['motifs']
mon_types = set(dex['encounter_data'][mon]['types'])
any_habitat = False
for h in habitats:
if h in mon_habitats:
val += 1
any_habitat = True
if not any_habitat:
val = val - 100000
for m in motifs:
if m in mon_motifs:
val += 5
for t in types:
if t in mon_types:
val += 10
for t in not_types:
if t in mon_types:
val -= 30
if mon not in assigned_mons:
val += 5
# TODO adjust for already encountered
return val
def try_generate_wild_encounters(mon_list):
with open(f'templates/{version.value}/wild_encounters.json_template') as f:
encs = json.load(f)
with open(f'encounter_data_{version.value}.json') as f:
enc_data = json.load(f, object_pairs_hook=OrderedDict)
enc_data_order = list(enc_data.keys())
entry_order = []
entries = {}
entry_sort_value = {}
for entry in encs['wild_encounter_groups'][0]['encounters']:
if (not 'LeafGreen' in entry['base_label']) and (not 'Sapphire' in entry['base_label']):
if entry['map'] == 'MAP_SIX_ISLAND_ALTERING_CAVE':
if entry['base_label'] != 'sSixIslandAlteringCave_FireRed':
continue
entry_order.append(entry['map'])
entries[entry['map']] = entry
data, map_id = get_map_data(entry['map'], enc_data)
entry_sort_value[entry['map']] = enc_data_order.index(map_id) if map_id in enc_data_order else 0
entry_order.sort(key=lambda map_id: entry_sort_value[map_id])
for entry_id in entry_order:
entry = entries[entry_id]
if 'LeafGreen' in entry['base_label'] or 'Sapphire' in entry['base_label']:
continue
map_name = entry['map']
data, map_id = get_map_data(map_name, enc_data)
if 'land_mons' in entry:
set_map_data(entry['map'], entry['land_mons'], enc_data, mon_list)
if 'water_mons' in entry:
if data is None or 'surfing' not in data:
print('!!!!!! surfing not declared in', map_name)
else:
if 'postgame' in data and data['postgame']:
enc_data[data['surfing']]['postgame'] = True
else:
enc_data[data['surfing']]['postgame'] = False
set_map_data(data['surfing'], entry['water_mons'], enc_data, mon_list)
if 'fishing_mons' in entry:
if data is None or 'fishing' not in data:
print('!!!!!! fishing not declared in', map_name)
else:
if 'postgame' in data and data['postgame']:
enc_data[data['fishing']]['postgame'] = True
else:
enc_data[data['fishing']]['postgame'] = False
set_map_data(data['fishing'], entry['fishing_mons'], enc_data, mon_list)
if 'rock_smash_mons' in entry:
if data is None or 'rock_smash' not in data:
print('!!!!!! rock smash not declared in', map_name)
else:
if 'postgame' in data and data['postgame']:
enc_data[data['rock_smash']]['postgame'] = True
else:
enc_data[data['rock_smash']]['postgame'] = False
set_map_data(data['rock_smash'], entry['rock_smash_mons'], enc_data, mon_list)
return encs
def base_form(pkmn):
while pkmn in evos_from:
pkmn = evos_from[pkmn]['from']
return pkmn
def pick_rare_pkmn(unavailable_families, available_families, req_type=None):
if len(unavailable_families) != 0:
rnd = random.choice(unavailable_families)
unavailable_families.remove(rnd)
return rnd
if req_type == None:
return random.choice(available_families)
else:
sel = random.choice(available_families)
while not req_type in dex['encounter_data'][sel]['types']:
sel = random.choice(available_families)
return sel
def generate_wild_encounters(mon_list):
encs = try_generate_wild_encounters(mon_list)
main_families = list(mon_list['main'])
post_families = list(mon_list['post'])
main_missing = list(main_families)
post_missing = list(set(post_families).difference(main_families))
for mon in assigned_mons:
if mon in post_missing:
post_missing.remove(mon)
if mon in main_missing:
main_missing.remove(mon)
print('unavailable families:', main_missing, post_missing)
if version == GameVersion.FIRERED:
generate_in_game_pokemon_pokefirered(main_families, post_families, main_missing, post_missing)
elif version == GameVersion.RUBY:
generate_in_game_pokemon_pokeruby(main_families, main_missing)
print('final unavailable families:', main_missing, post_missing)
with open(decomp_folder + 'src/data/wild_encounters.json', 'w') as f:
f.write(json.dumps(encs, indent=2, sort_keys=False))
def generate_in_game_pokemon_pokefirered(main_families, post_families, main_missing, post_missing):
# replace lapras gift
with open(decomp_folder + 'data/maps/SilphCo_7F/scripts.inc', 'w') as f: