forked from NSMBW-Community/Reggie-Next
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlevel.py
More file actions
1357 lines (1092 loc) · 42.8 KB
/
level.py
File metadata and controls
1357 lines (1092 loc) · 42.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import struct
from PyQt5 import QtWidgets
import globals_
import spritelib as SLib
import archive
from tiles import CreateTilesets, LoadTileset
from levelitems import EntranceItem, SpriteItem, ZoneItem, LocationItem, ObjectItem, PathItem, CommentItem
from misc2 import DecodeOldReggieInfo
from spriteeditor import SpriteEditorWidget
from raw_data import RawData
class AbstractLevel:
"""
Class for an abstract level from any game. Defines the API.
"""
def __init__(self):
"""
Initializes the level with default settings
"""
self.filepath = None
self.name = 'untitled'
self.areas = []
def load(self, data, areaNum):
"""
Loads a level from bytes data. You MUST reimplement this in subclasses!
"""
pass
def save(self):
"""
Returns the level as a bytes object. You MUST reimplement this in subclasses!
"""
return b''
def deleteArea(self, number):
"""
Removes the area specified. Number is a 1-based value, not 0-based;
so you would pass a 1 if you wanted to delete the first area.
"""
del self.areas[number - 1]
# change all later areas to use the correct num
for i, area in enumerate(self.areas, 1):
area.set_num(i)
return True
def changeArea(self, number):
"""
Changes the current area to the specified area in the loaded level
archive. Note that number is 1-based, not 0-based.
"""
return False
class Level_NSMBW(AbstractLevel):
"""
Class for a level from New Super Mario Bros. Wii
"""
def __init__(self):
"""
Initializes the level with default settings
"""
super().__init__()
self.new(False)
def new(self, load=True):
"""
Creates a completely new level
"""
# Create area objects
self.areas = []
new_area = Area(1)
if load:
new_area.load_defaults()
globals_.Area = new_area
SLib.Area = new_area
self.areas.append(new_area)
def load(self, data, areaToLoad):
"""
Loads a NSMBW level from bytes data.
"""
super().load(data, areaToLoad)
arc = archive.U8.load(data)
if "course" not in arc:
return False
# Sort the area data
areaData = [[None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None]]
for name, val in arc.files:
if val is None: continue
name = name.replace('\\', '/').split('/')[-1]
if not name.startswith('course'): continue
if not name.endswith('.bin'): continue
if '_bgdatL' in name:
# It's a layer file
if len(name) != 19: continue
try:
thisArea = int(name[6])
laynum = int(name[14])
except ValueError:
continue
if not (0 < thisArea < 5): continue
areaData[thisArea - 1][laynum + 1] = val
else:
# It's the course file
if len(name) != 11: continue
try:
thisArea = int(name[6])
except ValueError:
continue
if not (0 < thisArea < 5): continue
areaData[thisArea - 1][0] = val
# Create area objects
self.areas = []
for i, data in enumerate(areaData, 1):
course, L0, L1, L2 = data
if course is None:
continue
new_area = Area(i)
new_area.set_data(course, L0, L1, L2)
self.areas.append(new_area)
self.areas[areaToLoad - 1].load()
globals_.Area = self.areas[areaToLoad - 1]
SLib.Area = self.areas[areaToLoad - 1]
return True
def save(self):
"""
Save the level back to a file
"""
# Make a new archive
newArchive = archive.U8()
# Create a folder within the archive
newArchive['course'] = None
# Go through the areas, save them and add them back to the archive
for i, area in enumerate(self.areas):
assert area.areanum == i + 1, (area.areanum, i + 1)
course, L0, L1, L2 = area.save()
# Layers 0 and 2 are optional, but the game assumes that the course
# file and layer 1 will always exist (see dBg_c::CheckExistLayer())
newArchive['course/course%d.bin' % area.areanum] = course
newArchive['course/course%d_bgdatL1.bin' % area.areanum] = L1
if L0 is not None:
newArchive['course/course%d_bgdatL0.bin' % area.areanum] = L0
if L2 is not None:
newArchive['course/course%d_bgdatL2.bin' % area.areanum] = L2
# return the U8 archive data
return newArchive._dump()
def appendArea(self, course_new, L0_new, L1_new, L2_new):
"""
Creates a new area and adds it to the current level.
"""
# Add new area
new_area = Area(len(self.areas) + 1)
new_area.set_data(course_new, L0_new, L1_new, L2_new)
self.areas.append(new_area)
def changeArea(self, number):
"""
Changes the current area to the specified area in the loaded level
archive. Note that number is 1-based, not 0-based.
"""
current_num = globals_.Area.areanum
# self.areas[current_num - 1] should be unloaded.
self.areas[current_num - 1].unload()
# Set the globals properly
globals_.Area = self.areas[number - 1]
SLib.Area = self.areas[number - 1]
# self.areas[number - 1] should be loaded.
self.areas[number - 1].load()
return True
class Area:
"""
Class for a parsed NSMBW level area
"""
def __init__(self, area_num):
"""
Creates a completely new NSMBW area
"""
self.areanum = area_num
self.course = None
self.L0 = None
self.L1 = None
self.L2 = None
# Default tileset names
self.tileset0 = 'Pa0_jyotyu'
self.tileset1 = ''
self.tileset2 = ''
self.tileset3 = ''
self.blocks = [b''] * 14
self.blocks[0] = b'Pa0_jyotyu' + bytes(128 - len('Pa0_jyotyu'))
self.blocks[1] = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x2c\x00\x00\x00\x00\x00\x00\x00\x00'
self.blocks[3] = bytes(8)
self.blocks[7] = b'\xff\xff\xff\xff'
self.defEvents = 0
self.timeLimit = 300
self.creditsFlag = False
self.startEntrance = 0
self.ambushFlag = False
self.toadHouseType = 0
self.wrapFlag = False
self.unkFlag1 = False
self.unkFlag2 = False
self.unkVal1 = 0
self.unkVal2 = 0
self.spriteSettings = []
self.entrances = []
self.sprites = []
self.bounding = []
self.bgA = []
self.bgB = []
self.zones = []
self.locations = []
self.camprofiles = []
self.paths = []
self.comments = []
self.layers = [[], [], []]
self.loaded_sprites = set()
self.force_loaded_sprites = set()
self.sprite_idtypes = {} # {idtype: {id: number of usages of id}}
self.MetaData = None
self._is_loaded = False
CreateTilesets()
def set_num(self, area_num):
"""
Changes the area number of this area.
"""
self.areanum = area_num
def load_defaults(self):
"""
Loads default data.
"""
# Metadata
self.LoadReggieInfo(None)
# Load tilesets
CreateTilesets()
LoadTileset(0, self.tileset0)
LoadTileset(1, self.tileset1)
LoadTileset(2, self.tileset2)
LoadTileset(3, self.tileset3)
# Mark the area as loaded
self._is_loaded = True
def set_data(self, course, L0, L1, L2):
"""
Assigns the archive file data to this area.
"""
self.course = course
self.L0 = L0
self.L1 = L1
self.L2 = L2
def unload(self):
"""
Unloads most of an area, except for the raw data
"""
assert self._is_loaded
del self.blocks
del self.layers
del self.Metadata
del self.tileset0
del self.tileset1
del self.tileset2
del self.tileset3
del self.wrapFlag
del self.unkFlag1
del self.unkFlag2
del self.defEvents
del self.unkVal1
del self.unkVal2
del self.spriteSettings
del self.entrances
del self.sprites
del self.bgA
del self.bgB
del self.zones
del self.locations
del self.camprofiles
del self.paths
del self.comments
del self.sprite_idtypes
self._is_loaded = False
def load(self):
"""
Loads an area from the archive files
"""
assert not self._is_loaded
# Load in the course file and blocks - if the course file is None, we
# just create a new area with the default settings (as stored in the
# already initialised self.blocks)
if self.course is not None:
self.LoadBlocks(self.course)
# Load the editor metadata
if self.course is not None and self.block1pos[0] != 0x70:
rddata = self.course[0x70:self.block1pos[0]]
self.LoadReggieInfo(rddata)
else:
self.LoadReggieInfo(None)
if hasattr(self, "block1pos"):
del self.block1pos
# Load stuff from individual blocks
self.LoadTilesetNames() # block 1
self.LoadOptions() # block 2
self.LoadEntrances() # block 7
self.LoadLoadedSprites() # block 9
self.LoadZones() # block 10 (also blocks 3, 5, and 6)
self.LoadLocations() # block 11
self.LoadCamProfiles() # block 12
self.LoadPaths() # block 13 and 14
# Now, load the comments
self.LoadComments()
# Reset the tilesets if this is not the first load
if not globals_.firstLoad:
CreateTilesets()
else:
globals_.firstLoad = False
# Load the tilesets
LoadTileset(0, self.tileset0)
LoadTileset(1, self.tileset1)
LoadTileset(2, self.tileset2)
LoadTileset(3, self.tileset3)
# Load the object layers
self.layers = [[], [], []]
if self.L0 is not None:
self.LoadLayer(0, self.L0)
if self.L1 is not None:
self.LoadLayer(1, self.L1)
if self.L2 is not None:
self.LoadLayer(2, self.L2)
self.LoadSprites() # block 8
self.InitialiseIdTypes()
self._is_loaded = True
return True
def save(self):
"""
Save the area back to a file
"""
# first handle the case that the area is not loaded
if not self._is_loaded:
return (self.course, self.L0, self.L1, self.L2)
# prepare this because otherwise the game refuses to load some sprites
self.SortSpritesByZone()
# save each block first
self.SaveTilesetNames() # block 1
self.SaveOptions() # block 2
self.SaveEntrances() # block 7
self.SaveSprites() # block 8
self.SaveLoadedSprites() # block 9
self.SaveZones() # block 10 (and 3, 5 and 6)
self.SaveLocations() # block 11
self.SaveCamProfiles() # block 12
self.SavePaths() # blocks 13 and 14
rdata = bytearray(self.Metadata.save())
if len(rdata) % 4 != 0:
rdata += bytes(4 - (len(rdata) % 4))
rdata = bytes(rdata)
# Save the main course file
# We'll be passing over the blocks array two times.
# Using bytearray here because it offers mutable bytes
# and works directly with struct.pack_into(), so it's a
# win-win situation
FileLength = (14 * 8) + len(rdata)
for block in self.blocks:
FileLength += len(block)
course = bytearray(FileLength)
saveblock = struct.Struct('>II')
HeaderOffset = 0
FileOffset = (14 * 8) + len(rdata)
struct.pack_into('%ds' % len(rdata), course, 0x70, rdata)
for block in self.blocks:
blocksize = len(block)
saveblock.pack_into(course, HeaderOffset, FileOffset, blocksize)
if blocksize > 0:
course[FileOffset:FileOffset + blocksize] = block
HeaderOffset += 8
FileOffset += blocksize
self.course = bytes(course)
self.L0 = self.SaveLayer(0)
self.L1 = self.SaveLayer(1)
self.L2 = self.SaveLayer(2)
return (self.course, self.L0, self.L1, self.L2)
def RemoveFromLayer(self, obj):
"""
Removes a specific object from the level and updates Z-indices accordingly
"""
layer = self.layers[obj.layer]
idx = layer.index(obj)
del layer[idx]
for upd in layer[idx:]:
upd.setZValue(upd.zValue() - 1)
def SortSpritesByZone(self):
"""
Sorts the sprite list by zone ID so it will work in-game
"""
def compKey(zonelist, sprite):
id_ = SLib.MapPositionToZoneID(zonelist, sprite.objx, sprite.objy)
sprite.zoneID = zonelist[id_].id if id_ != -1 else -1
return id_
self.sprites.sort(key = lambda s: compKey(self.zones, s))
def LoadReggieInfo(self, data):
if not data:
self.Metadata = Metadata()
return
try:
self.Metadata = Metadata(data)
except Exception:
self.Metadata = Metadata() # fallback
def LoadBlocks(self, course):
"""
Loads self.blocks from the course file
"""
self.blocks = [None] * 14
getblock = struct.Struct('>II')
for i in range(14):
start, length = getblock.unpack_from(course, i * 8)
self.blocks[i] = course[start:start + length]
self.block1pos = getblock.unpack_from(course, 0)
def LoadTilesetNames(self):
"""
Loads block 1, the tileset names
"""
data = struct.unpack('>32s32s32s32s', self.blocks[0])
self.tileset0 = data[0].strip(b'\0').decode('latin-1')
self.tileset1 = data[1].strip(b'\0').decode('latin-1')
self.tileset2 = data[2].strip(b'\0').decode('latin-1')
self.tileset3 = data[3].strip(b'\0').decode('latin-1')
def LoadOptions(self):
"""
Loads block 2, the general options
"""
data = struct.unpack('>IIHh?BxxB?Bx', self.blocks[1])
defEventsA, defEventsB, wrapByte, self.timeLimit, self.creditsFlag, unkVal, self.startEntrance, self.ambushFlag, self.toadHouseType = data
self.wrapFlag = bool(wrapByte & 1)
self.unkFlag1 = bool(wrapByte >> 3)
self.unkFlag2 = unkVal == 100
self.defEvents = defEventsA | defEventsB << 32
"""
Loads block 4, the unknown maybe-more-general-options block + extended settings
"""
optdata2 = self.blocks[3][:8]
optdata2struct = struct.Struct('>xxHHxx')
data = optdata2struct.unpack(optdata2)
self.unkVal1, self.unkVal2 = data
def LoadOneSetting(data):
length = struct.unpack('>I', data[:4])[0]
settingArray = []
for i in range(length):
settingArray.append(data[4+4*i:8+4*i])
return settingArray
self.spriteSettings = []
if len(self.blocks[3]) <= 8:
amountOfSettings = 0
else:
amountOfSettings = struct.unpack('>I', self.blocks[3][8:12])[0]
for i in range(amountOfSettings):
offset = struct.unpack('>I', self.blocks[3][12+4*i:16+4*i])[0]
setting = LoadOneSetting(self.blocks[3][offset:])
self.spriteSettings.append(setting)
def LoadEntrances(self):
"""
Loads block 7, the entrances
"""
entdata = self.blocks[6]
entstruct = struct.Struct('>HHxxxxBBBBxBBBHBB')
entrances = []
for offset in range(0, len(entdata), 20):
data = entstruct.unpack_from(entdata, offset)
entrances.append(EntranceItem(*data))
self.entrances = entrances
def LoadSprites(self):
"""
Loads block 8, the sprites. This needs to be called after
'LoadLoadedSprites', because this relies on the loaded sprite ids being
loaded for calculating the sprites that are forced to load.
"""
spritedata = self.blocks[7]
sprstruct = struct.Struct('>HHH8sxx')
sprites = []
unpack = sprstruct.unpack_from
append = sprites.append
obj = SpriteItem
# Ignore the last 4 bytes because they are always 0xFFFFFFFF
for offset in range(0, len(spritedata) - 4, 16):
data = unpack(spritedata, offset)
type_, x, y, sd = data
is_extended = globals_.Sprites[type_].extendedSettings
extended_id = int.from_bytes(sd[2:6], 'big')
extended_settings = self.spriteSettings[extended_id] if is_extended else []
append(
obj(
type_,
x,
y,
RawData(
sd,
*extended_settings,
format = RawData.Format.Extended if is_extended else RawData.Format.Vanilla,
)
)
)
self.sprites = sprites
self.force_loaded_sprites = self.loaded_sprites - set(sprite.type for sprite in sprites)
# Adjust block counts for extended sprites
for sprite in self.sprites:
sprite: SpriteItem # type hint
sprite.spritedata.fix_size_if_needed(sprite.type)
def LoadLoadedSprites(self):
"""
Loads block 9, the loaded sprite resources.
"""
self.loaded_sprites = set()
loading_data = self.blocks[8]
struct_ = struct.Struct('>Hxx')
for offset in range(0, len(loading_data), 4):
sprite_id, = struct_.unpack_from(loading_data, offset)
self.loaded_sprites.add(sprite_id)
def LoadZones(self):
"""
Loads block 3, the bounding preferences
"""
bdngdata = self.blocks[2]
bdngstruct = struct.Struct('>4lHHhh')
bounding = []
for offset in range(0, len(bdngdata), 24):
data = bdngstruct.unpack_from(bdngdata, offset)
bounding.append(data)
self.bounding = bounding
"""
Loads block 5, the top level background values
"""
bgAdata = self.blocks[4]
bgAstruct = struct.Struct('>xBhhhhHHHxxxBxxxx')
bgA = []
for offset in range(0, len(bgAdata), 24):
data = bgAstruct.unpack_from(bgAdata, offset)
bgA.append(data)
self.bgA = bgA
"""
Loads block 6, the bottom level background values
"""
bgBdata = self.blocks[5]
bgBstruct = struct.Struct('>xBhhhhHHHxxxBxxxx')
bgB = []
for offset in range(0, len(bgBdata), 24):
data = bgBstruct.unpack_from(bgBdata, offset)
bgB.append(data)
self.bgB = bgB
"""
Loads block 10, the zone data
"""
zonedata = self.blocks[9]
zonestruct = struct.Struct('>HHHHHHBBBBxBBBBxBB')
zones = []
for offset in range(0, len(zonedata), 24):
dataz = zonestruct.unpack_from(zonedata, offset)
zones.append(ZoneItem(*dataz, bounding, bgA, bgB, offset // 24))
self.zones = zones
def LoadLocations(self):
"""
Loads block 11, the locations
"""
locdata = self.blocks[10]
locstruct = struct.Struct('>HHHHBxxx')
locations = []
for offset in range(0, len(locdata), 12):
data = locstruct.unpack_from(locdata, offset)
locations.append(LocationItem(*data))
self.locations = locations
def LoadLayer(self, idx, layerdata):
"""
Loads a specific object layer from a string
"""
objstruct = struct.Struct('>HHHHH')
z = (2 - idx) * 8192
append = self.layers[idx].append
obj = ObjectItem
unpack = objstruct.unpack_from
# Ignore the last 2 bytes, because they are always 0xFFFF.
for offset in range(0, len(layerdata) - 2, 10):
data = unpack(layerdata, offset)
append(obj(data[0] >> 12, data[0] & 4095, idx, *data[1:], z))
z += 1
def LoadCamProfiles(self):
"""
Loads block 12, the camera profiles
"""
profiledata = self.blocks[11]
profilestruct = struct.Struct('>xxxxxxxxxxxxBBBBxxBx')
offset = 0
camprofiles = []
for offset in range(0, len(profiledata), 20):
data = profilestruct.unpack_from(profiledata, offset)
if offset > 0 or any(data):
camprofiles.append([data[4], data[1], data[2]])
self.camprofiles = camprofiles
def LoadPaths(self):
"""
Loads blocks 13 and 14, the paths and path nodes
"""
pathdata = self.blocks[12]
pathstruct = struct.Struct('>BxHHH')
unpack = pathstruct.unpack_from
paths = []
from levelitems import Path
for offset in range(0, len(pathdata), 8):
data = unpack(pathdata, offset)
nodes = self.LoadPathNodes(data[1], data[2])
path = Path(int(data[0]), globals_.mainWindow.scene, data[3] == 2)
for node in nodes:
path.add_node(node['x'], node['y'], node['speed'], node['accel'], node['delay'], add_to_scene=False)
paths.append(path)
self.paths = paths
def LoadPathNodes(self, startindex, count):
"""
Loads block 14, the path nodes
"""
nodes = []
nodedata = self.blocks[13]
nodestruct = struct.Struct('>HHffhxx')
unpack = nodestruct.unpack_from
for offset in range(startindex * 16, (startindex + count) * 16, 16):
data = unpack(nodedata, offset)
nodes.append({
'x': int(data[0]),
'y': int(data[1]),
'speed': float(data[2]),
'accel': float(data[3]),
'delay': int(data[4])
})
return nodes
def LoadComments(self):
"""
Loads the comments from self.Metadata
"""
self.comments = []
data = self.Metadata.binData('InLevelComments_A%d' % self.areanum)
if data is None:
return
idx = 0
while idx < len(data):
xpos, ypos, tlen_maybe = struct.unpack_from(">3I", data, idx)
idx += 3 * 4
if tlen_maybe == 0xFFFF_FFFF:
# Updated version - the number of code points is stored in the
# next int.
tlen, = struct.unpack_from(">I", data, idx)
text = data[idx + 4: idx + 4 + tlen].decode("utf-8")
idx += 4 + tlen
else:
# Old version provided for compatibility. Also tries to properly
# load non-ascii comments, but that might not work out...
tlen = tlen_maybe
try:
text = data[idx: idx + tlen].decode("ascii")
idx += tlen
except UnicodeDecodeError:
# You used non-ascii characters... Try to save the comment
# The xpos is probably not > 2 ** 24, so the next comment
# starts with a null byte. We can use that to find the end
# of our string
null_idx = data.find(b"\0", idx)
if null_idx == -1:
# This is probably the last comment...
null_idx = len(data)
text = data[idx: null_idx].decode("utf-8")[:tlen]
idx = null_idx
com = CommentItem(xpos, ypos, text)
com.listitem = QtWidgets.QListWidgetItem()
self.comments.append(com)
com.UpdateListItem()
def SaveTilesetNames(self):
"""
Saves the tileset names back to block 1
"""
self.blocks[0] = struct.pack('>32s32s32s32s',
self.tileset0.encode('latin-1'),
self.tileset1.encode('latin-1'),
self.tileset2.encode('latin-1'),
self.tileset3.encode('latin-1')
)
def SaveOptions(self):
"""
Saves block 2, the general options
"""
wrapByte = 1 if self.wrapFlag else 0
if self.unkFlag1: wrapByte |= 8
unkVal = 100 if self.unkFlag2 else 0
self.blocks[1] = struct.pack('>IIHh?BBBB?Bx',
self.defEvents & 0xFFFFFFFF, self.defEvents >> 32, wrapByte,
self.timeLimit, self.creditsFlag, unkVal, unkVal, unkVal,
self.startEntrance, self.ambushFlag, self.toadHouseType
)
"""
Saves block 4, the unknown maybe-more-general-options block + extended settings
"""
self.spriteSettings = []
for sprite in self.sprites:
sprite: SpriteItem # type hint
if sprite.spritedata.format == RawData.Format.Extended:
sprite.spritedata.original = sprite.spritedata[0:2] + len(self.spriteSettings).to_bytes(4, 'big') + sprite.spritedata[6:]
self.spriteSettings.append(sprite.spritedata.optimized.blocks)
self.blocks[3] = struct.pack('>xxHHxx', self.unkVal1, self.unkVal2)
def SaveOneSetting(length, settingArray):
data = struct.pack('>I', length)
for sett in settingArray:
data += sett
return data
if len(self.spriteSettings) > 0:
data = struct.pack('>I', len(self.spriteSettings))
settings = []
offsets = []
currentOffset = 12 + 4 * len(self.spriteSettings)
for setting in self.spriteSettings:
oneSetting = SaveOneSetting(len(setting), setting)
settings.append(oneSetting)
offsets.append(currentOffset)
currentOffset += len(oneSetting)
for i in range(len(self.spriteSettings)):
data += struct.pack('>I', offsets[i])
for i in range(len(self.spriteSettings)):
data += settings[i]
self.blocks[3] += data
def SaveLayer(self, idx):
"""
Saves an object layer to a string
"""
layer = self.layers[idx]
if not layer:
# Don't create a layer file for an empty layer.
return None
offset = 0
objstruct = struct.Struct('>HHHHH')
buffer = bytearray((len(layer) * 10) + 2)
f_int = int
for obj in layer:
objstruct.pack_into(buffer,
offset,
f_int((obj.tileset << 12) | obj.type),
f_int(obj.objx),
f_int(obj.objy),
f_int(obj.width),
f_int(obj.height))
offset += 10
buffer[offset] = 0xFF
buffer[offset + 1] = 0xFF
return bytes(buffer)
def SaveEntrances(self):
"""
Saves the entrances back to block 7
"""
offset = 0
entstruct = struct.Struct('>HHxxxxBBBBxBBBHBB')
buffer = bytearray(len(self.entrances) * 20)
f_MapPositionToZoneID = SLib.MapPositionToZoneID
zonelist = self.zones
for entrance in self.entrances:
zoneID = f_MapPositionToZoneID(zonelist, entrance.objx, entrance.objy, True)
if zoneID == -1:
# No zone was found in the level.
# Pretend the entrance belongs to zone 0, even though this zone
# does not exist. The level won't work in-game anyway, because
# there are no zones. This default allows users to save areas
# without zones, so it adds greater flexibility.
zoneID = 0
entstruct.pack_into(buffer, offset, int(entrance.objx), int(entrance.objy),
int(entrance.entid), int(entrance.destarea), int(entrance.destentrance),
int(entrance.enttype), zoneID, int(entrance.entlayer), int(entrance.entpath),
int(entrance.entsettings), int(entrance.leave_level), int(entrance.cpdirection))
offset += 20
self.blocks[6] = bytes(buffer)
def SavePaths(self):
"""
Saves the paths back to block 13
"""
pathstruct = struct.Struct('>BxHHH')
nodecount = sum(len(path) for path in self.paths)
nodebuffer = bytearray(nodecount * 16)
nodeoffset = 0
nodeindex = 0
offset = 0
buffer = bytearray(len(self.paths) * 8)
for path in self.paths:
if not len(path):
continue
self.WritePathNodes(nodebuffer, nodeoffset, path)
pathstruct.pack_into(buffer, offset, path._id, nodeindex, len(path), 2 if path._loops else 0)
offset += 8
nodeoffset += len(path) * 16
nodeindex += len(path)
self.blocks[12] = bytes(buffer[:offset])
self.blocks[13] = bytes(nodebuffer)
def WritePathNodes(self, buffer, offset, path):
"""
Writes the path node data to the block 14 bytearray
"""
nodestruct = struct.Struct('>HHffhxx')
for i in range(len(path)):
nodestruct.pack_into(buffer, offset, *path.get_node_data(i))
offset += 16
def SaveSprites(self):
"""
Saves the sprites back to block 8
"""
offset = 0
sprstruct = struct.Struct('>HHH6sBcxx')
buffer = bytearray((len(self.sprites) * 16) + 4)
f_int = int
for sprite in self.sprites:
if sprite.zoneID == -1:
# No zone was found in the area.
# Pretend the sprite belongs to zone 0, even though this zone
# does not exist. The area won't work in-game anyway, because
# there are no zones. This default allows users to save areas
# without zones, so it adds greater flexibility.
sprite.zoneID = 0
try:
sprstruct.pack_into(buffer, offset, f_int(sprite.type) % 0xFFFF, f_int(sprite.objx), f_int(sprite.objy),
sprite.spritedata[:6], sprite.zoneID, bytes([sprite.spritedata[7]]))
except:
# Hopefully this will solve the mysterious bug, and will
# soon no longer be necessary.
raise ValueError('SaveSprites struct.error. Current sprite data dump:\n' + \
str(offset) + '\n' + \
str(sprite.type) + '\n' + \
str(sprite.objx) + '\n' + \
str(sprite.objy) + '\n' + \
str(sprite.spritedata[:6]) + '\n' + \