-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProGradientTool.py
More file actions
1632 lines (1426 loc) · 62.6 KB
/
ProGradientTool.py
File metadata and controls
1632 lines (1426 loc) · 62.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 sys
import math
import json
import random
from PySide6.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLabel, QListWidget, QListWidgetItem,
QSlider, QSpinBox, QDoubleSpinBox, QFileDialog,
QGroupBox, QSplitter, QMessageBox, QComboBox, QCheckBox,
QMainWindow, QMenu, QGridLayout, QScrollArea, QFrame,
QLineEdit)
from PySide6.QtGui import QAction, QPainter, QColor, QImage, QIcon, QPixmap, QPen, QPainterPath
from PySide6.QtCore import Qt, Signal, QPoint, QPointF, QDateTime, QSize
# === CONSTANTS ===
SNES_WIDTH = 256
SNES_HEIGHT = 224
# === MATH HELPERS ===
def clamp(val, min_val=0.0, max_val=1.0):
return max(min_val, min(max_val, val))
def srgb_to_linear(x):
return ((x + 0.055) / 1.055) ** 2.4 if x >= 0.04045 else x / 12.92
def linear_to_srgb(x):
return 1.055 * (x ** (1.0 / 2.4)) - 0.055 if x >= 0.0031308 else 12.92 * x
# --- Oklab / Oklch ---
def rgb_to_oklab(r, g, b):
lr, lg, lb = srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b)
l = 0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb
m = 0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb
s = 0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb
l_, m_, s_ = l**(1/3), m**(1/3), s**(1/3)
L = 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_
a = 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_
b_val = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_
return L, a, b_val
def oklab_to_rgb(L, a, b_val):
l_ = L + 0.3963377774 * a + 0.2158037573 * b_val
m_ = L - 0.1055613458 * a - 0.0638541728 * b_val
s_ = L - 0.0894841775 * a - 1.2914855480 * b_val
l, m, s = l_**3, m_**3, s_**3
lr = +4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s
lg = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s
lb = -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s
return linear_to_srgb(lr), linear_to_srgb(lg), linear_to_srgb(lb)
def rgb_to_oklch(r, g, b):
L, a, b_val = rgb_to_oklab(r, g, b)
C = math.sqrt(a**2 + b_val**2)
h = math.degrees(math.atan2(b_val, a))
return L, C, h
def oklch_to_rgb(L, C, h):
h_rad = math.radians(h)
a = C * math.cos(h_rad)
b_val = C * math.sin(h_rad)
return oklab_to_rgb(L, a, b_val)
# --- CIELAB / CIELCH ---
def rgb_to_cielab(r, g, b):
lr, lg, lb = srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b)
X = lr * 0.4124 + lg * 0.3576 + lb * 0.1805
Y = lr * 0.2126 + lg * 0.7152 + lb * 0.0722
Z = lr * 0.0193 + lg * 0.1192 + lb * 0.9505
Xn, Yn, Zn = 0.95047, 1.00000, 1.08883
def f(t): return t**(1/3) if t > 0.008856 else 7.787*t + 16/116
fx, fy, fz = f(X/Xn), f(Y/Yn), f(Z/Zn)
L = 116 * fy - 16
a = 500 * (fx - fy)
b_val = 200 * (fy - fz)
return L, a, b_val
def cielab_to_rgb(L, a, b_val):
def f_inv(t): return t**3 if t > 0.20689 else (t - 16/116) / 7.787
fy = (L + 16) / 116
fx = a / 500 + fy
fz = fy - b_val / 200
X = 0.95047 * f_inv(fx)
Y = 1.00000 * f_inv(fy)
Z = 1.08883 * f_inv(fz)
lr = X * 3.2406 + Y * -1.5372 + Z * -0.4986
lg = X * -0.9689 + Y * 1.8758 + Z * 0.0415
lb = X * 0.0557 + Y * -0.2040 + Z * 1.0570
return linear_to_srgb(lr), linear_to_srgb(lg), linear_to_srgb(lb)
def rgb_to_cielch(r, g, b):
L, a, b_val = rgb_to_cielab(r, g, b)
C = math.sqrt(a**2 + b_val**2)
h = math.degrees(math.atan2(b_val, a))
return L, C, h
def cielch_to_rgb(L, C, h):
h_rad = math.radians(h)
a = C * math.cos(h_rad)
b_val = C * math.sin(h_rad)
return cielab_to_rgb(L, a, b_val)
# --- Standard Easing Functions ---
def ease_linear(t): return t
def ease_in_quad(t): return t * t
def ease_out_quad(t): return t * (2 - t)
def ease_in_out_sine(t): return -(math.cos(math.pi * t) - 1) / 2
def ease_smoothstep(t): return t * t * (3 - 2 * t)
def ease_smootherstep(t): return t * t * t * (t * (t * 6 - 15) + 10)
EASING_FUNCS = {
"Linear": ease_linear,
"Ease In (Quad)": ease_in_quad,
"Ease Out (Quad)": ease_out_quad,
"Ease In/Out (Sine)": ease_in_out_sine,
"SmoothStep": ease_smoothstep,
"SmootherStep": ease_smootherstep
}
# --- Cubic Bezier Solver ---
def solve_cubic_bezier(t_x, p1x, p2x, epsilon=1e-5):
t = t_x
for _ in range(8):
cx = 3 * p1x
bx = 3 * (p2x - p1x) - cx
ax = 1 - cx - bx
x_est = (ax * t**3) + (bx * t**2) + (cx * t)
d_x = (3 * ax * t**2) + (2 * bx * t) + cx
if abs(d_x) < epsilon: break
diff = x_est - t_x
if abs(diff) < epsilon: return t
t = t - diff / d_x
return max(0.0, min(1.0, t))
def get_cubic_bezier_y(t, p1y, p2y):
cy = 3 * p1y
by = 3 * (p2y - p1y) - cy
ay = 1 - cy - by
return (ay * t**3) + (by * t**2) + (cy * t)
def eval_custom_curve(progress, p1, p2):
t_sol = solve_cubic_bezier(progress, p1[0], p2[0])
return get_cubic_bezier_y(t_sol, p1[1], p2[1])
# --- NEW COLOR SPACES ---
# 1. YIQ (NTSC)
def rgb_to_yiq(r, g, b):
y = 0.299 * r + 0.587 * g + 0.114 * b
i = 0.596 * r - 0.274 * g - 0.322 * b
q = 0.211 * r - 0.523 * g + 0.312 * b
return y, i, q
def yiq_to_rgb(y, i, q):
r = y + 0.956 * i + 0.621 * q
g = y - 0.272 * i - 0.647 * q
b = y - 1.106 * i + 1.703 * q
return clamp(r), clamp(g), clamp(b)
# 2. YDbDr (SECAM)
def rgb_to_ydbdr(r, g, b):
y = 0.299 * r + 0.587 * g + 0.114 * b
db = -0.450 * r - 0.883 * g + 1.333 * b
dr = -1.333 * r + 1.116 * g + 0.217 * b
return y, db, dr
def ydbdr_to_rgb(y, db, dr):
r_ = y - 0.526 * dr
g_ = y - 0.129 * db + 0.268 * dr
b_ = y + 0.665 * db
return clamp(r_), clamp(g_), clamp(b_)
# 3. CMY (Subtractive)
def rgb_to_cmy(r, g, b):
return 1.0 - r, 1.0 - g, 1.0 - b
def cmy_to_rgb(c, m, y):
return clamp(1.0 - c), clamp(1.0 - m), clamp(1.0 - y)
# 4. IPT (Perceptual)
def rgb_to_ipt(r, g, b):
# RGB -> LMS (Hunt-Pointer-Estevez)
l = 0.4002 * r + 0.4431 * g + 0.2044 * b
m = 0.2403 * r + 0.5228 * g + 0.2539 * b
s = 0.0000 * r + 0.0000 * g + 1.0890 * b
# Non-linearity
l_ = l ** 0.43 if l > 0 else 0
m_ = m ** 0.43 if m > 0 else 0
s_ = s ** 0.43 if s > 0 else 0
# LMS -> IPT
I = 0.4000 * l_ + 0.4000 * m_ + 0.2000 * s_
P = 4.4550 * l_ - 4.8510 * m_ + 0.3960 * s_
T = 0.8056 * l_ + 0.3572 * m_ - 1.1628 * s_
return I, P, T
def ipt_to_rgb(I, P, T):
l_ = I + 0.097569 * P + 0.205226 * T
m_ = I - 0.113880 * P + 0.133217 * T
s_ = I + 0.032615 * P - 0.676890 * T
def inv_nl(x): return x ** (1/0.43) if x > 0 else 0
l, m, s = inv_nl(l_), inv_nl(m_), inv_nl(s_)
r = 5.432622 * l - 4.67910 * m + 0.246257 * s
g = -1.10517 * l + 2.311198 * m - 0.20588 * s
b = 0.028104 * l - 0.19466 * m + 1.166325 * s
return clamp(r), clamp(g), clamp(b)
# 5. xyY (CIE 1931)
def rgb_to_xyy(r, g, b):
lr, lg, lb = srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b)
X = lr * 0.4124 + lg * 0.3576 + lb * 0.1805
Y = lr * 0.2126 + lg * 0.7152 + lb * 0.0722
Z = lr * 0.0193 + lg * 0.1192 + lb * 0.9505
sum_xyz = X + Y + Z
if sum_xyz == 0: return 0.3127, 0.3290, 0.0
x = X / sum_xyz
y = Y / sum_xyz
return x, y, Y
def xyy_to_rgb(x, y, Y):
if y == 0: return 0,0,0
X = (Y / y) * x
Z = (Y / y) * (1 - x - y)
lr = X * 3.2406 + Y * -1.5372 + Z * -0.4986
lg = X * -0.9689 + Y * 1.8758 + Z * 0.0415
lb = X * 0.0557 + Y * -0.2040 + Z * 1.0570
return linear_to_srgb(lr), linear_to_srgb(lg), linear_to_srgb(lb)
# Existing conversions
def rgb_to_xyz(r, g, b):
lr, lg, lb = srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b)
X = lr * 0.4124564 + lg * 0.3575761 + lb * 0.1804375
Y = lr * 0.2126729 + lg * 0.7151522 + lb * 0.0721750
Z = lr * 0.0193339 + lg * 0.1191920 + lb * 0.9503041
return X, Y, Z
def xyz_to_rgb(X, Y, Z):
lr = X * 3.2404542 + Y * -1.5371385 + Z * -0.4985314
lg = X * -0.9692660 + Y * 1.8760108 + Z * 0.0415560
lb = X * 0.0556434 + Y * -0.2040259 + Z * 1.0572252
return linear_to_srgb(lr), linear_to_srgb(lg), linear_to_srgb(lb)
def rgb_to_cieluv(r, g, b):
X, Y, Z = rgb_to_xyz(r, g, b)
Xn, Yn, Zn = 0.95047, 1.00000, 1.08883
den = (X + 15 * Y + 3 * Z)
u_prime = (4 * X) / den if den > 0 else 0
v_prime = (9 * Y) / den if den > 0 else 0
dn = (Xn + 15 * Yn + 3 * Zn)
u_prime_n = (4 * Xn) / dn
v_prime_n = (9 * Yn) / dn
y_ratio = Y / Yn
L = 116 * (y_ratio ** (1/3)) - 16 if y_ratio > 0.008856 else 903.3 * y_ratio
u = 13 * L * (u_prime - u_prime_n)
v = 13 * L * (v_prime - v_prime_n)
return L, u, v
def cieluv_to_rgb(L, u, v):
Xn, Yn, Zn = 0.95047, 1.00000, 1.08883
dn = (Xn + 15 * Yn + 3 * Zn)
u_prime_n = (4 * Xn) / dn
v_prime_n = (9 * Yn) / dn
if L <= 0: return 0.0, 0.0, 0.0
u_prime = (u / (13 * L)) + u_prime_n
v_prime = (v / (13 * L)) + v_prime_n
Y = Yn * ((L + 16) / 116) ** 3 if L > 8 else Yn * L / 903.3
X = Y * (9 * u_prime) / (4 * v_prime) if v_prime > 0 else 0
Z = Y * (12 - 3 * u_prime - 20 * v_prime) / (4 * v_prime) if v_prime > 0 else 0
return xyz_to_rgb(X, Y, Z)
def rgb_to_cielchuv(r, g, b):
L, u, v = rgb_to_cieluv(r, g, b)
C = math.sqrt(u**2 + v**2)
h = math.degrees(math.atan2(v, u))
return L, C, h
def cielchuv_to_rgb(L, C, h):
h_rad = math.radians(h)
u = C * math.cos(h_rad)
v = C * math.sin(h_rad)
return cieluv_to_rgb(L, u, v)
def rgb_to_ycbcr(r, g, b):
Y = 0.299 * r + 0.587 * g + 0.114 * b
Cb = -0.168736 * r - 0.331264 * g + 0.5 * b
Cr = 0.5 * r - 0.418688 * g - 0.081312 * b
return Y, Cb, Cr
def ycbcr_to_rgb(Y, Cb, Cr):
r = Y + 1.402 * Cr
g = Y - 0.344136 * Cb - 0.714136 * Cr
b = Y + 1.772 * Cb
return clamp(r), clamp(g), clamp(b)
def rgb_to_ypbpr(r, g, b):
Y = 0.299 * r + 0.587 * g + 0.114 * b
Pb = -0.169 * r - 0.331 * g + 0.5 * b
Pr = 0.5 * r - 0.419 * g - 0.081 * b
return Y, Pb, Pr
def ypbpr_to_rgb(Y, Pb, Pr):
r = Y + 1.402 * Pr
g = Y - 0.344 * Pb - 0.714 * Pr
b = Y + 1.772 * Pb
return clamp(r), clamp(g), clamp(b)
def rgb_to_hwb(r, g, b):
c = QColor.fromRgbF(r, g, b)
h = c.hueF()
v = c.valueF()
s = c.saturationF()
w = v * (1 - s)
bl = 1 - v
return h, w, bl
def hwb_to_rgb(h, w, bl):
if w + bl >= 1:
gray = w / (w + bl)
return gray, gray, gray
v = 1 - bl
s = 1 - (w / v) if v > 0 else 0
c = QColor.fromHsvF(max(0, min(1, h)), max(0, min(1, s)), max(0, min(1, v)))
return c.redF(), c.greenF(), c.blueF()
def rgb_to_lms(r, g, b):
lr, lg, lb = srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b)
L = 0.3897 * lr + 0.6890 * lg - 0.0787 * lb
M = -0.2298 * lr + 1.1834 * lg + 0.0464 * lb
S = 0.0000 * lr + 0.0000 * lg + 1.0000 * lb
return L, M, S
def lms_to_rgb(L, M, S):
lr = 1.9102 * L - 1.1121 * M + 0.2019 * S
lg = 0.3710 * L + 0.6291 * M + 0.0000 * S
lb = 0.0000 * L + 0.0000 * M + 1.0000 * S
return linear_to_srgb(lr), linear_to_srgb(lg), linear_to_srgb(lb)
# === DITHER PATTERNS ===
DITHER_MATRICES = {
"Bayer 2x2": {
"size": 2,
"data": [0, 2, 3, 1]
},
"Bayer 4x4": {
"size": 4,
"data": [
0, 8, 2, 10,
12, 4, 14, 6,
3, 11, 1, 9,
15, 7, 13, 5
]
},
"Bayer 8x8": {
"size": 8,
"data": [
0, 32, 8, 40, 2, 34, 10, 42,
48, 16, 56, 24, 50, 18, 58, 26,
12, 44, 4, 36, 14, 46, 6, 38,
60, 28, 52, 20, 62, 30, 54, 22,
3, 35, 11, 43, 1, 33, 9, 41,
51, 19, 59, 27, 49, 17, 57, 25,
15, 47, 7, 39, 13, 45, 5, 37,
63, 31, 55, 23, 61, 29, 53, 21
]
},
"Cluster 4x4": {
"size": 4,
"data": [
12, 5, 6, 13,
4, 0, 1, 7,
11, 3, 2, 8,
15, 10, 9, 14
]
}
}
# === 1. Custom 5-Bit Color Picker ===
class SnesColorPicker(QWidget):
colorChanged = Signal(int, int, int)
def __init__(self):
super().__init__()
self.setFixedSize(200, 200)
self.h, self.s, self.v = 0.0, 1.0, 1.0
self.r5, self.g5, self.b5 = 31, 0, 0
self.dragging_sv = False
self.dragging_h = False
self.RENDER_SIZE = 32
self.cached_square = None
self.cached_hue_bar = None
self.last_hue_for_square = -1
def set_color_5bit(self, r, g, b):
self.r5, self.g5, self.b5 = r, g, b
c = QColor(int(r/31*255), int(g/31*255), int(b/31*255))
self.h = max(0, c.hue())
self.s = c.saturationF()
self.v = c.valueF()
self.update()
def quantize_color(self, c):
r5 = int((c.red() / 255.0) * 31)
g5 = int((c.green() / 255.0) * 31)
b5 = int((c.blue() / 255.0) * 31)
return QColor(r5 << 3, g5 << 3, b5 << 3)
def paintEvent(self, event):
painter = QPainter(self)
square_rect = self.rect().adjusted(5, 5, -5, -35)
hue_rect = self.rect().adjusted(5, square_rect.height() + 10, -5, -5)
if self.cached_hue_bar is None:
self.cached_hue_bar = QImage(self.RENDER_SIZE, 1, QImage.Format_RGB32)
for x in range(self.RENDER_SIZE):
hue = (x / self.RENDER_SIZE) * 360.0
raw_c = QColor.fromHsvF(hue/360.0, 1.0, 1.0)
self.cached_hue_bar.setPixelColor(x, 0, self.quantize_color(raw_c))
painter.drawImage(hue_rect, self.cached_hue_bar.scaled(hue_rect.size(), Qt.IgnoreAspectRatio, Qt.FastTransformation))
if (self.cached_square is None or abs(self.h - self.last_hue_for_square) > 0.5):
self.last_hue_for_square = self.h
self.cached_square = QImage(self.RENDER_SIZE, self.RENDER_SIZE, QImage.Format_RGB32)
for y in range(self.RENDER_SIZE):
val = 1.0 - (y / self.RENDER_SIZE)
for x in range(self.RENDER_SIZE):
sat = x / self.RENDER_SIZE
raw_c = QColor.fromHsvF(self.h / 360.0, sat, val)
self.cached_square.setPixelColor(x, y, self.quantize_color(raw_c))
painter.drawImage(square_rect, self.cached_square.scaled(square_rect.size(), Qt.IgnoreAspectRatio, Qt.FastTransformation))
painter.setRenderHint(QPainter.Antialiasing)
cx = int(square_rect.left() + (self.s * square_rect.width()))
cy = int(square_rect.top() + ((1 - self.v) * square_rect.height()))
cx = max(square_rect.left(), min(square_rect.right(), cx))
cy = max(square_rect.top(), min(square_rect.bottom(), cy))
painter.setPen(QPen(Qt.black, 3))
painter.drawEllipse(QPoint(cx, cy), 6, 6)
painter.setPen(QPen(Qt.white, 1))
painter.drawEllipse(QPoint(cx, cy), 6, 6)
hx = int(hue_rect.left() + (self.h / 360.0 * hue_rect.width()))
hx = max(hue_rect.left(), min(hue_rect.right(), hx))
painter.setPen(QPen(Qt.black, 3))
painter.drawLine(hx, hue_rect.top()-2, hx, hue_rect.bottom()+2)
painter.setPen(QPen(Qt.white, 1))
painter.drawLine(hx, hue_rect.top()-2, hx, hue_rect.bottom()+2)
def mousePressEvent(self, event):
pos = event.position().toPoint()
square_rect = self.rect().adjusted(5, 5, -5, -35)
hue_rect = self.rect().adjusted(5, square_rect.height() + 10, -5, -5)
if square_rect.contains(pos):
self.dragging_sv = True
self.update_sv(pos, square_rect)
elif hue_rect.contains(pos):
self.dragging_h = True
self.update_h(pos, hue_rect)
def mouseMoveEvent(self, event):
pos = event.position().toPoint()
square_rect = self.rect().adjusted(5, 5, -5, -35)
hue_rect = self.rect().adjusted(5, square_rect.height() + 10, -5, -5)
if self.dragging_sv: self.update_sv(pos, square_rect)
elif self.dragging_h: self.update_h(pos, hue_rect)
def mouseReleaseEvent(self, event):
self.dragging_sv = False
self.dragging_h = False
def update_h(self, pos, rect):
x = max(0, min(rect.width(), pos.x() - rect.left()))
self.h = (x / rect.width()) * 360.0
self.emit_color()
self.update()
def update_sv(self, pos, rect):
x = max(0, min(rect.width(), pos.x() - rect.left()))
y = max(0, min(rect.height(), pos.y() - rect.top()))
self.s = x / rect.width()
self.v = 1.0 - (y / rect.height())
self.emit_color()
self.update()
def emit_color(self):
c = QColor.fromHsvF(self.h / 360.0, self.s, self.v)
r5 = int((c.red() / 255.0) * 31)
g5 = int((c.green() / 255.0) * 31)
b5 = int((c.blue() / 255.0) * 31)
if (r5 != self.r5 or g5 != self.g5 or b5 != self.b5):
self.r5, self.g5, self.b5 = r5, g5, b5
self.colorChanged.emit(r5, g5, b5)
# === 2. Curve Editor Widget ===
class CurveEditor(QWidget):
curveChanged = Signal(float, float, float, float)
def __init__(self):
super().__init__()
self.setFixedSize(160, 160)
self.setStyleSheet("background-color: #333; border: 1px solid #555;")
self.p1 = QPointF(0.25, 0.25)
self.p2 = QPointF(0.75, 0.75)
self.dragging = None # 1 or 2
self.hover = None
def set_curve(self, p1x, p1y, p2x, p2y):
self.p1 = QPointF(p1x, p1y)
self.p2 = QPointF(p2x, p2y)
self.update()
def transform_to_widget(self, pf):
rect = self.rect().adjusted(15, 15, -15, -15)
x = rect.left() + pf.x() * rect.width()
y = rect.bottom() - pf.y() * rect.height()
return QPointF(x, y)
def transform_from_widget(self, point):
rect = self.rect().adjusted(15, 15, -15, -15)
x = (point.x() - rect.left()) / rect.width()
y = (rect.bottom() - point.y()) / rect.height()
return QPointF(max(0, min(1, x)), max(0, min(1, y)))
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
rect = self.rect().adjusted(15, 15, -15, -15)
painter.setPen(QPen(QColor(80,80,80), 1))
painter.drawRect(rect)
painter.drawLine(rect.left(), rect.bottom(), rect.right(), rect.top())
start = QPointF(rect.left(), rect.bottom())
end = QPointF(rect.right(), rect.top())
cp1 = self.transform_to_widget(self.p1)
cp2 = self.transform_to_widget(self.p2)
painter.setPen(QPen(QColor(150, 150, 150), 1, Qt.DashLine))
painter.drawLine(start, cp1)
painter.drawLine(end, cp2)
path = QPainterPath()
path.moveTo(start)
path.cubicTo(cp1, cp2, end)
painter.setPen(QPen(Qt.white, 2))
painter.setBrush(Qt.NoBrush)
painter.drawPath(path)
def draw_handle(pt, col):
painter.setBrush(col)
painter.setPen(Qt.NoPen)
painter.drawEllipse(pt, 6, 6)
painter.setBrush(Qt.NoBrush)
painter.setPen(Qt.white)
painter.drawEllipse(pt, 6, 6)
draw_handle(cp1, QColor("#ff55aadd"))
draw_handle(cp2, QColor("#55aaffdd"))
def mousePressEvent(self, event):
pos = QPointF(event.position())
cp1 = self.transform_to_widget(self.p1)
cp2 = self.transform_to_widget(self.p2)
if (pos - cp1).manhattanLength() < 10:
self.dragging = 1
elif (pos - cp2).manhattanLength() < 10:
self.dragging = 2
def mouseMoveEvent(self, event):
if self.dragging:
norm_pos = self.transform_from_widget(QPointF(event.position()))
if self.dragging == 1:
self.p1 = norm_pos
else:
self.p2 = norm_pos
self.update()
self.curveChanged.emit(self.p1.x(), self.p1.y(), self.p2.x(), self.p2.y())
def mouseReleaseEvent(self, event):
self.dragging = None
# === 3. Preview Widget ===
class GradientPreviewWidget(QWidget):
def __init__(self):
super().__init__()
self.image = None
self.zoom_factor = 0 # 0 = Fit, 1 = 1x, etc.
self.current_w = 256
self.current_h = 224
self.setMinimumSize(1, 1)
self.setStyleSheet("background-color: #111;")
self.setSizePolicy(
sys.modules['PySide6.QtWidgets'].QSizePolicy.Ignored,
sys.modules['PySide6.QtWidgets'].QSizePolicy.Ignored
)
def set_image(self, image):
self.image = image
self.current_w = image.width()
self.current_h = image.height()
# Refresh the geometry based on the new image size if we are in fixed zoom mode
if self.zoom_factor > 0:
self.setFixedSize(self.current_w * self.zoom_factor, self.current_h * self.zoom_factor)
self.update()
def set_zoom(self, factor):
self.zoom_factor = factor
if factor > 0:
# Use the current image dimensions for the multiplier
self.setFixedSize(self.current_w * factor, self.current_h * factor)
else:
self.setMaximumSize(16777215, 16777215)
self.setMinimumSize(1, 1)
self.updateGeometry()
self.update()
def paintEvent(self, event):
painter = QPainter(self)
if not self.image:
painter.setPen(Qt.white)
painter.drawText(self.rect(), Qt.AlignCenter, "No Preview")
return
# "Fit to Window" Mode
if self.zoom_factor == 0:
scaled = self.image.scaled(self.size(), Qt.KeepAspectRatio, Qt.FastTransformation)
x = (self.width() - scaled.width()) // 2
y = (self.height() - scaled.height()) // 2
painter.drawImage(x, y, scaled)
# "Fixed Zoom" Mode
else:
painter.drawImage(self.rect(), self.image)
# === 4. Sidebar Settings Widget ===
class RenderSettingsWidget(QWidget):
settingsChanged = Signal()
def __init__(self):
super().__init__()
self.setFixedWidth(240)
# UPDATED STYLESHEET:
# Removed 'QSpinBox, QDoubleSpinBox' from the background/border rule
# so they use the native/Fusion style like the RGB inputs.
self.setStyleSheet("""
QWidget { background-color: #2b2b2b; color: #ddd; }
QGroupBox { font-weight: bold; border: 1px solid #444; margin-top: 6px; padding-top: 10px; }
QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px; }
QComboBox { background-color: #444; border: 1px solid #555; padding: 4px; }
QSlider::groove:horizontal { border: 1px solid #333; height: 6px; background: #111; margin: 2px 0; border-radius: 3px; }
QSlider::handle:horizontal { background: #0078d7; border: 1px solid #0078d7; width: 14px; margin: -5px 0; border-radius: 7px; }
QCheckBox { padding: 5px; }
""")
layout = QVBoxLayout(self)
# --- PREVIEW ZOOM SETTINGS ---
grp_view = QGroupBox("Preview View")
l_view = QVBoxLayout()
self.combo_zoom = QComboBox()
self.combo_zoom.addItems([
"Fit to Window",
"1x",
"2x",
"3x",
"4x"
])
self.combo_zoom.setCurrentIndex(3) # Default 3x
l_view.addWidget(QLabel("Scale:"))
l_view.addWidget(self.combo_zoom)
grp_view.setLayout(l_view)
layout.addWidget(grp_view)
# --- OUTPUT SETTINGS (Resolution / Bit Depth) ---
grp_out = QGroupBox("Output Settings")
l_out = QVBoxLayout()
# Resolution
res_layout = QGridLayout()
res_layout.addWidget(QLabel("W:"), 0, 0)
self.spin_width = QSpinBox()
self.spin_width.setRange(1, 512)
self.spin_width.setValue(SNES_WIDTH)
self.spin_width.valueChanged.connect(lambda: self.settingsChanged.emit())
res_layout.addWidget(self.spin_width, 0, 1)
res_layout.addWidget(QLabel("H:"), 0, 2)
self.spin_height = QSpinBox()
self.spin_height.setRange(1, 512)
self.spin_height.setValue(SNES_HEIGHT)
self.spin_height.valueChanged.connect(lambda: self.settingsChanged.emit())
res_layout.addWidget(self.spin_height, 0, 3)
l_out.addLayout(res_layout)
# Bit Depth
depth_layout = QHBoxLayout()
depth_layout.addWidget(QLabel("Bit Depth:"))
self.spin_depth = QSpinBox()
self.spin_depth.setRange(1, 8)
self.spin_depth.setValue(5) # Default SNES 5-bit
self.spin_depth.valueChanged.connect(lambda: self.settingsChanged.emit())
depth_layout.addWidget(self.spin_depth)
l_out.addLayout(depth_layout)
grp_out.setLayout(l_out)
layout.addWidget(grp_out)
# Color Space
grp_space = QGroupBox("Color Blending")
l_space = QVBoxLayout()
self.combo_space = QComboBox()
self.combo_space.addItems([
"Standard RGB",
"Linear RGB (Physical)",
"Oklab (Smooth)",
"Oklch (Vibrant)",
"IPT (Perceptual)",
"CMY (Subtractive)",
"YIQ (NTSC)",
"YDbDr (SECAM)",
"HSV (Rainbow)",
"HSL (Classic)",
"CIELAB (Standard)",
"CIELCH (Polar Lab)",
"xyY (CIE 1931)",
"XYZ",
"CIELUV",
"HWB"
])
self.combo_space.setCurrentIndex(0)
self.combo_space.currentIndexChanged.connect(lambda: self.settingsChanged.emit())
l_space.addWidget(QLabel("Color Space:"))
l_space.addWidget(self.combo_space)
grp_space.setLayout(l_space)
layout.addWidget(grp_space)
# Interpolation
grp_ease = QGroupBox("Default Interpolation")
l_ease = QVBoxLayout()
self.combo_ease = QComboBox()
self.combo_ease.addItems(list(EASING_FUNCS.keys()))
self.combo_ease.setCurrentText("Linear")
self.combo_ease.currentIndexChanged.connect(lambda: self.settingsChanged.emit())
l_ease.addWidget(QLabel("Global Easing:"))
l_ease.addWidget(self.combo_ease)
grp_ease.setLayout(l_ease)
layout.addWidget(grp_ease)
# Dithering
grp_dither = QGroupBox("Smoothing")
l_dither = QVBoxLayout()
self.check_enable_dither = QCheckBox("Enable Dithering")
self.check_enable_dither.setChecked(False)
self.check_enable_dither.toggled.connect(self.on_dither_toggle)
l_dither.addWidget(self.check_enable_dither)
self.container_dither_settings = QWidget()
self.container_dither_settings.setVisible(False)
l_dither_inner = QVBoxLayout(self.container_dither_settings)
l_dither_inner.setContentsMargins(0,0,0,0)
self.combo_dither = QComboBox()
self.combo_dither.addItems([
"Bayer 2x2",
"Bayer 4x4 (Standard)",
"Bayer 8x8 (Smooth)",
"Cluster 4x4 (Dot)",
"Scanline Horizontal",
"Scanline Vertical",
"White Noise (Grainy)"
])
self.combo_dither.setCurrentIndex(1)
self.combo_dither.currentIndexChanged.connect(lambda: self.settingsChanged.emit())
l_dither_inner.addWidget(QLabel("Dither Pattern:"))
l_dither_inner.addWidget(self.combo_dither)
self.lbl_strength = QLabel("Strength: 100%")
l_dither_inner.addWidget(self.lbl_strength)
self.slider_strength = QSlider(Qt.Horizontal)
self.slider_strength.setRange(0, 150)
self.slider_strength.setValue(100)
self.slider_strength.valueChanged.connect(self.on_strength_change)
l_dither_inner.addWidget(self.slider_strength)
l_dither.addWidget(self.container_dither_settings)
grp_dither.setLayout(l_dither)
layout.addWidget(grp_dither)
layout.addStretch()
def on_dither_toggle(self, checked):
self.container_dither_settings.setVisible(checked)
self.settingsChanged.emit()
def on_strength_change(self, val):
self.lbl_strength.setText(f"Strength: {val}%")
self.settingsChanged.emit()
# === 5. Data Class ===
class SnesStop:
def __init__(self, position, r, g, b, locked_pos=False):
self.position = position
self.r = int(r)
self.g = int(g)
self.b = int(b)
self.locked_pos = locked_pos
self.ease_mode = "Global (Default)"
self.curve_p1 = (0.25, 0.25)
self.curve_p2 = (0.75, 0.75)
def get_qt_color(self):
return QColor(self.r << 3, self.g << 3, self.b << 3)
def to_dict(self):
return {
'position': self.position,
'r': self.r,
'g': self.g,
'b': self.b,
'locked_pos': self.locked_pos,
'ease_mode': self.ease_mode,
'curve_p1': self.curve_p1,
'curve_p2': self.curve_p2
}
@classmethod
def from_dict(cls, data):
stop = cls(
position=data['position'],
r=data['r'],
g=data['g'],
b=data['b'],
locked_pos=data.get('locked_pos', False)
)
stop.ease_mode = data.get('ease_mode', "Global (Default)")
stop.curve_p1 = data.get('curve_p1', (0.25, 0.25))
stop.curve_p2 = data.get('curve_p2', (0.75, 0.75))
return stop
# === 6. Main Application ===
class SnesGradientTool(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Purp's PRO-Gradient Tool")
self.resize(1150, 750)
# Init Data
self.stops = []
self.selected_index = 0
self.generated_image = None
self.updating_ui = False
self.is_dragging_slider = False
# Setup UI
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.setup_ui()
self.setup_menu()
self.apply_preset_white_to_black()
def setup_menu(self):
menubar = self.menuBar()
# --- File ---
file_menu = menubar.addMenu("File")
act_save = QAction("Save PNG...", self)
act_save.triggered.connect(self.save_image)
file_menu.addAction(act_save)
file_menu.addSeparator()
act_exit = QAction("Exit", self)
act_exit.triggered.connect(self.close)
file_menu.addAction(act_exit)
# --- Presets (TOP LEVEL) ---
presets_menu = menubar.addMenu("Presets")
builtin_menu = QMenu("Built-in", self)
actions = [
("Normal White → Black", self.apply_preset_white_to_black),
("Sunset (Purple → Orange)", self.apply_preset_sunset),
("Forest (Green)", self.apply_preset_forest),
("Ocean (Blue)", self.apply_preset_ocean),
("Neon Cyber", self.apply_preset_neon),
("Heatmap", self.apply_preset_heatmap),
]
for name, fn in actions:
act = QAction(name, self)
act.triggered.connect(fn)
builtin_menu.addAction(act)
presets_menu.addMenu(builtin_menu)
presets_menu.addSeparator()
act_save_preset = QAction("Save Current as Preset...", self)
act_save_preset.triggered.connect(self.save_preset)
presets_menu.addAction(act_save_preset)
act_load_preset = QAction("Load Preset...", self)
act_load_preset.triggered.connect(self.load_preset)
presets_menu.addAction(act_load_preset)
def apply_preset_white_to_black(self):
self.stops = [
SnesStop(0.0, 31, 31, 31, locked_pos=True),
SnesStop(1.0, 0, 0, 0, locked_pos=True)
]
self.refresh_stop_list()
self.update_preview()
def apply_preset_sunset(self):
self.stops = [
SnesStop(0.0, 10, 2, 18, locked_pos=True),
SnesStop(0.5, 31, 10, 5),
SnesStop(1.0, 31, 28, 0, locked_pos=True)
]
self.refresh_stop_list()
self.update_preview()
def apply_preset_forest(self):
self.stops = [
SnesStop(0.0, 2, 8, 2, locked_pos=True),
SnesStop(0.5, 10, 25, 5),
SnesStop(1.0, 28, 31, 15, locked_pos=True)
]
self.refresh_stop_list()
self.update_preview()
def apply_preset_ocean(self):
self.stops = [
SnesStop(0.0, 0, 2, 12, locked_pos=True),
SnesStop(0.5, 0, 15, 31),
SnesStop(1.0, 25, 31, 31, locked_pos=True)
]
self.refresh_stop_list()
self.update_preview()
def apply_preset_neon(self):
self.stops = [
SnesStop(0.0, 31, 0, 20, locked_pos=True),
SnesStop(1.0, 0, 31, 31, locked_pos=True)
]
self.refresh_stop_list()
self.update_preview()
def apply_preset_heatmap(self):
self.stops = [
SnesStop(0.0, 0, 0, 31, locked_pos=True),
SnesStop(0.5, 0, 31, 0),
SnesStop(1.0, 31, 0, 0, locked_pos=True)
]
self.refresh_stop_list()
self.update_preview()
def save_preset(self):
if len(self.stops) == 0: return
file_path, _ = QFileDialog.getSaveFileName(self, "Save Preset", "", "JSON Preset Files (*.json);;All Files (*)")
if not file_path: return
if not file_path.lower().endswith('.json'): file_path += '.json'
try:
preset_data = {
'stops': [stop.to_dict() for stop in self.stops],
'settings': {
'color_space': self.settings_sidebar.combo_space.currentText(),
'global_easing': self.settings_sidebar.combo_ease.currentText(),
'dither_enabled': self.settings_sidebar.check_enable_dither.isChecked(),
'dither_mode': self.settings_sidebar.combo_dither.currentText(),
'dither_strength': self.settings_sidebar.slider_strength.value()
}
}
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(preset_data, f, indent=2)
QMessageBox.information(self, "Preset Saved", f"Preset saved to:\n{file_path}")
except Exception as e:
QMessageBox.critical(self, "Save Error", f"Failed to save preset:\n{str(e)}")
def load_preset(self):
file_path, _ = QFileDialog.getOpenFileName(self, "Load Preset", "", "JSON Preset Files (*.json);;All Files (*)")
if not file_path: return
try:
with open(file_path, 'r', encoding='utf-8') as f:
preset_data = json.load(f)
self.stops = []
for stop_data in preset_data['stops']:
self.stops.append(SnesStop.from_dict(stop_data))
if 'settings' in preset_data:
settings = preset_data['settings']
color_space = settings.get('color_space', 'Oklch (Vibrant)')
idx = self.settings_sidebar.combo_space.findText(color_space)
if idx >= 0: self.settings_sidebar.combo_space.setCurrentIndex(idx)
global_easing = settings.get('global_easing', 'Linear')
idx = self.settings_sidebar.combo_ease.findText(global_easing)
if idx >= 0: self.settings_sidebar.combo_ease.setCurrentIndex(idx)
dither_en = settings.get('dither_enabled', True)
self.settings_sidebar.check_enable_dither.setChecked(dither_en)
dither_mode = settings.get('dither_mode', "Bayer 4x4 (Standard)")
idx = self.settings_sidebar.combo_dither.findText(dither_mode)
if idx >= 0: self.settings_sidebar.combo_dither.setCurrentIndex(idx)
self.settings_sidebar.slider_strength.setValue(settings.get('dither_strength', 100))
self.refresh_stop_list()
self.update_preview()
except Exception as e:
QMessageBox.critical(self, "Load Error", f"Failed to load preset:\n{str(e)}")