-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathmisc.py
More file actions
1862 lines (1477 loc) · 67.2 KB
/
misc.py
File metadata and controls
1862 lines (1477 loc) · 67.2 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
from PyQt6 import QtCore, QtWidgets, QtGui
import collections
import itertools
import sys
import os
from xml.etree import ElementTree
################################################################################
################################################################################
################################################################################
import globals_
from ui import GetIcon, ReggieTheme, clipStr
from dirty import setting, setSetting
from dialogs import DiagnosticToolDialog
from translation import ReggieTranslation
from libs import lh
from misc2 import LevelViewWidget
from levelitems import Path, CommentItem
################################################################################
################################################################################
################################################################################
def module_path():
"""
This will get us the program's directory, even if we are frozen using
PyInstaller.
"""
if hasattr(sys, 'frozen') and hasattr(sys, '_MEIPASS'): # PyInstaller
if sys.platform == 'darwin': # macOS
# sys.executable is /x/y/z/reggie.app/Contents/MacOS/reggie
# We need to return /x/y/z/reggie.app/Contents/Resources/
macos = os.path.dirname(sys.executable)
if os.path.basename(macos) != 'MacOS':
return None
return os.path.join(os.path.dirname(macos), 'Resources')
else: # Windows, Linux
return os.path.dirname(sys.executable)
if __name__ == 'misc':
return os.path.dirname(os.path.abspath(__file__))
return None
def checkContent(data):
if not data.startswith(b'U\xAA8-'):
return False
required = (b'course\0', b'course1.bin\0', b'\0\0\0\x80')
for r in required:
if r not in data:
return False
return True
def IsNSMBLevel(filename):
"""
Does some basic checks to confirm a file is a NSMB level
"""
if not os.path.isfile(filename): return False
with open(filename, 'rb') as f:
data = f.read()
if (data[0] & 0xF0) == 0x40 or not data.startswith(b"U\xAA8-"): # If LH-compressed or LZ-compressed
return True
return checkContent(data)
def FilesAreMissing():
"""
Checks to see if any of the required files for Reggie are missing
"""
if not os.path.isdir('reggiedata'):
QtWidgets.QMessageBox.warning(None, globals_.trans.string('Err_MissingFiles', 0), globals_.trans.string('Err_MissingFiles', 1))
return True
required = ['icon.png', 'about.png', ]
missing = []
for check in required:
if not os.path.isfile(os.path.join('reggiedata', check)):
missing.append(check)
if missing:
QtWidgets.QMessageBox.warning(None, globals_.trans.string('Err_MissingFiles', 0),
globals_.trans.string('Err_MissingFiles', 2, '[files]', ', '.join(missing)))
return True
return False
def SetGamePaths(new_stage_path, new_texture_path):
"""
Sets the NSMBW game path
"""
# os.path.join crashes if QStrings are used, so we must change the paths to
# a Python string manually
globals_.gamedef.SetStageGamePath(str(new_stage_path))
globals_.gamedef.SetTextureGamePath(str(new_texture_path))
def areValidGamePaths(stage_check='ug', texture_check='ug'):
"""
Checks to see if the path for NSMBW contains a valid game
"""
if stage_check == 'ug':
stage_check = globals_.gamedef.GetStageGamePath()
if texture_check == 'ug':
texture_check = globals_.gamedef.GetTextureGamePath()
if not stage_check or not texture_check:
return False
# Check that both the stage and texture folders exist
if not os.path.isdir(stage_check) or not os.path.isdir(texture_check):
return False
# Check that a readable 01-01 file is located in the stage folder
for ext in globals_.FileExtentions:
if os.path.isfile(os.path.join(stage_check, "01-01" + ext)):
return True
return False
def getResourcePaths(res_name):
"""
Returns an iterable containing the paths that have the specified resource.
The paths are included in order from general to specific. That is, the base
comes before the patch.
"""
# To make sure that the gamedef is translatable as well, we first need to
# figure out what paths the gamedef loads its files from
gamedef_files, is_patch, gamedef_names = globals_.gamedef.recursiveFiles(res_name)
# Then, we ask the current translation to give a path for each of those
# gamedefs. If there is no translation for a specific resource and gamedef,
# the corresponding entry will have the value 'None'.
trans_files = globals_.trans.paths(res_name, gamedef_names)
# Combine the gamedef_files and trans_files lists to get them in the right
# order.
# [gamedef_files[0], trans_files[0], ..., gamedef[i], trans_files[i]]
# If any entry (gamedef or translation) has no value, it will have None. As
# such, we also need to filter out the None values from the final iterable.
return filter(lambda x: x is not None, itertools.chain.from_iterable(zip(gamedef_files, trans_files)))
def LoadLevelNames():
"""
Ensures that the level name info is loaded
"""
for path in getResourcePaths('levelnames'):
tree = ElementTree.parse(path)
root = tree.getroot()
# Parse the nodes (root acts like a large category)
globals_.LevelNames = LoadLevelNames_Category(root)
def LoadLevelNames_Category(node):
"""
Loads a LevelNames XML category
"""
cat = []
for child in node:
if child.tag.lower() == 'category':
cat.append((str(child.attrib['name']), LoadLevelNames_Category(child)))
elif child.tag.lower() == 'level':
cat.append((str(child.attrib['name']), str(child.attrib['file'])))
return tuple(cat)
def LoadTilesetNames(reload_=False):
"""
Ensures that the tileset name info is loaded
"""
if (globals_.TilesetNames is not None) and (not reload_): return
# Get paths
paths = getResourcePaths('tilesets')
# Read each file
globals_.TilesetNames = [[[], False], [[], False], [[], False], [[], False]]
for path in paths:
tree = ElementTree.parse(path)
root = tree.getroot()
# Go through each slot
for node in root:
if node.tag.lower() != 'slot': continue
try:
slot = int(node.attrib['num'])
except ValueError:
continue
if slot > 3: continue
# Parse the category data into a list
newlist = [LoadTilesetNames_Category(node), ]
if 'sorted' in node.attrib:
newlist.append(node.attrib['sorted'].lower() == 'true')
else:
newlist.append(globals_.TilesetNames[slot][1]) # inherit
# Apply it as a patch over the current entry
newlist[0] = CascadeTilesetNames_Category(globals_.TilesetNames[slot][0], newlist[0])
# Sort it
if not newlist[1]:
newlist[0] = SortTilesetNames_Category(newlist[0])
globals_.TilesetNames[slot] = newlist
def LoadTilesetNames_Category(node):
"""
Loads a TilesetNames XML category
"""
cat = []
for child in node:
if child.tag.lower() == 'category':
new = [
str(child.attrib['name']),
LoadTilesetNames_Category(child),
]
if 'sorted' in child.attrib:
new.append(str(child.attrib['sorted'].lower()) == 'true')
else:
new.append(False)
cat.append(new)
elif child.tag.lower() == 'tileset':
fname = str(child.attrib['filename'])
cat.append((fname, str(child.attrib['name'])))
# read override attribute
if 'override' not in child.attrib:
continue
# override present, add it to the correct type
type_ = str(child.attrib['override'])
if type_ not in globals_.OverriddenTilesets:
raise ValueError("Unknown override type '%s' for tileset '%s'" % (type_, fname))
globals_.OverriddenTilesets[type_].add(fname)
return list(cat)
def CascadeTilesetNames_Category(lower, upper):
"""
Applies upper as a patch of lower
"""
lower = list(lower)
for item in upper:
if isinstance(item[1], tuple) or isinstance(item[1], list):
# It's a category
found = False
for i, lowitem in enumerate(lower):
lowitem = lower[i]
if lowitem[0] == item[0]: # names are ==
lower[i] = list(lower[i])
lower[i][1] = CascadeTilesetNames_Category(lowitem[1], item[1])
found = True
break
if not found:
i = 0
while (i < len(lower)) and (isinstance(lower[i][1], tuple) or isinstance(lower[i][1], list)): i += 1
lower.insert(i + 1, item)
else: # It's a tileset entry
found = False
for i, lowitem in enumerate(lower):
lowitem = lower[i]
if lowitem[0] == item[0]: # filenames are ==
lower[i] = list(lower[i])
lower[i][1] = item[1]
found = True
break
if not found: lower.append(item)
return lower
def SortTilesetNames_Category(cat):
"""
Sorts a tileset names category
"""
cat = list(cat)
# First, remove all category nodes
cats = []
for node in cat:
if isinstance(node[1], tuple) or isinstance(node[1], list):
cats.append(node)
for node in cats: cat.remove(node)
# Sort the tileset names
cat.sort(key=lambda entry: entry[1])
# Sort the data within each category
for i, cat_ in enumerate(cats):
cats[i] = list(cat_)
if not cats[i][2]: cats[i][1] = SortTilesetNames_Category(cats[i][1])
# Put them back together
new = []
for category in cats: new.append(tuple(category))
for tileset in cat: new.append(tuple(tileset))
return tuple(new)
def LoadObjDescriptions(reload_=False):
"""
Ensures that the object description is loaded
"""
if (globals_.ObjDesc is not None) and not reload_: return
paths = getResourcePaths('ts1_descriptions')
globals_.ObjDesc = {}
for path in paths:
with open(path, 'r', encoding='utf-8') as f:
raw = [x.strip() for x in f.readlines()]
for line in raw:
w = line.split('=')
globals_.ObjDesc[int(w[0])] = w[1]
def LoadBgANames(reload_=False):
"""
Ensures that the background name info is loaded
"""
if (globals_.BgANames is not None) and not reload_: return
paths = getResourcePaths('bga')
globals_.BgANames = []
for path in paths:
with open(path, 'r', encoding='utf-8') as f:
raw = [x.strip() for x in f.readlines()]
for line in raw:
w = line.split('=')
found = False
for check in globals_.BgANames:
if check[0] == w[0]:
check[1] = w[1]
found = True
if not found: globals_.BgANames.append([w[0], w[1]])
globals_.BgANames.sort(key=lambda entry: int(entry[0], 16))
def LoadBgBNames(reload_=False):
"""
Ensures that the background name info is loaded
"""
if (globals_.BgBNames is not None) and not reload_: return
paths = getResourcePaths('bgb')
globals_.BgBNames = []
for path in paths:
with open(path, 'r', encoding='utf-8') as f:
raw = [x.strip() for x in f.readlines()]
for line in raw:
w = line.split('=')
found = False
for check in globals_.BgBNames:
if check[0] == w[0]:
check[1] = w[1]
found = True
if not found: globals_.BgBNames.append([w[0], w[1]])
globals_.BgBNames.sort(key=lambda entry: int(entry[0], 16))
def LoadZoneThemes(reload_=False):
"""
Ensures that custom zone themes get loaded
"""
if (globals_.ZoneThemeValues is not None) and not reload_: return
paths = getResourcePaths('zonethemes')
for path in paths:
with open(path, 'r', encoding='utf-8') as f:
globals_.ZoneThemeValues = [x.strip() for x in f]
class SpriteDefinition:
"""
Stores and manages the data info for a specific sprite
"""
class ListPropertyModel(QtCore.QAbstractListModel):
"""
Contains all the possible values for a list property on a sprite
"""
def __init__(self, entries):
"""
Constructor
"""
QtCore.QAbstractListModel.__init__(self)
self.entries = entries
def rowCount(self, parent=None):
"""
Required by Qt
"""
return len(self.entries)
def data(self, index, role=QtCore.Qt.ItemDataRole.DisplayRole):
"""
Get what we have for a specific row
"""
if not index.isValid() or role != QtCore.Qt.ItemDataRole.DisplayRole:
return None
n = index.row()
if not 0 <= n < len(self.entries):
return None
return '%d: %s' % self.entries[n]
def loadFrom(self, elem):
"""
Loads in all the field data from an XML node
"""
self.fields = []
fields = self.fields
allowed = ['checkbox', 'list', 'value', 'bitfield', 'multibox', 'dualbox',
'dependency', 'external', 'multidualbox']
for field in elem:
if field.tag not in allowed:
continue
attribs = field.attrib
if field.tag == 'dualbox':
title = attribs['title1'] + " / " + attribs['title2']
elif field.tag == 'multidualbox':
title = attribs['title1'] + " / " + attribs['title2']
elif 'title' in attribs:
title = attribs['title']
else:
title = globals_.trans.string('SpriteDataEditor', 28)
advanced = attribs.get("advanced", "False") == "True"
comment = comment2 = advancedcomment = required = idtype = None
if 'comment' in attribs:
comment = globals_.trans.string('SpriteDataEditor', 1, '[name]', title, '[note]', attribs['comment'])
if 'comment2' in attribs:
comment2 = globals_.trans.string('SpriteDataEditor', 1, '[name]', title, '[note]', attribs['comment2'])
if 'advancedcomment' in attribs:
advancedcomment = globals_.trans.string('SpriteDataEditor', 1, '[name]', title, '[note]', attribs['advancedcomment'])
if 'requirednybble' in attribs:
bit_ranges, _ = self.parseBits(attribs.get("requirednybble"))
required = []
if 'requiredval' in attribs:
vals = attribs['requiredval'].split(",")
if len(bit_ranges) != len(vals):
raise ValueError("Required bits and vals have different lengths.")
else:
vals = [None] * len(bit_ranges)
# The associated values are a comma-separated list of values or
# (inclusive) ranges.
for bit_range, sval in zip(bit_ranges, vals):
if sval is None:
a = 1
b = (1 << (bit_range[1] - bit_range[0] + 1)) - 1
elif '-' not in sval:
a = b = int(sval)
else:
a, b = map(int, sval.split('-'))
required.append(((bit_range,), (a, b + 1)))
if 'idtype' in attribs:
idtype = attribs['idtype']
if field.tag not in {'value', 'list'}:
raise ValueError("Only values and lists support idtypes.")
# Parse the remaining type-specific attributes.
if field.tag == 'checkbox':
bit, _ = self.parseBits(attribs.get("nybble"))
mask = int(attribs.get('mask', 1))
fields.append((0, attribs['title'], bit, mask, comment, required, advanced, comment2, advancedcomment))
elif field.tag == 'list':
bit, _ = self.parseBits(attribs.get("nybble"))
entries = []
for e in field:
if e.tag != 'entry': continue
entries.append((int(e.attrib['value']), e.text))
model = SpriteDefinition.ListPropertyModel(entries)
fields.append((1, title, bit, model, comment, required, advanced, comment2, advancedcomment, idtype))
elif field.tag == 'value':
bit, max_ = self.parseBits(attribs.get("nybble"))
fields.append((2, attribs['title'], bit, max_, comment, required, advanced, comment2, advancedcomment, idtype))
elif field.tag == 'bitfield':
startbit = int(attribs['startbit'])
bitnum = int(attribs['bitnum'])
fields.append((3, attribs['title'], startbit, bitnum, comment, required, advanced, comment2, advancedcomment))
elif field.tag == 'multibox':
bit, _ = self.parseBits(attribs.get("nybble"))
fields.append((4, attribs['title'], bit, comment, required, advanced, comment2, advancedcomment))
elif field.tag == 'dualbox':
bit, _ = self.parseBits(attribs.get("nybble"))
fields.append((5, attribs['title1'], attribs['title2'], bit, comment, required, advanced, comment2, advancedcomment))
elif field.tag == 'dependency':
type_dict = {'required': 0, 'suggested': 1}
for entry in field:
if entry.attrib['sprite'] == "":
continue
self.dependencies.append((int(entry.attrib['sprite']), type_dict[entry.tag]))
self.dependencynotes = attribs.get('notes')
elif field.tag == 'external':
# Uses a list from an external resource. This is used for big
# lists like actors, sound effects etc.
bit, _ = self.parseBits(attribs.get("nybble"))
type_ = attribs['type']
fields.append((6, title, bit, comment, required, advanced, comment2, advancedcomment, type_))
elif field.tag == 'multidualbox':
# multibox but with dualboxes instead of checkboxes
bit, _ = self.parseBits(attribs.get("nybble"))
fields.append((7, attribs['title1'], attribs['title2'], bit, comment, required, advanced, comment2, advancedcomment))
def parseBits(self, nybble_val):
"""
Parses a description of the bits a setting affects into a tuple of a
list of ranges and the number of possible values. Ranges include the
start and exclude the end. The most significant bit is considered 1.
Precise bits can be specified by adding a period after the number,
followed by a number from 1 to 4, where 1 is the most significant bit in
a nybble, and 4 the least significant bit.
Raises a ValueError if 'nybble_val' is None or if any of the specified
ranges refer to bits that are not in the first 8 bytes.
"""
if nybble_val is None:
raise ValueError("No nybble specification given.")
# The total number of bits that can be controlled.
bit_length = 0
# A list of tuples (start_bit, end_bit) that represent inclusive ranges.
bit_ranges = []
for range_ in nybble_val.split(","):
if "-" in range_:
# Multiple nybbles
a, b = range_.split("-")
else:
# Just a nybble
a = b = range_
if "." in a:
nybble, bits = map(int, a.split("."))
else:
nybble, bits = int(a), 1
a = 4 * (nybble - 1) + bits
if "." in b:
nybble, bits = map(int, b.split("."))
else:
nybble, bits = int(b), 4
b = 4 * (nybble - 1) + bits
# Check if the resulting range would be valid.
if not 1 <= a < b + 1 <= 65:
raise ValueError("Indexed bits out of bounds: " + str(range_) + "->" + str((a, b + 1)))
bit_length += b - a + 1
bit_ranges.append((a, b + 1))
return bit_ranges, 1 << bit_length
def LoadSpriteData():
"""
Ensures that the sprite data info is loaded
"""
errors = []
errortext = []
sprite_ids = [-1]
# Convert the iterable to list, because we need to iterate over it twice
paths = list(getResourcePaths('spritedata'))
for path in paths:
# Add XML sprite data, if there is any
if not isinstance(path, str):
path = path.path
tree = ElementTree.parse(path)
for sprite in tree.iter("sprite"):
id_text = sprite.get("id")
try:
id_ = int(id_text)
except ValueError:
continue
sprite_ids.append(id_)
globals_.NumSprites = max(sprite_ids) + 1
globals_.Sprites = [None] * globals_.NumSprites
for sdpath in paths:
# Add XML sprite data, if there is any
if sdpath in (None, ''):
continue
path = sdpath if isinstance(sdpath, str) else sdpath.path
tree = ElementTree.parse(path)
root = tree.getroot()
for sprite in tree.iter("sprite"):
try:
spriteid = int(sprite.get("id"))
except ValueError:
continue
spritename = sprite.get("name")
notes = None
advNotes = None
relatedObjFiles = None
yoshiNotes = None
attribs = sprite.keys()
if 'notes' in attribs:
notes = globals_.trans.string('SpriteDataEditor', 2, '[notes]', sprite.get('notes'))
if 'advancednotes' in attribs:
advNotes = globals_.trans.string('SpriteDataEditor', 11, '[notes]', sprite.get('advancednotes'))
if 'files' in attribs:
relatedObjFiles = globals_.trans.string('SpriteDataEditor', 8, '[list]',
sprite.get('files').replace(';', '<br>'))
if 'yoshinotes' in attribs:
yoshiNotes = globals_.trans.string('SpriteDataEditor', 9, '[notes]',
sprite.get('yoshinotes'))
noyoshi = sprite.get('noyoshi', 'False') == "True"
asm = sprite.get('asmhacks', 'False') == "True"
size = sprite.get('sizehacks', 'False') == "True"
sdef = SpriteDefinition()
sdef.id = spriteid
sdef.name = spritename
sdef.notes = notes
sdef.advNotes = advNotes
sdef.relatedObjFiles = relatedObjFiles
sdef.yoshiNotes = yoshiNotes
sdef.noyoshi = noyoshi
sdef.asm = asm
sdef.size = size
sdef.dependencies = []
sdef.dependencynotes = None
try:
sdef.loadFrom(sprite)
except Exception as e:
errors.append(str(spriteid))
errortext.append(str(e))
globals_.Sprites[spriteid] = sdef
# Warn the user if errors occurred
if errors:
QtWidgets.QMessageBox.warning(None, globals_.trans.string('Err_BrokenSpriteData', 0),
globals_.trans.string('Err_BrokenSpriteData', 1, '[sprites]', ', '.join(errors)),
QtWidgets.QMessageBox.StandardButton.Ok)
QtWidgets.QMessageBox.warning(None, globals_.trans.string('Err_BrokenSpriteData', 2), repr(errortext))
def LoadSpriteCategories(reload_=False):
"""
Ensures that the sprite category info is loaded
"""
if (globals_.SpriteCategories is not None) and not reload_: return
paths = getResourcePaths('spritecategories')
globals_.SpriteCategories = []
# Add a Search category
globals_.SpriteCategories.append((globals_.trans.string('Sprites', 19), [(globals_.trans.string('Sprites', 16), list(range(globals_.NumSprites)))], []))
globals_.SpriteCategories[-1][1][0][1].append(9999) # 'no results' special case
for path in paths:
tree = ElementTree.parse(path)
root = tree.getroot()
CurrentView = None
for view in root:
if view.tag.lower() != 'view': continue
viewname = view.attrib['name']
# See if it's in there already
CurrentView = []
for potentialview in globals_.SpriteCategories:
if potentialview[0] == viewname: CurrentView = potentialview[1]
if CurrentView == []: globals_.SpriteCategories.append((viewname, CurrentView, []))
CurrentCategory = None
for category in view:
if category.tag.lower() != 'category': continue
catname = category.attrib['name']
# See if it's in there already
CurrentCategory = []
for potentialcat in CurrentView:
if potentialcat[0] == catname: CurrentCategory = potentialcat[1]
if CurrentCategory == []: CurrentView.append((catname, CurrentCategory))
for attach in category:
if attach.tag.lower() != 'attach': continue
sprite = attach.attrib['sprite']
if '-' not in sprite:
if int(sprite) not in CurrentCategory:
CurrentCategory.append(int(sprite))
else:
x = sprite.split('-')
for i in range(int(x[0]), int(x[1]) + 1):
if i not in CurrentCategory:
CurrentCategory.append(i)
def LoadSpriteListData(reload_=False):
"""
Ensures that the sprite list modifier data is loaded
"""
if (globals_.SpriteListData is not None) and not reload_: return
paths = getResourcePaths('spritelistdata')
globals_.SpriteListData = [[] for _ in range(24)]
for path in paths:
with open(path, 'r', encoding='utf-8') as f:
data = f.read()
split = data.replace('\n', '').split(';')
for lineidx in range(24):
line = split[lineidx]
splitline = line.split(',')
# Add them
for item in splitline:
try:
newitem = int(item)
except ValueError:
continue
if newitem in globals_.SpriteListData[lineidx]: continue
globals_.SpriteListData[lineidx].append(newitem)
globals_.SpriteListData[lineidx].sort()
def LoadEntranceNames(reload_=False):
"""
Ensures that the entrance names are loaded
"""
if (globals_.EntranceTypeNames is not None) and not reload_: return
paths = getResourcePaths('entrancetypes')
names = collections.OrderedDict()
for path in paths:
with open(path, 'r', encoding='utf-8') as f:
for line in f.readlines():
id_, name = line.strip().split(':')
names[int(id_)] = name
globals_.EntranceTypeNames = collections.OrderedDict()
for idx in names:
globals_.EntranceTypeNames[idx] = globals_.trans.string('EntranceDataEditor', 28, '[id]', idx, '[name]', names[idx])
def LoadTilesetInfo(reload_=False):
def parseRandom(node, types):
"""Parses all 'random' tags that are a child of the given node"""
randoms = {}
for type_ in node:
# if this uses the 'name' attribute, insert the settings of the type
# and go to the next child
if 'name' in type_.attrib:
name = type_.attrib['name']
randoms.update(types[name])
continue
# [list | range] = input space
if 'list' in type_.attrib:
list_ = list(map(lambda s: int(s, 0), type_.attrib['list'].split(",")))
else:
numbers = type_.attrib['range'].split(",")
# inclusive range
list_ = range(int(numbers[0], 0), int(numbers[1], 0) + 1)
# values = output space [= [list | range] by default]
if 'values' in type_.attrib:
values = list(map(lambda s: int(s, 0), type_.attrib['values'].split(",")))
else:
values = list(list_)[:]
direction = 0
if 'direction' in type_.attrib:
direction_s = type_.attrib['direction']
if direction_s in ['horizontal', 'both']:
direction |= 0b01
if direction_s in ['vertical', 'both']:
direction |= 0b10
else:
direction = 0b11
special = 0
if 'special' in type_.attrib:
special_s = type_.attrib['special']
if special_s == 'double-top':
special = 0b01
elif special_s == 'double-bottom':
special = 0b10
for item in list_:
randoms[item] = [values, direction, special]
return randoms
if (globals_.TilesetInfo is not None) and not reload_:
return
# Convert the iterable to list, because we need to iterate over it twice
paths = list(getResourcePaths('tilesetinfo'))
# go through the types
types = {}
for path in paths:
tree = ElementTree.parse(path)
root = tree.getroot()
for node in root:
if node.tag.lower() == "types":
# read all types
for type_ in node:
name = type_.attrib['name'].strip()
stuff = parseRandom(type_, types)
types[name] = stuff
del tree
del root
# go through the groups
info = {}
for path in paths:
tree = ElementTree.parse(path)
root = tree.getroot()
for node in root:
if node.tag.lower() == "group":
randoms = parseRandom(node, types)
for name in node.attrib['names'].split(","):
name = name.strip()
info[name] = randoms
del tree
del root
globals_.TilesetInfo = info
def LoadMusicInfo(reload_=False):
"""
Uses the current gamedef + translation to load the music data, and saves it
in the MusicInfo global.
"""
if (globals_.MusicInfo is not None) and not reload_:
return
paths = getResourcePaths('music')
songs = {}
for path in paths:
with open(path, 'r', encoding='utf-8') as musicfile:
data = musicfile.read()
del musicfile
# Apply the data
for line in data.split('\n'):
line_items = line.strip().split(':')
if len(line_items) != 2:
# Ignore lines that do not follow the <songid>:<name> format
continue
songid, name = line_items
songs[songid] = name
globals_.MusicInfo = sorted(songs.items(), key=lambda kv: int(kv[0]))
class ChooseLevelNameDialog(QtWidgets.QDialog):
"""
Dialog which lets you choose a level from a list
"""
def __init__(self):
"""
Creates and initializes the dialog
"""
QtWidgets.QDialog.__init__(self)
self.setWindowTitle(globals_.trans.string('OpenFromNameDlg', 0))
self.setWindowIcon(GetIcon('open'))
LoadLevelNames()
self.currentlevel = None
# create the tree
tree = QtWidgets.QTreeWidget()
tree.setColumnCount(1)
tree.setHeaderHidden(True)
tree.setIndentation(16)
tree.currentItemChanged.connect(self.HandleItemChange)
tree.itemActivated.connect(self.HandleItemActivated)
# add items (LevelNames is effectively a big category)
tree.addTopLevelItems(self.ParseCategory(globals_.LevelNames))
# assign it to self.leveltree
self.leveltree = tree
# create the buttons
self.buttonBox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.StandardButton.Ok | QtWidgets.QDialogButtonBox.StandardButton.Cancel)
self.buttonBox.button(QtWidgets.QDialogButtonBox.StandardButton.Ok).setEnabled(False)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
# create the layout