-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRM2C.py
2328 lines (2237 loc) · 69 KB
/
RM2C.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 sys, os, struct, shutil, math, re, gc, time, cProfile, pstats
import GeoWrite as GW
import F3D
import ColParse
from pathlib import Path
from capstone import *
from bitstring import *
from RM2CData import *
import BinPNG
import groups as GD
import disassemble_sound as d_s
import multiprocessing as mp
import BhvParse as BP
import Log
#these all exist as data modules for comparisons to see if content is new or not
import ActorCHKSM
import BehComp
import ColComp
#So that each Script class doesn't open up a half MB file.
mapF = open('sm64.us.map','r')
map = mapF.readlines()
class Script():
def __init__(self,level):
global map
self.map=map
self.banks=[None for a in range(32)]
self.asm=[[0x80400000,0x1200000,0x1220000],[0x80246000,0x1000,0x21f4c0]]
self.models=[None for a in range(256)]
self.Currlevel=level
self.levels={}
self.levels[self.Currlevel]=[None for a in range(8)]
self.texScrolls=False
self.verts = []
#stack is simply a stack of ptrs
#base is the prev pos
#top is the current pos
self.Base=None
self.Stack=[]
self.Top=-1
self.CurrArea=None
self.header=[]
self.objects = []
self.ScrollArray=[]
def B2P(self,B):
Bank=B>>24
offset=B&0xFFFFFF
if Bank==0:
if offset>0x400000 and offset<0x420000:
return 0x1200000+(B&0xFFFFF)
else:
#check for MOP models
if offset>0x5F0000 and offset<0x620000:
return offset+0x1E0000
#Its some random garbage nice
return offset
seg = self.banks[Bank]
if not seg:
print(hex(B),hex(Bank),self.banks[Bank-2:Bank+3])
raise ''
return seg[0]+offset
def L4B(self,T):
x=0
for i,b in enumerate(T):
x+=b<<(8*(3-i))
return x
def GetArea(self):
try:
return self.levels[self.Currlevel][self.CurrArea]
except:
return None
def GetNumAreas(self,level):
count=[]
for i,area in enumerate(self.levels[level]):
if area:
count.append(i)
return count
def GetLabel(self,addr):
#behavior is in bank 0 and won't be in map ever
# if addr[0:2]=='00':
# print(addr + ' is in bank 0 cannot be found')
# return '0x'+addr
for l in self.map:
if addr in l:
q = l.rfind(" ")
return l[q:-1]
return "0x"+addr
def GetAddr(self,label):
for l in self.map:
if label in l:
return "0x"+l.split("0x")[1][8:16]
return None
def RME(self,num,rom):
if self.editor:
return
start=self.B2P(0x19005f00)
start=TcH(rom[start+num*16:start+num*16+4])
end=TcH(rom[start+4+num*16:start+num*16+8])
self.banks[0x0e]=[start,end]
def MakeDec(self,name):
self.header.append(name)
def Seg2(self,rom):
UPH = (lambda x,y: struct.unpack(">H",x[y:y+2])[0])
start=UPH(rom,0x3ac2)<<16
start+=UPH(rom,0x3acE)
end=UPH(rom,0x3ac6)<<16
end+=UPH(rom,0x3acA)
#mio0 for seg2 just happens to expand start by 0x3156 idk how it really works
self.banks[2]=[start+0x3156,end+0x3156]
class Area():
def __init__(self):
pass
#tuple convert to hex
def TcH(bytes):
a = struct.pack(">%dB"%len(bytes),*bytes)
if len(bytes)==4:
return struct.unpack(">L",a)[0]
if len(bytes)==2:
return struct.unpack(">H",a)[0]
if len(bytes)==1:
return struct.unpack(">B",a)[0]
def U2S(half):
return struct.unpack(">h",struct.pack(">H",half))[0]
def LoadRawJumpPush(rom,cmd,start,script):
arg=cmd[2]
bank=arg[0:2]
begin = arg[2:6]
end = arg[6:10]
jump = arg[10:14]
script.banks[TcH(bank)]=[TcH(begin),TcH(end)]
script.Stack.append(start)
script.Top+=1
script.Stack.append(script.Base)
script.Top+=1
script.Base=script.Top
return script.B2P(TcH(jump))
def LoadRawJump(rom,cmd,start,script):
arg=cmd[2]
bank=arg[0:2]
begin = arg[2:6]
end = arg[6:10]
jump = arg[10:14]
script.banks[TcH(bank)]=[TcH(begin),TcH(end)]
script.Top=script.Base
return script.B2P(TcH(jump))
def Exit(rom,cmd,start,script):
script.Top=script.Base
script.Base=script.Stack[script.Top]
script.Stack.pop()
script.Top-=1
start=script.Stack[script.Top]
script.Stack.pop()
script.Top-=1
return start
def JumpRaw(rom,cmd,start,script):
arg=cmd[2]
return script.B2P(TcH(arg[2:6]))
def JumpPush(rom,cmd,start,script):
script.Top+=1
script.Stack.append(start)
arg=cmd[2]
return script.B2P(TcH(arg[2:6]))
def Pop(rom,cmd,start,script):
start=script.Stack[script.Top]
script.Top-=1
script.Stack.pop()
return start
def CondPop(rom,cmd,start,script):
#this is where the script loops
#Ill assume no custom shit is done
#meaning this will always signal end of level
return None
def CondJump(rom,cmd,start,script):
arg=cmd[2]
level=arg[2:6]
jump=arg[6:10]
if script.Currlevel==TcH(level):
return script.B2P(TcH(jump))
else:
return start
def SetLevel(rom,cmd,start,script):
#gonna ignore this and take user input instead
#script.Currlevel=TcH(cmd[2])
# if not script.levels.get("Currlevel"):
# script.levels[script.Currlevel]=[None for a in range(8)]
return start
def LoadAsm(rom,cmd,start,script):
arg=cmd[2]
ram=arg[2:6]
begin=arg[6:10]
end=arg[10:14]
Q=[TcH(ram),TcH(begin),TcH(end)]
if Q not in script.asm:
script.asm.append(Q)
return start
def LoadData(rom,cmd,start,script):
arg=cmd[2]
bank=arg[1:2]
begin = arg[2:6]
end = arg[6:10]
script.banks[TcH(bank)]=[TcH(begin),TcH(end)]
return start
def LoadMio0(rom,cmd,start,script):
pass
def LoadMio0Tex(rom,cmd,start,script):
return LoadData(rom,cmd,start,script)
def StartArea(rom,cmd,start,script):
#ignore stuff in bank 0x14 because thats star select/file select and messes up export
arg=cmd[2]
if TcH(arg[2:3])==0x14:
return start
area=arg[0]+script.Aoffset
script.CurrArea=area
q=Area()
q.geo=script.B2P(TcH(arg[2:6]))
q.objects=[]
q.warps=[]
q.rom=rom
script.levels[script.Currlevel][script.CurrArea]=q
return start
def EndArea(rom,cmd,start,script):
script.CurrArea=None
return start
def LoadPolyF3d(rom,cmd,start,script):
arg=cmd[2]
id=arg[1:2]
layer=TcH(arg[0:1])>>4
f3d=TcH(arg[2:6])
script.models[TcH(id)]=(f3d,'f3d',layer,script.B2P(f3d),script)
return start
def LoadPolyGeo(rom,cmd,start,script):
arg=cmd[2]
id=arg[1:2]
geo=TcH(arg[2:6])
script.models[TcH(id)]=(geo,'geo',None,script.B2P(geo),script)
return start
#yep, this is what rock bottom coding looks like
ScrollCount=0
def ConvertTexScrolls(script,Obj,rom):
if script.editor:
return ConvertEditorTexScrolls(script,Obj,rom)
else:
return ConvertRMTexScrolls(script,Obj,rom)
def ConvertRMTexScrolls(script,Obj,rom):
# RM rules
# Verts addr = bparam
# Verts axis = Y&0xF000 (0x8000 - Y, 0xA000 - X, 0x4000 - Z, 0x2000 - Y, 0x0000 - X)
# Scroll Type = Y&0F00 (0x000 - normal, 0x0100 - sine, 0x0200 - jumping)
# Speed= Z pos
# NumVerts = X
Addr=int(Obj[7],16)
Num=Obj[1]
Speed = Obj[3]
dir = Obj[2]
# cycle = Obj[]
Bhvs = {
0xA000:'x',
0x8000:'y',
0x4000:'xPos',
0x2000:'yPos',
0x0000:'zPos'
}
Types = {
0x0:'normal',
0x100:'sine',
0x200:'jumping'
}
if script.texScrolls:
script.texScrolls.append([Obj,script.CurrArea,Addr,Num,Speed,Bhvs[dir&0xF000],Types[dir&0xF00],dir&0xFF])
else:
script.texScrolls = [[Obj,script.CurrArea,Addr,Num,Speed,Bhvs[dir&0xF000],Types[dir&0xF00],dir&0xFF]]
return Obj
def DetScrollType(rom):
a=struct.unpack(">L",rom[0x1202400:0x1202404])[0]
#false means the old, aka original version
if a==0x27bdffe8:
return False
else:
return True
def ConvertEditorTexScrolls(script,Obj,rom):
# Editor rules
# Verts scrolled = 0x0E000000+(Byte2(Zpos)-2)<<16+(bparam>>16)
# Verts addr = Verts scrolled&0xFFFFFFF0
# Verts axis = Verts scrolled&0xF (0x8 = x, 0xA = y)
# Num verts scrolled = Byte2(Zpos)*3
# Speed=Byte2(Zpos)
# I have zero clue if this is true for all editor versions
# it likely isn't
PosByte = (lambda x: struct.pack('>f',x)[1])
#Addr = 0x8040+PosByte+Bparam1+2. Seg E starts at 0x8045 always??
if 'editor_Scroll_Texture2' in Obj[-2]:
Obj[-2] = 'editor_Scroll_Texture'
#check for other behavior type
else:
if DetScrollType(rom):
return ConvertEditorTexScrollsAlt(script,Obj,PosByte)
Addr=0x0E000000+((PosByte(Obj[1])-2)<<16)+(int(Obj[7],16)>>16) #x
if Obj[2]:
Num=PosByte(Obj[2])*3 #y
else:
Num=0 #different scroll type idk theres too many types of scrolls
Speed = PosByte(Obj[3]) #z
dir = Addr&0xF
if dir==0x8:
dir='x'
else:
dir='y'
if script.texScrolls:
script.texScrolls.append([Obj,script.CurrArea,Addr&0xFFFFFFF0,Num,Speed,dir,'normal',0])
else:
script.texScrolls = [[Obj,script.CurrArea,Addr&0xFFFFFFF0,Num,Speed,dir,'normal',0]]
return Obj
def ConvertEditorTexScrollsAlt(script,Obj,PB):
#Different format used in later versions of editor
#Addr=0x8040+Byte2(X)<<16+Bparam1+2
#Num=Bparam34
#Speed=Byte2(Z)
Addr=0x0E000000+((PB(Obj[1])-2)<<16)+(int(Obj[7],16)>>16) #x
Num=int(Obj[7],16)&0xFFFF
Speed=PB(Obj[3])
dir = Addr&0xF
if dir==0x8:
dir='x'
else:
dir='y'
if script.texScrolls:
script.texScrolls.append([Obj,script.CurrArea,Addr&0xFFFFFFF0,Num,Speed,dir,'normal',0])
else:
script.texScrolls = [[Obj,script.CurrArea,Addr&0xFFFFFFF0,Num,Speed,dir,'normal',0]]
return Obj
def FormatScrollObject(scroll,verts,obj,s,area):
#not efficient at all, but number of scrolls is low and I'm lazy
#vert = [seg ptr, rom ptr, num verts], sorted by seg ptrs
if not verts:
return None
addr=scroll[2]
closest=0
offset=0
#if verts are not in order, I can falsely assume the vert does not exist
#becuase I see a gap and mistake it for the end of an area or something.
verts.sort(key=lambda x: x[0])
for v in verts:
if addr>=v[0]:
closest = v[0]
offset = addr-v[0]
if v[0]>addr:
if offset>0xf0:
offset=0xFF0
Log.InvalidScroll(s.Currlevel,area,scroll)
break
else:
Log.InvalidScroll(s.Currlevel,area,scroll)
closest=addr
offset=0xFF0
global ScrollCount
bparam = '%d'%ScrollCount
ScrollCount+=1
Bhvs = {
'x':4,
'y':5,
'xPos':0,
'yPos':1,
'zPos':2,
}
Types = {
'normal':0,
'sine':1,
'jumping':2,
}
#format I will use is bparam=addr,z=vert amount,x=spd,y=bhv,ry=type, rz=cycle
# (Obj,script.CurrArea,Addr,Num,Speed,Bhvs[dir&0xF000],Types[dir&0xFFF],cycle)
# PO=[id,x,y,z,rx,ry,rz,bparam,bhv,mask]
obj[1]=scroll[4] #x
obj[2]=Bhvs[scroll[-3]] #y
obj[3]=scroll[3] #z
obj[5]=Types[scroll[-2]] #ry
obj[6]=scroll[-1] #rz
obj[4]=int(offset/0x10) #rx
obj[-3] = bparam
s.ScrollArray.append(['VB_%s_%d_0x%x'%(Num2Name[s.Currlevel],scroll[1],closest),int(offset/0x10)])
return obj
def PlaceObject(rom,cmd,start,script):
arg=cmd[2]
A=script.GetArea()
if not A:
return start
mask=arg[0]
#remove disabled objects
if mask==0:
return start
id=arg[1]
#efficiency
x=U2S(TcH(arg[2:4]))
y=U2S(TcH(arg[4:6]))
z=U2S(TcH(arg[6:8]))
rx=U2S(TcH(arg[8:10]))
ry=U2S(TcH(arg[10:12]))
rz=U2S(TcH(arg[12:14]))
bparam=hex(TcH(arg[14:18]))
#check for MOP stuff first
for a,b in MOPObjAddr.items():
if (id,TcH(arg[18:22]))==a:
bhv=' bhv'+b[0]
PO=[id,x,y,z,rx,ry,rz,bparam,bhv,mask]
break
else:
bhv=script.GetLabel("{:08x}".format(TcH(arg[18:22])))
if bhv in "0x{:08x}".format(TcH(arg[18:22])):
bhv = " Bhv_Custom_0x{:08x}".format(TcH(arg[18:22]))
Log.UnkObject(script.Currlevel,script.CurrArea,bhv)
PO=[id,x,y,z,rx,ry,rz,bparam,bhv,mask]
if 'editor_Scroll_Texture' in bhv or 'RM_Scroll_Texture' in bhv:
PO = ConvertTexScrolls(script,PO,rom)
A.objects.append(PO)
#for parsing later at the end
script.objects.append([*PO,script.CurrArea,TcH(arg[18:22])])
return start
def MacroObjects(rom,cmd,start,script):
arg=cmd[2]
macros = script.B2P(TcH(arg[2:6]))
A=script.GetArea()
A.macros = []
x=0
while(True):
m = BitArray(rom[macros+x:macros+x+10])
[yRot,Preset,X,Y,Z,Bp] = m.unpack("uint:7,uint:9,4*uint:16")
if Preset<0x1F:
break
else:
A.macros.append([yRot,Preset,X,Y,Z,Bp])
x+=10
return start
def PlaceMario(rom,cmd,start,script):
#do nothing
return start
def ConnectWarp(rom,cmd,start,script):
A=script.GetArea()
if not A:
return start
arg=cmd[2]
W=(arg[0],arg[1],arg[2]+script.Aoffset,arg[3],arg[4])
A.warps.append(W)
return start
def PaintingWarp(rom,cmd,start,script):
return start
def InstantWarp(rom,cmd,start,script):
return start
def SetMarioDefault(rom,cmd,start,script):
arg=cmd[2]
script.mStart = [arg[0],U2S(TcH(arg[2:4])),U2S(TcH(arg[4:6])),U2S(TcH(arg[6:8])),U2S(TcH(arg[8:10]))]
return start
def LoadCol(rom,cmd,start,script):
arg=cmd[2]
col=TcH(arg[2:6])
A=script.GetArea()
if not A:
return start
A.col=col
return start
def LoadRoom(rom,cmd,start,script):
return start
def SetDialog(rom,cmd,start,script):
return start
def SetMusic(rom,cmd,start,script):
A=script.GetArea()
if A:
arg=cmd[2]
A.music=TcH(arg[3:4])
return start
def SetMusic2(rom,cmd,start,script):
A=script.GetArea()
if A:
arg=cmd[2]
A.music=TcH(arg[1:2])
return start
def SetTerrain(rom,cmd,start,script):
A=script.GetArea()
if A:
arg=cmd[2]
A.terrain=TcH(arg[1:2])
return start
def ULC(rom,start):
cmd = struct.unpack(">B",rom[start:start+1])[0]
len = struct.unpack(">B",rom[start+1:start+2])[0]
q=len-2
args = struct.unpack(">%dB"%q,rom[start+2:start+len])
return [cmd,len,args]
#iterates through script until a cmd is found that
#requires new action, then returns that cmd
def PLC(rom,start):
(cmd,len,args) = ULC(rom,start)
start+=len
if cmd in jumps:
return (cmd,len,args,start)
return PLC(rom,start)
def WriteModel(rom,dls,s,name,Hname,id,tdir):
x=0
ModelData=[]
while(x<len(dls)):
#check for bad ptr
st=dls[x][0]
first=TcH(rom[st:st+4])
c=rom[st]
if first==0x01010101 or not F3D.DecodeFmt.get(c):
return
try:
(dl,verts,textures,amb,diff,ranges,starts,fog)=F3D.DecodeVDL(rom,dls[x],s,id,1)
if fog:
f = name.relative_to(Path(sys.path[0])) / 'custom.model.inc.c'
Log.LevelFog(str(f))
ModelData.append([starts,dl,verts,textures,amb,diff,ranges,0])
except:
print("{} has a broken level DL and is being skipped".format(Num2LevelName.get(s.Currlevel)))
x+=1
s.verts.extend(verts) #for texture scrolls
[refs,crcs] = F3D.ModelWrite(rom,ModelData,name,id,tdir,s.editor,s.Currlevel)
modelH = name/'custom.model.inc.h'
mh = open(modelH,'w')
headgaurd="%s_HEADER_H"%(Hname)
mh.write('#ifndef %s\n#define %s\n#include "types.h"\n'%(headgaurd,headgaurd))
for r in refs:
mh.write('extern '+r+';\n')
mh.write("#endif")
mh.close()
del ModelData
return dls
def ClosestIntinDict(num,dict):
min=0xFFFFFFFFFFFFFF
res = None
for k,v in dict.items():
if abs(k-num)<min:
min=abs(k-num)
res = v
return res
def InsertBankLoads(s,f):
banks = [s.banks[10],s.banks[15],s.banks[12],s.banks[13]]
for i,b in enumerate(banks):
if not i:
if s.editor:
d=skyboxesEditor
else:
d=skyboxesRM
else:
d=Groups
if b and b[1]>b[0]:
banks[i]=ClosestIntinDict(b[0],d)
if not i:
#custom skybox
if b[0]>0x1220000:
name = '_%s_skybox_mio0'%('SkyboxCustom%d'%b[0])
load = "LOAD_MIO0(0xA,"+name+"SegmentRomStart,"+name+"SegmentRomEnd),\n"
else:
load = "LOAD_MIO0(0xA,"+banks[i]+"SegmentRomStart,"+banks[i]+"SegmentRomEnd),\n"
else:
load = "LOAD_MIO0(%d,"%banks[i][1]+banks[i][0]+"_mio0SegmentRomStart,"+banks[i][0]+"_mio0SegmentRomEnd),\n"
load += "LOAD_RAW(%d,"%banks[i][2]+banks[i][0]+"_geoSegmentRomStart,"+banks[i][0]+"_geoSegmentRomEnd),\n"
if f:
f.write(load)
return banks
def DetLevelSpecBank(s,f):
level = None
if s.banks[7]:
#RM custom bank 7 check
if s.banks[7][0]>0x1220000:
return level
level =ClosestIntinDict(s.banks[7][0],LevelSpecificBanks)
return level
def LoadUnspecifiedModels(s,file,level):
Grouplines = Group_Models.split("\n")
for i,model in enumerate(s.models):
if model:
#Bank 0x14 is for menus, I will ignore it
Seg = (model[0]>>24)
if Seg==0x14:
continue
#Model Loads need to use groups because seg addresses are repeated so you can get the wrong ones
#if you just use the map which has no distinction on which bank is loaded.
addr = "{:08x}".format(model[0])
if Seg==0x12:
lab = GD.__dict__[level].get((i,'0x'+addr))
if not lab:
# print(addr,level,i)
lab = s.GetLabel(addr)
else:
lab= lab[1]
#actor groups, unlikely to exist outside existing group loads
elif Seg==0xD or Seg==0xC:
group = ClosestIntinDict(s.banks[Seg][0],Groups)[0][1:]
lab = GD.__dict__[group].get((i,'0x'+addr))
if not lab:
lab = s.GetLabel(addr)
else:
lab= lab[1]
#generally MOP
elif Seg==0 or Seg==3 or Seg==0xF:
for a,b in MOPModels.items():
if (i,model[0])==a:
#mops are loaded in entry script
lab='MOP'
break
else:
lab = s.GetLabel(addr)
#group0, common0, common1 banks that have unique geo layouts
else:
lab = s.GetLabel(addr)
if lab=='MOP':
continue
if '0x' in lab or not lab:
comment = "// "
else:
comment = ""
if LevelSpecificModels.get(level) and Seg==0x12:
for l in LevelSpecificModels[level].split("\n"):
if lab in l:
break
else:
if model[1]=='geo':
file.write(comment+"LOAD_MODEL_FROM_GEO(%d,%s),\n"%(i,lab))
else:
#Its just a guess but I think 4 will lead to the least issues
file.write(comment+"LOAD_MODEL_FROM_DL(%d,%s,4),\n"%(i,lab))
elif not (any([lab in l for l in Grouplines])):
if model[1]=='geo':
file.write(comment+"LOAD_MODEL_FROM_GEO(%d,%s),\n"%(i,lab))
else:
#Its just a guess but I think 4 will lead to the least issues
file.write(comment+"LOAD_MODEL_FROM_DL(%d,%s,4),\n"%(i,lab))
def WriteLevelScript(name,Lnum,s,level,Anum,envfx):
f = open(name,'w')
f.write(scriptHeader)
for a in Anum:
f.write('#include "areas/%d/custom.model.inc.h"\n'%a)
f.write('#include "levels/%s/header.h"\nextern u8 _%s_segment_ESegmentRomStart[]; \nextern u8 _%s_segment_ESegmentRomEnd[];\n'%(Lnum,Lnum,Lnum))
#This is the ideal to match hacks, but currently the way the linker is
#setup, level object data is in the same bank as level mesh so this cannot be done.
LoadLevel = DetLevelSpecBank(s,f)
if LoadLevel and LoadLevel!=Lnum:
f.write('#include "levels/%s/header.h"\n'%LoadLevel)
f.write('const LevelScript level_%s_custom_entry[] = {\n'%Lnum)
s.MakeDec('const LevelScript level_%s_custom_entry[]'%Lnum)
#entry stuff
f.write("INIT_LEVEL(),\n")
if LoadLevel:
f.write("LOAD_MIO0(0x07, _"+LoadLevel+"_segment_7SegmentRomStart, _"+LoadLevel+"_segment_7SegmentRomEnd),\n")
f.write("LOAD_RAW(0x1A, _"+LoadLevel+"SegmentRomStart, _"+LoadLevel+"SegmentRomEnd),\n")
f.write("LOAD_RAW(0x0E, _"+Lnum+"_segment_ESegmentRomStart, _"+Lnum+"_segment_ESegmentRomEnd),\n")
if envfx:
f.write("LOAD_MIO0( /*seg*/ 0x0B, _effect_mio0SegmentRomStart, _effect_mio0SegmentRomEnd),\n")
#add in loaded banks
banks = InsertBankLoads(s,f)
f.write("ALLOC_LEVEL_POOL(),\nMARIO(/*model*/ MODEL_MARIO, /*behParam*/ 0x00000001, /*beh*/ bhvMario),\n")
if LoadLevel:
f.write(LevelSpecificModels[LoadLevel])
#Load models that the level uses that are outside groups/level
LoadUnspecifiedModels(s,f,LoadLevel)
#add in jumps based on banks returned
for b in banks:
if type(b)==list and len(b)>2:
f.write("JUMP_LINK("+b[3]+"),\n")
#a bearable amount of cringe
for a in Anum:
id = Lnum+"_"+str(a)+"_"
f.write('JUMP_LINK(local_area_%s),\n'%id)
#end script
f.write("FREE_LEVEL_POOL(),\n")
f.write("MARIO_POS({},{},{},{},{}),\n".format(*s.mStart))
f.write("CALL(/*arg*/ 0, /*func*/ lvl_init_or_update),\nCALL_LOOP(/*arg*/ 1, /*func*/ lvl_init_or_update),\nCLEAR_LEVEL(),\nSLEEP_BEFORE_EXIT(/*frames*/ 1),\nEXIT(),\n};\n")
for a in Anum:
id = Lnum+"_"+str(a)+"_"
area=level[a]
WriteArea(f,s,area,a,id)
def WriteArea(f,s,area,Anum,id):
#begin area
ascript = "const LevelScript local_area_%s[]"%id
f.write(ascript+' = {\n')
s.MakeDec(ascript)
Gptr='Geo_'+id+hex(area.geo)
f.write("AREA(%d,%s),\n"%(Anum,Gptr))
f.write("TERRAIN(%s),\n"%("col_"+id+hex(area.col)))
f.write("SET_BACKGROUND_MUSIC(0,%d),\n"%area.music)
f.write("TERRAIN_TYPE(%d),\n"%(area.terrain))
f.write("JUMP_LINK(local_objects_%s),\nJUMP_LINK(local_warps_%s),\n"%(id,id))
if hasattr(area,'macros'):
f.write("MACRO_OBJECTS('local_macro_objects_%s')"%id)
f.write("END_AREA(),\nRETURN()\n};\n")
asobj = 'const LevelScript local_objects_%s[]'%id
f.write(asobj+' = {\n')
s.MakeDec(asobj)
#write objects
for o in area.objects:
if s.texScrolls:
if 'Scroll_Texture' in o[-2]:
for scroll in s.texScrolls:
if scroll[0]==o and scroll[1]==Anum:
o = FormatScrollObject(scroll,s.verts,o,s,Anum)
break
if o:
if o[4]==255 and 'Scroll_Texture' in o[-2]:
comment='// '
else:
comment=''
f.write(comment+"OBJECT_WITH_ACTS({},{},{},{},{},{},{},{},{},{}),\n".format(*o))
f.write("RETURN()\n};\n")
aswarps = 'const LevelScript local_warps_%s[]'%id
f.write(aswarps+' = {\n')
s.MakeDec(aswarps)
#write warps
for w in area.warps:
f.write("WARP_NODE({},{},{},{},{}),\n".format(*w))
#write macro objects if they exist
if hasattr(area,'macros'):
asobj = 'const MacroObject local_macro_objects_%s[]'%id
f.write(asobj+' = {\n')
for m in area.macros:
f.write("MACRO_OBJECT_WITH_BEH_PARAM({},{},{},{},{},{}),\n".format(MacroNames[m[1]],m[0],*m[2:]))
f.write("MACRO_OBJECT_END(),\n};")
f.write("RETURN()\n};\n")
def GrabOGDatH(q,rootdir,name):
dir = rootdir/'originals'/name
head = open(dir/'header.h','r')
head = head.readlines()
for l in head:
if not l.startswith('extern'):
continue
q.write(l)
return q
def GrabOGDatld(L,rootdir,name):
dir = rootdir/'originals'/name
ld = open(dir/'leveldata.c','r')
ld = ld.readlines()
grabbed = []
for l in ld:
if not l.startswith('#include "levels/%s/'%name):
continue
#mem bloat but makes up for mov tex being dumb
# if ('/areas/' in l and '/model.inc.c' in l):
# continue
#for the specific case of levels without subfolders
q = l.split('/')
if len(q)>4:
if ('areas' in q[2] and 'model.inc.c' in q[4]):
continue
#I want to include static objects in collision
# if ('/areas/' in l and '/collision.inc.c' in l):
# continue
L.write(l)
grabbed.append(l)
return [L,grabbed]
def WriteVanillaLevel(rom,s,num,areas,rootdir,m64dir,AllWaterBoxes,Onlys,romname,m64s,seqNums,MusicExtend):
WaterOnly = Onlys[0]
ObjectOnly = Onlys[1]
MusicOnly = Onlys[2]
OnlySkip = any(Onlys)
name=Num2Name[num]
level=Path(rootdir)/'levels'/("%s"%name)
original = rootdir/'originals'/("%s"%name)
shutil.copytree(original,level)
#open original script
script = level / 'script.c'
scriptO = open(script,'r')
Slines = scriptO.readlines()
scriptO.close()
script = open(script,'w')
#go until an area is found
x=0 #line pos
restrict = ['OBJECT','WARP_NODE','JUMP_LINK']
CheckRestrict = (lambda x: any([r in x for r in restrict]))
macro=0
for a in areas:
j=0
area=s.levels[num][a]
#advanced past includes for first area
if a==1:
while(x<len(Slines)):
if '"levels/%s/header.h"'%name in Slines[x]:
x+=1
break
#scripts always start with some static data
if 'static' in Slines[x]:
break
x+=1
#write macro objects if they exist
CheckMacro = (lambda x: 0)
if hasattr(area,'macros'):
CheckMacro = (lambda x: 'MACRO_OBJECTS(' in x )
if not macro:
hd = '#include "level_misc_macros.h"\n#include "macro_presets.h"\n'
Slines.insert(x,(hd))
x+=1
macro=1
asobj = 'static const MacroObject local_macro_objects_%s_%d[]'%(name,a)
Slines.insert(x,(asobj+' = {\n'))
x+=1
for m in area.macros:
Slines.insert(x,"MACRO_OBJECT_WITH_BEH_PARAM({},{},{},{},{},{}),\n".format(MacroNames[m[1]],m[0],*m[2:]))
x+=1
Slines.insert(x,"MACRO_OBJECT_END(),\n};\n")
x+=1
for a in areas:
while(x<len(Slines)):
if ' AREA(' in Slines[x]:
x+=1
break
x+=1
#remove other objects/warps
while(j+x<len(Slines)):
if CheckRestrict(Slines[j+x]) or CheckMacro(Slines[j+x]):
Slines.pop(j+x)
continue
elif 'END_AREA()' in Slines[j+x]:
j+=1
break
else:
j+=1
for o in area.objects:
Slines.insert(x,"OBJECT_WITH_ACTS({},{},{},{},{},{},{},{},{},{}),\n".format(*o))
for w in area.warps:
Slines.insert(x,"WARP_NODE({},{},{},{},{}),\n".format(*w))
if hasattr(area,'macros'):
Slines.insert(x,"MACRO_OBJECTS(local_macro_objects_%s_%d),\n"%(name,a))
x=j+x
#area dir
Arom = area.rom
if area.music and not (ObjectOnly or WaterOnly):
[m64,seqNum] = RipSequence(Arom,area.music,m64dir,num,a,romname,MusicExtend)
if m64 not in m64s:
m64s.append(m64)
seqNums.append(seqNum)
#write objects and warps for each area
[script.write(l) for l in Slines]
return [AllWaterBoxes,m64s,seqNums]
def WriteLevel(rom,s,num,areas,rootdir,m64dir,AllWaterBoxes,Onlys,romname,m64s,seqNums,MusicExtend):
#create level directory
WaterOnly = Onlys[0]
ObjectOnly = Onlys[1]
MusicOnly = Onlys[2]
OnlySkip = any(Onlys)
name=Num2Name[num]
level=Path(rootdir)/'levels'/("%s"%name)
original = rootdir/'originals'/("%s"%name)
shutil.copytree(original,level)
Areasdir = level/"areas"
Areasdir.mkdir(exist_ok=True)
#create area directory for each area
envfx = 0
for a in areas:
#area dir
adir = Areasdir/("%d"%a)
adir.mkdir(exist_ok=True)
area=s.levels[num][a]
Arom = area.rom
if area.music and not (ObjectOnly or WaterOnly):
[m64,seqNum] = RipSequence(Arom,area.music,m64dir,num,a,romname,MusicExtend)
if m64 not in m64s:
m64s.append(m64)
seqNums.append(seqNum)
#get real bank 0x0e location
s.RME(a,Arom)
id = name+"_"+str(a)+"_"
if s.banks[10] and s.banks[10][1]>s.banks[10][0] and s.banks[10][0]>0x1220000:
CBG=1
cskybox='%s_skybox_Index'%('SkyboxCustom%d'%(s.banks[10][0]))
else:
CBG=0
cskybox=''
(geo,dls,WB,vfx)=GW.GeoParse(Arom,area.geo,s,area.geo,id,cskybox,CBG,a)
#deal with some areas having it vs others not
if vfx:
envfx = 1
if not OnlySkip:
GW.GeoWrite(geo,adir/"custom.geo.inc.c",id)
for g in geo:
s.MakeDec("const GeoLayout Geo_%s[]"%(id+hex(g[1])))
if not OnlySkip:
dls = WriteModel(Arom,dls,s,adir,"%s_%d"%(name.upper(),a),id,level)
if not dls:
print("{} has no Display Lists, that is very bad".format(name))
else:
for d in dls:
s.MakeDec("Gfx DL_%s[]"%(id+hex(d[1])))
#write collision file
if not OnlySkip:
ColParse.ColWrite(adir/"custom.collision.inc.c",s,Arom,area.col,id)
s.MakeDec('const Collision col_%s[]'%(id+hex(area.col)))
#write mov tex file
if not (ObjectOnly or MusicOnly):
#WB = [types][array of type][box data]
MovTex = adir / "movtextNew.inc.c"
MovTex = open(MovTex,'w')
Wrefs = []
for k,Boxes in enumerate(WB):
wref = []
for j,box in enumerate(Boxes):
#Now a box is an array of all the data
#Movtex is just an s16 array, it uses macros but
#they don't matter
dat = repr(box).replace("[","{").replace("]","}")
dat = "static Movtex %sMovtex_%d_%d[] = "%(id,j,k) + dat+";\n\n"
MovTex.write(dat)
wref.append("%sMovtex_%d_%d"%(id,j,k))
Wrefs.append(wref)
for j,Type in enumerate(Wrefs):
MovTex.write("const struct MovtexQuadCollection %sMovtex_%d[] = {\n"%(id,j))
for k,ref in enumerate(Type):
MovTex.write("{%d,%s},\n"%(k,ref))
MovTex.write("{-1, NULL},\n};\n")
s.MakeDec("struct MovtexQuadCollection %sMovtex_%d[]"%(id,j))
AllWaterBoxes.append(["%sMovtex_%d"%(id,j),num,a,j])
print('finished area '+str(a)+ ' in level '+name)
#now write level script
if not (WaterOnly or MusicOnly):
WriteLevelScript(level/"custom.script.c",name,s,s.levels[num],areas,envfx)
s.MakeDec("const LevelScript level_%s_entry[]"%name)
if not OnlySkip:
#finally write header
H=level/"header.h"
q = open(H,'w')
headgaurd="%s_HEADER_H"%(name.upper())
q.write('#ifndef %s\n#define %s\n#include "types.h"\n#include "game/moving_texture.h"\n'%(headgaurd,headgaurd))
for h in s.header:
q.write('extern '+h+';\n')
#now include externs from stuff in original level
q = GrabOGDatH(q,rootdir,name)
q.write("#endif")
q.close()
#append to geo.c, maybe the original works good always??
G = level/"custom.geo.c"
g = open(G,'w')
g.write(geocHeader)
g.write('#include "levels/%s/header.h"\n'%name)
for i,a in enumerate(areas):
geo = '#include "levels/%s/areas/%d/custom.geo.inc.c"\n'%(name,(i+1))
g.write(geo) #add in some support for level specific objects somehow
g.close
#write leveldata.c
LD = level/"custom.leveldata.c"
ld = open(LD,'w')
ld.write(ldHeader)
Ftypes = ['custom.model.inc.c"\n','custom.collision.inc.c"\n']
ld.write('#include "levels/%s/textureNew.inc.c"\n'%(name))
for i,a in enumerate(areas):
ld.write('#include "levels/%s/areas/%d/movtextNew.inc.c"\n'%(name,(i+1)))
start = '#include "levels/%s/areas/%d/'%(name,(i+1))
for Ft in Ftypes:
ld.write(start+Ft)
ld.close