-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
2053 lines (1822 loc) · 78.1 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import rom
from rom import readword, readtablebyte, readtableword, readbyte
import copy
import traceback
import hashlib
VERSION_INT=2023041819
VERSION_NAME="v1.3"
def flatten(l):
a = []
for b in l:
a += b
return a
def gcd(*args):
# implemented by ChatGPT
result = args[0]
for arg in args[1:]:
result = gcd_two(result, arg)
return result
def gcd_two(a, b):
# implemented by ChatGPT
while b != 0:
a, b = b, a % b
return a
def lcm(*args):
# implemented by ChatGPT
result = args[0]
for arg in args[1:]:
result = lcm_two(result, arg)
return result
def lcm_two(a, b):
# implemented by ChatGPT
return a * b // gcd_two(a, b)
class JSONDict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args)
for key, value in kwargs.items():
self[key] = value
# This class implemented by ChatGPT
# WARNING! some attributes are overshadowed by native dict attributes
# for example, you can't access groove.values directly, must do groove["values"].
# if you're experiencing an issue where your code works only if you change the
# key's name, this is probably the reason.
def __getattr__(self, attr):
if hasattr(dict, attr):
return getattr(dict, attr).__get__(self, type(self))
try:
return self[attr]
except KeyError:
raise AttributeError(attr)
def __setattr__(self, attr, value):
if hasattr(dict, attr):
setattr(dict, attr, value)
else:
self[attr] = value
# returns a pair: gb: bytes, data: JSONDict
def loadRom(path):
with open(path, "rb") as f:
rom.readrom(f.read())
j = JSONDict()
j.VERSION=VERSION_INT
j.tileset_common = getTilesetAtAddr(rom.LEVEL_TILESET_TABLE_BANK, rom.LEVEL_TILESET_COMMON)
j.screenTilesAddr = rom.readtableword(rom.BANK2, rom.LEVTAB_TILES_BANK2, 1, 0)
loadGlobalSpritePatches(j)
j.levels = []
for i, levelname in enumerate(rom.LEVELS):
jl = JSONDict()
j.levels.append(jl)
if i == 0:
jl.index = i
jl.name = "select"
else:
jl.index = i
jl.name = levelname
loadLevelTileset(j, i)
loadLevelChunks(j, i)
jl.sublevels = []
for sublevel in range(rom.SUBSTAGECOUNT[i]):
jsl = JSONDict()
jl.sublevels.append(jsl)
loadSublevelScreens(j, i, sublevel)
loadSublevelTimer(j, i, sublevel);
loadSublevelScreenTable(j, i, sublevel)
loadSublevelScreenEntities(j, i, sublevel)
loadSublevelInitRoutine(j, i, sublevel)
loadSublevelSpritesPatch(j, i, sublevel)
if sublevel >= 1:
loadSublevelTilesPatch(j, i, sublevel)
j.entC4Routine = loadInitRoutine(j, rom.ENT4C_FLICKER_ROUTINE_BANK, rom.ENT4C_FLICKER_ROUTINE, maxAddr = rom.ENT4C_FLICKER_ROUTINE_END)
j.ent78Routine = loadInitRoutine(j, rom.ENT78_FLICKER_ROUTINE_BANK, rom.ENT78_FLICKER_ROUTINE, maxaddr=rom.ENT78_FLICKER_ROUTINE_END)
j.crusherRoutine = loadInitRoutine(j, rom.CRUSHER_ROUTINE_BANK, rom.CRUSHER_ROUTINE, maxaddr=rom.CRUSHER_ROUTINE_END)
return rom.data, j
# returns a json object for the sprite located at the given address
# also returns the address of the end of the sprite
def readSprite(bank, addr):
jsprite = JSONDict({
"srcAddr": f"{bank:X}:{addr:04X}",
"tileCount": rom.readbyte(bank, addr),
"tiles": []
})
addr += 1
for t in range(jsprite.tileCount):
jtile = JSONDict()
jsprite.tiles.append(jtile)
jtile.yoff = rom.readSignedByte(bank, addr)
addr += 1
jtile.xoff = rom.readSignedByte(bank, addr)
addr += 1
jtile.tidx = rom.readbyte(bank, addr)
addr += 1
if jtile.tidx & 1 == 1:
jtile.tidx &= ~1
jtile.flags = rom.readbyte(bank, addr)
addr += 1
return jsprite, addr
# each sublevel (other than 0) edits/patches a portion of the vram tile palette
# we presume this is only to change the sprites available
def loadSublevelTilesPatch(j, level, sublevel):
assert sublevel >= 1, "sublevel 0 does not patch tiles"
if rom.ROMTYPE not in ["us", "jp"]:
return
jl = j.levels[level]
jsl = jl.sublevels[sublevel]
bank = 0
addr = readtableword(bank, rom.SUBLEVEL_TILES_PATCH_TABLE, level, sublevel-1)
jsl.tilePatches = []
count = rom.readbyte(bank, addr)
addr += 1
for i in range(count):
jpatch = JSONDict()
idx = rom.readbyte(bank, addr + i)
patchaddr = idx + rom.TILES_PATCH_LIST
jpatch.count = rom.readbyte(bank, patchaddr)
jpatch.bank = rom.readbyte(bank, patchaddr+1)
jpatch.source = rom.readword(bank, patchaddr+2)
jpatch.dst = rom.readword(bank, patchaddr+4)
jsl.tilePatches.append(jpatch)
# each sublevel edits/patches a portion of the sprite lookup table, which is at $DF00-$DFFF in WRAM.
def loadSublevelSpritesPatch(j, level, sublevel):
if rom.ROMTYPE not in ["us", "jp"]:
return
jl = j.levels[level]
jsl = jl.sublevels[sublevel]
bank = rom.BANK3
patchstructaddr = readtableword(bank, rom.SPRITE_PATCH_TABLE, level) + 4*sublevel
count = rom.readbyte(bank, patchstructaddr)
start = rom.readbyte(bank, patchstructaddr+1)
source = rom.readword(bank, patchstructaddr+2)
if count != 0:
jsl.spritePatch = JSONDict({
"startidx": start,
"sprites": []
})
for i in range(count):
ptr = rom.readword(bank, source + 2*i)
sprite, end = readSprite(bank, ptr)
jsl.spritePatch.sprites.append(sprite)
def readSpritePatchRoutine(bank, addr):
# ld hl, xxxx
source = rom.readword(bank, addr+1)
addr += 3
# ld a, xx
start = rom.readbyte(bank, addr+1)
addr += 2
# ld b, xx
count = rom.readbyte(bank, addr+1)
assert(count > 0)
jpatch = JSONDict({
"startidx": start,
"sprites": []
})
for i in range(count):
ptr = rom.readword(bank, source + 2*i)
sprite, end = readSprite(bank, ptr)
jpatch.sprites.append(sprite)
# (jr $7048)
return jpatch
def loadGlobalSpritePatches(j):
bank = rom.BANK3
addr = rom.LOAD_SPRITES_ROUTINES
if rom.ROMTYPE not in ["us", "jp"]:
return
j.globalSpritePatches = JSONDict({
"init": readSpritePatchRoutine(bank, addr),
"title": readSpritePatchRoutine(bank, addr+9),
"unk2": readSpritePatchRoutine(bank, addr+18),
"unk3": readSpritePatchRoutine(bank, addr+27),
})
def loadSublevelInitRoutine(j, level, sublevel):
jl = j.levels[level]
jsl = jl.sublevels[sublevel]
bank = rom.BANK3
addr = readtableword(bank, rom.VRAM_SPECIAL_ROUTINES, level, sublevel)
jsl.initRoutines = loadInitRoutine(j, bank, addr, level)
def loadInitRoutine(j, bank, addr, level=None, **kwargs):
r = []
maxaddr = kwargs.get("maxaddr", None)
while True:
if maxaddr is not None and addr >= maxaddr:
return r
assert len(r) < 10 # seems reasonable
if rom.readbyte(bank, addr) == 0xC9: # ret
return r
elif rom.readword(bank, addr + 1) == rom.UNK_254:
r.append(JSONDict({"type": "UNK254"}))
addr += 8
elif rom.readword(bank, addr + 1) == rom.UNK_7001:
# length of this one depends on rom type
# too complicated, but it's only ever alone like so,
# so we just call it here.
r.append(JSONDict({"type": "UNK7001"}))
return r
elif rom.readbyte(bank, addr+1) == 0x20:
r.append(JSONDict({"type": "CNTEFFECT", "effect": 0x0f, "scanline": 0x10}))
addr += 11
if rom.readbyte(bank, addr-3) == 0xC3: # jp
break
elif rom.readbyte(bank, addr+1) == 0x1B:
r.append(JSONDict({"type": "UNKD802"}))
addr += 8
elif rom.readbyte(bank, addr+6) == 0xFA:
de = [0, 0]
hl = [0, 0]
de[0] = rom.readword(bank, addr+1)
hl[0] = rom.readword(bank, addr+1+3)
de[1] = rom.readword(bank, addr+13+1)
hl[1] = rom.readword(bank, addr+13+1+3)
cplvl = rom.readbyte(bank, addr+10)
bc = rom.readword(bank, addr+19+1)
addr += 25
if level is not None:
assert hl == rom.readtableword(rom.BANK2, rom.LEVTAB_TILES4x4_BANK2, level)
else:
for i in range(len(rom.LEVELS)):
if rom.readtableword(rom.BANK2, rom.LEVTAB_TILES4x4_BANK2, i) == hl[0] and i > 0:
level = i
break
assert level is not None
assert hl[1] == rom.readtableword(rom.BANK2, rom.LEVTAB_TILES4x4_BANK2, cplvl)
levels = [level, cplvl]
screendata = [None, None]
linkscreen = [None, None]
levelRoutineSpec = []
for i in range(2):
screendata[i] = [rom.readbyte(rom.BANK6, de[i]+j) for j in range(20)]
for _level, jl in enumerate(j.levels):
if _level != 0:
for sublevel, jsl in enumerate(jl.sublevels):
for screen, js in enumerate(jsl.screens):
if js.data == screendata:
linkscreen[i] = (_level, sublevel, screen)
screendata[i] = None
levelRoutineSpec.append(JSONDict({
"srcAddr": de[i],
"level": levels[i]
}))
if screendata[i] is not None:
levelRoutineSpec[-1].data = screendata[i]
if linkscreen[i] is not None:
levelRoutineSpec[-1].data = linkscreen[i]
r.append(JSONDict({"type": "LVLSCREEN", "dstAddr": bc, "levels": levelRoutineSpec}))
if rom.readbyte(bank, addr-3) == 0xC3: # jp
break
elif rom.readbyte(bank, addr) == 0x11:
de = rom.readword(bank, addr+1)
hl = rom.readword(bank, addr+1+3)
bc = rom.readword(bank, addr+1+6)
assert type(bc) == int
if level is not None:
assert hl == rom.readtableword(rom.BANK2, rom.LEVTAB_TILES4x4_BANK2, level)
else:
for i in range(len(rom.LEVELS)):
if rom.readtableword(rom.BANK2, rom.LEVTAB_TILES4x4_BANK2, i) == hl and i > 0:
level = i
break
assert level is not None
screendata = [rom.readbyte(rom.BANK6, de+i) for i in range(20)]
r.append(JSONDict({"type": "SCREEN", "dstAddr": bc, "data": screendata, "srcAddr": de, "level": level}))
# instead of data, link to an existing screen if possible
linkscreen = None
for _level, jl in enumerate(j.levels):
if _level != 0:
for sublevel, jsl in enumerate(jl.sublevels):
for screen, js in enumerate(jsl.screens):
if js.data == screendata:
linkscreen = (_level, sublevel, screen)
if linkscreen is not None:
r[-1].linkscreen = linkscreen
del r[-1]["data"]
addr += 3*4
# exception -- these seem to be spurious! Pop these.
if (level, sublevel) in [(1, 0)]:
r = r[:-1]
if rom.readbyte(bank, addr-3) == 0xC3: # jp
break
else:
assert False, f"unrecognized routine at {bank:X}:{addr:04X}"
return r
def loadSublevelScreens(j, level, sublevel):
tiles_start_addr = readtableword(rom.BANK2, rom.LEVTAB_TILES_BANK2, level, sublevel)
tiles_end_addr = rom.get_entry_end(rom.BANK2, rom.LEVTAB_TILES_BANK2, level, sublevel)
assert (tiles_end_addr - tiles_start_addr) % 20 == 0
screenc = (tiles_end_addr - tiles_start_addr) // 20
jl = j.levels[level]
jsl = jl.sublevels[sublevel]
jsl.screens = []
for i in range(screenc):
js = JSONDict()
js.data = []
for y in range(4):
js.data.append([])
for x in range(5):
js.data[y].append(readbyte(rom.BANK6, tiles_start_addr + i * 20 + y * 5 + x))
jsl.screens.append(js)
CATS = ["misc", "enemies", "items"]
entmargins = dict()
def getStandardMarginForEntity(id, vertical=0):
vertical = {0:0, 1:1, False:0, True:1}[vertical]
if (id, vertical) in entmargins:
lst = entmargins[(id, vertical)]
return max(set(lst), key=lst.count)
else:
return 0x88 if vertical else 0xA8
def loadSublevelScreenEntities(j, level, sublevel):
jl = j.levels[level]
jsl = jl.sublevels[sublevel]
startx, starty, vertical, layout = rom.produce_sublevel_screen_arrangement(level, sublevel)
entstable = rom.get_entities_in_screens(level, sublevel)
for x in range(16):
for y in range(16):
if layout[x][y] == 0:
continue
screen = layout[x][y] & 0xF
if screen >= len(jsl.screens):
continue
js = jsl.screens[screen]
for cat, ents in zip(CATS, entstable[x][y]):
jents = []
for ent in ents:
je = JSONDict()
je.x = ent["x"]
je.y = ent["y"]
je.type = ent["type"]
je.slot = ent["slot"]
jents.append(je)
margin = ent.get("margin-x", ent.get("margin-y", ent.get("margin")))
if margin is not None:
entmargins[(vertical, je.type)] = entmargins.get((vertical, je.type), []) + [margin]
je.margin = margin or (0x80 if vertical == 1 else 0xA0)
if cat in js and jents != js[cat]:
# Mystery: why does 3-4 split off..?
#print(f"screen {screen:X} appears twice in level {level}-{sublevel+1} with different entities (second appearance at {x:X},{y:X})")
# split out to new screen
js = copy.deepcopy(js)
screen = len(jsl.screens)
jsl.screens.append(js)
assert screen < 0xF, "too many screens after splitting screens due to differing entities"
jsl.layout[x][y] &= ~0x0F
jsl.layout[x][y] |= screen
js[cat] = jents
else:
js[cat] = jents
# set defaults
for js in jsl.screens:
for cat in CATS:
if cat not in js:
js[cat] = []
# screens can only appear with an edge type of 0xB/0xA/0x9 at most once
def getScreenEdgeType(j, level, sublevel, screen):
jsl = j.levels[level].sublevels[sublevel]
rv = 0x0
for x in range(16):
for y in range(16):
c = jsl.layout[x][y]
if c & 0x0F == screen:
rv = c >> 4
if rv > 8:
return rv
return rv
def loadSublevelScreenTable(j, level, sublevel):
jl = j.levels[level]
jsl = jl.sublevels[sublevel]
jsl.startx, jsl.starty, jsl.vertical, jsl.layout = rom.produce_sublevel_screen_arrangement(level, sublevel)
# remove values outside of this level's screen array
for x in range(16):
for y in range(16):
if jsl.layout[x][y] & 0xF >= len(jsl.screens):
jsl.layout[x][y] = 0
def getLevelChunksAndGlitchChunks(j, level):
if j.levels[level].get("chunks", None) is not None:
chunks = j.levels[level].chunks
if len(chunks) < 0x100 and rom.LEVELS[level+1] != "Drac3":
return chunks + getLevelChunksAndGlitchChunks(j, level+1)
return chunks + []
else:
return getLevelChunksAndGlitchChunks(j, j.levels[level].chunklink)
def getLevelChunks(j, level):
if j.levels[level].get("chunks", None) is not None:
return j.levels[level].chunks
else:
return getLevelChunks(j, j.levels[level].chunklink)
def loadLevelChunks(j, level):
jl = j.levels[level]
if rom.LEVELS[level] == "Drac3":
jl.chunklink = level-1
else:
jl.chunks = [[0] * 16]
chunk_start = readtableword(rom.BANK2, rom.LEVTAB_TILES4x4_BANK2, level)
chunk_end = rom.get_entry_end(rom.BANK2, rom.LEVTAB_TILES4x4_BANK2, level)
assert (chunk_end - chunk_start) % 0x10 == 0
for i in range((chunk_end - chunk_start) // 0x10):
chunk = [readbyte(rom.BANK2, chunk_start + i*0x10 + j) for j in range(0x10)]
jl.chunks.append(chunk)
def getTilesetAtAddr(bank, addr):
l = []
while readbyte(bank, addr) != 0:
jt = JSONDict()
jt.destaddr = ((rom.readbyte(bank, addr) << 12) + (rom.readbyte(bank, addr + 1) << 4)) & 0xffff
addr += 2
jt.destlen = rom.readbyte(bank, addr) << 4
addr += 1
jt.srcbank = rom.readbyte(bank, addr)
addr += 1
jt.srcaddr = rom.readword(bank, addr)
addr += 2
l.append(jt)
return l
def loadLevelTileset(j, level):
jl = j.levels[level]
bank = rom.LEVEL_TILESET_TABLE_BANK
addr = readtableword(bank, rom.LEVEL_TILESET_TABLE, level)
jl.tileset = getTilesetAtAddr(bank, addr)
# returns list of (level, sublevel, screen, (x, y))
# if infodepth < 4, crops the above tuples to infodepth entries.
def getChunkUsage(j, clevel, chidx, infodepth=4):
uses = []
for level, jl in enumerate(j.levels):
if jl is not None and level > 0:
if level <= clevel:
compoffset = sum([len(getLevelChunks(j, lev))-1 for lev in range(level, clevel)])
if compoffset + chidx >= 0x100:
continue
else:
break
for sublevel, jsl in enumerate(jl.get("sublevels", [])):
for screen, js in enumerate(jsl.screens):
for x in range(5):
for y in range(4):
if js.data[y][x] == chidx + compoffset:
uses.append(tuple([level, sublevel, screen, (y, x)][:infodepth]))
return uses
def addEmptyScreens(j):
for jl in j.levels:
if jl is not None and "sublevels" in jl:
for jsl in jl.sublevels:
for i in range(0x10 - len(jsl.screens)):
js = JSONDict()
js.data = [[0 for a in range(5)] for b in range(4)]
for cat in CATS:
js[cat] = []
jsl.screens.append(js)
# returns subset of {-1, 1}
def getScreenExitDoor(j, level, sublevel, screen):
jl = j.levels[level]
jsl = jl.sublevels[sublevel]
js = jsl.screens[screen]
chunks = getLevelChunksAndGlitchChunks(j, level)
exits = set()
DOORTILES = [0x17,0x18,0x19,0x1A]
for dir, x in [(-1, 0), (1, 4)]:
for y in range(4):
chidx = js.data[y][x]
if chidx < len(chunks):
chunk = chunks[chidx]
for i in range(4):
for j in range(4):
if chunk[i+j*4] in DOORTILES:
exits.add(dir)
break # ideally, break to outermost loop.
return exits
# gets list of 'exits' from this screen (via ropes)
# returns subset of {(-1, 0), (1, 0), (0, -1), (0, 1)}
def getScreenPortals(j, level, sublevel, screen):
jl = j.levels[level]
jsl = jl.sublevels[sublevel]
js = jsl.screens[screen]
chunks = getLevelChunksAndGlitchChunks(j, level)
ROPES = [0x1B]
# FIXME: find the way that secret ropes occur... probably by entities?
portals = set()
for x in range(5):
for ydir, y in [(-1, 0), (1, 3)]:
chidx = js.data[y][x]
if chidx < len(chunks):
chunk = chunks[chidx]
for i in range(4):
j = y
if chunk[i+j*4] in ROPES:
portals.add((0, ydir))
break # ideally, break to outermost loop.
return portals
def screenUsed(j, level, sublevel, screen):
jsl = j.levels[level].sublevels[sublevel]
for x in range(16):
for y in range(16):
if jsl.layout[x][y] & 0xF == screen:
return True
return False
# is there a way to enter this screen through a portal or door?
def getScreenEnterable(j, level, sublevel, x, y):
jl = j.levels[level]
jsl = jl.sublevels[sublevel]
if (x, y) == (jsl.startx, jsl.starty):
return True
if jsl.layout[x][y] == 0:
return False
if jsl.layout[x][y] >> 4 == 0xB:
# we just assume that all 1x1 enclosed screens are enterable
# surely the user would remove it if it weren't..?
# This saves us from having to check for hidden ropes, as in the base game they all connect to 1x1 rooms.
return True
for xoff, yoff in [(0, -1), (0, 1), (1, 0), (-1, 0)]:
if x + xoff in range(16):
neighbour = jsl.layout[x+xoff][(y+yoff + 16) % 16]
if neighbour > 0:
t = neighbour >> 4
# don't count continuous scrolling
if jsl.vertical == 1 and yoff > 0 and t in [0x8, 0x9]:
continue
if jsl.vertical == 1 and yoff < 0 and t in [0x8, 0xA]:
continue
if jsl.vertical == 0 and xoff > 0 and t in [0x8, 0x9]:
continue
if jsl.vertical == 0 and xoff < 0 and t in [0x8, 0xA]:
continue
if (-xoff, -yoff) in getScreenPortals(j, level, sublevel, neighbour & 0x0F):
return True
return False
def getEnterabilityLayout(j, level, sublevel):
return [[getScreenEnterable(j, level, sublevel, x, y) for y in range(16)] for x in range(16)]
def loadSublevelTimer(j, level, sublevel):
jl = j.levels[level]
jsl = jl.sublevels[sublevel]
levelTimerPointer = rom.readword(rom.BANK3, rom.LEVEL_TIMER_TABLE + level*2) # fetch timer table of the level
levelTimerPointerData = rom.readbyte(rom.BANK3, levelTimerPointer + sublevel) # fetch sublevel timer value
jsl.timer = levelTimerPointerData
# ------------------------------------------------------
class SaveContext:
def __init__(self, gb, j, **kwargs):
self.gb = list(copy.copy(gb))
self.j = j
self.playtestStart = kwargs.get("playtestStart", None)
self.errors = []
self.regions = JSONDict({
"ScreenTilesTable": {
"shortname": "ST",
"max": 0x4316 - 0x42C4,
"addr": rom.LEVTAB_TILES_BANK2,
"bank": rom.BANK2,
},
# could combine this with the above, which ends at the same spot
# we just need to adjust calls to the routine at $4316
"SublevelVertical": {
"shortname": "SV",
"max": 0x4339 - 0x4316,
"addr": rom.LEVEL_SCROLLDIR_TABLE-10, # routine before this table is 10 bytes, and we rewrite it.
"bank": rom.BANK2,
},
"ChunkTable": {
"shortname": "CT",
"max": 0x10,
"addr": rom.LEVTAB_TILES4x4_BANK2,
"bank": rom.BANK2,
},
"ChunkValues": {
"shortname": "CV",
"max": 0x6500 - 0x44C0 + 0x820,
"addr": rom.TILES4x4_BEGIN,
"bank": rom.BANK2,
"units": ("chunk",),
"unitdiv": 0x10,
},
# could combine the next four into one if we edit the accesses to their base addresses.
"Entmisc": {
"shortname": "EM",
"max": rom.LEVTAB_B - rom.LEVTAB_A,
"addr": rom.LEVTAB_A,
"bank": rom.BANK3,
},
"Entenemies": {
"shortname": "EE",
"max": rom.LEVTAB_C - rom.LEVTAB_B,
"addr": rom.LEVTAB_B,
"bank": rom.BANK3,
},
"Entitems": {
"shortname": "EI",
"max": rom.SCREEN_ENT_TABLE - rom.LEVTAB_C,
"addr": rom.LEVTAB_C,
"bank": rom.BANK3,
},
"EntLookup": {
"shortname": "EL",
"max": 0x6991 - 0x62C1,
"addr": rom.SCREEN_ENT_TABLE,
"bank": rom.BANK3,
},
"SublevelInitRoutines": {
"shortname": "SI",
"max": rom.VRAM_SPECIAL_ROUTINES_END - rom.VRAM_SPECIAL_ROUTINES + 7,
"addr": rom.VRAM_SPECIAL_ROUTINES - 7,
"bank": rom.BANK3,
},
"ScreenTiles": {
"shortname": "ZT",
"max": 0x73F8 - 0x62B4 + 20 * 5,
"addr": j.screenTilesAddr,
"bank": rom.BANK6,
"units": ("screen",),
"unitdiv": 20,
},
"Layouts": {
"shortname": "L",
"max": 0x52C1 - 0x5020 + 12,
"addr": rom.LEVEL_SCREEN_TABLE,
"bank": rom.BANK6,
},
# this routine loads a screen (on cloud castle), so we need to modify it
"EntC4Routine": {
"shortname": "CF",
"max": rom.ENT4C_FLICKER_ROUTINE_END - rom.ENT4C_FLICKER_ROUTINE,
"addr": rom.ENT4C_FLICKER_ROUTINE,
"bank": rom.ENT4C_FLICKER_ROUTINE_BANK,
},
# as above, but rock castle
"Ent78Routine": {
"shortname": "RF",
"max": rom.ENT78_FLICKER_ROUTINE_END - rom.ENT78_FLICKER_ROUTINE,
"addr": rom.ENT78_FLICKER_ROUTINE,
"bank": rom.ENT78_FLICKER_ROUTINE_BANK,
},
"CrusherRoutine": {
"shortname": "CR",
"max": rom.CRUSHER_ROUTINE_END - rom.CRUSHER_ROUTINE,
"addr": rom.CRUSHER_ROUTINE,
"bank": rom.CRUSHER_ROUTINE_BANK,
},
"SublevelTime": {
"shortname": "ST",
"max": 0x31,
"addr": rom.LEVEL_TIMER_TABLE,
"bank": rom.BANK3
}
})
for key in self.regions.keys():
self.regions[key] = JSONDict(self.regions[key])
self.regions[key].key = key
self.regions[key].name = key
self.regions[key].used = 0
self.regions[key].subranges = JSONDict()
# maps (level, sublevel) -> list[(x, y, l)]
self.uniqueScreens = dict()
# maps (level, sublevel, x, y) -> index in ctx.uniqueScreens[sublevel, level]
self.screenRemap = dict()
# maps (level, sublevel) -> int (index into self.uniqueScreens[(level, sublevel)])
self.numPriorityUniqueScreens = dict()
# maps (level, sublevel, cat, uscreen) ->
self.enterableScreenData = dict()
self.sublevelInitSubroutines = dict()
# returns screen, js
def getUniqueScreenOriginalScreen(self, level, sublevel, uscreen):
key = (level, sublevel)
assert key in self.uniqueScreens
s = self.uniqueScreens[key][uscreen][2] & 0xF
return s, self.j.levels[level].sublevels[sublevel].screens[s]
def romaddr(self, bank, addr):
if (addr < 0x4000 and bank != 0) or (addr >= 0x4000 and bank == 0) or addr >= 0x8000:
raise Exception(f"Address {addr:04X} out of bounds for bank {bank:X}")
return bank * 0x4000 + addr % 0x4000
def writeBytes(self, bank, addr, bl):
for b in bl:
self.writeByte(bank, addr, b)
addr += 1
def writeByte(self, bank, addr, v):
if type(v) != int or v < 0 or v >= 0x100:
raise Exception(f"Error with value {v}")
self.gb[self.romaddr(bank, addr)] = v
def writeWord(self, bank, addr, v, littleEndian=True):
if littleEndian:
self.writeByte(bank, addr, v & 0xff)
self.writeByte(bank, addr+1, v >> 8)
else:
self.writeByte(bank, addr, v >> 8)
self.writeByte(bank, addr+1, v & 0xff)
def readByte(self, bank, addr):
return self.gb[self.romaddr(bank, addr)]
def readWord(self, bank, addr, littleEndian=True):
if littleEndian:
return self.readByte(bank, addr) | (self.readByte(bank, addr+1) << 8)
else:
return self.readByte(bank, addr+1) | (self.readByte(bank, addr) << 8)
# returns:
# - a list of (regionname, size, maxsize)
# - a list of errors, or empty if successful
def saveRom(gb, j, path=None, **kwargs):
assert(len(gb) > 0 and len(gb) % 0x4000 == 0)
ctx = SaveContext(gb, j, **kwargs)
_saveRom(ctx)
regions, errors, gb = ctx.result
if path is not None and gb is not None:
try:
with open(path, "wb") as f:
f.write(gb)
except IOError as e:
errors += [f"I/O Error writing to file {path}: {e}"]
except OSError as e:
errors += [f"OS Error writing to file {path}: {e}"]
return regions, errors
def _saveRom(ctx: SaveContext):
try:
writeRom(ctx)
for key in ctx.regions.keys():
c = ctx.regions[key].used
m = ctx.regions[key].max
if c > m:
ctx.errors.append(f"Region \"{key}\" exceeded ({c:04X} > {m:04X} bytes)")
ctx.result = [ctx.regions[key] for key in ctx.regions.keys()], ctx.errors, bytes(ctx.gb)
except Exception as e:
errors = [f"Fatal: {e}\n{traceback.format_exc()}"]
for key, region in ctx.regions.items():
region.used = None
region.subranges = {}
regions = [ctx.regions[key] for key in ctx.regions.keys()]
ctx.result = regions, errors, None
def writeRom(ctx: SaveContext):
# TODO: tileset_common (* no gui support)
# TODO: level.tileset (* no gui support)
constructScreenRemapping(ctx)
writeScreenTiles(ctx)
writeScreenLayout(ctx)
writeSublevelTimer(ctx)
writeSublevelVertical(ctx)
writeEntities(ctx)
writeChunks(ctx)
if ctx.playtestStart is not None:
writePlaytestStart(ctx, *ctx.playtestStart)
# this one reads some of the screenTiles from before
writeSublevelInitRoutines(ctx)
writeEntLoadRoutine(ctx, ctx.regions.EntC4Routine, ctx.j.entC4Routine, label="EntC4")
writeEntLoadRoutine(ctx, ctx.regions.Ent78Routine, ctx.j.ent78Routine, False, label="Ent78")
writeEntLoadRoutine(ctx, ctx.regions.CrusherRoutine, ctx.j.crusherRoutine, False, label="Crusher")
# do this one last, it's an opportunist
writeLoadEnclosedScreenEntityBugfixPatch(ctx)
writeLoadLayoutPatch(ctx)
# basically just for cloud castle flicker preview at door to final sublevel
def requiresVerticalPreview(jsl):
for routine in jsl.initRoutines:
if routine.type == "SCREEN" and routine.dstAddr == 0x9A00:
return True
return False
def constructScreenRemapping(ctx: SaveContext):
for i, jl in enumerate(ctx.j.levels):
if i > 0:
for sublevel, jsl in enumerate(jl.sublevels):
constructScreenRemappingForSublevel(ctx, i, sublevel)
def constructScreenRemappingForSublevel(ctx: SaveContext, level: int, sublevel: int):
jl = ctx.j.levels[level]
jsl = jl.sublevels[sublevel]
enterable = getEnterabilityLayout(ctx.j, level, sublevel)
# screenMap: coords -> out index
# - skip unused screens
# - ensure enterable screens come first
# - deduplicate screens if possible
screenCoords = []
for x in range(16):
for y in range(16):
l = jsl.layout[x][y]
if l > 0:
screenCoords.append((x, y))
# screens are combinable if:
# - they have the same tiles, and
# - either of them is not enterable, or
# - both are enterable, but both also appear in identical continuous rooms at the same x value (y if vertical)
# - the last condition is a lot of work to check, so instead we simplify it to
# "both are enclosed (0xB*)"
def combinable(x1, y1, x2, y2):
l1 = jsl.layout[x1][y1]
l2 = jsl.layout[x2][y2]
e1 = enterable[x1][y1]
e2 = enterable[x2][y2]
t1 = l1 >> 4
t2 = l2 >> 4
s1 = l1 & 0x0F
s2 = l2 & 0x0F
js1 = jsl.screens[s1]
js2 = jsl.screens[s2]
if js1.data == js2.data: # tiles the same
if not e1 or not e2:
return True
else:
assert e1 and e2
return t1 == 0xB and t2 == 0xB
return False
uniqueScreens = []
uniqueScreensPriority = []
def getPriority(x, y):
priority = 0 if enterable[x][y] else 2
if (x, y) == (jsl.startx, jsl.starty):
priority = -2
if sublevel > 0:
# TODO: we can do slightly better by figuring out which of (x-1,y) and (x+1,y) is relevant,
# given direction previous sublevel exits.
if (jsl.startx, jsl.starty) in [(x-1, y), (x+1, y)]:
priority -= 1
elif (jsl.startx, jsl.starty) in [(x, y-1), (x+1, y)] and requiresVerticalPreview(jsl):
priority -= 1
return priority
for i, (x, y) in enumerate(screenCoords):
l = jsl.layout[x][y]
if not screenUsed(ctx.j, level ,sublevel, l & 0x0F):
continue
else:
for j, (x2, y2) in enumerate(screenCoords[:i]):
if combinable(x, y, x2, y2):
uscreen = ctx.screenRemap[(level, sublevel, x2, y2)]
ctx.screenRemap[(level, sublevel, x, y)] = uscreen
uniqueScreensPriority[uscreen] = min(getPriority(x, y), uniqueScreensPriority[uscreen])
break
else:
ctx.screenRemap[(level, sublevel, x, y)] = len(uniqueScreens)
uniqueScreensPriority.append(getPriority(x, y))
uniqueScreens.append((x, y, l))
if len(uniqueScreens) >= 0x10:
levelname = rom.LEVELS[level]
raise Exception(f"Level {levelname} Sublevel {sublevel} requires {len(uniqueScreens)} screens to fully represent uniqueness of screens in layout, but 16 is the max.")
numPrioritizedScreens = sum([p <= 0 for p in uniqueScreensPriority])
numNonPrioritizedPreviewScreens = sum([p == 1 for p in uniqueScreensPriority])
if numNonPrioritizedPreviewScreens > 0 and sublevel > 0:
#print(level, sublevel+1, uniqueScreensPriority)
if len(jl.sublevels[sublevel-1]) + numPrioritizedScreens + numNonPrioritizedPreviewScreens > 0x10:
# move preview screens so that they are at the start
# unusual behaviour, so let's print it out in case it causes problems.
print(f"{rom.LEVELS[level]}-{sublevel+1} - Remapping some screen IDs to allow previous sublevel access to the start-adjacent room(s)...")
print("<- ", level, sublevel+1, uniqueScreensPriority)
uniqueScreensPriority = [(u if u != 1 else -1) for u in uniqueScreensPriority]
print(" -> ", level, sublevel+1, uniqueScreensPriority)
ctx.numPriorityUniqueScreens[(level, sublevel)] = sum([p <= 0 for p in uniqueScreensPriority])
# remap unique screens to ensure the enterable ones come first, and starting room is the very first.
remapEnterable = sorted(list(range(len(uniqueScreens))), key=lambda i: uniqueScreensPriority[i])
remapEnterableIndices = [remapEnterable.index(i) for i in range(len(uniqueScreens))]
#if level == 4 and sublevel == 1:
# print(uniqueScreens, "|", remapEnterable)
# for (_level, _sublevel, x, y), v in ctx.screenRemap.items():
# if _level == level and _sublevel == sublevel:
# print(x, y, v)
# apply remapping
for x, y in screenCoords:
ctx.screenRemap[(level, sublevel, x, y)] = remapEnterableIndices[ctx.screenRemap[(level, sublevel, x, y)]]
ctx.uniqueScreens[(level, sublevel)] = [uniqueScreens[remapEnterable[i]] for i in range(len(uniqueScreens))]
#if level == 7:
# printRemappedScreenLayout(ctx, level, sublevel)
def printRemappedScreenLayout(ctx, level, sublevel):
jsl = ctx.j.levels[level].sublevels[sublevel]
uniqueScreens = ctx.uniqueScreens[(level, sublevel)]
x1, x2, y1, y2 = rom.get_screensbuff_boundingbox(jsl.layout)
print(f"{rom.LEVELS[level]}-{sublevel+1}:")
for y in range(y1, y2):
s = ";"
for x in range(x1, x2):
if jsl.layout[x][y] > 0:
i = ctx.screenRemap[(level, sublevel, x, y)]
assert i < len(uniqueScreens)
l = (jsl.layout[x][y] & 0xF0) | i
s += f" {l:02X}"
else:
s += " "
print(s)
def writeScreenTiles(ctx: SaveContext):
tbank = ctx.regions.ScreenTilesTable.bank
taddr = ctx.regions.ScreenTilesTable.addr
bank = ctx.regions.ScreenTiles.bank
addr = ctx.regions.ScreenTiles.addr
subranges = ctx.regions.ScreenTiles.subranges
tsaddr = taddr + len(ctx.j.levels)*2
for level, jl in enumerate(ctx.j.levels):
if level == 0:
taddr += 2
else: