forked from DRGN-DRC/Melee-Modding-Wizard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtextureEditing.py
2224 lines (1805 loc) · 110 KB
/
textureEditing.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
#!/usr/bin/python
# This file's encoding: UTF-8, so that non-ASCII characters can be used in strings.
#
# ███╗ ███╗ ███╗ ███╗ ██╗ ██╗ ------- -------
# ████╗ ████║ ████╗ ████║ ██║ ██║ # -=======---------------------------------------------------=======- #
# ██╔████╔██║ ██╔████╔██║ ██║ █╗ ██║ # ~ ~ Written by DRGN of SmashBoards (Daniel R. Cappel); May, 2020 ~ ~ #
# ██║╚██╔╝██║ ██║╚██╔╝██║ ██║███╗██║ # [ Built with Python v2.7.16 and Tkinter 8.5 ] #
# ██║ ╚═╝ ██║ ██║ ╚═╝ ██║ ╚███╔███╔╝ # -======---------------------------------------------------======- #
# ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══╝╚══╝ ------ ------
# - - Melee Modding Wizard - -
# External dependencies
import ttk
import math
import time
import tkMessageBox
import Tkinter as Tk
from PIL import Image, ImageTk
from Tkinter import TclError
from binascii import hexlify
from collections import OrderedDict
# Internal dependencies
import globalData
from tplCodec import TplDecoder
from FileSystem import hsdStructures, DatFile
from basicFunctions import isNaN, validHex, humansize, grammarfyList, msg, copyToClipboard, printStatus, uHex, constructTextureFilename
from guiSubComponents import ( exportMultipleTextures, importSingleTexture, BasicWindow,
HexEditEntry, EnumOptionMenu, HexEditDropdown, ColorSwatch, MeleeColorPicker,
FlagDecoder, ToolTip, VerticalScrolledFrame, ClickText )
imageFormats = { 0:'I4', 1:'I8', 2:'IA4', 3:'IA8', 4:'RGB565', 5:'RGB5A3', 6:'RGBA8', 8:'CI4', 9:'CI8', 10:'CI14x2', 14:'CMPR' }
userFriendlyFormatList = [ '_0 (I4)', '_1 (I8)',
'_2 (IA4)', '_3 (IA8)',
'_4 (RGB565)', '_5 (RGB5A3)', '_6 (RGBA8)',
'_8 (CI4)', '_9 (CI8)', '_10 (CI14x2)',
'_14 (CMPR)' ]
class TexturesEditor( ttk.Notebook ):
def __init__( self, parent, mainGui ):
ttk.Notebook.__init__( self, parent )
# Add this tab to the main GUI, and add drag-and-drop functionality
mainGui.mainTabFrame.add( self, text=' Textures Editor ' )
mainGui.dnd.bindtarget( self, mainGui.dndHandler, 'text/uri-list' )
def addTab( self, fileObj ):
""" Creates a new tab in the Textures Editor interface for the given file. """
# Create the new tab for the given file
newTab = TexturesEditorTab( self, fileObj )
self.add( newTab, text=fileObj.filename )
# Switch to and populate the new tab
self.select( newTab )
newTab.populate()
def haltAllScans( self, programClosing=False ):
""" Used to gracefully stop all ongoing file scans. Without a method like this,
if the program's GUI (mainloop) is closed/destroyed, there may be errors from
the scan loops acting on a GUI that no longer exists. """
# Instruct all tabs to stop current scans
# tabWidgets = []
for tabName in self.tabs():
tabWidget = globalData.gui.root.nametowidget( tabName )
tabWidget.haltScan = True
# tabWidgets.append( tabWidget )
# Wait until all tabs have stopped scanning (waits for GUI event loop to iterate and cancel all scan loops)
# while 1:
# for tab in tabWidgets:
# if tab.scanningFile:
# break
# else: # The loop above didn't break; no tabs are currently scanning
# break # From the while loop
# # Reset the haltScan flag if the progrom isn't closing
# if not programClosing:
# for tab in tabWidgets:
# tab.haltScan = False
def closeCurrentTab( self ):
""" Removes the currently selected tab. If all tabs are removed,
the entire notebook (within main tab interface) should be removed. """
mainGui = globalData.gui
currentTab = mainGui.root.nametowidget( self.select() )
currentTab.destroy()
if not self.tabs():
# Remove this tab from the main tab interface
self.destroy()
mainGui.texturesTab = None
# Most likely the Disc File Tree was last used, so let's go back to that
if mainGui.discTab:
mainGui.mainTabFrame.select( mainGui.discTab )
class TexturesEditorTab( ttk.Frame ):
def __init__( self, parent, fileObj=None ):
ttk.Frame.__init__( self, parent )
self.tabManager = parent
self.file = fileObj
self.texturesInfo = []
self.scanningFile = False
self.restartFileScan = False
self.haltScan = False
self.imageFilters = {
'widthFilter': ( '=', '' ),
'heightFilter': ( '=', '' ),
'aspectRatioFilter': ( '=', '' ),
'imageTypeFilter': ( '=', '' ),
'offsetFilter': ( '=', '' ),
}
# Top header row | Filepath field and close button
topRow = ttk.Frame( self, padding="12 12 12 0" ) # Left, Top, Right, Bottom
ttk.Label( topRow, text=" DAT / USD:" ).pack( side='left' )
self.datDestination = Tk.StringVar()
datDestinationLabel = ttk.Entry( topRow, textvariable=self.datDestination )
datDestinationLabel.bind( '<Return>', self.openNewFile )
datDestinationLabel.pack( side='left', fill='x', expand=1, padx=12 )
closeBtn = ttk.Button( topRow, text='X', command=parent.closeCurrentTab, width=4 )
closeBtn.pack( side='right' )
ToolTip( closeBtn, text='Close', delay=1000, bg='#ee9999', location='n' )
topRow.pack( fill='x', side='top' )
# Second row | Frame for the image tree and info pane
secondRow = ttk.Frame( self, padding="12 12 12 0" ) # Contains the tree and the info pane. Padding order: Left, Top, Right, Bottom.
# File Tree start
datTreeScroller = Tk.Scrollbar( secondRow )
self.datTextureTree = ttk.Treeview( secondRow, columns=('texture', 'dimensions', 'type'), yscrollcommand=datTreeScroller.set )
self.datTextureTree.heading( '#0', anchor='center', text='Preview' )
self.datTextureTree.column( '#0', anchor='center', minwidth=104, stretch=0, width=104 ) # "#0" is implicit in columns definition above.
self.datTextureTree.heading( 'texture', anchor='center', text='Offset (len)', command=lambda: self.treeview_sort_column('texture', False) )
self.datTextureTree.column( 'texture', anchor='center', minwidth=80, stretch=0, width=100 )
self.datTextureTree.heading( 'dimensions', anchor='center', text='Dimensions', command=lambda: self.treeview_sort_column('dimensions', False) )
self.datTextureTree.column( 'dimensions', anchor='center', minwidth=80, stretch=0, width=100 )
self.datTextureTree.heading( 'type', anchor='center', text='Texture Type', command=lambda: self.treeview_sort_column('type', False) )
self.datTextureTree.column( 'type', anchor='center', minwidth=75, stretch=0, width=100 )
self.datTextureTree.pack( fill='both', side='left' )
datTreeScroller.config( command=self.datTextureTree.yview )
datTreeScroller.pack( side='left', fill='y' )
self.datTextureTree.lastLoaded = None # Used by the 'Prev./Next' file loading buttons on the DAT Texture Tree tab
self.datTextureTree.bind( '<<TreeviewSelect>>', self.onTextureTreeSelect )
self.datTextureTree.bind( "<3>", self.summonContextMenu )
# Create repositories to store image data (needed to prevent garbage collection)
self.datTextureTree.fullTextureRenders = {}
self.datTextureTree.textureThumbnails = {}
# Background widgets for treeview when not populated
self.datTextureTreeBg = Tk.Label( self.datTextureTree, image=globalData.gui.imageBank('dndTarget'), borderwidth=0, highlightthickness=0 )
self.datTextureTreeBg.place( relx=0.5, rely=0.5, anchor='center' )
self.datTextureTreeStatusMsg = Tk.StringVar()
self.datTextureTreeStatusLabel = ttk.Label( self.datTextureTree, textvariable=self.datTextureTreeStatusMsg, background='white' )
# Item highlighting. The order of the configs below reflects (but does not dictate) the priority of their application
self.datTextureTree.tag_configure( 'warn', background='#f6c6d7' ) # light red
self.datTextureTree.tag_configure( 'mipmap', background='#d7e1ff' ) # light blue; same as SA tab 'marked' items
# File Tree end; beginning texture display pane
defaultCanvasDimensions = 258 # Default size for the height and width of the texture viewing canvas. 256 + 1px border
self.imageManipTabs = ttk.Notebook( secondRow )
self.textureTreeImagePane = Tk.Frame( self.imageManipTabs )
self.imageManipTabs.add( self.textureTreeImagePane, text=' Image ', sticky='nsew' )
canvasOptionsPane = ttk.Frame( self.textureTreeImagePane, padding='0 15 0 0' )
ClickText( canvasOptionsPane, 'Texture Filters', self.adjustTextureFilters ).pack( side='left', padx=7 )
ttk.Checkbutton( canvasOptionsPane, command=self.updateCanvasGrid, text='Show Grid', variable=globalData.boolSettings['showCanvasGrid'] ).pack( side='left', padx=7 )
ttk.Checkbutton( canvasOptionsPane, command=self.updateCanvasTextureBoundary, text='Show Texture Boundary', variable=globalData.boolSettings['showTextureBoundary'] ).pack( side='left', padx=7 )
canvasOptionsPane.pack()
self.textureDisplayFrame = Tk.Frame( self.textureTreeImagePane ) # The border and highlightthickness for the canvas below must be set to 0, so that the canvas has a proper origin of (0, 0).
self.textureDisplay = Tk.Canvas( self.textureDisplayFrame, width=defaultCanvasDimensions, height=defaultCanvasDimensions, borderwidth=0, highlightthickness=0 )
self.textureDisplay.pack( expand=1 ) # fill='both', padx=10, pady=10
self.updateCanvasGrid( False )
self.textureDisplay.defaultDimensions = defaultCanvasDimensions
self.textureDisplayFrame.pack( expand=1 )
datPreviewPaneBottomRow = Tk.Frame( self.textureTreeImagePane ) # This object uses grid alignment for its children so that they're centered and equally spaced amongst each other.
self.previousDatButton = ttk.Label( datPreviewPaneBottomRow, image=globalData.gui.imageBank('previousDatButton') )
self.previousDatButton.grid( column=0, row=0, sticky='e', ipadx=10, pady=(10, 0) )
self.previousDatText = Tk.StringVar()
ToolTip( self.previousDatButton, textvariable=self.previousDatText, delay=300, location='n' )
datFileDetails = ttk.Labelframe( datPreviewPaneBottomRow, text=' File Details ', labelanchor='n' )
self.datFilesizeText = Tk.StringVar( value='File Size: ' )
ttk.Label( datFileDetails, textvariable=self.datFilesizeText )
self.totalTextureSpaceText = Tk.StringVar( value='Total Texture Size: ' )
ttk.Label( datFileDetails, textvariable=self.totalTextureSpaceText )
self.texturesFoundText = Tk.StringVar( value='Textures Found: ' )
ttk.Label( datFileDetails, textvariable=self.texturesFoundText )
self.texturesFilteredText = Tk.StringVar( value='Filtered Out: ' )
ttk.Label( datFileDetails, textvariable=self.texturesFilteredText )
for widget in datFileDetails.winfo_children():
widget.pack( padx=20, pady=0, anchor='w' )
datFileDetails.grid( column=1, row=0, ipady=4, sticky='ew', padx=(10, 34) )
self.nextDatButton = ttk.Label( datPreviewPaneBottomRow, image=globalData.gui.imageBank('nextDatButton') )
self.nextDatButton.grid( column=2, row=0, sticky='w', ipadx=10, pady=(10, 0) )
self.nextDatText = Tk.StringVar()
ToolTip( self.nextDatButton, textvariable=self.nextDatText, delay=300, location='n' )
datPreviewPaneBottomRow.columnconfigure( 0, weight=1 )
datPreviewPaneBottomRow.columnconfigure( 1, weight=2 )
datPreviewPaneBottomRow.columnconfigure( 2, weight=1 )
datPreviewPaneBottomRow.rowconfigure( 0, weight=1 )
datPreviewPaneBottomRow.pack( side='bottom', fill='x', padx=20, pady=7 )
# Palette tab
self.palettePane = ttk.Frame( self.imageManipTabs, padding='16 0 0 0' )
self.imageManipTabs.add( self.palettePane, text=' Palette ', state='disabled' )
self.imageManipTabs.bind( '<<NotebookTabChanged>>', self.imageManipTabChanged )
# Left-side column (canvas and bg color changer button)
paletteTabLeftSide = Tk.Frame(self.palettePane)
self.paletteCanvas = Tk.Canvas( paletteTabLeftSide, borderwidth=3, relief='ridge', background='white', width=187, height=405 )
paletteBgColorChanger = ttk.Label( paletteTabLeftSide, text='Change Background Color', foreground='#00F', cursor='hand2' )
self.paletteCanvas.paletteEntries = []
self.paletteCanvas.itemColors = {}
paletteBgColorChanger.bind( '<1>', self.cyclePaletteCanvasColor )
self.paletteCanvas.pack( pady=11, padx=0 )
self.paletteCanvas.entryBorderColor = '#3399ff' # This is the same blue as used for treeview selection highlighting
paletteBgColorChanger.pack()
paletteTabLeftSide.grid( column=0, row=0 )
# Right-side column (palette info)
paletteDetailsFrame = Tk.Frame(self.palettePane)
self.paletteDataText = Tk.StringVar( value='Data Offset:' )
ttk.Label( paletteDetailsFrame, textvariable=self.paletteDataText ).pack(pady=3)
self.paletteHeaderText = Tk.StringVar( value='Header Offset:' )
ttk.Label( paletteDetailsFrame, textvariable=self.paletteHeaderText ).pack(pady=3)
self.paletteTypeText = Tk.StringVar( value='Palette Type:' )
ttk.Label( paletteDetailsFrame, textvariable=self.paletteTypeText ).pack(pady=3)
self.paletteMaxColorsText = Tk.StringVar( value='Max Colors:')
ttk.Label( paletteDetailsFrame, textvariable=self.paletteMaxColorsText ).pack(pady=3)
self.paletteStatedColorsText = Tk.StringVar( value='Stated Colors:' )
ttk.Label( paletteDetailsFrame, textvariable=self.paletteStatedColorsText ).pack(pady=3)
#self.paletteActualColorsText = Tk.StringVar( value='Actual Colors:' ) # todo:reinstate?
#ttk.Label( paletteDetailsFrame, textvariable=self.paletteActualColorsText ).pack(pady=3)
paletteDetailsFrame.grid( column=1, row=0, pady=60, sticky='n' )
self.palettePane.columnconfigure( 0, weight=1 )
self.palettePane.columnconfigure( 1, weight=2 )
# Add a help button to explain the above
helpText = ( 'Max Colors is the maximum number of colors this texture has space for with its current texture format.\n\n'
'Stated Colors is the number of colors that the palette claims are actually used by the texture (described by the palette data header).\n\n'
'The number of colors actually used may still differ from both of these numbers, especially for very old texture hacks.' )
helpBtn = ttk.Label( self.palettePane, text='?', foreground='#445', cursor='hand2' )
helpBtn.place( relx=1, x=-17, y=18 )
helpBtn.bind( '<1>', lambda e, message=helpText: msg(message, 'Palette Properties') )
# Model parts tab
self.modelPropertiesPane = VerticalScrolledFrame( self.imageManipTabs )
self.imageManipTabs.add( self.modelPropertiesPane, text='Model', state='disabled' )
self.modelPropertiesPane.interior.imageDataHeaders = []
self.modelPropertiesPane.interior.nonImageDataHeaders = [] # Not expected
self.modelPropertiesPane.interior.textureStructs = [] # Direct model attachments
self.modelPropertiesPane.interior.headerArrayStructs = [] # Used for animations
self.modelPropertiesPane.interior.unexpectedStructs = []
self.modelPropertiesPane.interior.materialStructs = []
self.modelPropertiesPane.interior.displayObjects = []
self.modelPropertiesPane.interior.hideJointChkBtn = None
self.modelPropertiesPane.interior.polyDisableChkBtn = None
self.modelPropertiesPane.interior.opacityEntry = None
self.modelPropertiesPane.interior.opacityBtn = None
self.modelPropertiesPane.interior.opacityScale = None
# Texture properties tab
self.texturePropertiesPane = VerticalScrolledFrame( self.imageManipTabs )
self.texturePropertiesPane.flagWidgets = [] # Useful for the Flag Decoder to more easily find widgets that need updating
self.imageManipTabs.add( self.texturePropertiesPane, text='Properties', state='disabled' )
self.imageManipTabs.pack( fill='both', expand=1 )
secondRow.pack( fill='both', expand=1 )
def openNewFile( self, event=None, path='', newTab=False ):
""" This is only called by pressing Enter/Return on the top file path display/entry of
the DAT Texture Tree tab. Verifies given the path and loads the file for viewing. """
if not path:
path = self.datDestination.get().replace( '"', '' )
if path not in globalData.disc.files:
msg( 'Unable to find "{}" in the disc.'.format(path), 'File Not Found', warning=True )
return
if newTab:
self.tabManager.addTab( globalData.disc.files[path] )
else:
# Change the file associated with this tab
self.file = globalData.disc.files[path]
# Clear and repopulate the tab
self.clear()
self.update_idletasks() # Visual indication for the user that the tab has refreshed
self.populate()
def clear( self ):
# Remove any existing entries in the treeview.
for item in self.datTextureTree.get_children():
self.datTextureTree.delete( item )
# Reset the size of the texture display canvas, and clear its contents (besides the grid)
self.textureDisplay.configure( width=self.textureDisplay.defaultDimensions, height=self.textureDisplay.defaultDimensions )
self.textureDisplay.delete( self.textureDisplay.find_withtag('border') )
self.textureDisplay.delete( self.textureDisplay.find_withtag('texture') )
# Remove the background drag-n-drop image
self.datTextureTreeStatusLabel.place_forget()
# Reset the values on the Image tab.
# self.datFilesizeText.set( 'File Size: ' )
# self.totalTextureSpaceText.set( 'Total Texture Size: ' )
# self.texturesFoundText.set( 'Textures Found: ' )
# self.texturesFilteredText.set( 'Filtered Out: ' )
# Reset scroll position to the top
self.datTextureTree.yview_moveto( 0 )
# Disable some tabs by default (within the DAT Texture Tree tab), and if viewing one of them, switch to the Image tab
self.imageManipTabs.select( 0 )
self.imageManipTabs.tab( self.palettePane, state='disabled' )
self.imageManipTabs.tab( self.modelPropertiesPane, state='disabled' )
self.imageManipTabs.tab( self.texturePropertiesPane, state='disabled' )
def rescanPending( self ):
""" If restartFileScan or haltScan are set to True, this will gracefully
prevent the next loop iteration of the scan loop from starting.
If a new scan is desired, this allows the previous scan to start it,
so that there are never two scan loops running at once (for this tab). """
if self.restartFileScan:
#cancelCurrentRenders() # Should be enabled if multiprocess texture decoding is enabled
self.scanningFile = False
self.restartFileScan = False
# Restart the DAT/DOL file scan
self.clear()
self.populate()
return True
elif self.haltScan:
self.scanningFile = False
self.restartFileScan = False
printStatus( 'File scan stopped', warning=True )
return True
else:
return False
def passesImageFilters( self, imageDataOffset, width, height, imageType ):
""" Used to pass or filter out textures displayed in the DAT Texture Tree tab when loading files.
Accessed and controled by the main menu's "Settings -> Adjust Texture Filters" option. """
aspectRatio = float( width ) / height
def comparisonPasses( subjectValue, comparator, limitingValue ):
if comparator == '>' and not (subjectValue > limitingValue): return False
if comparator == '>=' and not (subjectValue >= limitingValue): return False
if comparator == '=' and not (subjectValue == limitingValue): return False
if comparator == '<' and not (subjectValue < limitingValue): return False
if comparator == '<=' and not (subjectValue <= limitingValue): return False
return True
# For each setting, break the value into its respective components (comparator & filter value), and then run the appropriate comparison.
widthComparator, widthValue = self.imageFilters['widthFilter']
if widthValue != '' and not isNaN(int(widthValue)):
if not comparisonPasses( width, widthComparator, int(widthValue) ): return False
heightComparator, heightValue = self.imageFilters['heightFilter']
if heightValue != '' and not isNaN(int(heightValue)):
if not comparisonPasses( height, heightComparator, int(heightValue) ): return False
aspectRatioComparator, aspectRatioValue = self.imageFilters['aspectRatioFilter']
if aspectRatioValue != '':
if ':' in aspectRatioValue:
numerator, denomenator = aspectRatioValue.split(':')
aspectRatioValue = float(numerator) / float(denomenator)
elif '/' in aspectRatioValue:
numerator, denomenator = aspectRatioValue.split('/')
aspectRatioValue = float(numerator) / float(denomenator)
else: aspectRatioValue = float(aspectRatioValue)
if not isNaN(aspectRatioValue) and not comparisonPasses( aspectRatio, aspectRatioComparator, aspectRatioValue ): return False
imageTypeComparator, imageTypeValue = self.imageFilters['imageTypeFilter']
if imageTypeValue != '' and not isNaN(int(imageTypeValue)):
if not comparisonPasses( imageType, imageTypeComparator, int(imageTypeValue) ): return False
offsetComparator, offsetValue = self.imageFilters['offsetFilter']
if offsetValue.startswith('0x') and offsetValue != '' and not isNaN(int(offsetValue, 16)):
if not comparisonPasses( imageDataOffset + 0x20, offsetComparator, int(offsetValue, 16) ): return False
elif offsetValue != '' and not isNaN(int(offsetValue)):
if not comparisonPasses( imageDataOffset + 0x20, offsetComparator, int(offsetValue) ): return False
return True
def populate( self, priorityTargets=(), useCache=False ):
self.scanningFile = True
self.datTextureTreeBg.place_forget() # Removes the drag-and-drop image
# Update the name of the tab, top DAT/USD file path bar, and the Prev./Next buttons
fileName = self.file.isoPath.split( '/' )[-1]
self.tabManager.tab( self, text=fileName )
self.datDestination.set( self.file.isoPath )
self.updatePrevNextFileButtons()
tic = time.clock()
texturesShown = totalTextureSpace = 0
filteredTexturesInfo = []
if not useCache:
# Scan the file for textures
printStatus( 'Scanning File...' )
self.texturesInfo = self.file.identifyTextures()
# Clear the repositories for storing image data (used to prevent garbage collection)
self.datTextureTree.fullTextureRenders = {}
self.datTextureTree.textureThumbnails = {}
if self.rescanPending():
return
elif self.texturesInfo: # i.e. textures were found
loadingImage = globalData.gui.imageBank( 'loading' )
for imageDataOffset, imageHeaderOffset, paletteDataOffset, paletteHeaderOffset, width, height, imageType, maxLOD in self.texturesInfo:
# Ignore textures that don't match the user's filters
if not self.passesImageFilters( imageDataOffset, width, height, imageType ):
if imageDataOffset in priorityTargets:
pass # Overrides the filter
else:
continue
# Initialize a structure for the image data
texture = self.file.initTexture( imageDataOffset, imageHeaderOffset, paletteDataOffset, paletteHeaderOffset, width, height, imageType, maxLOD, 0 )
imageDataLength = texture.imageDataLength
texturesShown += 1
filteredTexturesInfo.append( (imageDataOffset, width, height, imageType, imageDataLength, maxLOD, 0) )
totalTextureSpace += texture.length # Length of the struct (includes all mipmap levels)
# Highlight any textures that need to stand out
# tags = []
# #if width > 1024 or width % 2 != 0 or height > 1024 or height % 2 != 0: tags.append( 'warn' )
# if width % 2 != 0 or height % 2 != 0: tags.append( 'warn' )
# if maxLOD > 0: tags.append( 'mipmap' )
# Add this texture to the DAT Texture Tree tab, using the thumbnail generated above
try:
self.datTextureTree.insert( '', 'end', # '' = parent/root, 'end' = insert position
iid=str( imageDataOffset ),
image=loadingImage
# values=(
# uHex(0x20 + imageDataOffset) + '\n('+uHex(imageDataLength)+')', # offset to image data, and data length
# str(width)+' x '+str(height), # width and height
# '_'+str(imageType)+' ('+imageFormats[imageType]+')' # the image type and format
# ),
# tags=tags
)
except TclError:
print( hex(imageDataOffset) + ' already exists!' )
continue
# Add any associated mipmap images, as treeview children
if maxLOD > 0:
parent = imageDataOffset
for i in range( int(maxLOD) ):
# Adjust the parameters for the next mipmap image
imageDataOffset += imageDataLength # This is of the last image, not the current imageDataLength below
width = int( math.ceil(width / 2.0) )
height = int( math.ceil(height / 2.0) )
imageDataLength = hsdStructures.ImageDataBlock.getDataLength( width, height, imageType )
# Create a new structure for this block of data
self.file.initTexture( imageDataOffset, imageHeaderOffset, paletteDataOffset, paletteHeaderOffset, width, height, imageType, maxLOD, i+1 )
# Add this texture to the DAT Texture Tree tab, using the thumbnail generated above
self.datTextureTree.insert( parent, 'end', # 'end' = insertion position
iid=str( imageDataOffset ),
image=loadingImage
# values=(
# uHex(0x20 + imageDataOffset) + '\n('+uHex(imageDataLength)+')', # offset to image data, and data length
# (str(width)+' x '+str(height)), # width and height
# '_'+str(imageType)+' ('+imageFormats[imageType]+')' # the image type and format
# ),
# tags=tags
)
filteredTexturesInfo.append( (imageDataOffset, width, height, imageType, imageDataLength, maxLOD, i+1) )
# Immediately decode and display any high-priority targets
if priorityTargets:
for textureInfo in filteredTexturesInfo:
if textureInfo[0] not in priorityTargets: continue
#imageDataOffset, _, _, _, width, height, imageType, _, maxLOD = textureInfo
#dataBlockStruct = self.file.getStruct( imageDataOffset )
self.renderTextureData( *textureInfo, useCache=useCache )
# Update the GUI with some of the file's main info regarding textures
self.datFilesizeText.set( "File Size: {} ({:,} bytes)".format(humansize(self.file.size), self.file.size) )
self.totalTextureSpaceText.set( "Total Texture Size: {} ({:,} b)".format(humansize(totalTextureSpace), totalTextureSpace) )
self.texturesFoundText.set( 'Textures Found: ' + str(len(self.texturesInfo)) )
self.texturesFilteredText.set( 'Filtered Out: ' + str(len(self.texturesInfo)-texturesShown) )
if self.rescanPending():
return
elif filteredTexturesInfo:
# tic = time.clock()
# if 0: # Disabled, until this process can be made more efficient
# #print 'using multiprocessing decoding'
# # Start a loop for the GUI to watch for updates (such updates should not be done in a separate thread or process)
# globalData.gui.thumbnailUpdateJob = globalData.gui.root.after( globalData.gui.thumbnailUpdateInterval, globalData.gui.updateTextureThumbnail )
# # Start up a separate thread to handle and wait for the image rendering process
# renderingThread = Thread( target=startMultiprocessDecoding, args=(filteredTexturesInfo, self.file, globalData.gui.textureUpdateQueue, dumpImages) )
# renderingThread.daemon = True # Allows this thread to be killed automatically when the program quits
# renderingThread.start()
# else: # Perform standard single-process, single-threaded decoding
#print 'using standard, single-process decoding'
i = 1
for textureInfo in filteredTexturesInfo:
# Skip items that should have already been processed
if imageDataOffset in priorityTargets: continue
# Update this item
self.renderTextureData( *textureInfo, useCache=useCache )
# Update the GUI to show new renders every n textures
if i % 10 == 0:
if self.rescanPending(): return
self.datTextureTree.update()
i += 1
self.scanningFile = False
toc = time.clock()
print( 'scan time: ' + str(toc - tic) )
if useCache:
printStatus( 'Filtering complete', success=True )
else:
printStatus( 'File scan complete', success=True )
if self.datTextureTree.get_children() == (): # Display a message that no textures were found, or they were filtered out.
if not self.texturesInfo:
self.datTextureTreeStatusMsg.set( 'No textures were found.' )
else:
self.datTextureTreeStatusMsg.set( 'No textures were found that pass your current filters.' )
self.datTextureTreeStatusLabel.place( relx=0.5, rely=0.5, anchor='center' )
def renderTextureData( self, imageDataOffset, width=-1, height=-1, imageType=-1, imageDataLength=-1, maxLOD=0, mipLevel=-1, problem=False, useCache=False ):
""" Decodes image data from the globally loaded DAT file at a given offset and creates an image out of it. This then
stores/updates the full image and a preview/thumbnail image (so that they're not garbage collected) and displays it in the GUI.
The image and its info is then displayed in the DAT Texture Tree tab's treeview (does not update the Dat Texture Tree subtabs). """
# If using the cache, there's no need to re-decode texture data (useful when just applying texture filtering)
if not useCache or imageDataOffset not in self.datTextureTree.textureThumbnails:
if not problem:
#tic = time.clock()
try:
pilImage = self.file.getTexture( imageDataOffset, width, height, imageType, imageDataLength, getAsPilImage=True )
except Exception as errMessage:
print( 'Unable to make out a texture for data at 0x{:X}; {}'.format(0x20+imageDataOffset, errMessage) )
problem = True
# toc = time.clock()
# print 'time to decode image for', hex(0x20+imageDataOffset) + ':', toc-tic
# Store the full image (or error image) so it's not garbage collected, and generate the preview thumbnail.
if problem:
# The error image is already 64x64, so it doesn't need to be resized for the thumbnail.
errorImage = globalData.gui.imageBank( 'noImage' )
self.datTextureTree.fullTextureRenders[imageDataOffset] = errorImage
self.datTextureTree.textureThumbnails[imageDataOffset] = errorImage
else:
self.datTextureTree.fullTextureRenders[imageDataOffset] = ImageTk.PhotoImage( pilImage )
pilImage.thumbnail( (64, 64), Image.ANTIALIAS )
self.datTextureTree.textureThumbnails[imageDataOffset] = ImageTk.PhotoImage( pilImage )
# Collect texture properties
if imageType == -1:
width, height, imageType, _, _, maxLOD, mipLevel = self.file.getTextureInfo( imageDataOffset )
assert imageType != -1, 'Unable to get texture info for the texture at 0x{:X}'.format( 0x20+imageDataOffset )
imageDataLength = hsdStructures.ImageDataBlock.getDataLength( width, height, imageType )
# Highlight any textures that need to stand out
tags = []
if maxLOD > 0: tags.append( 'mipmap' )
elif width % 2 != 0 or height % 2 != 0: tags.append( 'warn' )
# Build new strings for the properties
newValues = (
uHex(0x20 + imageDataOffset) + '\n('+uHex(imageDataLength)+')', # offset to image data, and data length
(str(width)+' x '+str(height)), # width and height
'_'+str(imageType)+' ('+imageFormats[imageType]+')' # the image type and format
)
# Update the icon and info display
iid = str( imageDataOffset )
self.datTextureTree.item( iid, image=self.datTextureTree.textureThumbnails[imageDataOffset], values=newValues, tags=tags )
# Update any mipmap textures below this one
if maxLOD > 0 and mipLevel < maxLOD:
width = int( math.ceil(width / 2.0) )
height = int( math.ceil(height / 2.0) )
imageDataOffset += imageDataLength
imageDataLength = hsdStructures.ImageDataBlock.getDataLength( width, height, imageType )
mipLevel += 1
self.renderTextureData( imageDataOffset, width, height, imageType, imageDataLength, maxLOD, mipLevel, problem )
def updatePrevNextFileButtons( self ):
""" Updates the Next/Previous DAT buttons on the DAT Texture Tree tab. Sets their target file to load,
their tooltip/pop-up text, and the mouse cursor to appear when hovering over it. 'currentFile' will
be an iid for the file in the Disc File Tree tab. """
isoFileTree = globalData.gui.discTab.isoFileTree
currentFile = self.file.isoPath
# Update the prev. file button
prevItem = isoFileTree.prev( currentFile )
while prevItem != '' and isoFileTree.item( prevItem, 'values' )[1] != 'file':
prevItem = isoFileTree.prev( prevItem ) # Skips over any folders.
if prevItem != '':
text = 'Click to load {}\nShift-click to open in a new tab.'.format( prevItem )
self.previousDatText.set( text )
self.previousDatButton.bind( '<Button-1>', lambda event, item=prevItem: self.openNewFile(path=item) )
self.previousDatButton.bind( '<Shift-Button-1>', lambda event, item=prevItem: self.openNewFile(path=item, newTab=True) )
self.previousDatButton.config( cursor='hand2' )
else:
self.previousDatText.set( 'No more!' )
self.previousDatButton.unbind('<Button-1>')
self.previousDatButton.unbind('<Shift-Button-1>')
self.previousDatButton.config( cursor='' )
# Update the next file button
nextItem = isoFileTree.next( currentFile )
while nextItem != '' and isoFileTree.item( nextItem, 'values' )[1] != 'file':
nextItem = isoFileTree.next( nextItem ) # Skips over any folders.
if nextItem != '':
text = 'Click to load {}\nShift-click to open in a new tab.'.format( nextItem )
self.nextDatText.set( text )
self.nextDatButton.bind( '<Button-1>', lambda event, item=nextItem: self.openNewFile(path=item) )
self.nextDatButton.bind( '<Shift-Button-1>', lambda event, item=nextItem: self.openNewFile(path=item, newTab=True) )
self.nextDatButton.config( cursor='hand2' )
else:
self.nextDatText.set( 'No more!' )
self.nextDatButton.unbind('<Button-1>')
self.nextDatButton.unbind('<Shift-Button-1>')
self.nextDatButton.config( cursor='' )
def treeview_sort_column( self, col, reverse ):
# Create a list of the items, as tuples of (statOfInterest, iid), and sort them
iids = self.datTextureTree.get_children('')
if col == 'texture': rowsList = [ (int( self.datTextureTree.set(iid, col).split()[0], 16 ), iid) for iid in iids ]
#elif col == 'dimensions': rowsList = [( int(self.datTextureTree.set(iid, col).split(' x ')[0]) * int(self.datTextureTree.set(iid, col).split(' x ')[1]), iid ) for iid in iids]
elif col == 'dimensions':
# Sort the dimensions category by total image area
def textureArea( dimensions ):
width, height = dimensions.split( ' x ' )
return int( width ) * int( height )
rowsList = [ (textureArea(self.datTextureTree.set(iid, col)), iid ) for iid in iids ]
elif col == 'type': rowsList = [ (self.datTextureTree.set(iid, col).replace('_', ''), iid) for iid in iids ]
# Sort the rows and rearrange the treeview based on the newly sorted list.
rowsList.sort( reverse=reverse )
for index, ( _, iid ) in enumerate( rowsList ):
self.datTextureTree.move( iid, '', index )
# Set the function call for the next (reversed) sort.
self.datTextureTree.heading( col, command=lambda: self.treeview_sort_column(col, not reverse) )
def onTextureTreeSelect( self, event, iid='' ):
# Ensure there is an iid, or do nothing
if not iid:
iid = self.datTextureTree.selection()
if not iid: return
iid = iid[-1] # Selects the lowest position item selected in the treeview if multiple items are selected.
# Update the main display with the texture's stored image.
imageDataOffset = int( iid )
self.drawTextureToMainDisplay( imageDataOffset )
# Stop here if this is not a typical DAT file
if not isinstance( self.file, DatFile ):
return
# Get the texture struct
texture = self.file.structs[imageDataOffset]
imageDataHeaderOffsets = texture.getParents()
# Determine whether to enable and update the Palette tab.
currentTab = globalData.gui.root.nametowidget( self.imageManipTabs.select() )
if texture.imageType in ( 8, 9, 10 ):
# Enable the palette tab and prepare the data displayed on it.
self.imageManipTabs.tab( 1, state='normal' )
self.populatePaletteTab( imageDataOffset, texture.imageDataLength, texture.imageType )
else:
# No palette for this texture. Check the currently viewed tab, and if it's the Palette tab, switch to the Image tab.
if currentTab == self.palettePane:
self.imageManipTabs.select( self.textureTreeImagePane )
self.imageManipTabs.tab( self.palettePane, state='disabled' )
wraplength = self.imageManipTabs.winfo_width() - 20
lackOfUsefulStructsDescription = ''
# Check if this is a file that doesn't have image data headers :(
if (0x1E00, 'MemSnapIconData') in self.file.rootNodes: # The file is LbMcSnap.usd or LbMcSnap.dat (Memory card banner/icon file from SSB Melee)
lackOfUsefulStructsDescription = 'This file has no known image data headers or other structures to modify.'
elif (0x4E00, 'MemCardIconData') in self.file.rootNodes: # The file is LbMcGame.usd or LbMcGame.dat (Memory card banner/icon file from SSB Melee)
lackOfUsefulStructsDescription = 'This file has no known image data headers or other structures to modify.'
elif self.file.rootNodes[0][1].startswith( 'SIS_' ): # SdMenu.dat/.usd
lackOfUsefulStructsDescription = 'This file has no known image data headers or other structures to modify.'
# elif imageDataOffset >= effectTextureRange[0] and imageDataOffset <= effectTextureRange[1]:
# # e2eHeaderOffset = imageDataStruct.imageHeaderOffset
# # textureCount = struct.unpack( '>I', self.file.getData(e2eHeaderOffset, 4) )[0]
# lackOfUsefulStructsDescription = ( 'Effects files and some stages have unique structuring for some textures, like this one, '
# 'which do not have a typical image data header, texture object, or other common structures.' )
# # if textureCount == 1:
# # lackOfUsefulStructsDescription += ' This texture is not grouped with any other textures,'
# # elif textureCount == 2:
# # lackOfUsefulStructsDescription += ' This texture is grouped with 1 other texture,'
# # else:
# # lackOfUsefulStructsDescription += ' This texture is grouped with {} other textures,'.format( textureCount )
# # lackOfUsefulStructsDescription += ' with an E2E header at 0x{:X}.'.format( 0x20+e2eHeaderOffset )
elif not texture: # Make sure an image data struct exists to check if this might be something like a DOL texture
lackOfUsefulStructsDescription = ( 'There are no image data headers or other structures associated '
'with this texture. These are stored end-to-end in this file with '
'other similar textures.' )
elif not imageDataHeaderOffsets:
lackOfUsefulStructsDescription = 'This file has no known image data headers or other structures to modify.'
self.texturePropertiesPane.clear()
self.texturePropertiesPane.flagWidgets = [] # Useful for the Flag Decoder to more easily find widgets that need updating
# If the following string has something, there isn't much customization to be done for this texture
if lackOfUsefulStructsDescription:
# Disable the model parts tab, and if on that tab, switch to the Image tab.
if currentTab == self.modelPropertiesPane:
self.imageManipTabs.select( self.textureTreeImagePane )
self.imageManipTabs.tab( self.modelPropertiesPane, state='disabled' )
# Add some info to the texture properties tab
self.imageManipTabs.tab( self.texturePropertiesPane, state='normal' )
ttk.Label( self.texturePropertiesPane.interior, text=lackOfUsefulStructsDescription, wraplength=wraplength ).pack( pady=30 )
return # Nothing more to say about this texture
# Enable and update the Model tab
self.imageManipTabs.tab( self.modelPropertiesPane, state='normal' )
self.populateModelTab( imageDataHeaderOffsets, wraplength )
# Enable and update the Properties tab
self.imageManipTabs.tab( self.texturePropertiesPane, state='normal' )
self.populateTexPropertiesTab( wraplength, texture )
def drawTextureToMainDisplay( self, imageDataOffset ):
""" Updates the main display area (the Image tab of the DAT Texture Tree tab) with a
texture's stored full-render image, if it has been rendered, and adjusts GUI size. """
texture = self.file.structs[imageDataOffset]
textureWidth = texture.width
textureHeight = texture.height
# Check for a previously rendered texture image (should exist)
textureImage = self.datTextureTree.fullTextureRenders.get( imageDataOffset )
if not textureImage:
print( 'Unable to get a texture image for ' + hex(imageDataOffset) )
return # May not have been rendered yet
# Get the current dimensions of the program.
self.textureDisplay.update_idletasks() # Ensures the info gathered below is accurate
programWidth = globalData.gui.root.winfo_width()
programHeight = globalData.gui.root.winfo_height()
canvasWidth = self.textureDisplay.winfo_width()
canvasHeight = self.textureDisplay.winfo_height()
# Get the total width/height used by everything other than the canvas.
baseW = globalData.gui.defaultWindowWidth - canvasWidth
baseH = programHeight - canvasHeight
# Set the new program and canvas widths. (The +2 allows space for a texture border.)
if textureWidth > canvasWidth:
newProgramWidth = baseW + textureWidth + 2
newCanvasWidth = textureWidth + 2
else:
newProgramWidth = programWidth
newCanvasWidth = canvasWidth
# Set the new program and canvas heights. (The +2 allows space for a texture border.)
if textureHeight > canvasHeight:
newProgramHeight = baseH + textureHeight + 2
newCanvasHeight = textureHeight + 2
else:
newProgramHeight = programHeight
newCanvasHeight = canvasHeight
# Apply the new sizes for the canvas and root window.
self.textureDisplay.configure( width=newCanvasWidth, height=newCanvasHeight ) # Adjusts the canvas size to match the texture.
globalData.gui.root.geometry( str(newProgramWidth) + 'x' + str(newProgramHeight) )
# Delete current contents of the canvas, and redraw the grid if it's enabled
self.textureDisplay.delete( 'all' )
self.updateCanvasGrid( saveChange=False )
# Add the texture image to the canvas, and draw the texture boundary if it's enabled
self.textureDisplay.create_image( newCanvasWidth/2, newCanvasHeight/2, anchor='center', image=textureImage, tags='texture' )
self.updateCanvasTextureBoundary( saveChange=False )
def populatePaletteTab( self, imageDataOffset, imageDataLength, imageType ):
# If a palette entry was previously highlighted/selected, keep it that way
previouslySelectedEntryOffset = -1
selectedEntries = self.paletteCanvas.find_withtag( 'selected' )
if selectedEntries:
tags = self.paletteCanvas.gettags( selectedEntries[0] )
# Get the other tag, which will be the entry's file offset
for tag in tags:
if tag != 'selected':
previouslySelectedEntryOffset = int( tag.replace('t', '') ) # 't' included in the first place because the tag cannot be purely a number
break
self.paletteCanvas.delete( 'all' )
self.paletteCanvas.paletteEntries = [] # Storage for the palette square images, so they're not garbage collected. (Using images for their canvas-alpha support.)
self.paletteCanvas.itemColors = {} # For remembering the associated color within the images (rather than looking up pixel data within the image) and other info, to be passed on to the color picker
# Try to get info on the palette
paletteDataOffset, paletteHeaderOffset, paletteLength, paletteType, colorCount = self.file.getPaletteInfo( imageDataOffset )
if paletteDataOffset == -1: # Couldn't find the data. Set all values to 'not available (n/a)'
self.paletteDataText.set( 'Data Offset:\nN/A' )
self.paletteHeaderText.set( 'Header Offset:\nN/A' )
self.paletteTypeText.set( 'Palette Type:\nN/A' )
self.paletteMaxColorsText.set( 'Max Colors:\nN/A' )
self.paletteStatedColorsText.set( 'Stated Colors:\nN/A' )
#self.paletteActualColorsText.set( 'Actual Colors:\nN/A' )
return
# Get the image and palette data
imageData = self.file.getData( imageDataOffset, imageDataLength )
paletteData = self.file.getPaletteData( paletteDataOffset=paletteDataOffset, imageData=imageData, imageType=imageType )[0]
paletteData = hexlify( paletteData ) # At least until the TPL codec is rewritten to operate with bytearrays
# Update all fields and the palette canvas (to display the color entries).
self.paletteDataText.set( 'Data Offset:\n' + uHex(paletteDataOffset + 0x20) )
if paletteHeaderOffset == -1: self.paletteHeaderText.set( 'Header Offset:\nNone' )
else: self.paletteHeaderText.set( 'Header Offset:\n' + uHex(paletteHeaderOffset + 0x20) )
if paletteType == 0: self.paletteTypeText.set( 'Palette Type:\n0 (IA8)' )
if paletteType == 1: self.paletteTypeText.set( 'Palette Type:\n1 (RGB565)' )
if paletteType == 2: self.paletteTypeText.set( 'Palette Type:\n2 (RGB5A3)' )
self.paletteMaxColorsText.set( 'Max Colors:\n' + str(self.determineMaxPaletteColors( imageType, paletteLength )) )
self.paletteStatedColorsText.set( 'Stated Colors:\n' + str(colorCount) )
#self.paletteActualColorsText.set( 'Actual Colors:\n' + str(len(paletteData)/4) )
# Create the initial/top offset indicator.
x = 7
y = 11
self.paletteCanvas.create_line( 105, y-3, 120, y-3, 130, y+4, 175, y+4, tags='descriptors' ) # x1, y1, x2, y2, etc....
self.paletteCanvas.create_text( 154, y + 12, text=uHex(paletteDataOffset + 0x20), tags='descriptors' )
# Populate the canvas with the palette entries.
for i in range( 0, len(paletteData), 4 ): # For each palette entry....
paletteEntry = paletteData[i:i+4]
entryNum = i/4
paletteEntryOffset = paletteDataOffset + i/2
x = x + 12
rgbaColor = TplDecoder.decodeColor( paletteType, paletteEntry, decodeForPalette=True ) # rgbaColor = ( r, g, b, a )
# Prepare and store an image object for the entry (since .create_rectangle doesn't support transparency)
paletteSwatch = Image.new( 'RGBA', (8, 8), rgbaColor )
self.paletteCanvas.paletteEntries.append( ImageTk.PhotoImage(paletteSwatch) )
# Draw a rectangle for a border; start by checking whether this is a currently selected entry
if paletteEntryOffset == previouslySelectedEntryOffset:
borderColor = self.paletteCanvas.entryBorderColor
tags = ( 'selected', 't'+str(paletteEntryOffset) )
else:
borderColor = 'black'
tags = 't'+str(paletteEntryOffset)
self.paletteCanvas.create_line( x-1, y-1, x+8, y-1, x+8, y+8, x-1, y+8, x-1, y-1, fill=borderColor, tags=tags )
# Draw the image onto the canvas.
itemId = self.paletteCanvas.create_image( x, y, image=self.paletteCanvas.paletteEntries[entryNum], anchor='nw', tags='entries' )
self.paletteCanvas.itemColors[itemId] = ( rgbaColor, paletteEntry, paletteEntryOffset, imageDataOffset )
if x >= 103: # End of the row (of 8 entries); start a new row.
x = 7
y = y + 11
i = i / 4 + 1
# Check if the current palette entry is a multiple of 32 (4 lines)
if float( i/float(32) ).is_integer() and i < len( paletteData )/4: # (second check prevents execution after last chunk of 0x40)
y = y + 6
self.paletteCanvas.create_line( 105, y-3, 117, y-3, 130, y+4, 176, y+4, tags='descriptors' ) # x1, y1, x2, y2, etc....
self.paletteCanvas.create_text( 154, y + 12, text=uHex(paletteDataOffset + 0x20 + i*2), tags='descriptors' )
def onColorClick( event ):
# Determine which canvas item was clicked on, and use that to look up all entry info
itemId = event.widget.find_closest( event.x, event.y )[0]
if itemId not in self.paletteCanvas.itemColors: return # Abort. Probably clicked on a border.
canvasItemInfo = self.paletteCanvas.itemColors[itemId]
initialHexColor = ''.join( [ "{0:0{1}X}".format( channel, 2 ) for channel in canvasItemInfo[0] ] )
MeleeColorPicker( 'Change Palette Color', initialHexColor, paletteType, windowId=itemId, datDataOffsets=canvasItemInfo, targetFile=self.file )
def onMouseEnter(e): self.paletteCanvas['cursor']='hand2'
def onMouseLeave(e): self.paletteCanvas['cursor']=''
self.paletteCanvas.tag_bind( 'entries', '<1>', onColorClick )
self.paletteCanvas.tag_bind( 'entries', '<Enter>', onMouseEnter )
self.paletteCanvas.tag_bind( 'entries', '<Leave>', onMouseLeave )
def determineMaxPaletteColors( self, imageType, paletteStructLength ):
""" Determines the maximum number of colors that are suppored by a palette. Image type and palette
data struct length are both considered, going with the lower limit between the two. """
if imageType == 8: # 4-bit
maxColors = 16
elif imageType == 9: # 8-bit
maxColors = 256
elif imageType == 10: # 14-bit
maxColors = 16384
else:
print( 'Invalid image type given to determineMaxPaletteColors(): ' + str(imageType) )
return 0
# The actual structure length available overrides the image's type limitation
maxColorsBySpace = paletteStructLength / 2
if maxColorsBySpace < maxColors:
maxColors = maxColorsBySpace
return maxColors
def populateModelTab( self, imageDataHeaderOffsets, wraplength ):
modelPane = self.modelPropertiesPane.interior
vertPadding = 10
# Clear the current contents
self.modelPropertiesPane.clear()
modelPane.imageDataHeaders = []
modelPane.nonImageDataHeaders = [] # Not expected
modelPane.textureStructs = [] # Direct model attachments
modelPane.headerArrayStructs = [] # Used for animations
modelPane.unexpectedStructs = []
# Double-check that all of the parents are actually image data headers, and get grandparent structs
for imageHeaderOffset in imageDataHeaderOffsets: # This should exclude any root/reference node parents (such as a label)
headerStruct = self.file.initSpecificStruct( hsdStructures.ImageObjDesc, imageHeaderOffset )
if headerStruct:
modelPane.imageDataHeaders.append( headerStruct )
# Check the grandparent structs; expected to be Texture Structs or Image Data Header Arrays
for grandparentOffset in headerStruct.getParents():
texStruct = self.file.initSpecificStruct( hsdStructures.TextureObjDesc, grandparentOffset, printWarnings=False )