-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodingTools.py
More file actions
2042 lines (1658 loc) · 75.6 KB
/
codingTools.py
File metadata and controls
2042 lines (1658 loc) · 75.6 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
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import os
import time
import zlib
class fileTools:
"""
A class to handle various operations involving files
"""
def ext(filepath):
"""
Returns the extension from the input filename
"""
return os.path.splitext(filepath)[1][1:]
def name(path):
"""
Returns the input filename without a path
"""
return os.path.basename(path)
def nameNoExt(path):
"""
Returns the filename with no extension
"""
return os.path.splitext(os.path.basename(path))[0]
def size(path):
"""
Returns the size of the file referenced by the path
"""
return os.path.getsize(path)
def folder(path):
"""
Returns the folder with no file attached
"""
return os.path.dirname(path)
def outputDirectory(path): #
"""
Takes a file path as input and generates/returns an output directory
"""
outPath = os.getcwd()+"/OUTPUT/"+fileTools.nameNoExt(path)+"/"
if not os.path.exists(outPath):
os.makedirs(outPath)
return outPath
def compress(data):
"""
Compresses data (loaded as bytes) with ZLIB
"""
return zlib.compress(data)
def decompress(data):
"""
Decompresses ZLIB-compressed data
"""
return zlib.decompress(data)
def scanForBytes(path, string):
"""
Reads an entire file into memory and checks it for a byte string
Returns: True or False, string offset if found
Format: scanForBytes(file path, byte string)
"""
with open(path, 'rb') as file:
content = file.read()
offset = content.find(string)
return string in content, offset
def scanForAllBytes(path, byte_string):
"""
Reads an entire file into memory and checks it for all occurrences of a byte string.
Returns: List of offsets where the string is found.
Format: scanForAllBytes(file path, byte string)
"""
with open(path, 'rb') as file:
content = file.read()
offsets = []
index = content.find(byte_string)
while index != -1:
offsets.append(index)
index = content.find(byte_string, index + 1) # Continue searching after the last occurrence
return offsets if offsets else None # Returns None if no matches are found
def scanForBytesUpTo(path, string, end):
"""
Reads part of a file (from the beginning) into memory and checks
it for a byte string.
Returns: True or False, string offset if found
Format: scanForBytesUpTo(file path, byte string, read length)
"""
with open(path, 'rb') as file:
content = file.read(end)
offset = content.find(string)
return string in content, offset
def scanForBytesInRange(path, string, start, end):
"""
Reads part of a file (from the specified start offset to the specified end offset)
into memory and checks it for a byte string.
Returns: True or False, string offset if found
Format: scanForBytesInRange(file path, byte string, start offset, end offset)
"""
with open(path, 'rb') as file:
file.seek(start)
content = file.read(end-start)
offset = content.find(string)
return string in content, offset
def getZeroTerminatedString(file, offset):
"""
Gets any zero-terminated string at any given offset
"""
string = ""
scan = b''
with open(file, "rb") as fileWithString:
fileWithString.seek(offset)
while scan != b'\x00':
scan = fileWithString.read(1)
if scan != b'\x00':
string = string+scan.decode("UTF-8")
return string
def writeNewBinaryFile(file, data): #For use when writing a single chunk of data to a new binary file
with open(file, "w+b") as outputFile:
outputFile.write(data)
def writeNewTextFile(file, data): #For use when writing text to a new file
with open(file, "w+") as outputFile:
outputFile.write(data)
class dialogs:
"""
You can quickly open a dialog with this class
"""
def file():
"""
Opens a file dialog and returns a single file path after you select it
"""
root = tk.Tk()
root.withdraw()
file = filedialog.askopenfilename()
root.destroy()
return file
def files():
"""
Opens a file dialog and returns a list of file paths after you select them
"""
root = tk.Tk()
root.withdraw()
files = filedialog.askopenfilenames()
root.destroy()
return files
def folder():
"""
Opens a file dialog and returns the path after you select a folder
"""
root = tk.Tk()
root.withdraw()
folder = filedialog.askdirectory()
root.destroy()
return folder
def listedFolder():
"""
Opens a file dialog and returns the path contents after you select a folder
"""
root = tk.Tk()
root.withdraw()
folder = filedialog.askdirectory()
root.destroy()
return os.listdir(folder)
def yesno(windowName, message):
"""Creates a yes or no prompt for the user to interact with
format: yesno(windowName, message)
"""
root = tk.Tk()
root.withdraw()
result = messagebox.askyesno(windowName, message)
if result:
return True
else:
return False
class encode:
"""
Has functions for encoding strings
"""
def utf8(data):
return data.encode("UTF-8")
def utf16(data):
return data.encode("UTF-16")
def utf32(data):
return data.encode("UTF-32")
def ascii(data):
return data.encode("ASCII")
class decode:
"""
Has functions for decoding strings
"""
def utf8(data):
return data.decode("UTF-8")
def utf16(data):
return data.decode("UTF-16")
def utf32(data):
return data.decode("UTF-32")
def ascii(data):
return data.decode("ASCII")
class LE_pack:
"""
Has functions for packing a single value
"""
def byte(value):
return struct.pack("<b", value)
def ubyte(value):
return struct.pack("<B", value)
def short(value):
return struct.pack("<h", value)
def ushort(value):
return struct.pack("<H", value)
def int(value):
return struct.pack("<i", value)
def uint(value):
return struct.pack("<I", value)
def long(value):
return struct.pack("<q", value)
def ulong(value):
return struct.pack("<Q", value)
def float(value):
return struct.pack("<f", value)
def double(value):
return struct.pack("<d", value)
class LE_multipack:
"""
Has functions for packing multiple values at once
"""
def byte(values):
return struct.pack("<{}b".format(len(values)), *values)
def ubyte(values):
return struct.pack("<{}B".format(len(values)), *values)
def short(values):
return struct.pack("<{}h".format(len(values)), *values)
def ushort(values):
return struct.pack("<{}H".format(len(values)), *values)
def int(values):
return struct.pack("<{}i".format(len(values)), *values)
def uint(values):
return struct.pack("<{}I".format(len(values)), *values)
def long(values):
return struct.pack("<{}q".format(len(values)), *values)
def ulong(values):
return struct.pack("<{}Q".format(len(values)), *values)
def float(values):
return struct.pack("<{}f".format(len(values)), *values)
def double(values):
return struct.pack("<{}d".format(len(values)), *values)
class LE_unpack:
"""
Has functions for unpacking a single value
"""
def byte(data):
return struct.unpack("<b", data)[0]
def ubyte(data):
return struct.unpack("<B", data)[0]
def short(data):
return struct.unpack("<h", data)[0]
def ushort(data):
return struct.unpack("<H", data)[0]
def s24(data):
return int.from_bytes(data, byteorder='little', signed=True)
def u24(data):
return int.from_bytes(data, byteorder='little', signed=False)
def int(data):
return struct.unpack("<i", data)[0]
def uint(data):
return struct.unpack("<I", data)[0]
def long(data):
return struct.unpack("<q", data)[0]
def ulong(data):
return struct.unpack("<Q", data)[0]
def float(data):
return struct.unpack("<f", data)[0]
def double(data):
return struct.unpack("<d", data)[0]
class LE_multiunpack:
"""
Has functions for unpacking multiple values at once
"""
def byte(data):
count = len(data)
return struct.unpack("<{}b".format(count), data)
def ubyte(data):
count = len(data)
return struct.unpack("<{}B".format(count), data)
def short(data):
count = len(data) // 2
return struct.unpack("<{}h".format(count), data)
def ushort(data):
count = len(data) // 2
return struct.unpack("<{}H".format(count), data)
def int(data):
count = len(data) // 4
return struct.unpack("<{}i".format(count), data)
def uint(data):
count = len(data) // 4
return struct.unpack("<{}I".format(count), data)
def long(data):
count = len(data) // 8
return struct.unpack("<{}q".format(count), data)
def ulong(data):
count = len(data) // 8
return struct.unpack("<{}Q".format(count), data)
def float(data):
count = len(data) // 4
return struct.unpack("<{}f".format(count), data)
def double(data):
count = len(data) // 8
return struct.unpack("<{}d".format(count), data)
class BE_pack:
"""
Has functions for packing a single value
"""
def byte(value):
return struct.pack(">b", value)
def ubyte(value):
return struct.pack(">B", value)
def short(value):
return struct.pack(">h", value)
def ushort(value):
return struct.pack(">H", value)
def int(value):
return struct.pack(">i", value)
def uint(value):
return struct.pack(">I", value)
def long(value):
return struct.pack(">q", value)
def ulong(value):
return struct.pack(">Q", value)
def float(value):
return struct.pack(">f", value)
def double(value):
return struct.pack(">d", value)
class BE_multipack:
"""
Has functions for packing multiple values at once
"""
def byte(values):
return struct.pack(">{}b".format(len(values)), *values)
def ubyte(values):
return struct.pack(">{}B".format(len(values)), *values)
def short(values):
return struct.pack(">{}h".format(len(values)), *values)
def ushort(values):
return struct.pack(">{}H".format(len(values)), *values)
def int(values):
return struct.pack(">{}i".format(len(values)), *values)
def uint(values):
return struct.pack(">{}I".format(len(values)), *values)
def long(values):
return struct.pack(">{}q".format(len(values)), *values)
def ulong(values):
return struct.pack(">{}Q".format(len(values)), *values)
def float(values):
return struct.pack(">{}f".format(len(values)), *values)
def double(values):
return struct.pack(">{}d".format(len(values)), *values)
class BE_unpack:
"""
Has functions for unpacking a single value
"""
def byte(data):
return struct.unpack(">b", data)[0]
def ubyte(data):
return struct.unpack(">B", data)[0]
def short(data):
return struct.unpack(">h", data)[0]
def ushort(data):
return struct.unpack(">H", data)[0]
def s24(data):
return int.from_bytes(data, byteorder='big', signed=True)
def u24(data):
return int.from_bytes(data, byteorder='big', signed=False)
def int(data):
return struct.unpack(">i", data)[0]
def uint(data):
return struct.unpack(">I", data)[0]
def long(data):
return struct.unpack(">q", data)[0]
def ulong(data):
return struct.unpack(">Q", data)[0]
def float(data):
return struct.unpack(">f", data)[0]
def double(data):
return struct.unpack(">d", data)[0]
class BE_multiunpack:
"""
Has functions for unpacking multiple values at once
"""
def byte(data):
count = len(data)
return struct.unpack(">{}b".format(count), data)
def ubyte(data):
count = len(data)
return struct.unpack(">{}B".format(count), data)
def short(data):
count = len(data) // 2
return struct.unpack(">{}h".format(count), data)
def ushort(data):
count = len(data) // 2
return struct.unpack(">{}H".format(count), data)
def int(data):
count = len(data) // 4
return struct.unpack(">{}i".format(count), data)
def uint(data):
count = len(data) // 4
return struct.unpack(">{}I".format(count), data)
def long(data):
count = len(data) // 8
return struct.unpack(">{}q".format(count), data)
def ulong(data):
count = len(data) // 8
return struct.unpack(">{}Q".format(count), data)
def float(data):
count = len(data) // 4
return struct.unpack(">{}f".format(count), data)
def double(data):
count = len(data) // 8
return struct.unpack(">{}d".format(count), data)
class magic:
def checkHeader(path, magicBytes):
"""
Checks a file's header for "magic bytes" to see if they match the input byte string
"""
length = len(magicBytes)
with open(path, "rb") as file:
magic = file.read(length)
if magic == magicBytes:
return True
else:
return False
def checkOffset(path, magicBytes, offset):
"""
Checks a file for "magic bytes" at a specified offset to see if they match the input byte string
"""
length = len(magicBytes)
with open(path, "rb") as file:
magic = file.read(length)
if magic == magicBytes:
return True
else:
return False
class BE_BitReader:
def __init__(self, file, offset=0):
"""Initialize BitReader with a file object opened in binary mode ('rb')
Args:
file: File object opened in binary mode
offset (int): Starting byte offset in the file
"""
self.file = file
self.bitBuffer = 0
self.bitsInBuffer = 0
if offset > 0:
self.file.seek(offset)
def read(self, num_bits):
"""Read specified number of bits from the file
Args:
num_bits (int): Number of bits to read
Returns:
int: Value read from the bits
"""
while self.bitsInBuffer < num_bits:
byte = self.file.read(1)
if not byte:
raise EOFError("Reached end of file while reading bits")
self.bitBuffer = (self.bitBuffer << 8) | int.from_bytes(byte, 'big')
self.bitsInBuffer += 8
value = (self.bitBuffer >> (self.bitsInBuffer - num_bits)) & ((1 << num_bits) - 1)
self.bitsInBuffer -= num_bits
return value
def align(self):
"""Align the bit reader to the next byte boundary by discarding remaining bits"""
self.bitBuffer = 0
self.bitsInBuffer = 0
def seek(self, offset):
"""Seek to a specific byte offset in the file
Args:
offset (int): Byte offset to seek to
"""
self.file.seek(offset)
self.bitBuffer = 0
self.bitsInBuffer = 0
def tell(self):
"""Get current position in the file
Returns:
tuple: (byte_offset, bits_into_byte)
- byte_offset is the offset of the last byte read
- bits_into_byte is how many bits we've read into the current byte
"""
byte_pos = self.file.tell()
if self.bitsInBuffer > 0:
complete_bytes = self.bitsInBuffer // 8
byte_pos -= complete_bytes
bits_into_byte = 8 - (self.bitsInBuffer % 8)
if bits_into_byte == 8:
bits_into_byte = 0
else:
bits_into_byte = 0
return (byte_pos, bits_into_byte)
class LE_BitReader:
def __init__(self, file, chunk_size=1, offset=0):
"""Initialize BitReaderLE with a file object opened in binary mode ('rb')
Args:
file: File object opened in binary mode
chunk_size (int): Number of bytes to read at once for each data chunk
offset (int): Starting byte offset in the file
"""
self.file = file
self.chunk_size = chunk_size
self.bitBuffer = 0
self.bitsInBuffer = 0
if offset > 0:
self.file.seek(offset)
def read(self, num_bits):
"""Read specified number of bits from the file in little endian order
Args:
num_bits (int): Number of bits to read
Returns:
int: Value read from the bits
"""
while self.bitsInBuffer < num_bits:
bytes_needed = max(self.chunk_size, (num_bits - self.bitsInBuffer + 7) // 8)
chunk = self.file.read(bytes_needed)
if not chunk:
raise EOFError("Reached end of file while reading bits")
# Process bytes in little endian order
value = int.from_bytes(chunk, 'little')
self.bitBuffer |= value << self.bitsInBuffer
self.bitsInBuffer += len(chunk) * 8
# Extract the requested bits
value = self.bitBuffer & ((1 << num_bits) - 1)
self.bitBuffer >>= num_bits
self.bitsInBuffer -= num_bits
return value
def align(self):
"""Align the bit reader to the next byte boundary by discarding remaining bits"""
remaining_bits = self.bitsInBuffer % 8
if remaining_bits:
self.bitBuffer >>= remaining_bits
self.bitsInBuffer -= remaining_bits
def seek(self, offset):
"""Seek to a specific byte offset in the file
Args:
offset (int): Byte offset to seek to
"""
self.file.seek(offset)
self.bitBuffer = 0
self.bitsInBuffer = 0
def tell(self):
"""Get current position in the file
Returns:
tuple: (byte_offset, bits_into_byte)
- byte_offset is the offset of the last byte read
- bits_into_byte is how many bits we've read into the current byte
"""
byte_pos = self.file.tell()
if self.bitsInBuffer > 0:
complete_bytes = self.bitsInBuffer // 8
byte_pos -= complete_bytes
bits_into_byte = self.bitsInBuffer % 8
else:
bits_into_byte = 0
return (byte_pos, bits_into_byte)
class imageData:
@staticmethod
def maxValueForBits(bits):
"""Calculate the maximum value for a given bit width"""
return (1 << bits) - 1
@staticmethod
def indexedLinear(bits, file, offset, order, x, y):
"""Reads indexed pixel data of the specified bit width from a file
Format: indexed(bits, file, offset, order, x, y)
bits defines how many bits there is per pixel
file defines the file path
offset defines the start offset in the file
order defines the pixel order (0 is linear, 1 is reverse order)
x is the width, y is the height
Returns: A list of integers used to assign colors from a palette to each pixel
"""
#These might be common mistakes. Fix them automatically for the user.
x = max(1, x)
y = max(1, y)
convertedPixels = []
with open(file, "rb") as pixels:
pixels.seek(offset)
pixelReader = BitReader(pixels)
pixels_needed = x * y
convertedPixels = [0] * pixels_needed # Pre-allocate list
idx = 0
for _ in range(y):
for _ in range(x//2): # Divide by 2 since we're reading pairs
if order == 0: #Linear order (1, 2)
pixel1 = pixelReader.read(bits)
pixel2 = pixelReader.read(bits)
else: #Reverse order (2, 1)
pixel2 = pixelReader.read(bits)
pixel1 = pixelReader.read(bits)
convertedPixels[idx] = pixel1
convertedPixels[idx+1] = pixel2
idx += 2
return convertedPixels[:pixels_needed] # Return only needed pixels
@staticmethod
def indexedLinearFrame(bits, file, offset, order, x, y, frame):
"""Reads indexed pixel data of the specified bit width from a file (and gets the specified frame or tile)
Format: indexed(bits, file, offset, order, x, y)
bits defines how many bits there is per pixel
file defines the file path
offset defines the start offset in the file
order defines the pixel order (0 is linear, 1 is reverse order)
x is the width, y is the height
frame is the frame number you want parsed
Returns: A list of integers used to assign colors from a palette to each pixel
"""
x = max(1, x)
y = max(1, y)
pixels_per_frame = x * y
pixels_needed = pixels_per_frame
convertedPixels = [0] * pixels_needed # Pre-allocate list
with open(file, "rb") as pixels:
pixels.seek(offset)
pixelReader = BE_BitReader(pixels)
# Skip forward (frame) number of frames - more efficient calculation
pixels_to_skip = frame * pixels_per_frame
pairs_to_skip = pixels_to_skip // 2
for _ in range(pairs_to_skip):
pixelReader.read(bits)
pixelReader.read(bits)
idx = 0
for _ in range(y):
for _ in range(x//2): # Divide by 2 since we're reading pairs
if order == 0: #Linear order (1, 2)
pixel1 = pixelReader.read(bits)
pixel2 = pixelReader.read(bits)
else: #Reverse order (2, 1)
pixel2 = pixelReader.read(bits)
pixel1 = pixelReader.read(bits)
convertedPixels[idx] = pixel1
convertedPixels[idx+1] = pixel2
idx += 2
return convertedPixels[:pixels_needed] # Return only needed pixels
@staticmethod
def _process_color_channels(pixelReader, channelBits, alphaMode):
"""Helper method to process rgb/bgr color channels"""
c1 = pixelReader.read(channelBits)
c2 = pixelReader.read(channelBits)
c3 = pixelReader.read(channelBits)
alpha = pixelReader.read(1)
# Scale to 8-bit range (0-255)
max_val = (1 << channelBits) - 1
c1 = (c1 * 255) // max_val
c2 = (c2 * 255) // max_val
c3 = (c3 * 255) // max_val
alpha = alpha * 255
if alphaMode == 0:
return (c1, c2, c3)
else:
return (c1, c2, c3, alpha)
@staticmethod
def bgr555(file, offset, alphaMode, x, y):
"""Reads a BGR555/5551 palette from a file at the specified offset
Format: bgr555(file, offset, alphaMode)
file defines the file path
offset defines the start offset in the file
alphaMode defines if there is or isn't an alpha channel - 1 for True, 0 for False
x is the width, y is the height
Returns: A list of integers used to assign colors from a palette
For color palettes, X should be the color count and Y should be 1
"""
x = max(1, x)
y = max(1, y)
alphaMode = min(1, alphaMode)
pixels_needed = x * y
convertedPixels = [None] * pixels_needed # Pre-allocate list
with open(file, "rb") as pixels:
pixels.seek(offset)
pixelReader = BitReader(pixels)
for i in range(pixels_needed):
blue = pixelReader.read(5)
green = pixelReader.read(5)
red = pixelReader.read(5)
alpha = pixelReader.read(1)
# Scale to 8-bit range (0-255)
blue = (blue * 255) // 31
green = (green * 255) // 31
red = (red * 255) // 31
alpha = alpha * 255
if alphaMode == 0:
convertedPixels[i] = (red, green, blue)
else:
convertedPixels[i] = (red, green, blue, alpha)
return convertedPixels
@staticmethod
def bgr555LE(file, offset, alphaMode, x, y):
"""Reads a BGR555/5551 palette from a file at the specified offset in little endian byte order
Format: bgr555_little_endian(file, offset, alphaMode)
file defines the file path
offset defines the start offset in the file
alphaMode defines if there is or isn't an alpha channel - 1 for True, 0 for False
x is the width, y is the height
Returns: A list of integers used to assign colors from a palette
For color palettes, X should be the color count and Y should be 1
"""
x = max(1, x)
y = max(1, y)
alphaMode = min(1, alphaMode)
pixels_needed = x * y
convertedPixels = [None] * pixels_needed # Pre-allocate list
with open(file, "rb") as pixels:
pixels.seek(offset)
# Use 2-byte chunks since BGR555 uses 16 bits per pixel
pixelReader = BitReaderLE(pixels, chunk_size=2)
for i in range(pixels_needed):
# In little endian, the order is reversed at the byte level
# but we still read the bits in the same order within each 16-bit word
red = pixelReader.read(5)
green = pixelReader.read(5)
blue = pixelReader.read(5)
alpha = pixelReader.read(1)
# Scale to 8-bit range (0-255)
blue = (blue * 255) // 31
green = (green * 255) // 31
red = (red * 255) // 31
alpha = alpha * 255
if alphaMode == 0:
convertedPixels[i] = (red, green, blue)
else:
convertedPixels[i] = (red, green, blue, alpha)
return convertedPixels
@staticmethod
def rgb555LE(file, offset, alphaMode, x, y):
"""Reads a RGB555/5551 palette from a file at the specified offset in little endian byte order
Format: rgb555_little_endian(file, offset, alphaMode)
file defines the file path
offset defines the start offset in the file
alphaMode defines if there is or isn't an alpha channel - 1 for True, 0 for False
x is the width, y is the height
Returns: A list of integers used to assign colors from a palette
For color palettes, X should be the color count and Y should be 1
"""
x = max(1, x)
y = max(1, y)
alphaMode = min(1, alphaMode)
pixels_needed = x * y
convertedPixels = [None] * pixels_needed # Pre-allocate list
with open(file, "rb") as pixels:
pixels.seek(offset)
# Use 2-byte chunks since RGB555 uses 16 bits per pixel
pixelReader = BitReaderLE(pixels, chunk_size=2)
for i in range(pixels_needed):
red = pixelReader.read(5)
green = pixelReader.read(5)
blue = pixelReader.read(5)
alpha = pixelReader.read(1)
# Scale to 8-bit range (0-255)
blue = (blue * 255) // 31
green = (green * 255) // 31
red = (red * 255) // 31
alpha = alpha * 255
if alphaMode == 0:
convertedPixels[i] = (blue, green, red)
else:
convertedPixels[i] = (blue, green, red, alpha)
return convertedPixels
@staticmethod
def rgb555(file, offset, alphaMode, x, y):
"""Reads an RGB555/5551 palette from a file at the specified offset
Format: rgb555(file, offset, alphaMode)
file defines the file path
offset defines the start offset in the file
alphaMode defines if there is or isn't an alpha channel - 1 for True, 0 for False
x is the width, y is the height
Returns: A list of integers used to assign colors from a palette
For color palettes, X should be the color count and Y should be 1
"""
x = max(1, x)
y = max(1, y)
alphaMode = min(1, alphaMode)
pixels_needed = x * y
convertedPixels = [None] * pixels_needed # Pre-allocate list
with open(file, "rb") as pixels:
pixels.seek(offset)
pixelReader = BitReader(pixels)
for i in range(pixels_needed):
red = pixelReader.read(5)
green = pixelReader.read(5)
blue = pixelReader.read(5)
alpha = pixelReader.read(1)
# Scale to 8-bit range (0-255)
red = (red * 255) // 31
green = (green * 255) // 31
blue = (blue * 255) // 31
alpha = alpha * 255
if alphaMode == 0:
convertedPixels[i] = (red, green, blue)
else:
convertedPixels[i] = (red, green, blue, alpha)
return convertedPixels
@staticmethod
def customWidthsAndOrder(file, offset, alphaMode, x, y, channelBits, channelOrder, littleEndian=True):
"""Reads a color palette from a file at the specified offset with custom bit widths and channel order
Parameters:
file: str - defines the file path
offset: int - defines the start offset in the file
alphaMode: int - defines if there is or isn't an alpha channel - 1 for True, 0 for False
x: int - the width (for palettes, this is the color count)
y: int - the height (for palettes, this should be 1)
channelBits: list[int] - list of 4 integers defining bit widths for [R,G,B,A]
channelOrder: list[int] - list of 4 integers defining channel order using [0=R,1=G,2=B,3=A]
littleEndian: bool - determines which bit reader to use (default: True for little endian)
Returns: A list of tuples containing color values (RGB or RGBA)