summaryrefslogtreecommitdiff
path: root/Plugin.cs
blob: 9cb230e6dd942f67afba7b25d44b6bac524c04c4 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
//#define ENABLE_ASSERTS
//#define OVERSIZED_SHADOW_MAP
//#define SHADER_FEATURES
//#define RESOURCE_ADJUSTMENT

using System.Numerics;
using System.Globalization;
using System.Runtime.CompilerServices;
#if ENABLE_ASSERTS
using System.Diagnostics;
#endif

using ImGuiNET;
using SharpPluginLoader.Core;
using SharpPluginLoader.Core.Configuration;
using SharpPluginLoader.Core.Memory;
#if SHADER_FEATURES
using SharpPluginLoader.Core.Rendering;
#endif
#if RESOURCE_ADJUSTMENT
using SharpPluginLoader.Core.Resources;
#endif

// @TODO:
//  - Configurable Broad Area Shadow Resolution.
//  - Hook sMhScene constructor to set hqMode.
//  - Optimized update logic.
//   - Only update non-override values when UI is shown.
//  - Map sky params.
//  - Lights refactor.
//  - Descriptions.
//  - float format.
//  - Lights iterop.
//  - SPL Patches:
//   - No crash on empty config.
//   - Style change
//  - Hotload nukes config?
//
// Areas that need Shadow Distance retuning:
//  - Exit of central camp in Horfrost Reach.
//  - Sporepuff area in The Ancient Forest.
//  - Wildspire Waste entrence to enclosed area past the waterfall.
//  - The Rotten Vale jump out of Southeast Camp. Wall on the opposite side slightly to the left.
//  - Rotten vale lower area.
//  - Special Arena.
//  - Elder's Recess Lavasioth area.
//  - Hoarfrost pit area with wedge beetles.
//
// Known issues to think about:
//  - Hair clipping when character looks down.
//   - Vangis headband.
//  - Volume rendering can look really bad with multiple overlapped sources(?) (Guding lands vines).
//  - Screen space reflections often look bad.
//  - Facial contact shadows unnaturally move based on camera position.

namespace WorldTuningTool
{
    using static Config;

    public unsafe class Plugin : IPlugin
    {
        public string Name => "World Tuning Tool";
        public string Author => "Akon City Software";

        private static bool loggedAssertFailed = false;
        public static void Assert(bool condition, [CallerLineNumber] int line = 0)
        {
            if (!condition && !loggedAssertFailed)
            {
                Log.Error($"Assert failed on line {line}.");
                loggedAssertFailed = true;
            }
#if ENABLE_ASSERTS
            Trace.Assert(condition);
#endif
        }

        public static nint lton(long l) { unchecked { return (nint)l; } }

        private static byte ByteFlag(bool f) { return f ? (byte)0x1 : (byte)0x0; }

        private static int BitIndex(int mask)
        {
            return BitOperations.Log2((uint)(mask & (-mask)));
        }

        private static Vector4 ColorVectorFromInt(int c)
        {
            return new Vector4(
                ((c      ) & 0xFF) / 255.0f,
                ((c >> 8 ) & 0xFF) / 255.0f,
                ((c >> 16) & 0xFF) / 255.0f,
                ((c >> 24) & 0xFF) / 255.0f);
        }

        private static int ColorVectorToInt(Vector4 v)
        {
            return ((int)MathF.Round(v.X * 255.0f)     |
                ((int)MathF.Round(v.Y * 255.0f) << 8)  |
                ((int)MathF.Round(v.Z * 255.0f) << 16) |
                ((int)MathF.Round(v.W * 255.0f) << 24));
        }

        private static float StringToSingle(string s) { return Convert.ToSingle(s, CultureInfo.InvariantCulture); }
        private static bool StringToBoolean(string s) { return Convert.ToBoolean(s, CultureInfo.InvariantCulture); }
        private static int StringToInt32(string s, int fromBase = 10)
        {
            if (fromBase == 10) return Convert.ToInt32(s, CultureInfo.InvariantCulture);
            return Convert.ToInt32(s, fromBase);
        }
        private static string SingleToString(float f, string? format = null) { return f.ToString(format, CultureInfo.InvariantCulture); }
        private static string BooleanToString(bool b) { return b.ToString(CultureInfo.InvariantCulture); }
        private static string Int32ToString(int i, string? format = null) { return i.ToString(format, CultureInfo.InvariantCulture); }

        public static Vector2 StringToVector2(string s, char delim = ',')
        {
            if (String.IsNullOrEmpty(s)) throw new FormatException();
            string[] sp = s.Split(delim).Select(v => v.Trim()).ToArray();
            if (sp.Length != 2) throw new FormatException();
            return new Vector2(StringToSingle(sp[0]), StringToSingle(sp[1]));
        }

        public static Vector3 StringToVector3(string s, char delim = ',')
        {
            if (String.IsNullOrEmpty(s)) throw new FormatException();
            string[] sp = s.Split(delim).Select(v => v.Trim()).ToArray();
            if (sp.Length != 3) throw new FormatException();
            return new Vector3(StringToSingle(sp[0]), StringToSingle(sp[1]), StringToSingle(sp[2]));
        }

        public static Vector4 StringToVector4(string s, char delim = ',')
        {
            if (String.IsNullOrEmpty(s)) throw new FormatException();
            string[] sp = s.Split(delim).Select(v => v.Trim()).ToArray();
            if (sp.Length != 4) throw new FormatException();
            return new Vector4(StringToSingle(sp[0]), StringToSingle(sp[1]), StringToSingle(sp[2]), StringToSingle(sp[3]));
        }

        private static string Vector2ToString(Vector2 v)
        {
            return string.Format(CultureInfo.InvariantCulture, "{0},{1}", v.X, v.Y);
        }

        private static string Vector3ToString(Vector3 v)
        {
            return string.Format(CultureInfo.InvariantCulture, "{0},{1},{2}", v.X, v.Y, v.Z);
        }

        private static string Vector4ToString(Vector4 v)
        {
            return string.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", v.X, v.Y, v.Z, v.W);
        }

        public enum ParameterType
        {
            BOOL,
            FLAG,
            BYTE,
            INT,
            ALIGNED_INT,
            HEX,
            COLOR,
            COLOR_FACTOR,
            FLOAT,
            VECTOR3,
            VECTOR2,
            VECTOR4,
            PATCH_FLOAT,
            SHADOW_RESOLUTION
        }

        private static IPlugin? Instance = null;

        private static Config getConfig()
        {
            return ConfigManager.GetConfig<Config>(Instance!);
        }

        private static void rebuildConfig(Config config, List<Override> overrides)
        {
            List<Override> selectedGlobals = config.Globals[selectedGlobal];
            selectedGlobals.Clear();
            foreach (Override ovG in overrides)
            {
                selectedGlobals.Add(ovG);
            }
        }

        private static int configState = 0;
        private const int SelectedNotSaved = 1;
        private const int SetNotSaved = (1 << 1);

        private static void saveConfig(Config config)
        {
            List<Override> tmpOverrides = config.Overrides[globalStage];
            config.Overrides.Remove(globalStage);
            ConfigManager.SaveConfig<Config>(Instance!);
            config.Overrides[globalStage] = tmpOverrides;
            configState = 0;
        }

        private const float defaultParamWidth = 0.215f;

        private static bool ignoreMinMax = false;

        private const StageExt globalStage = StageExt.Global;
        private static StageExt currentStage => (StageExt)Area.CurrentStage;
        private static List<Override>? maybeGetStageOverrides(Config config)
        {
            if (!config.Overrides.ContainsKey(currentStage))
            {
                return null;
            }
            return (currentStage != StageExt.Global) ? config.Overrides[currentStage] : null;
        }

        private static StageExt selectedStage = globalStage;
        private static StageExt previousStage = selectedStage;

        private static string selectedGlobal = "";

        private static string selectedSet = "";
        private static bool renamingSet = false;
        private static string typedSetName = "";

        private static Dictionary<int, Override> externalOverrides = new Dictionary<int, Override>();
        private static int externalId = 0;

        private static bool overridesContainsParam(IEnumerable<Override> overrides, Parameter param)
        {
            foreach (Override ov in overrides)
            {
                if (ov.Param == param)
                {
                    return true;
                }
            }
            return false;
        }

        private static bool unsetIfOverridesContainsParam(IEnumerable<Override> overrides, Parameter param)
        {
            foreach (Override ov in overrides)
            {
                if (ov.Param == param)
                {
                    ov.Unset();
                    return true;
                }
            }
            return false;
        }

        private static bool setIfOverridesContainsParam(IEnumerable<Override> overrides, Parameter param)
        {
            foreach (Override ov in overrides)
            {
                if (ov.Param == param)
                {
                    ov.Set();
                    return true;
                }
            }
            return false;
        }

        // globalOverrides == null: selectedStage is globalStage.
        private static bool selectedOverrideSuperseded(Config config, List<Override>? globalOverrides, List<Override>? stageOverrides, Parameter? param)
        {
            // Non-current stage always superseded (inactive).
            bool superseded = globalOverrides != null && selectedStage != currentStage;
            if (!superseded && param != null)
            {
                // If Global is selected, check if superseded by a currentStage override.
                superseded |= globalOverrides == null && stageOverrides != null && overridesContainsParam(stageOverrides, param);
                // Any other selectedStage override is either inactive or could only be superseded by a set or external override.
                superseded |= selectedSet != "" && overridesContainsParam(config.Sets[selectedSet], param);
                superseded |= overridesContainsParam(externalOverrides.Values, param);
            }
            return superseded;
        }

        private static bool stageOverrideSuperseded(Config config, Parameter? param)
        {
            bool superseded = false;
            if (param != null)
            {
                superseded |= selectedSet != "" && overridesContainsParam(config.Sets[selectedSet], param);
                superseded |= overridesContainsParam(externalOverrides.Values, param);
            }
            return superseded;
        }

        private static class ParameterFlags
        {
            public const int ViewOnly = 1;
        }

        public abstract class Parameter
        {
            public string Name;
            private string hiddenName;
            public ParameterType Type;

            private nint offset;
            private int mask;
            private nint lastAddr = 0x0;
            private bool overrideValue = false;
            private bool overrideForStage = false;
            private bool overrideWasOn = false;

            private int flags;
            public bool ViewOnly => (flags & ParameterFlags.ViewOnly) == ParameterFlags.ViewOnly;

            protected float stepf, minf, maxf;
            protected int step, min, max;

            private bool fallbackUpdate = true;
            private bool pendingWrite = false;
            private Vector4 valueV = default;
            private int valueInt = 0;
            private Vector4 oValueV; // Original value.
            private int oValueInt;

            private bool pendingUpdate = true;
            private bool queuedOverride = false;
            private bool queuedValue = false;
            private Vector4 qValueV; // Queued value.
            private int qValueInt;

            private bool bValue = false;
            private Vector4 bValueV; // B value in A/B.
            private int bValueInt;

            public Parameter(string name, nint offset, int mask, ParameterType type, int flags)
            {
                Name = name;
                hiddenName = "##" + Name;
                Type = type;
                switch (Type)
                {
                    case ParameterType.FLAG:
                        Assert(mask != 0);
                        break;
                    case ParameterType.PATCH_FLOAT:
                        valueV.X = MemoryUtil.Read<float>(offset);
                        pendingUpdate = false;
                        break;
                    case ParameterType.SHADOW_RESOLUTION:
                        valueInt = 1;
                        pendingUpdate = false;
                        break;
                }
                this.offset = offset;
                this.mask = mask;
                this.flags = flags;
            }

            public bool PendingUpdate()
            {
                return pendingUpdate;
            }

            public (Vector4, int) GetValue()
            {
                return (valueV, valueInt);
            }

            public int GetMask()
            {
                return mask;
            }

            public void Resolve()
            {
                Assert(!InTransition && pendingWrite);
                pendingWrite = false;
                maybeWriteCurrentValue();
            }

            private void maybeWriteCurrentValue()
            {
                if (InTransition)
                {
                    if (!DirtyParams.Contains(this))
                    {
                        pendingWrite = true;
                        DirtyParams.Add(this);
                    }
                    else
                    {
                        Assert(pendingWrite);
                    }
                    return;
                }
                Assert(!pendingWrite);
                switch (Type)
                {
                    case ParameterType.PATCH_FLOAT:
                        new Patch(offset, BitConverter.GetBytes(valueV.X)).Enable();
                        break;
                    case ParameterType.SHADOW_RESOLUTION:
                        if (valueInt > 1)
                        {
                            shadowResEnable(valueInt);
                        }
                        else
                        {
                            shadowResDisable();
                        }
                        break;
                }
                if (lastAddr == 0x0)
                {
                    return;
                }
                switch (Type)
                {
                    case ParameterType.BOOL:
                    case ParameterType.BYTE:
                        MemoryUtil.GetRef<byte>(lastAddr + offset) = (byte)valueInt;
                        break;
                    case ParameterType.FLAG:
                    {
                        ref int i1 = ref MemoryUtil.GetRef<int>(lastAddr + offset);
                        if (valueInt != 0)
                        {
                            i1 |= mask;
                        }
                        else
                        {
                            i1 &= ~mask;
                        }
                        break;
                    }
                    case ParameterType.INT:
                    case ParameterType.ALIGNED_INT:
                    case ParameterType.HEX:
                    case ParameterType.COLOR:
                    {
                        ref int i1 = ref MemoryUtil.GetRef<int>(lastAddr + offset);
                        if (mask != 0)
                        {
                            i1 = (i1 & ~mask) | ((valueInt << BitIndex(mask)) & mask);
                        }
                        else
                        {
                            i1 = valueInt;
                        }
                        break;
                    }
                    case ParameterType.FLOAT:
                        MemoryUtil.GetRef<float>(lastAddr + offset) = valueV.X;
                        break;
                    case ParameterType.VECTOR2:
                        MemoryUtil.GetRef<Vector2>(lastAddr + offset) = new Vector2(valueV.X, valueV.Y);
                        break;
                    case ParameterType.VECTOR3:
                    case ParameterType.COLOR_FACTOR:
                        MemoryUtil.GetRef<Vector3>(lastAddr + offset) = new Vector3(valueV.X, valueV.Y, valueV.Z);
                        break;
                    case ParameterType.VECTOR4:
                        MemoryUtil.GetRef<Vector4>(lastAddr + offset) = valueV;
                        break;
                }
            }

            public void ForceOverrideOn()
            {
                if (!queuedOverride && !overrideValue)
                {
                    OverrideOn(false);
                }
            }

            public void ForceOverrideOff()
            {
                if (queuedOverride || overrideValue)
                {
                    OverrideOff();
                }
            }

            public void OverrideOn(bool forStage)
            {
                if (pendingUpdate)
                {
                    if (queuedOverride)
                    {
                        Assert(!overrideWasOn && forStage);
                        overrideWasOn = true;
                    }
                    else
                    {
                        queuedOverride = true;
                    }
                }
                else
                {
                    if (overrideValue)
                    {
                        Assert(!overrideWasOn && forStage);
                        overrideWasOn = true;
                    }
                    else
                    {
                        oValueV = valueV;
                        oValueInt = valueInt;
                        maybeWriteCurrentValue();
                        overrideValue = true;
                    }
                }
                overrideForStage = forStage;
            }

            public void OverrideOff()
            {
                if (queuedOverride)
                {
                    if (overrideWasOn)
                    {
                        Assert(overrideForStage);
                        overrideWasOn = false;
                    }
                    else
                    {
                        queuedOverride = false;
                    }
                }
                else
                {
                    Assert(overrideValue);
                    if (overrideWasOn)
                    {
                        Assert(overrideForStage);
                        overrideWasOn = false;
                    }
                    else
                    {
                        valueV = oValueV;
                        valueInt = oValueInt;
                        maybeWriteCurrentValue();
                        bValue = false;
                        overrideValue = false;
                    }
                }
                overrideForStage = false;
            }

            public void SetOverrideValue(Vector4 v4, int i1)
            {
                if (queuedOverride)
                {
                    qValueV = v4;
                    qValueInt = i1;
                    queuedValue = true;
                }
                else
                {
                    valueV = v4;
                    valueInt = i1;
                    maybeWriteCurrentValue();
                }
            }

            public void Update(nint baseObject, bool fromHook = false)
            {
                lastAddr = baseObject;

                if (baseObject == 0x0)
                {
                    pendingUpdate = true;
                    return;
                }

                if (fromHook)
                {
                    fallbackUpdate = false;
                }
                else if (!fallbackUpdate)
                {
                    fallbackUpdate = true;
                    return;
                }

                // Trying to track changes to the original value is a "best effort"
                // approach because it can't work if the in-game value is updated
                // to the same value as a current override.
                switch (Type)
                {
                    case ParameterType.BOOL:
                    case ParameterType.BYTE:
                    {
                        ref byte b1 = ref MemoryUtil.GetRef<byte>(baseObject + offset);
                        if (overrideValue)
                        {
                            if (b1 != (byte)valueInt)
                            {
                                oValueInt = b1;
                            }
                            b1 = (byte)valueInt;
                        }
                        else
                        {
                            valueInt = b1;
                        }
                        break;
                    }
                    case ParameterType.FLAG:
                    {
                        ref int i1 = ref MemoryUtil.GetRef<int>(baseObject + offset);
                        int b1 = ByteFlag((i1 & mask) == mask);
                        if (overrideValue)
                        {
                            if (b1 != valueInt)
                            {
                                oValueInt = b1;
                            }
                            if (valueInt != 0)
                            {
                                i1 |= mask;
                            }
                            else
                            {
                                i1 &= ~mask;
                            }
                        }
                        else
                        {
                            valueInt = b1;
                        }
                        break;
                    }
                    case ParameterType.INT:
                    case ParameterType.ALIGNED_INT:
                    case ParameterType.HEX:
                    case ParameterType.COLOR:
                    {
                        ref int i1 = ref MemoryUtil.GetRef<int>(baseObject + offset);
                        int m1 = i1;
                        if (mask != 0)
                        {
                            m1 = (i1 & mask) >> BitIndex(mask);
                        }
                        if (overrideValue)
                        {
                            if (m1 != valueInt)
                            {
                                oValueInt = m1;
                            }
                            if (mask != 0)
                            {
                                i1 = (i1 & ~mask) | ((valueInt << BitIndex(mask)) & mask);
                            }
                            else
                            {
                                i1 = valueInt;
                            }
                        }
                        else
                        {
                            valueInt = m1;
                        }
                        break;
                    }
                    case ParameterType.FLOAT:
                    {
                        ref float f1 = ref MemoryUtil.GetRef<float>(baseObject + offset);
                        if (overrideValue)
                        {
                            if (f1 != valueV.X)
                            {
                                oValueV.X = f1;
                            }
                            f1 = valueV.X;
                        }
                        else
                        {
                            valueV.X = f1;
                        }
                        break;
                    }
                    case ParameterType.VECTOR2:
                    {
                        ref Vector2 v2 = ref MemoryUtil.GetRef<Vector2>(baseObject + offset);
                        Vector2 valueV2 = new Vector2(valueV.X, valueV.Y);
                        if (overrideValue)
                        {
                            if (v2 != valueV2)
                            {
                                oValueV = new Vector4(v2.X, v2.Y, 0.0f, 0.0f);
                            }
                            v2 = valueV2;
                        }
                        else
                        {
                            valueV = new Vector4(v2.X, v2.Y, 0.0f, 0.0f);
                        }
                        break;
                    }
                    case ParameterType.VECTOR3:
                    case ParameterType.COLOR_FACTOR:
                    {
                        ref Vector3 v3 = ref MemoryUtil.GetRef<Vector3>(baseObject + offset);
                        Vector3 valueV3 = new Vector3(valueV.X, valueV.Y, valueV.Z);
                        if (overrideValue)
                        {
                            if (v3 != valueV3)
                            {
                                oValueV = new Vector4(v3.X, v3.Y, v3.Z, 0.0f);
                            }
                            v3 = valueV3;
                        }
                        else
                        {
                            valueV = new Vector4(v3.X, v3.Y, v3.Z, 0.0f);
                        }
                        break;
                    }
                    case ParameterType.VECTOR4:
                    {
                        ref Vector4 v4 = ref MemoryUtil.GetRef<Vector4>(baseObject + offset);
                        if (overrideValue)
                        {
                            if (v4 != valueV)
                            {
                                oValueV = v4;
                            }
                            v4 = valueV;
                        }
                        else
                        {
                            valueV = v4;
                        }
                        break;
                    }
                }

                if (pendingUpdate)
                {
                    pendingUpdate = false;
                    if (queuedOverride)
                    {
                        Assert(!overrideValue);
                        OverrideOn(overrideForStage);
                        if (queuedValue)
                        {
                            valueV = qValueV;
                            valueInt = qValueInt;
                            maybeWriteCurrentValue();
                            queuedValue = false;
                        }
                        queuedOverride = false;
                    }
                }
            }

            public void AdjustValue(ref Vector4 v4, ref int i1)
            {
                if (Type == ParameterType.SHADOW_RESOLUTION) // Hard limit.
                {
#if OVERSIZED_SHADOW_MAP
                    i1 = Math.Clamp(i1, 1, 6);
#else
                    i1 = Math.Clamp(i1, 1, 5);
#endif
                }
                else if (!ignoreMinMax)
                {
                    switch (Type)
                    {
                        case ParameterType.BOOL:
                        case ParameterType.FLAG:
                        case ParameterType.BYTE:
                        case ParameterType.INT:
                        case ParameterType.HEX:
                            i1 = Math.Clamp(i1, min, max);
                            break;
                        case ParameterType.ALIGNED_INT:
                            i1 = Math.Clamp((i1 + (step - 1))&~(step - 1), min, max);
                            break;
                        case ParameterType.FLOAT:
                        case ParameterType.PATCH_FLOAT:
                        case ParameterType.VECTOR2:
                        case ParameterType.VECTOR3:
                        case ParameterType.COLOR_FACTOR:
                        case ParameterType.VECTOR4:
                            v4 = new Vector4(
                                Math.Clamp(v4.X, minf, maxf),
                                Math.Clamp(v4.Y, minf, maxf),
                                Math.Clamp(v4.Z, minf, maxf),
                                Math.Clamp(v4.W, minf, maxf));
                            break;
                    }
                }
            }

            public bool DrawValue(ref Vector4 v4, ref int i1, float width, bool drawLabel)
            {
                bool valueChanged = false;
                string label = drawLabel ? Name : hiddenName;
                float displayMinf = ignoreMinMax ? 0.0f : minf;
                float displayMaxf = ignoreMinMax ? 0.0f : maxf;
                switch (Type)
                {
                    case ParameterType.BOOL:
                    case ParameterType.FLAG:
                    {
                        bool b = i1 != 0;
                        if (ImGui.Checkbox(label, ref b))
                        {
                            i1 = ByteFlag(b);
                            valueChanged = true;
                        }
                        break;
                    }
                    case ParameterType.BYTE:
                    {
                        ImGuiInputTextFlags flags = ImGuiInputTextFlags.EnterReturnsTrue;
                        ImGui.SetNextItemWidth(width * defaultParamWidth);
                        if (ImGui.InputInt(label, ref i1, step, 0, flags))
                        {
                            valueChanged = true;
                        }
                        break;
                    }
                    case ParameterType.INT:
                    case ParameterType.ALIGNED_INT:
                    case ParameterType.HEX:
                    case ParameterType.SHADOW_RESOLUTION:
                    {
                        ImGuiInputTextFlags flags = ImGuiInputTextFlags.EnterReturnsTrue;
                        if (Type == ParameterType.HEX)
                        {
                            flags |= ImGuiInputTextFlags.CharsHexadecimal;
                        }
                        ImGui.SetNextItemWidth(width * defaultParamWidth);
                        if (ImGui.InputInt(label, ref i1, step, 0, flags))
                        {
                            valueChanged = true;
                        }
                        break;
                    }
                    case ParameterType.COLOR:
                    {
                        Vector4 colorV = ColorVectorFromInt(i1);
                        ImGui.SetNextItemWidth(width * defaultParamWidth * 3.0f);
                        if (ImGui.ColorEdit4(label, ref colorV))
                        {
                            i1 = ColorVectorToInt(colorV);
                            valueChanged = true;
                        }
                        break;
                    }
                    case ParameterType.FLOAT:
                    case ParameterType.PATCH_FLOAT:
                    {
                        float f1 = v4.X;
                        ImGui.SetNextItemWidth(width * defaultParamWidth);
                        if (ImGui.DragFloat(label, ref f1, stepf, displayMinf, displayMaxf, "%.6f", ImGuiSliderFlags.NoRoundToFormat))
                        {
                            v4 = new Vector4(f1, 0.0f, 0.0f, 0.0f);
                            valueChanged = true;
                        }
                        break;
                    }
                    case ParameterType.VECTOR2:
                    {
                        Vector2 v2 = new Vector2(v4.X, v4.Y);
                        ImGui.SetNextItemWidth(width * defaultParamWidth * 2.0f);
                        if (ImGui.DragFloat2(label, ref v2, stepf, displayMinf, displayMaxf, "%.5f", ImGuiSliderFlags.NoRoundToFormat))
                        {
                            v4 = new Vector4(v2.X, v2.Y, 0.0f, 0.0f);
                            valueChanged = true;
                        }
                        break;
                    }
                    case ParameterType.VECTOR3:
                    case ParameterType.COLOR_FACTOR:
                    {
                        Vector3 v3 = new Vector3(v4.X, v4.Y, v4.Z);
                        if (Type == ParameterType.COLOR_FACTOR)
                        {
                            Vector3 v3Scale = Vector3.Abs(v3);
                            float max = MathF.Max(v3.X, MathF.Max(v3.Y, v3.Z));
                            if (max != 0.0f)
                            {
                                v3Scale = (v3Scale / max) * v3Scale;
                            }
                            ImGui.ColorEdit3(label, ref v3Scale, ImGuiColorEditFlags.NoPicker | ImGuiColorEditFlags.NoLabel | ImGuiColorEditFlags.NoInputs);
                            ImGui.SameLine();
                        }
                        ImGui.SetNextItemWidth(width * defaultParamWidth * 3.0f);
                        if (ImGui.DragFloat3(label, ref v3, stepf, displayMinf, displayMaxf, "%.5f", ImGuiSliderFlags.NoRoundToFormat))
                        {
                            v4 = new Vector4(v3.X, v3.Y, v3.Z, 0.0f);
                            valueChanged = true;
                        }
                        break;
                    }
                    case ParameterType.VECTOR4:
                    {
                        ImGui.SetNextItemWidth(width * defaultParamWidth * 4.0f);
                        if (ImGui.DragFloat4(label, ref v4, stepf, displayMinf, displayMaxf, "%.5f", ImGuiSliderFlags.NoRoundToFormat))
                        {
                            valueChanged = true;
                        }
                        break;
                    }
                }
                if (valueChanged)
                {
                    AdjustValue(ref v4, ref i1);
                }
                return valueChanged;
            }

            public void DrawReferenceValue(string name, Vector4 v4, int i1)
            {
                ImGui.PushStyleVar(ImGuiStyleVar.Alpha, ImGui.GetStyle().Alpha * 0.7f);
                switch (Type)
                {
                    case ParameterType.BOOL:
                    case ParameterType.FLAG:
                        ImGui.Text($"({name}: {i1 != 0})");
                        break;
                    case ParameterType.BYTE:
                    case ParameterType.INT:
                    case ParameterType.ALIGNED_INT:
                    case ParameterType.SHADOW_RESOLUTION:
                        ImGui.Text($"({name}: {i1})");
                        break;
                    case ParameterType.HEX:
                    case ParameterType.COLOR:
                        ImGui.Text($"({name}: {i1:X})");
                        break;
                    case ParameterType.FLOAT:
                    case ParameterType.PATCH_FLOAT:
                        ImGui.Text($"({name}: {v4.X:0.000000})");
                        break;
                    case ParameterType.VECTOR2:
                        ImGui.Text($"({name}: {v4.X:0.00000}, {v4.Y:0.00000})");
                        break;
                    case ParameterType.VECTOR3:
                    case ParameterType.COLOR_FACTOR:
                        ImGui.Text($"({name}: {v4.X:0.00000}, {v4.Y:0.00000}, {v4.Z:0.00000})");
                        break;
                    case ParameterType.VECTOR4:
                        ImGui.Text($"({name}: {v4.X:0.00000}, {v4.Y:0.00000}, {v4.Z:0.00000}, {v4.W:0.00000})");
                        break;
                }
                ImGui.PopStyleVar();
            }

            public string SetByLine(Config config, List<Override>? stageOverrides, List<Override>? globalOverrides, bool forSet, bool allowGlobal)
            {
                // Reverse order of selectedOverrideSuperseded().
                if (overridesContainsParam(externalOverrides.Values, this))
                {
                    return "Set by 'External'";
                }
                Assert(!forSet);
                if (selectedSet != "" && overridesContainsParam(config.Sets[selectedSet], this))
                {
                    return $"Set by '{selectedSet}'";
                }
                if ((allowGlobal || globalOverrides == null) && stageOverrides != null && overridesContainsParam(stageOverrides, this))
                {
                    return $"Set by '{StageToString(currentStage)}'";
                }
                if (allowGlobal)
                {
                    return "Set by \'Global\'";
                }
                // Superseded because inactive.
                Assert(globalOverrides != null && selectedStage != currentStage);
                return "";
            }

            public void Draw(float width, bool assumeOverride = false)
            {
                Draw(ref valueV, ref valueInt, width, assumeOverride);
            }

            public void Draw(ref Vector4 v4, ref int i1, float width, bool assumeOverride)
            {
                ImGui.PushID(Name);

                if (ViewOnly)
                {
                    ImGui.SetCursorPos(ImGui.GetCursorPos() + new Vector2(ImGui.GetFrameHeight() + ImGui.GetStyle().ItemSpacing.X, 0.0f));
                }
                else if (!assumeOverride)
                {
                    if (overrideForStage)
                    {
                        ImGui.PushItemFlag(ImGuiItemFlags.Disabled, true);
                        ImGui.PushItemFlag(ImGuiItemFlags.MixedValue, true);
                    }
                    // If OverrideOn() were to set queuedOverride instead of overrideValue, this parameter shouldn't be drawn.
                    Assert(!PendingUpdate());
                    bool toggleOverride = overrideValue;
                    if (ImGui.Checkbox("##Override", ref toggleOverride))
                    {
                        if (toggleOverride)
                        {
                            OverrideOn(false);
                        }
                        else
                        {
                            OverrideOff();
                        }
                    }
                    if (ImGui.BeginItemTooltip())
                    {
                        if (overrideForStage)
                        {
                            Config config = getConfig();
                            List<Override>? globalOverrides = config.Overrides[globalStage];
                            List<Override>? stageOverrides = maybeGetStageOverrides(config);
                            ImGui.Text(SetByLine(config, stageOverrides, globalOverrides, false, true));
                        }
                        else if (overrideValue)
                        {
                            ImGui.Text("Set");
                        }
                        else
                        {
                            ImGui.Text("Set override");
                        }
                        ImGui.EndTooltip();
                    }
                    if (overrideForStage)
                    {
                        ImGui.PopItemFlag();
                        ImGui.PopItemFlag();
                    }
                    ImGui.SameLine();
                }

                if (!overrideValue)
                {
                    ImGui.PushItemFlag(ImGuiItemFlags.Disabled, true);
                }
                if (DrawValue(ref valueV, ref valueInt, width, !bValue))
                {
                    maybeWriteCurrentValue();
                }
                if (!overrideValue)
                {
                    ImGui.PopItemFlag();
                }

                bool showButtons = !assumeOverride && overrideValue && !pendingUpdate;
                if (showButtons)
                {
                    ImGui.SameLine();
                    if (!bValue)
                    {
                        if (ImGui.Button("B"))
                        {
                            bValueV = oValueV;
                            bValueInt = oValueInt;
                            bValue = true;
                        }
                    }
                    else
                    {
                        if (ImGui.Button("A/B"))
                        {
                            (bValueV, valueV) = (valueV, bValueV);
                            (bValueInt, valueInt) = (valueInt, bValueInt);
                            maybeWriteCurrentValue();
                        }
                        ImGui.SameLine();
                        DrawValue(ref bValueV, ref bValueInt, width, true);
                        ImGui.SameLine();
                        if (ImGui.Button("< B"))
                        {
                            bValue = false;
                        }
                    }

                    Config config = getConfig();
                    List<Override> selectedOverrides = config.Overrides[selectedStage];
                    List<Override>? stageOverrides = maybeGetStageOverrides(config);
                    // Deciding when to set globalOverrides copies the logic in OnImGuiRender().
                    //  Selected: Set if selectedStage != globalStage.
                    //  Set:      Always set.
                    List<Override>? globalOverrides = null;
                    if (selectedSet != "")
                    {
                        List<Override> setOverrides = config.Sets[selectedSet];
                        if (!overridesContainsParam(setOverrides, this))
                        {
                            ImGui.SameLine();
                            if (ImGui.Button("â–²"))
                            {
                                // Create the new override before unsetting any lower priority overrides.
                                // Effectively, copy the current override value.
                                Override ov = new Override(this, v4, i1);
                                globalOverrides = config.Overrides[globalStage];
                                bool superseded = overridesContainsParam(externalOverrides.Values, this);
                                if (!superseded)
                                {
                                    BeginTransition();
                                    if (!(stageOverrides != null && unsetIfOverridesContainsParam(stageOverrides, this)))
                                    {
                                        unsetIfOverridesContainsParam(globalOverrides, this);
                                    }
                                    ov.Set();
                                    EndTransition();
                                }
                                setOverrides.Add(ov);
                                configState |= SetNotSaved;
                            }
                            if (ImGui.BeginItemTooltip())
                            {
                                ImGui.Text($"Add to '{selectedSet}'");
                                ImGui.EndTooltip();
                            }
                        }
                    }
                    else if (!overridesContainsParam(selectedOverrides, this))
                    {
                        ImGui.SameLine();
                        if (ImGui.Button("â–²"))
                        {
                            Override ov = new Override(this, v4, i1);
                            if (selectedStage != globalStage)
                            {
                                globalOverrides = config.Overrides[globalStage];
                            }
                            bool superseded = selectedOverrideSuperseded(config, globalOverrides, stageOverrides, this);
                            if (!superseded)
                            {
                                BeginTransition();
                                if (globalOverrides != null)
                                {
                                    unsetIfOverridesContainsParam(globalOverrides, this);
                                }
                                ov.Set();
                                EndTransition();
                            }
                            selectedOverrides.Add(ov);
                            if (selectedStage == globalStage)
                            {
                                rebuildConfig(config, selectedOverrides);
                            }
                            configState |= SelectedNotSaved;
                        }
                        if (ImGui.BeginItemTooltip())
                        {
                            ImGui.Text($"Add to '{StageToString(selectedStage)}'");
                            ImGui.EndTooltip();
                        }
                    }

                    ImGui.SameLine();
                    DrawReferenceValue("Original", oValueV, oValueInt);
                }

                ImGui.PopID();
            }
        }

        public class Parameter<T> : Parameter where T : unmanaged
        {
            public Parameter(string name, nint offset, int mask, ParameterType type, T? min, T? max, T? step, int flags) : base(name, offset, mask, type, flags)
            {
                if (typeof(T) == typeof(float))
                {
                    this.stepf = (step != null) ? Convert.ToSingle(step) : 0.1f;
                    this.minf = (min != null) ? Convert.ToSingle(min) : -Single.MaxValue;
                    this.maxf = (max != null) ? Convert.ToSingle(max) :  Single.MaxValue;
                }
                else if (typeof(T) == typeof(int) || typeof(T) == typeof(byte) || typeof(T) == typeof(bool))
                {
                    this.step = (step != null) ? Convert.ToInt32(step) : 0;
                    if (typeof(T) == typeof(int))
                    {
                        this.min = (min != null) ? Convert.ToInt32(min) : Int32.MinValue;
                        this.max = (max != null) ? Convert.ToInt32(max) : Int32.MaxValue;
                    }
                    else if (typeof(T) == typeof(byte))
                    {
                        this.min = (min != null) ? Convert.ToInt32(min) : 0x0;
                        this.max = (max != null) ? Convert.ToInt32(max) : 0xFF;
                    }
                    else if (typeof(T) == typeof(bool))
                    {
                        this.min = 0;
                        this.max = 1;
                    }
                }
            }
        }

        public static (float?, float?, float?) pStep(float step) { return (null, null, step); }
        public static (float?, float?, float?) pMin(float min) { return (min, null, null); }
        public static (float?, float?, float?) pMax(float max) { return (null, max, null); }
        public static (float?, float?, float?) pMinStep(float min, float step) { return (min, null, step); }
        public static (float?, float?, float?) pMaxStep(float max, float step) { return (null, max, step); }
        public static (float?, float?, float?) pMinMaxStep(float min, float max, float step) { return (min, max, step); }
        public static (int?, int?, int?) pStep(int step) { return (null, null, step); }
        public static (int?, int?, int?) pMin(int min) { return (min, null, null); }
        public static (int?, int?, int?) pMax(int max) { return (null, max, null); }
        public static (int?, int?, int?) pMinStep(int min, int step) { return (min, null, step); }
        public static (int?, int?, int?) pMaxStep(int max, int step) { return (null, max, step); }
        public static (int?, int?, int?) pMinMaxStep(int min, int max, int step) { return (min, max, step); }
        public static (byte?, byte?, byte?) pStep(byte step) { return (null, null, step); }

        public static Parameter<T> P<T>(string name, nint offset, ParameterType type, (T? min, T? max, T? step) m = default) where T : unmanaged
        {
            return new Parameter<T>(name, offset, 0, type, m.min, m.max, m.step, 0);
        }

        public static Parameter<T> V<T>(string name, nint offset, ParameterType type, (T? min, T? max, T? step) m = default) where T : unmanaged
        {
            return new Parameter<T>(name, offset, 0, type, m.min, m.max, m.step, ParameterFlags.ViewOnly);
        }

        public static Parameter<T> M<T>(string name, nint offset, ParameterType type, int mask, (T? min, T? max, T? step) m = default) where T : unmanaged
        {
            return new Parameter<T>(name, offset, mask, type, m.min, m.max, m.step, 0);
        }

        private static Parameter? getParameterByName(string name)
        {
            foreach (Parameter param in allParameters)
            {
                if (param.Name == name)
                {
                    return param;
                }
            }
            return null;
        }

        public class Override
        {
            public Parameter? Param = null;
            public string Name
            {
                get => (Param != null) ? Param.Name : "";
                set => Param = getParameterByName(value);
            }
            public string Value
            {
                get
                {
                    if (Param != null)
                    {
                        switch (Param.Type)
                        {
                            case ParameterType.BOOL:
                            case ParameterType.FLAG:
                                return BooleanToString(sValueInt != 0);
                            case ParameterType.BYTE:
                            case ParameterType.INT:
                            case ParameterType.ALIGNED_INT:
                            case ParameterType.SHADOW_RESOLUTION:
                                return Int32ToString(sValueInt);
                            case ParameterType.HEX:
                            case ParameterType.COLOR:
                                return Int32ToString(sValueInt, "X8");
                            case ParameterType.FLOAT:
                            case ParameterType.PATCH_FLOAT:
                                return SingleToString(sValueV.X);
                            case ParameterType.VECTOR2:
                                Vector2 sValueV2 = new Vector2(sValueV.X, sValueV.Y);
                                return Vector2ToString(sValueV2);
                            case ParameterType.VECTOR3:
                            case ParameterType.COLOR_FACTOR:
                                Vector3 sValueV3 = new Vector3(sValueV.X, sValueV.Y, sValueV.Z);
                                return Vector3ToString(sValueV3);
                            case ParameterType.VECTOR4:
                                return Vector4ToString(sValueV);
                        }
                    }
                    return "";
                }
                set
                {
                    if (Param == null) return;
                    try
                    {
                        switch (Param.Type)
                        {
                            case ParameterType.BOOL:
                            case ParameterType.FLAG:
                                valueInt = ByteFlag(StringToBoolean(value));
                                break;
                            case ParameterType.BYTE:
                            case ParameterType.INT:
                            case ParameterType.ALIGNED_INT:
                            case ParameterType.SHADOW_RESOLUTION:
                                valueInt = StringToInt32(value);
                                break;
                            case ParameterType.HEX:
                            case ParameterType.COLOR:
                                valueInt = StringToInt32(value, 16);
                                break;
                            case ParameterType.FLOAT:
                            case ParameterType.PATCH_FLOAT:
                                valueV.X = StringToSingle(value);
                                break;
                            case ParameterType.VECTOR2:
                                Vector2 valueV2 = StringToVector2(value);
                                valueV = new Vector4(valueV2.X, valueV2.Y, 0.0f, 0.0f);
                                break;
                            case ParameterType.VECTOR3:
                            case ParameterType.COLOR_FACTOR:
                                Vector3 valueV3 = StringToVector3(value);
                                valueV = new Vector4(valueV3.X, valueV3.Y, valueV3.Z, 0.0f);
                                break;
                            case ParameterType.VECTOR4:
                                valueV = StringToVector4(value);
                                break;
                        }
                    }
                    catch (FormatException)
                    {
                        Log.Warn($"Failed to parse value of '{Name}' override.");
                    }
                    catch (OverflowException)
                    {
                        Log.Warn($"Value of '{Name}' override too large.");
                    }
                    Param.AdjustValue(ref valueV, ref valueInt);
                    Save();
                }
            }
            // This could different from the Parameter's valueV/valueInt if this override is unset.
            private Vector4 valueV = default;
            private int valueInt = 0;
            private bool isSet = false;
            private Vector4 sValueV = default; // Saved value.
            private int sValueInt = 0;

            public Override() { }
            public Override(Parameter param, Vector4 v4, int i1)
            {
                Param = param;
                valueV = v4;
                valueInt = i1;
                Save();
            }

            public void Save()
            {
                (sValueV, sValueInt) = (valueV, valueInt);
            }

            public void Set()
            {
                Assert(!isSet);
                isSet = true;
                if (Param != null)
                {
                    Param.OverrideOn(true);
                    Param.SetOverrideValue(valueV, valueInt);
                }
            }

            public void Unset()
            {
                Assert(isSet);
                isSet = false;
                if (Param != null)
                {
                    Param.OverrideOff();
                }
            }

            public void Draw(bool forSet, List<Override>? currentOverrides, List<Override>? stageOverrides, List<Override>? globalOverrides, bool superseded, float width)
            {
                Assert(!superseded == isSet);
                if (superseded)
                {
                    ImGui.PushStyleVar(ImGuiStyleVar.Alpha, ImGui.GetStyle().Alpha * 0.5f);
                }
                if (currentOverrides == null)
                {
                    ImGui.PushItemFlag(ImGuiItemFlags.Disabled, true);
                }
                ImGui.PushItemWidth(width * 0.475f);
                bool beginCombo = ImGui.BeginCombo("##Parameters", (Param != null) ? Param.Name : "", ImGuiComboFlags.HeightLarge);
                if (superseded)
                {
                    ImGui.PopStyleVar();
                }
                Config config = getConfig();
                if (beginCombo)
                {
                    if (currentOverrides != null)
                    {
                        foreach (Parameter iterParam in allParameters)
                        {
                            if (iterParam.ViewOnly) continue;
                            if (overridesContainsParam(currentOverrides, iterParam)) continue;
                            bool isSelected = Param == iterParam;
                            if (ImGui.Selectable(iterParam.Name, isSelected))
                            {
                                BeginTransition();
                                if (!superseded)
                                {
                                    Unset();
                                    if (Param != null)
                                    {
                                        if (forSet)
                                        {
                                            if (!(stageOverrides != null && setIfOverridesContainsParam(stageOverrides, Param)))
                                            {
                                                if (globalOverrides != null)
                                                {
                                                    setIfOverridesContainsParam(globalOverrides, Param);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (globalOverrides != null)
                                            {
                                                setIfOverridesContainsParam(globalOverrides, Param);
                                            }
                                        }
                                    }
                                }
                                Param = iterParam;
                                (valueV, valueInt) = Param.GetValue();
                                Save();
                                if (forSet)
                                {
                                    Assert(globalOverrides != null);
                                    superseded = overridesContainsParam(externalOverrides.Values, Param);
                                    if (!superseded)
                                    {
                                        if (!(stageOverrides != null && unsetIfOverridesContainsParam(stageOverrides, Param)))
                                        {
                                            unsetIfOverridesContainsParam(globalOverrides!, Param);
                                        }
                                        Set();
                                    }
                                    configState |= SetNotSaved;
                                }
                                else
                                {
                                    superseded = selectedOverrideSuperseded(config, globalOverrides, stageOverrides, Param);
                                    if (!superseded)
                                    {
                                        if (globalOverrides != null)
                                        {
                                            unsetIfOverridesContainsParam(globalOverrides, Param);
                                        }
                                        Set();
                                    }
                                    configState |= SelectedNotSaved;
                                }
                                EndTransition();
                                Assert(!superseded == isSet);
                            }
                            if (isSelected) ImGui.SetItemDefaultFocus();
                        }
                    }
                    ImGui.EndCombo();
                }
                ImGui.PopItemWidth();
                if (currentOverrides == null)
                {
                    ImGui.PopItemFlag();
                }
                if (Param != null)
                {
                    ImGui.SameLine();
                    if (superseded)
                    {
                        ImGui.PushStyleVar(ImGuiStyleVar.Alpha, ImGui.GetStyle().Alpha * 0.5f);
                    }
                    if (Param.DrawValue(ref valueV, ref valueInt, width, false))
                    {
                        if (!superseded)
                        {
                            Param.SetOverrideValue(valueV, valueInt);
                        }
                    }
                    (Vector4 v4, int i1) = Param.GetValue();
                    bool valueDiffers = (valueV, valueInt) != (v4, i1);
                    bool valueNotSaved = (valueV, valueInt) != (sValueV, sValueInt);
                    if ((!Param.PendingUpdate() && valueDiffers && !superseded) || valueNotSaved)
                    {
                        ImGui.SameLine();
                        if (ImGui.Button("⇄"))
                        {
                            valueV = sValueV;
                            valueInt = sValueInt;
                            if (!superseded)
                            {
                                Param.SetOverrideValue(valueV, valueInt);
                            }
                        }
                    }
                    if (superseded)
                    {
                        ImGui.PopStyleVar();
                    }
                    if (valueNotSaved)
                    {
                        ImGui.SameLine();
                        Param.DrawReferenceValue("Saved", sValueV, sValueInt);
                    }
                    if (Param.PendingUpdate())
                    {
                        ImGui.SameLine();
                        ImGui.PushStyleVar(ImGuiStyleVar.Alpha, ImGui.GetStyle().Alpha * 0.7f);
                        ImGui.Text("(Pending)");
                        ImGui.PopStyleVar();
                        if (ImGui.BeginItemTooltip())
                        {
                            ImGui.Text("The type this parameter belongs to has no current object.");
                            ImGui.EndTooltip();
                        }
                    }
                    else if (valueDiffers)
                    {
                        ImGui.SameLine();
                        string byLine = "";
                        if (superseded)
                        {
                            // Global is the lowest priority so "Set by 'Global'" never applies here.
                            byLine = Param.SetByLine(config, stageOverrides, globalOverrides, forSet, false);
                        }
                        Param.DrawReferenceValue((byLine == "") ? "Current" : byLine, v4, i1);
                    }
                }
            }
        }

        // Start of Parameter Definitions.

        private delegate void OnAreaChange(nint unknownPtr);
        private Hook<OnAreaChange>? onAreaChange;

        private static bool InTransition = false;
        private static List<Parameter> DirtyParams = new List<Parameter>();
        private static void BeginTransition()
        {
            Assert(!InTransition && DirtyParams.Count == 0);
            InTransition = true;
        }
        private static void EndTransition()
        {
            Assert(InTransition);
            InTransition = false;
            foreach (Parameter param in DirtyParams)
            {
                param.Resolve();
            }
            DirtyParams.Clear();
        }

        private static MtObject? sMhScene = null;
        private static MtObject? sMhMain = null;
        private static MtObject? sMhRender = null;

        private static Lights lights = new Lights();

        private static Parameter hqMode = P<bool>("HQ Mode", 0xE9A3, ParameterType.BOOL);

        private static Parameter[] lodParameters = {
            P<float>("LOD Bias 1", 0x21C, ParameterType.FLOAT, pMin(0.0f)),
            P<float>("LOD Bias 2", 0x220, ParameterType.FLOAT, pMin(0.0f)),
            P<float>("LOD Caster Bias", 0x1E4, ParameterType.FLOAT, pMin(0.0f)),
            // If platform is PS4/Xbox/PC it appears [2] is PC.
            P<float>("LOD Length Platform Bias[2]", 0x22C + (4 * 2), ParameterType.FLOAT, pMin(0.0f)),
            P<float>("LOD Pixel Size Platform Bias[2]", 0x244 + (4 * 2), ParameterType.FLOAT, pMin(0.0f)),
            P<int>("LOD Limit", 0xE898, ParameterType.INT, pStep(1)),
            P<float>("LOD Passthrough Culling Rate", 0x1F0, ParameterType.FLOAT, pMin(0.0f)),
            P<float>("LOD Far Culling Fade Length Max", 0x20C, ParameterType.FLOAT, pMin(0.0f)),
            P<float>("LOD Far Culling Fade Pixel Max", 0x210, ParameterType.FLOAT, pMin(0.0f)),
            P<float>("Speed Tree LOD Billboard Fade Range", 0x214, ParameterType.FLOAT, pMin(0.0f)),
            P<float>("LOD Culling Length Bias", 0x224, ParameterType.FLOAT, pMin(0.0f)),
            P<float>("LOD Culling Pixel Bias", 0x228, ParameterType.FLOAT, pMin(0.0f))
        };

        private static Parameter[] snowParameters = {
            P<float>("Snow Field 4 Global LOD Param", 0x5718, ParameterType.FLOAT)
        };

        private static Parameter[] passthroughParameters = {
            P<bool>("Passthrough Active", 0xE9A0, ParameterType.BOOL),
            P<bool>("Passthrough Culling Active", 0xE9A2, ParameterType.BOOL),
            V<float>("Passthrough Near", 0xE940, ParameterType.FLOAT),
            V<float>("Passthrough Far", 0xE944, ParameterType.FLOAT),
            P<float>("Passthrough Near Alpha", 0xE948, ParameterType.FLOAT),
            P<float>("Passthrough Far Alpha", 0xE94C, ParameterType.FLOAT),
            P<float>("Passthrough Correct", 0xE950, ParameterType.FLOAT)
        };

        private static Parameter[] shadowCascadeParameters = {
            P<bool>("Primary Shadow HQ", 0xE5C0, ParameterType.BOOL),
            P<bool>("Primary Shadow HQ (HQ)", 0xE5C2, ParameterType.BOOL),
            P<float>("Shadow Cascade 2Way Bias (HQ)", 0x58, ParameterType.FLOAT),
            P<int>("Primary Shadow Sample Num (HQ)", 0xE5CC, ParameterType.INT, pStep(1))
        };

        private delegate void EvalSceneParams(nint unknownPtr, nint unknownPtr2, int unknownInt, nint unknownPtr3);
        private Hook<EvalSceneParams>? evalSceneParams;
        private static Parameter[] broadAreaShadowParameters = {
            P<bool>("Broad Area Shadow Enable", 0x5534, ParameterType.BOOL),
            P<float>("Broad Area Shadow Center", 0x5540 + 0x40, ParameterType.VECTOR3),
            P<float>("Broad Area Shadow Range", 0x5560 + 0x40, ParameterType.VECTOR3),
            P<float>("Broad Area Shadow Direction", 0x5550 + 0x40, ParameterType.VECTOR3, pStep(0.00025f)),
            P<float>("Broad Area Shadow Max LOD Level", 0x5524, ParameterType.FLOAT, pMin(0.0f)),
            P<float>("Broad Area Shadow Culling Size", 0x5528, ParameterType.FLOAT, pMin(0.0f)),
            P<int>("Broad Area Shadow Precision", 0x5518, ParameterType.INT, pMinMaxStep(0, 2, 1))
        };

        private static Parameter[] contactShadowParameters = {
            P<float>("Fake Light Intensity", 0xEC40, ParameterType.FLOAT),
            // MonsterHunterWorld.exe+1B18711 - mov [rbx+0000EC44],3F800000 (Other unknown reference).
            P<float>("Fake Light Intensity (Gameplay)", lton(0x141B1A19F) + 0x6, ParameterType.PATCH_FLOAT),
            P<float>("Fake Light Blend", lton(0x141CDE0CE) + 0x6, ParameterType.PATCH_FLOAT),
            P<bool>("Force Disable Contact Shadows", 0xB4ED, ParameterType.BOOL),
            P<bool>("Facial Contact Shadows Enabled", 0xB4EE, ParameterType.BOOL),
            P<bool>("Facial Contact Shadows Enable Noise", 0xB501, ParameterType.BOOL),
            P<float>("Contact Shadow Accept Maximum Length", 0xB4F8, ParameterType.FLOAT),
            P<float>("Contact Shadow Accept Minimum Length", 0xB4FC, ParameterType.FLOAT)
        };

        private delegate void UpdateCapsuleAOParams(nint sceneObjectInternal);
        private Hook<UpdateCapsuleAOParams>? updateCapsuleAoParams;
        private static Parameter[] capsuleLightParameters = {
            P<bool>("Force Disable Capsule AO", 0xB503, ParameterType.BOOL),
            P<bool>("Capsule AO Enabled", 0xB502, ParameterType.BOOL),
            P<float>("Capsule AO Distance Fall Coef", 0xE5B4, ParameterType.FLOAT, pStep(0.0001f)),
            P<int>("Capsule AO Light Channel Mask", 0xE5BC, ParameterType.INT, pStep(1)),
            P<float>("Capsule Light Direction XZY", 0xE548, ParameterType.VECTOR3),
            V<float>("Capsule Light W Direction", 0xE560, ParameterType.VECTOR3),
            P<float>("Capsule Light Angle", 0xE5B0, ParameterType.FLOAT),
            P<float>("Capsule AO Intensity", 0xE5B8, ParameterType.FLOAT, pStep(0.00025f))
        };

        private delegate void UpdateSSAOParams(nint stackOffset);
        private Hook<UpdateSSAOParams>? updateSSAOParams;
        private static Parameter[] ssaoParameters = {
            P<float>("SSAO Depth Bias", 0xB4B0, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("SSAO Sloped Depth Bias", 0xB4B4, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("SSAO Max Depth Bias", 0xB4B8, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("SSAO Dispersion", 0xB4BC, ParameterType.FLOAT),
            P<float>("SSAO Effect", 0xB430, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("SSAO Effect GI", 0xB434, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("SSAO Depth Difference", 0xB4C0, ParameterType.FLOAT, pStep(0.01f)),
            P<float>("SSAO Samples Per Pixel", 0xB4C4, ParameterType.FLOAT, pStep(1.0f)),
            P<int>("SSAO Max Sample Num", 0xB4C8, ParameterType.INT, pStep(1)),
            P<int>("SSAO Max Sample Num (HQ)", 0xB4D0, ParameterType.INT, pStep(1)),
            P<float>("SSAO Radius", 0xB4D4, ParameterType.FLOAT),
            P<float>("SSAO Bias", 0xB4D8, ParameterType.FLOAT, pStep(0.0001f)),
            P<float>("SSAO Intensity", 0xB4E0, ParameterType.FLOAT, pMin(0.0f)),
            P<bool>("SSAO Use HiZ", 0xB4E5, ParameterType.BOOL),
            P<float>("SSAO Edge Atten Rate", 0xB4DC, ParameterType.FLOAT, pStep(0.001f))
        };

        private delegate void UpdateSSLRParams(nint stackOffset);
        private Hook<UpdateSSLRParams>? updateSSLRParams;
        private static Parameter[] sslrParameters = {
            P<int>("SSLR Loop Count", 0xE628, ParameterType.INT, pStep(1)),
            P<float>("SSLR Loop Count Factor for CBR", 0xE62C, ParameterType.FLOAT),
            P<float>("SSLR Eliminate Depth", 0xE630, ParameterType.FLOAT),
            P<float>("SSLR Accurate Threshold", 0xE644, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("SSLR Accurate Threshold (HQ)", 0xE64C, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("SSLR Dither Radius", 0xE634, ParameterType.FLOAT),
            P<float>("SSLR Importance Bias", 0xE638, ParameterType.FLOAT),
            P<float>("SSLR Mip Scale", 0xE63C, ParameterType.FLOAT),
            P<float>("SSLR Mip Bias", 0xE640, ParameterType.FLOAT),
            P<bool>("SSLR Dither Resolve", 0xB43F, ParameterType.BOOL),
            P<float>("SSLR Edge Atten Rate", 0xB428, ParameterType.FLOAT),
            P<int>("SSLR Mip 0 Count Threshold", 0xB438, ParameterType.INT, pStep(1)),
            P<float>("SSLR Depth Eliminate Rate", 0xB42C, ParameterType.FLOAT),
            P<bool>("SSLR Use Mipmap", 0xE650, ParameterType.BOOL),
            P<bool>("SSLR GBuffer Jitter", 0xB440, ParameterType.BOOL),
            P<float>("SSLR Intensity", 0xB424, ParameterType.FLOAT)
        };

        private static Parameter shadowResParameter = P<int>("Shadow Resolution Multiplier", 0, ParameterType.SHADOW_RESOLUTION, pStep(1));
        private delegate void UpdateShadowParams(nint shadowParams, nint stackOffset);
        private delegate void StaticShadowParams(nint shadowParamsStatic, nint shadowObjectInternal);
        private Hook<UpdateShadowParams>? updateShadowParams;
        private Hook<StaticShadowParams>? staticShadowParams;
        private static Parameter[] shadowParameters1 = {
        };
        // This is actually an InfiniteLight object.
        // "Min Roughness" is +0xFC in params but is never read.
        private static Parameter[] shadowParameters2 = {
            P<int>("Sunlight Group", 0x14, ParameterType.INT, pMinMaxStep(1, 255, 1)),
            P<float>("Sunlight Direction", 0x110, ParameterType.VECTOR3, pStep(0.00025f)),
            P<float>("Sunlight Color", 0xE0, ParameterType.COLOR_FACTOR, pMaxStep(1.0f, 0.001f)),
            P<float>("Sunlight Intensity", 0xF4, ParameterType.FLOAT, pStep(0.001f)),
            P<bool>("Sunlight Is Primary", 0x1D, ParameterType.BOOL),
            P<bool>("Do Volumetric", 0x1F, ParameterType.BOOL),
            P<bool>("Shadow Cast", 0x23, ParameterType.BOOL),
            P<int>("Shadow Map Size", 0x30, ParameterType.ALIGNED_INT, pMinStep(0, 128)), // 0 = 64x64 no multiplier @TODO: Verify in the code.
            P<float>("Shadow Near Clip Distance", 0x28, ParameterType.FLOAT),
            P<int>("Shadow Cascade Mode", 0x174, ParameterType.INT, pMinMaxStep(0, 3, 1)),
            P<float>("Shadow Cascade 2Way Bias", 0x17C, ParameterType.FLOAT),
            P<float>("Shadow Distance", 0x6C, ParameterType.FLOAT, pStep(5.0f)),
            P<float>("Shadow Backforward Distance", 0x7C, ParameterType.FLOAT, pStep(5.0f)),
            P<bool>("Shadow Is Fixed Fov Mode", 0x1F9, ParameterType.BOOL),
            P<float>("Shadow Fov", 0x1F4, ParameterType.FLOAT, pStep(0.0001f)),
            P<bool>("Shadow Is Discretization Fov Mode", 0x205, ParameterType.BOOL),
            P<float>("Shadow Discretization Angle", 0x200, ParameterType.FLOAT, pStep(0.0001f)),
            P<float>("Shadow Distribution", 0x74, ParameterType.FLOAT, pStep(0.001f)),
            P<bool>("Cascade Manual Split", 0x4D, ParameterType.BOOL),
            P<float>("Cascade Manual Split Distance[0]", 0x54, ParameterType.FLOAT),
            P<float>("Cascade Manual Split Distance[1]", 0x5C, ParameterType.FLOAT),
            P<float>("Cascade Manual Split Distance[2]", 0x64, ParameterType.FLOAT),
            P<float>("Shadow Sloped Depth Bias", 0x40, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("Shadow Depth Bias", 0x38, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("Shadow Max Depth Bias", 0x48, ParameterType.FLOAT, pStep(0.00001f)),
            P<bool>("Cascade Individual Shadow Bias", 0x81, ParameterType.BOOL),
            P<float>("Cascade Depth Bias[0]", 0x88, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("Cascade Sloped Depth Bias[0]", 0xA0, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("Cascade Max Depth Bias[0]", 0xB8, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("Cascade Depth Bias[1]", 0x90, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("Cascade Sloped Depth Bias[1]", 0xA8, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("Cascade Max Depth Bias[1]", 0xC0, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("Cascade Depth Bias[2]", 0x98, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("Cascade Sloped Depth Bias[2]", 0xB0, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("Cascade Max Depth Bias[2]", 0xC8, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("Broad Area Shadow Depth Bias", 0x1C4, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("Broad Area Shadow Sloped Depth Bias", 0x1CC, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("Broad Area Shadow Max Depth Bias", 0x1D4, ParameterType.FLOAT, pStep(0.00001f)),
            P<float>("Projection Scale", 0x134, ParameterType.VECTOR2),
            P<float>("Projection Offset Speed", 0x144, ParameterType.VECTOR2),
            P<float>("Projection Up", 0x160, ParameterType.VECTOR3),
            P<int>("Primary Shadow Sample Num", 0x1DC, ParameterType.INT, pStep(1)),
            P<float>("Primary Shadow Radius", 0x1EC, ParameterType.FLOAT, pStep(0.0001f))
        };

        private static MtObject? sLightProbes = null;
        private delegate void UpdateLightProbesParams(nint unknownPtr, int unknownInt);
        private Hook<UpdateLightProbesParams>? updateLightProbesParams;
        private static Parameter[] sLightProbesParameters = {
            P<int>("Light Probes Probe Color", 0x38, ParameterType.COLOR),
            P<float>("Light Probes Probe Intensity", 0x3C, ParameterType.FLOAT),
            P<int>("Light Probes Top Color", 0x44, ParameterType.COLOR),
            P<float>("Light Probes Top Intensity", 0x48, ParameterType.FLOAT),
            P<int>("Light Probes Bottom Color", 0x4C, ParameterType.COLOR),
            P<float>("Light Probes Bottom Intensity", 0x50, ParameterType.FLOAT),
            P<float>("Light Probes Direction", 0x60, ParameterType.VECTOR3),
            P<int>("Light Probes Shadow Top Color", 0x70, ParameterType.COLOR),
            P<float>("Light Probes Shadow Top Intensity", 0x74, ParameterType.FLOAT),
            P<int>("Light Probes Shadow Bottom Color", 0x78, ParameterType.COLOR),
            P<float>("Light Probes Shadow Bottom Intensity", 0x7C, ParameterType.FLOAT),
            P<float>("Light Probes Shadow Direction", 0x80, ParameterType.VECTOR3),
            P<int>("Light Probes Daytime State", 0x9C, ParameterType.INT, pMinMaxStep(0, 6, 1)),
            P<float>("Light Probes Daytime Interpolation", 0xA0, ParameterType.FLOAT),
            P<int>("Light Probes Max Iter", 0xA4, ParameterType.INT),
            P<int>("Light Probes Debug Mode", 0x98, ParameterType.INT, pStep(1))
        };

        private delegate nint CreateLightingObject();
        private delegate nint DestroyLightingObject(nint lightingObjectInternal, int unknownInt);
        private Hook<CreateLightingObject>? createLightingObject;
        private Hook<DestroyLightingObject>? destroyLightingObject;
        private nint lightingObject = 0x0;
        private delegate void UpdateLightingParams(nint stackOffset, nint lightingObjectInternal);
        private Hook<UpdateLightingParams>? updateLightingParams;
        private Hook<UpdateLightingParams>? updateLutBlend;
        private static LUT luts = new LUT();
        private static Parameter[] lightingParameters = {
            P<int>("Light Tone Map Type", 0x16C, ParameterType.INT, pMinMaxStep(1, 6, 1)),
            P<bool>("Light Compute Luminance", 0x170, ParameterType.BOOL),
            P<bool>("Light Luminance Version", 0x168, ParameterType.BOOL),
            P<float>("Light Shoulder Strength", 0x174, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("Light Linear Strength", 0x178, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("Light Linear Angle", 0x17C, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("Light Toe Strength", 0x180, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("Light Toe Num", 0x184, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("Light Toe Denum", 0x188, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("Light White Point", 0x18C, ParameterType.FLOAT, pStep(0.01f)),
            P<float>("Light LUT Blend", 0x1C8, ParameterType.FLOAT, pMinMaxStep(0.0f, 1.0f, 0.01f)),
            P<float>("Light Vfx LUT Blend", 0x1D0, ParameterType.FLOAT, pMinMaxStep(0.0f, 1.0f, 0.01f)),
            P<bool>("Light Enable Color Grading", 0x1D8, ParameterType.BOOL),
            P<bool>("Light Is Linear To PQ", 0x1A1, ParameterType.BOOL),
            P<bool>("Light Is PQ To Linear", 0x1A0, ParameterType.BOOL),
            P<float>("Volume Dispersion", 0x19C, ParameterType.FLOAT),
            P<float>("Volume Edge Sharpness", 0x198, ParameterType.FLOAT, pStep(0.00001f)),
            P<bool>("Volume Downsample", 0x210, ParameterType.BOOL)
        };
        private static Parameter[] brightnessParameters = {
            P<float>("Gamma Correct", 0x1C8, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("Gamma Correct EX", 0x1CC, ParameterType.FLOAT, pStep(0.001f)),
            V<bool>("Hdr Output", 0x21A, ParameterType.BOOL),
            P<float>("Hdr Output White Level", 0x21C, ParameterType.FLOAT, pStep(0.05f)),
            P<float>("Hdr Output Gamut Mapping Ratio", 0x220, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("Hdr Output Gamma", 0x224, ParameterType.FLOAT, pStep(0.001f)),
            P<bool>("Hdr Is Gui Hdr Gamma", 0x228, ParameterType.BOOL)
        };

        private delegate nint CreateBloomObject();
        private delegate nint CreateBloomObject2(nint unknownPtr);
        private delegate nint DestroyBloomObject(nint bloomObjectInternal, int unknownInt);
        private Hook<CreateBloomObject>? createBloomObject;
        private Hook<CreateBloomObject2>? createBloomObject2;
        private Hook<DestroyBloomObject>? destroyBloomObject;
        private nint bloomObject = 0x0;
        private static Parameter[] bloomParameters = {
            // Disabling 'Draw' is a bad way to disable bloom. It breaks the filter on initial load which
            // can be seen when returning to title or opening a guild card for the first time. Setting 'Bloom Renormalize'
            // to 0.0 or 'Bloom Reduction Resolution' to -1 can both effectively disable bloom without that issue.
            //newFlag<byte>("Bloom Enabled", 0x14, ParameterType.FLAG, (1 << 1)), // Draw
            P<float>("Bloom Threshold", 0x204, ParameterType.FLOAT),
            P<float>("Bloom Renormalize", 0x208, ParameterType.FLOAT, pMin(0.0f)),
            P<int>("Bloom Color", 0x200, ParameterType.COLOR),
            P<int>("Bloom Downsample Count", 0x168, ParameterType.INT, pMinMaxStep(0, 8, 1)),
            P<int>("Bloom Reduction Resolution", 0x16C, ParameterType.INT, pStep(1)),
            P<bool>("Bloom Is SRGB Gamut", 0x214, ParameterType.BOOL),
            P<bool>("Bloom Compute Luminance", 0x241, ParameterType.BOOL)
        };

        private delegate nint CreateDofObject();
        private delegate nint CreateDofObject2(nint unknownPtr);
        private delegate nint DestroyDofObject(nint dofObjectInternal, int unknownInt);
        private Hook<CreateDofObject>? createDofObject;
        private Hook<CreateDofObject2>? createDofObject2;
        private Hook<DestroyDofObject>? destroyDofObject;
        private delegate void UpdateDofParams(nint unknownPtr);
        private Hook<UpdateDofParams>? updateDofParams;
        private nint dofObject = 0x0;
        private static Parameter[] dofParameters = {
            P<bool>("Dof Enabled", 0x1DD, ParameterType.BOOL),
            P<bool>("Dof New Version", 0x1DC, ParameterType.BOOL),
            P<float>("Dof F Number", 0x1A0, ParameterType.FLOAT, pMinStep(0.0f, 0.001f)),
            P<float>("Dof Sensor Size", 0x1A4, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("Dof Focus Distance", 0x1A8, ParameterType.FLOAT, pStep(0.2f)),
            P<float>("Dof Near Coef", 0x1CC, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("Dof Far Coef", 0x1C8, ParameterType.FLOAT, pStep(0.001f)),
            P<bool>("Dof Near Enable", 0x1DE, ParameterType.BOOL),
            P<bool>("Dof Far Enable", 0x1DF, ParameterType.BOOL),
            P<bool>("Dof Debug Draw", 0x1E0, ParameterType.BOOL),
            P<float>("Dof Radius", 0x1D0, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("Dof Depth Scale Foreground", 0x1D4, ParameterType.FLOAT, pMinStep(0.0f, 0.0001f)),
            P<float>("Dof Aspect", 0x1D8, ParameterType.FLOAT, pMinStep(0.0f, 0.001f)),
            P<bool>("Vignetting Enabled", 0x200, ParameterType.BOOL),
            P<bool>("Vignetting Ellipse", 0x201, ParameterType.BOOL),
            P<float>("Vignetting Ellipticity", 0x204, ParameterType.FLOAT, pStep(0.01f)),
            P<float>("Vignetting Offset", 0x1F8, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("Vignetting Pow", 0x1FC, ParameterType.FLOAT, pStep(0.01f)),
            P<int>("Vignetting Color", 0x208, ParameterType.COLOR)
        };

        private delegate nint CreateMotionBlurObject();
        private delegate nint CreateMotionBlurObject2(nint unknownPtr);
        private delegate nint DestroyMotionBlurObject(nint motionBlurObjectInternal, int unknownInt);
        private Hook<CreateMotionBlurObject>? createMotionBlurObject;
        private Hook<CreateMotionBlurObject2>? createMotionBlurObject2;
        private Hook<DestroyMotionBlurObject>? destroyMotionBlurObject;
        private delegate void UpdateMotionBlurParams(nint unknownPtr, nint unknownPtr2);
        private Hook<UpdateMotionBlurParams>? updateMotionBlurParams;
        private nint motionBlurObject = 0x0;
        private static Parameter[] motionBlurParameters = {
            P<int>("Motion Blur Type", 0x168, ParameterType.INT, pStep(1)),
            P<int>("Motion Blur Sample Num", 0x180, ParameterType.INT, pMinStep(0, 1)),
            P<float>("Motion Blur Shutter Speed", 0x184, ParameterType.FLOAT, pMinStep(0.0f, 0.001f)),
            P<float>("Motion Blur Fur Shutter Speed", 0x188, ParameterType.FLOAT, pStep(0.001f)),
            P<float>("Motion Blur Threshold", 0x18C, ParameterType.FLOAT, pMinStep(0.0f, 0.01f))
        };

        private delegate nint CreateSimpleSkyObject(nint unknownPtr);
        private delegate nint DestroySimpleSkyObject(nint simpleSkyObjectInternal, int unknownInt);
        private delegate void RenderSimpleSky(nint simpleSkyObjectInternal, nint unknownPtr);
        private Hook<CreateSimpleSkyObject>? createSimpleSkyObject;
        private Hook<DestroySimpleSkyObject>? destroySimpleSkyObject;
        private Hook<RenderSimpleSky>? renderSimpleSky;
        private nint simpleSkyObject = 0x0;
        private static Parameter[] simpleSkyParameters = {
            P<float>("Sky Global Intensity", 0x270, ParameterType.COLOR_FACTOR, pStep(0.001f)),
            P<float>("Sky Global Cloud Speed", 0x3A8, ParameterType.FLOAT),
            P<float>("Sky Top Cloud UV Scale[0]", 0x3D0, ParameterType.FLOAT),
            P<float>("Sky Top Cloud UV Scale[1]", 0x3D8, ParameterType.FLOAT),
            P<float>("Sky Blend", 0x3B0, ParameterType.FLOAT, pMinMaxStep(0.0f, 1.0f, 0.0025f)),
            P<float>("Sky Water Reflection Factor", 0x7A0, ParameterType.COLOR_FACTOR, pStep(0.001f)),
            P<bool>("Sky Fog", 0x3B4, ParameterType.BOOL),
            P<float>("Sky Fog Blend", 0x3B8, ParameterType.FLOAT),
            P<bool>("Sky DeGamma", 0x3BC, ParameterType.BOOL),
            P<float>("Sky DeGamma Value", 0x3C0, ParameterType.FLOAT),
            P<float>("Sky Cloud Highlight Intensity", 0x3C4, ParameterType.FLOAT),
            P<float>("Sky Cloud Shadow Intensity", 0x3C8, ParameterType.FLOAT),
            P<float>("Sky Cloud Contrast", 0x3CC, ParameterType.FLOAT),
            P<float>("Sky Sun Map Factor", 0x280, ParameterType.COLOR_FACTOR),
            P<float>("Sky Sun Size", 0x2A8, ParameterType.FLOAT),
            P<float>("Sky Sun Rotation Y", 0x3A4, ParameterType.FLOAT),
            P<float>("Sky Sun Height", 0x39C, ParameterType.FLOAT, pStep(0.0001f)),
            P<float>("Sky Sun Light Mask Height Adjustment", 0x3A0, ParameterType.FLOAT),
            P<float>("Sky Sun Light Mask Transparency", 0x2CC, ParameterType.FLOAT),
            P<float>("Sky Sun Light Mask UV Scale", 0x2D0, ParameterType.FLOAT),
            P<float>("Sky Sun Bloom Intensity", 0x2AC, ParameterType.FLOAT),
            P<float>("Sky Sun Bloom Transparency Coefficient", 0x2B0, ParameterType.FLOAT),
            P<float>("Sky Sun Bloom Threshold", 0x2B4, ParameterType.FLOAT),
            P<float>("Sky Sun Bloom Dispersion", 0x2B8, ParameterType.FLOAT),
            P<float>("Sky Sun Bloom Downsample Count", 0x2C0, ParameterType.FLOAT),
            P<float>("Sky Sun Bloom Reduction Resolution", 0x2C4, ParameterType.FLOAT),
            P<float>("Sky Sun Light Sky Color", 0x2E0, ParameterType.COLOR_FACTOR, pStep(0.001f)),
            P<float>("Sky Sun Light Sky Mask UV Scale", 0x2F0, ParameterType.FLOAT),
            P<float>("Sky Base Fov", 0x2BC, ParameterType.FLOAT),
            P<float>("Sky Base Map Factor", 0x3E0, ParameterType.COLOR_FACTOR, pStep(0.001f)),
            P<float>("Sky Base Side Cloud UV Offset", 0x3F0, ParameterType.FLOAT),
            P<float>("Sky Base Top Cloud0 UV Offset", 0x3F8, ParameterType.FLOAT),
            P<float>("Sky Base Top Cloud1 UV Offset", 0x400, ParameterType.FLOAT),
            P<float>("Sky Base Sun Cloud Highlight Color[0]", 0x440, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Sun Cloud Shadow Color[0]", 0x480, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Middle Highlight Color[0]", 0x4C0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Middle Shadow Color[0]", 0x500, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Background Highlight Color[0]", 0x540, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Background Shadow Color[0]", 0x580, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Cloud Speed[0]", 0x408, ParameterType.VECTOR2),
            P<float>("Sky Base Cloud Alpha[0]", 0x428, ParameterType.FLOAT),
            P<float>("Sky Base Sun Cloud Highlight Color[1]", 0x450, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Sun Cloud Shadow Color[1]", 0x490, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Middle Highlight Color[1]", 0x4D0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Middle Shadow Color[1]", 0x510, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Background Highlight Color[1]", 0x550, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Background Shadow Color[1]", 0x590, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Cloud Speed[1]", 0x410, ParameterType.VECTOR2),
            P<float>("Sky Base Cloud Alpha[1]", 0x42C, ParameterType.FLOAT),
            P<float>("Sky Base Sun Cloud Highlight Color[2]", 0x460, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Sun Cloud Shadow Color[2]", 0x4A0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Middle Highlight Color[2]", 0x4E0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Middle Shadow Color[2]", 0x520, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Background Highlight Color[2]", 0x560, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Background Shadow Color[2]", 0x5A0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Cloud Speed[2]", 0x418, ParameterType.VECTOR2),
            P<float>("Sky Base Cloud Alpha[2]", 0x430, ParameterType.FLOAT),
            P<float>("Sky Base Sun Cloud Highlight Color[3]", 0x470, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Sun Cloud Shadow Color[3]", 0x4B0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Middle Highlight Color[3]", 0x4F0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Middle Shadow Color[3]", 0x530, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Background Highlight Color[3]", 0x570, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Background Shadow Color[3]", 0x5B0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Base Cloud Speed[3]", 0x420, ParameterType.VECTOR2),
            P<float>("Sky Base Cloud Alpha[3]", 0x434, ParameterType.FLOAT),
            P<float>("Sky Blend Base Map Factor", 0x5C0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Side Cloud UV Offset", 0x5D0, ParameterType.FLOAT),
            P<float>("Sky Blend Top Cloud0 UV Offset", 0x5D8, ParameterType.FLOAT),
            P<float>("Sky Blend Top Cloud1 UV Offset", 0x5E0, ParameterType.FLOAT),
            P<float>("Sky Blend Sun Cloud Highlight Color[0]", 0x620, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Sun Cloud Shadow Color[0]", 0x660, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Middle Highlight Color[0]", 0x6A0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Middle Shadow Color[0]", 0x6E0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Background Highlight Color[0]", 0x720, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Background Shadow Color[0]", 0x760, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Cloud Speed[0]", 0x5E8, ParameterType.VECTOR2),
            P<float>("Sky Blend Cloud Alpha[0]", 0x608, ParameterType.FLOAT),
            P<float>("Sky Blend Sun Cloud Highlight Color[1]", 0x630, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Sun Cloud Shadow Color[1]", 0x670, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Middle Highlight Color[1]", 0x6B0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Middle Shadow Color[1]", 0x6F0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Background Highlight Color[1]", 0x730, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Background Shadow Color[1]", 0x770, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Cloud Speed[1]", 0x5F0, ParameterType.VECTOR2),
            P<float>("Sky Blend Cloud Alpha[1]", 0x60C, ParameterType.FLOAT),
            P<float>("Sky Blend Sun Cloud Highlight Color[2]", 0x640, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Sun Cloud Shadow Color[2]", 0x680, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Middle Highlight Color[2]", 0x6C0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Middle Shadow Color[2]", 0x700, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Background Highlight Color[2]", 0x740, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Background Shadow Color[2]", 0x780, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Cloud Speed[2]", 0x5F8, ParameterType.VECTOR2),
            P<float>("Sky Blend Cloud Alpha[2]", 0x610, ParameterType.FLOAT),
            P<float>("Sky Blend Sun Cloud Highlight Color[3]", 0x650, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Sun Cloud Shadow Color[3]", 0x690, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Middle Highlight Color[3]", 0x6D0, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Middle Shadow Color[3]", 0x710, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Background Highlight Color[3]", 0x750, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Background Shadow Color[3]", 0x790, ParameterType.COLOR_FACTOR),
            P<float>("Sky Blend Cloud Speed[3]", 0x600, ParameterType.VECTOR2),
            P<float>("Sky Blend Cloud Alpha[3]", 0x614, ParameterType.FLOAT),
            P<float>("Sky Starry Sky Map Factor", 0x290, ParameterType.COLOR_FACTOR, pStep(0.001f)),
        };

        private delegate nint CreateFogObject();
        private delegate nint CreateFogObject2(nint unknownPtr);
        private delegate nint DestroyFogObject(nint fogObjectInternal, int unknownInt);
        private Hook<CreateFogObject>? createFogObject;
        private Hook<CreateFogObject2>? createFogObject2;
        private Hook<DestroyFogObject>? destroyFogObject;
        private delegate void UpdateFogParams(nint unknownPtr, int unknownInt);
        private Hook<UpdateFogParams>? updateFogParams;
        private nint fogObject = 0x0;
        private static Parameter[] fogParameters = {
            P<float>("Fog Mip Fog Intensity", 0x2C0, ParameterType.FLOAT, pStep(0.0025f)),
            P<float>("Fog Mip Fog Color", 0x330, ParameterType.COLOR_FACTOR, pStep(0.001f))
        };

        private delegate nint CreateWaterWaveObject(nint unknownPtr);
        private delegate nint DestroyWaterWaveObject(nint waterWaveObjectInternal, int unknownInt);
        private Hook<CreateWaterWaveObject>? createWaterWaveObject;
        private Hook<DestroyWaterWaveObject>? destroyWaterWaveObject;
        private nint waterWaveObject = 0x0;
        private static Parameter[] waterWaveParameters = {
            P<float>("Water Murkiness", 0x40C, ParameterType.FLOAT),
            P<int>("Water Color", 0x404, ParameterType.COLOR),
            P<float>("Water Scattering Intensity", 0x408, ParameterType.FLOAT, pStep(0.001f))
        };

        private delegate nint CreateFXAAObject();
        private delegate nint CreateFXAAObject2(nint unknownPtr);
        private delegate nint DestroyFXAAObject(nint fxaaObjectInternal, int unknownInt);
        private Hook<CreateFXAAObject>? createFXAAObject;
        private Hook<CreateFXAAObject2>? createFXAAObject2;
        private Hook<DestroyFXAAObject>? destroyFXAAObject;
        private nint fxaaObject = 0x0;
        private static Parameter[] fxaaParameters = {
            P<float>("FXAA Subpix", 0x178, ParameterType.FLOAT, pMinMaxStep(0.0f, 1.0f, 0.005f)),
            P<float>("FXAA Edge Threshold", 0x17C, ParameterType.FLOAT, pMinMaxStep(0.0f, 1.0f, 0.001f)),
            P<float>("FXAA Edge Threshold Min", 0x180, ParameterType.FLOAT, pMinMaxStep(0.0f, 1.0f, 0.001f))
        };

        private delegate nint CreateTAAObject();
        private delegate nint CreateTAAObject2(nint unknownPtr);
        private delegate nint DestroyTAAObject(nint taaObjectInternal, int unknownInt);
        private Hook<CreateTAAObject>? createTAAObject;
        private Hook<CreateTAAObject2>? createTAAObject2;
        private Hook<DestroyTAAObject>? destroyTAAObject;
        private nint taaObject = 0x0;
        private static Parameter[] taaParameters = {
            P<bool>("TAA Reprojection", 0x19D, ParameterType.BOOL),
            P<bool>("TAA Jitter Enable", 0x184, ParameterType.BOOL),
            P<float>("TAA Blend Rate", 0x180, ParameterType.FLOAT),
            P<float>("TAA Variance Gamma", 0x194, ParameterType.FLOAT),
            P<bool>("TAA Sharpen", 0x187, ParameterType.BOOL),
            P<float>("TAA Sharpen Amount", 0x198, ParameterType.FLOAT),
            P<bool>("TAA Sharpend Ignore Edges", 0x19C, ParameterType.BOOL)
        };

        private static Parameter[] allParameters = new Parameter[]{ hqMode }
            .Concat(lodParameters)
            .Concat(snowParameters)
            .Append(shadowResParameter)
            .Concat(shadowParameters2)
            .Concat(shadowCascadeParameters)
            .Concat(broadAreaShadowParameters)
            .Concat(sLightProbesParameters)
            .Concat(contactShadowParameters)
            .Concat(capsuleLightParameters)
            .Concat(ssaoParameters)
            .Concat(sslrParameters)
            .Concat(passthroughParameters)
            .Concat(lightingParameters)
            .Concat(brightnessParameters)
            .Concat(bloomParameters)
            .Concat(dofParameters)
            .Concat(motionBlurParameters)
            .Concat(simpleSkyParameters)
            .Concat(fogParameters)
            .Concat(waterWaveParameters)
            .Concat(fxaaParameters)
            .Concat(taaParameters)
            .ToArray();

        private static int currentShadowResMultiplier = 1;
        private static NativeAction<int> setShadowQuality;
        private static Patch shadowRes1_2x;
        private static Patch shadowRes1_3x;
        private static Patch shadowRes1_4x;
        private static Patch shadowRes1_5x;
#if OVERSIZED_SHADOW_MAP
        private static Patch shadowRes1_6x;
#endif
        private static Patch shadowRes1_1;
        private static Patch shadowRes1_2;
        private static Patch shadowRes1_3;
        private static Patch shadowRes1_4;
        private static nint broadAreaShadowRes1_Addr;
        private static nint broadAreaShadowRes2_Addr;

        private static void setBroadAreaShadowResolution(int multiplier)
        {
            bool reset = multiplier == 1;
            int unused1Value = Math.Clamp(0x1000 * multiplier, 0x1000, 0x4000);
            int unused2Value = Math.Clamp(0xC00 * multiplier, 0xC00, 0x4000);
            int highValue = Math.Clamp((reset ? 0x800 : 0xC00) * multiplier, reset ? 0x800 : 0xC00, 0x4000);
            int midValue = Math.Clamp( (reset ? 0x600 : 0x800) * multiplier, reset ? 0x600 : 0x800, 0x4000);
            int lowValue = Math.Clamp( (reset ? 0x400 : 0x600) * multiplier, reset ? 0x400 : 0x600, 0x4000);
            new Patch(broadAreaShadowRes1_Addr + 0x45, BitConverter.GetBytes(unused1Value)).Enable();
            new Patch(broadAreaShadowRes1_Addr + 0x45 + 0xB, BitConverter.GetBytes(unused2Value)).Enable();
            new Patch(broadAreaShadowRes1_Addr + 0x45 + 0x16, BitConverter.GetBytes(highValue)).Enable();
            new Patch(broadAreaShadowRes1_Addr + 0x45 + 0x21, BitConverter.GetBytes(midValue)).Enable();
            new Patch(broadAreaShadowRes1_Addr + 0x45 + 0x2C, BitConverter.GetBytes(lowValue)).Enable();
            // Likely unused.
            new Patch(broadAreaShadowRes2_Addr + 0x3A, BitConverter.GetBytes(unused1Value)).Enable();
            new Patch(broadAreaShadowRes2_Addr + 0x3A + 0xB, BitConverter.GetBytes(unused2Value)).Enable();
            new Patch(broadAreaShadowRes2_Addr + 0x3A + 0x16, BitConverter.GetBytes(highValue)).Enable();
            new Patch(broadAreaShadowRes2_Addr + 0x3A + 0x21, BitConverter.GetBytes(midValue)).Enable();
            new Patch(broadAreaShadowRes2_Addr + 0x3A + 0x2C, BitConverter.GetBytes(lowValue)).Enable();
        }

        private static void shadowResEnable(int multiplier)
        {
            Assert(multiplier != 1);
            if (multiplier == currentShadowResMultiplier)
            {
                return;
            }
            switch (currentShadowResMultiplier)
            {
                case 1:
                    shadowRes1_1.Enable();
                    shadowRes1_2.Enable();
                    shadowRes1_3.Enable();
                    shadowRes1_4.Enable();
                    break;
                case 2:
                    shadowRes1_2x.Disable();
                    break;
                case 3:
                    shadowRes1_3x.Disable();
                    break;
                case 4:
                    shadowRes1_4x.Disable();
                    break;
                case 5:
                    shadowRes1_5x.Disable();
                    break;
#if OVERSIZED_SHADOW_MAP
                case 6:
                    shadowRes1_6x.Disable();
                    break;
#endif
            }
            switch (multiplier)
            {
                case 2:
                    shadowRes1_2x.Enable();
                    break;
                case 3:
                    shadowRes1_3x.Enable();
                    break;
                case 4:
                    shadowRes1_4x.Enable();
                    break;
                case 5:
                    shadowRes1_5x.Enable();
                    break;
#if OVERSIZED_SHADOW_MAP
                case 6:
                    shadowRes1_6x.Enable();
                    break;
#endif
            }
            setBroadAreaShadowResolution(multiplier);
            currentShadowResMultiplier = multiplier;
            setShadowQuality.Invoke(MemoryUtil.Read<int>(sMhScene!.Instance + 0x5530) + 1);
        }

        private static void shadowResDisable()
        {
            if (currentShadowResMultiplier == 1)
            {
                return;
            }
            switch (currentShadowResMultiplier)
            {
                case 2:
                    shadowRes1_2x.Disable();
                    break;
                case 3:
                    shadowRes1_3x.Disable();
                    break;
                case 4:
                    shadowRes1_4x.Disable();
                    break;
                case 5:
                    shadowRes1_5x.Disable();
                    break;
#if OVERSIZED_SHADOW_MAP
                case 6:
                    shadowRes1_6x.Disable();
                    break;
#endif
            }
            shadowRes1_1.Disable();
            shadowRes1_2.Disable();
            shadowRes1_3.Disable();
            shadowRes1_4.Disable();
            setBroadAreaShadowResolution(1);
            currentShadowResMultiplier = 1;
            setShadowQuality.Invoke(MemoryUtil.Read<int>(sMhScene!.Instance + 0x5530) + 1);
        }

#if SHADER_FEATURES
        private bool fullResSSLR = false;
#endif
        private Patch ssrRes1;
        private Patch ssrRes2;
        private Patch ssrRes3;
        private Patch ssrShr1;
        private Patch ssrShr2;
        private Patch ssrShr3;
        private Patch ssrShr4;
        private Patch ssrShr5;
        private Patch ssrShr6;
        private Patch ssrShr7;
        private Patch ssrShr8;
        private Patch ssrSars1;
        private Patch ssrSars2;
        private Patch ssrSars3;
        private Patch ssrSars4;
        private Patch ssrSars5;
        private Patch ssrSars6;
        private Patch ssrSars7;
        private Patch ssrSars8;
        private Patch ssrSars9;
        private Patch ssrSars10;
        private Patch ssrSars11;
        private Patch ssrSars12;
        private Patch ssrSars13;
        private Patch ssrSars14;
        private Patch ssrSars15;
        private Patch ssrSars16;
        private Patch ssrSars17;
        private Patch ssrSars18;
        private Patch ssrSars19;
        private Patch ssrSars20;
        private Patch ssrSars21;
        private Patch ssrSars22;
        private Patch ssrSars23;

        private bool skipSSLRMipMapping = false;
        private bool continousSSLRTemporalReset = false;
        private Patch forceSSLRTemporalReset;

        private bool fullResVolumeBlur = false;
        private Patch volumeSars1;
        private Patch volumeSars2;
        private Patch volumeSars3;
        private Patch volumeSars4;
        private Patch volumeSars5;
        private Patch volumeSars6;
        private Patch volumeSars7;
        private Patch volumeSars8;
        private Patch volumeSars9;

        private void fullResVolumeBlurEnable()
        {
            volumeSars1.Enable();
            volumeSars2.Enable();
            volumeSars3.Enable();
            volumeSars4.Enable();
            volumeSars5.Enable();
            volumeSars6.Enable();
            volumeSars7.Enable();
            volumeSars8.Enable();
            volumeSars9.Enable();
        }

        private void fullResVolumeBlurDisable()
        {
            volumeSars1.Disable();
            volumeSars2.Disable();
            volumeSars3.Disable();
            volumeSars4.Disable();
            volumeSars5.Disable();
            volumeSars6.Disable();
            volumeSars7.Disable();
            volumeSars8.Disable();
            volumeSars9.Disable();
        }

        private bool higherVolumeQuality = false;
        private Patch value2ForVolumeQuality;

        private bool disableLODLimits = false;
        private Patch defaultViewModeLODLimit;
        private Patch defaultViewModeLODLimit_1;
        private Patch defaultViewModeLODLimit_2;
        private Patch defaultViewModeLODLimit_3;
        private Patch defaultViewModeLODLimit_4;

        private void disableLODLimitsEnable()
        {
            defaultViewModeLODLimit.Enable();
            defaultViewModeLODLimit_1.Enable();
            defaultViewModeLODLimit_2.Enable();
            defaultViewModeLODLimit_3.Enable();
            defaultViewModeLODLimit_4.Enable();
        }

        private void disableLODLimitsDisable()
        {
            defaultViewModeLODLimit.Disable();
            defaultViewModeLODLimit_1.Disable();
            defaultViewModeLODLimit_2.Disable();
            defaultViewModeLODLimit_3.Disable();
            defaultViewModeLODLimit_4.Disable();
        }

        private bool largerFoliageSwayRange = false;
        private Patch addressHigherValueForFoliageSway;

        private bool disableReducedRateAnimations = false;
        private Patch zeroFrameSkip;

        public int AddOverride(string name, Vector4 v4, int i1)
        {
            foreach (Parameter param in allParameters)
            {
                if (param.Name == name)
                {
                    Override ov = new Override(param, v4, i1);
                    Config config = getConfig();
                    BeginTransition();
                    if (!(selectedSet != "" && unsetIfOverridesContainsParam(config.Sets[selectedSet], param)))
                    {
                        List<Override>? stageOverrides = maybeGetStageOverrides(config);
                        if (!(stageOverrides != null && unsetIfOverridesContainsParam(stageOverrides, param)))
                        {
                            unsetIfOverridesContainsParam(config.Overrides[globalStage], param);
                        }
                    }
                    ov.Set();
                    EndTransition();
                    externalId++;
                    externalOverrides.Add(externalId, ov);
                    return externalId;
                }
            }
            return 0;
        }

        public void RemoveOverride(int id)
        {
            if (externalOverrides.ContainsKey(id))
            {
                Override ovE = externalOverrides[id];
                BeginTransition();
                ovE.Unset();
                Config config = getConfig();
                if (!(selectedSet != "" && setIfOverridesContainsParam(config.Sets[selectedSet], ovE.Param!)))
                {
                    List<Override>? stageOverrides = maybeGetStageOverrides(config);
                    if (!(stageOverrides != null && setIfOverridesContainsParam(stageOverrides, ovE.Param!)))
                    {
                        setIfOverridesContainsParam(config.Overrides[globalStage], ovE.Param!);
                    }
                }
                EndTransition();
                externalOverrides.Remove(id);
            }
        }

        public PluginData Initialize()
        {
            Instance = this;

            // Assert no duplicate names.
            foreach (Parameter param in allParameters)
            {
                Assert(Array.FindAll(allParameters, (p => p.Name == param.Name)).Length == 1);
            }

            // Assert OrderedStages covers all values.
            foreach (StageExt stage in Enum.GetValues(typeof(StageExt)))
            {
                if (stage == StageExt.Global) continue;
                Assert(OrderedStages.Contains(stage));
            }

            onAreaChange = Hook.Create<OnAreaChange>(0x141AC27D0, OnAreaChangeHook); // nint

            // Needed for at least "Broad Area Shadow Direction". Otherwise it will flicker on center change.
            evalSceneParams = Hook.Create<EvalSceneParams>(0x1423C3790, EvalSceneParamsHook); // nint, nint, int, nint

            // Light Dir XZY is updated seperately at 0x1420397F0, we assume this function always happens later, though.
            updateCapsuleAoParams = Hook.Create<UpdateCapsuleAOParams>(0x141B19E10, UpdateCapsuleAOParamsHook); // nint

            // These run in a loop during cutscenes.
            updateSSAOParams = Hook.Create<UpdateSSAOParams>(0x1416D8B10, UpdateSSAOParamsHook); // nint
            updateSSLRParams = Hook.Create<UpdateSSLRParams>(0x1416DA3F0, UpdateSSLRParamsHook); // nint
            updateLightingParams = Hook.Create<UpdateLightingParams>(0x1416DAAB0, UpdateLightingParamsHook); // nint, nint

            createLightingObject = Hook.Create<CreateLightingObject>(0x1424CDE20, CreateLightingObjectHook);
            destroyLightingObject = Hook.Create<DestroyLightingObject>(0x1424CE380, DestroyLightingObjectHook); // nint, int
            updateLutBlend = Hook.Create<UpdateLightingParams>(0x1416D8DF0, UpdateLutBlendHook); // nint, nint
            updateLightProbesParams = Hook.Create<UpdateLightProbesParams>(0x141AB92C0, UpdateLightProbesParamsHook); // nint, int

            createBloomObject = Hook.Create<CreateBloomObject>(0x1424CB3C0, CreateBloomObjectHook);
            createBloomObject2 = Hook.Create<CreateBloomObject2>(0x1424CB5E0, CreateBloomObject2Hook); // nint
            destroyBloomObject = Hook.Create<DestroyBloomObject>(0x1424CB750, DestroyBloomObjectHook); // nint, int

            createDofObject = Hook.Create<CreateDofObject>(0x142421E80, CreateDofObjectHook);
            createDofObject2 = Hook.Create<CreateDofObject2>(0x1424220A0, CreateDofObject2Hook); // nint
            destroyDofObject = Hook.Create<DestroyDofObject>(0x142422290, DestroyDofObjectHook); // nint, int
            updateDofParams = Hook.Create<UpdateDofParams>(0x1412BA6A0, UpdateDofParamsHook); // nint

            createMotionBlurObject = Hook.Create<CreateMotionBlurObject>(0x1424C95E0, CreateMotionBlurObjectHook);
            createMotionBlurObject2 = Hook.Create<CreateMotionBlurObject2>(0x1424C9740, CreateMotionBlurObject2Hook); // nint
            destroyMotionBlurObject = Hook.Create<DestroyMotionBlurObject>(0x1424C97E0, DestroyMotionBlurObjectHook); // nint, int
            updateMotionBlurParams = Hook.Create<UpdateMotionBlurParams>(0x1424CADF0, UpdateMotionBlurParamsHook); // nint, nint

            createSimpleSkyObject = Hook.Create<CreateSimpleSkyObject>(0x141FCCC20, CreateSimpleSkyObjectHook); // nint
            destroySimpleSkyObject = Hook.Create<DestroySimpleSkyObject>(0x141FCD840, DestroySimpleSkyObjectHook); // nint, int
            renderSimpleSky = Hook.Create<RenderSimpleSky>(0x141FD58E0, RenderSimpleSkyHook); // nint, nint

            createFogObject = Hook.Create<CreateFogObject>(0x141FADB50, CreateFogObjectHook);
            createFogObject2 = Hook.Create<CreateFogObject2>(0x141FADC80, CreateFogObject2Hook); // nint
            destroyFogObject = Hook.Create<DestroyFogObject>(0x141FADD50, DestroyFogObjectHook); // nint, int
            updateFogParams = Hook.Create<UpdateFogParams>(0x1416D8F00, UpdateFogParamsHook); // nint, int

            createWaterWaveObject = Hook.Create<CreateWaterWaveObject>(0x1423F0850, CreateWaterWaveObjectHook); // nint
            destroyWaterWaveObject = Hook.Create<DestroyWaterWaveObject>(0x1423F0EE0, DestroyWaterWaveObjectHook); // nint, int

            createFXAAObject = Hook.Create<CreateFXAAObject>(0x142393560, CreateFXAAObjectHook);
            createFXAAObject2 = Hook.Create<CreateFXAAObject2>(0x142393680, CreateFXAAObject2Hook); // nint
            destroyFXAAObject = Hook.Create<DestroyFXAAObject>(0x142393740, DestroyFXAAObjectHook); // nint, int

            createTAAObject = Hook.Create<CreateTAAObject>(0x1423911A0, CreateTAAObjectHook);
            createTAAObject2 = Hook.Create<CreateTAAObject2>(0x142391320, CreateTAAObject2Hook); // nint
            destroyTAAObject = Hook.Create<DestroyTAAObject>(0x1423916E0, DestroyTAAObjectHook); // nint, int

            lights.Initialize();

            nint addr = PatternScanner.FindFirst(Pattern.FromString("48 89 5C 24 10 48 89 74 24 18 48 89 7C 24 20 55 41 56 41 57 48 8B EC 48 83 EC 30 48 8B FA 48 8B D9 E8 AA B6 C1 FF 48 8B 47 10 48 8D 57 50"));
            Assert(addr == 0x141AB2260); // nint, nint
            updateShadowParams = Hook.Create<UpdateShadowParams>(addr, UpdateShadowParamsHook);
            staticShadowParams = Hook.Create<StaticShadowParams>(0x1416D94F0, StaticShadowParamsHook); // nint, nint

            setShadowQuality = new NativeAction<int>(0x14043FF80);

            addr = PatternScanner.FindFirst(Pattern.FromString("48 83 EC 28 F3 0F 10 0D ?? ?? ?? ?? 80 F9 04 75 2F 48 8B 0D ?? ?? ?? ?? E8 D3 8A E4 01 48 8B 0D ?? ?? ?? ?? 33 D2 E8 ?? ?? ?? ??"));
            Assert(addr == 0x14043FF80);
            Assert(MemoryUtil.Read<int>(0x142EE1A90) == 0x40000000); // 2.0.
            Assert(MemoryUtil.Read<int>(0x142E4FE5C) == 0x40400000); // 3.0.
            Assert(MemoryUtil.Read<int>(0x142F1FD4C) == 0x40800000); // 4.0.
            Assert(MemoryUtil.Read<int>(0x142F1FD50) == 0x40A00000); // 5.0.
            Assert(MemoryUtil.Read<int>(0x14321222C) == 0x40C00000); // 6.0.
            shadowRes1_2x = new Patch(addr + 0x8, [0x04, 0x1B, 0xAA, 0x02]);
            shadowRes1_3x = new Patch(addr + 0x8, [0xD0, 0xFE, 0xA0, 0x02]);
            shadowRes1_4x = new Patch(addr + 0x8, [0xC0, 0xFD, 0xAD, 0x02]);
            shadowRes1_5x = new Patch(addr + 0x8, [0xC4, 0xFD, 0xAD, 0x02]);
#if OVERSIZED_SHADOW_MAP
            shadowRes1_6x = new Patch(addr + 0x8, [0xA0, 0x22, 0xDD, 0x02]);
#endif
            shadowRes1_1 = new Patch(addr + 0x65, [0x17]); // Always set "Value is not 1.0" flag.
            shadowRes1_2 = new Patch(addr + 0x68, [0x59]); // movss -> mulss.
            shadowRes1_3 = new Patch(addr + 0x77, [0x59]); // movss -> mulss.
#if OVERSIZED_SHADOW_MAP
            shadowRes1_4 = new Patch(lton(0x142288AAA) + 0x4, [0x7A, 0x97, 0xF8, 0x00]); // Limit 4.0 -> 6.0.
#else
            shadowRes1_4 = new Patch(lton(0x142288AAA) + 0x4, [0x9E]); // Limit 4.0 -> 5.0.
#endif
            addr = PatternScanner.FindFirst(Pattern.FromString("89 91 00 55 00 00 83 FA 05 77 41 48 63 C2 4C 8D 05 ?? ?? ?? ?? 41 8B 94 80 84 8B 28 02 49 03 D0 FF E2 B8 00 08 00 00"));
            Assert(addr == 0x142288B00);
            // This value controls the shadow map texture resolution. 16384x16384 is likely the limit for many drivers
            // and any value higher would crash. Keeping this at the default value (unpatched) *should* work unless the
            // game does something unpredictable. At 3x Shadow Resolution + High, the shadow map will be 8448x8448.
            /* At 3x Shadow Resolution, results in a 16320x16320 shadow map. Adjusting the shadow map resolution via this
             * value feels unsafe, especially if the result is not a multiple of something the game would produce.
            shadowRes4_Limit = new Patch(addr + 0x29, [ // N/64 = 255, fractional values closer to 256 not tested.
                0xB8, 0x40, 0x15, 0x00, 0x00, 0xEB, 0x21 // This case is used for Low, Medium and High in-game.
            ]);
            */

            // shadowRes2/3 control the detail of the infrequently updated fallback shadows (Broad Area).
            addr = PatternScanner.FindFirst(Pattern.FromString("83 FA FF 74 06 89 91 1C 55 00 00 8B 91 30 55 00 00 83 FA FF 7F 06 8B 91 1C 55 00 00 85 D2 74 4B 83 EA 01 74 3B 83 EA 01 74 2B 83 EA 01 74 1B 83 FA 01 74 0B C7 81 20 55 00 00 01 00 00 00 C3 C7 81 20 55 00 00 00 10 00 00"));
            Assert(addr == 0x142287A50);
            broadAreaShadowRes1_Addr = addr;
            // This function seems to never be used, but is nearly identical to the first one. So might as well adjust it.
            addr = PatternScanner.FindFirst(Pattern.FromString("89 91 30 55 00 00 83 FA FF 7F 06 8B 91 1C 55 00 00 85 D2 74 4B 83 EA 01 74 3B 83 EA 01 74 2B 83 EA 01 74 1B 83 FA 01 74 0B C7 81 20 55 00 00 01 00 00 00 C3 C7 81 20 55 00 00 00 10 00 00"));
            Assert(addr == 0x142287AD0);
            broadAreaShadowRes2_Addr = addr;

            // The volume blur filter is created at a different place in the code and happens at a different
            // time (area change/createLightingObject() vs change of Volume Quality setting). It's also rendered
            // in a seperate pass that happens after the initial volume rendering. So keep that in mind if inspecting
            // a frame in renderdoc.
            volumeSars1 = new Patch(lton(0x1424D0159), [0x90, 0x90]);
            volumeSars2 = new Patch(lton(0x1424D01A0), [0x90, 0x90]);
            volumeSars3 = new Patch(lton(0x1424D01C6), [0x90, 0x90]);
            volumeSars4 = new Patch(lton(0x1424D0219), [0x90, 0x90]);
            volumeSars5 = new Patch(lton(0x1424D0242), [0x90, 0x90]);
            volumeSars6 = new Patch(lton(0x1424D029D), [0x90, 0x90]);
            volumeSars7 = new Patch(lton(0x1424D02C6), [0x90, 0x90]);
            volumeSars8 = new Patch(lton(0x1424D0321), [0x90, 0x90]);
            volumeSars9 = new Patch(lton(0x1424D034A), [0x90, 0x90]);
            /* As far as I can tell, this is limited by buffers created cpu-side. Seems like
             * it would be an extremely hard change.
            froxelRes1 = new Patch(lton(0x142384F15) + 0x1, [0x02]); // 4 -> 2
            froxelRes2 = new Patch(lton(0x142389711) + 0x1, [0x02]); // 4 -> 2
            froxelRes3 = new Patch(lton(0x142389878) + 0x1, [0x02]); // 4 -> 2
            froxelRes4 = new Patch(lton(0x14238989E) + 0x1, [0x02]); // 4 -> 2
            froxelRes5 = new Patch(lton(0x1423898D8) + 0x1, [0x02]); // 4 -> 2
            froxelRes6 = new Patch(lton(0x14238992B) + 0x1, [0x02]); // 4 -> 2
            froxelRes7 = new Patch(lton(0x14238FED1) + 0x4, [0x7B, 0xFF, 0xAB, 0x00]); // 0.25 -> 0.50
            froxelRes8 = new Patch(lton(0x14239009C) + 0x4, [0xB0, 0xFD, 0xAB, 0X00]); // 0.25 -> 0.50
            */
            /* Would require a complicated shader edit to maybe work. Similar to SSLR.
            checkerRes1 = new Patch(lton(0x14238580D) + 0x4, [0x43]); // 0.5 -> 1.0
            checkerRes2 = new Patch(lton(0x14238FFC3) + 0x4, [0x8D]); // 0.5 -> 1.0
            */

            value2ForVolumeQuality = new Patch(lton(0x142389652), [0xB8, 0x02, 0x00, 0x00, 0x00, 0x90]);

            // Gameplay.
            addr = PatternScanner.FindFirst(Pattern.FromString("80 BB 34 EC 00 00 00 88 8B 31 EC 00 00 C6 83 30 EC 00 00 00 74 1C C6 83 34 EC 00 00 00 48 8B 0D 68 4B 4F 03 80 B9 58 02 00 00 00 75 05 E8 5A F5 01 00 48 8B CB E8 E2 05 00 00 83 BB DC EB 00 00 06 74 0A C7 83 DC EB 00 00 06 00 00 00"));
            Assert(addr == 0x141B1A0B4);
            defaultViewModeLODLimit = new Patch(addr + 0x40, [0x07, 0x74, 0x0A, 0xC7, 0x83, 0xDC, 0xEB, 0x00, 0x00, 0x07]);

            // In room.
            addr = PatternScanner.FindFirst(Pattern.FromString("8B 9F CC 00 00 00 81 FB F9 01 00 00 74 0C 8B CB E8 95 3F 65 01 83 F8 05 75 11 48 8B 0D 61 C8 F6 04 BA 02 00 00 00 E8 DF 2D 8C 01 48 8B 0D A0 C7 F6 04 8B D3"));
            Assert(addr == 0x140257AE6);
            defaultViewModeLODLimit_1 = new Patch(addr + 0x22, [0x07]);

            // Forging/Changing Equipment.
            addr = PatternScanner.FindFirst(Pattern.FromString("BA 02 00 00 00 E8 6E C0 80 00 48 8B 74 24 38 48 8B 57 28 48 8D 4F 30 E8 4C 79 B4 FE 48 8B 0D 0D FF A6 03 BA 04 00 00 00 E8 8B 64 3C 00 48 8B 05 D4 01 A7 03 80 B8 FD 46 01 00 00"));
            Assert(addr == 0x141754438);
            defaultViewModeLODLimit_2 = new Patch(addr + 0x24, [0x07]);

            // Talking to NPC.
            defaultViewModeLODLimit_3 = new Patch(lton(0x14128F1AC) + 0x1, [0x07]);
            defaultViewModeLODLimit_4 = new Patch(lton(0x14128F1AC) + 0xF, [0x07]);

            addr = PatternScanner.FindFirst(Pattern.FromString("74 4D 33 C0 48 81 C1 00 02 00 00 F3 0F 10 11 0F 2F CA 72 0C FF C0 48 83 C1 04 83 F8 03 72 EC C3"));
            Assert(addr == 0x1426D89CA);
            addressHigherValueForFoliageSway = new Patch(addr + 0x7, [0x04]);

            // Found using mFrameSkipNum annotation from MHW-DTI-Dumps.
            zeroFrameSkip = new Patch(lton(0x142246948), [0x31, 0xC0, 0x90, 0x90, 0x90, 0x90]);

            // The game will crash when trying to switch to the FULL_RES path for SSR. It's likley because
            // it tries to access shaders that are not available in the game files.
            // Ex: MonsterHunterWorld.exe+259329B - lea rcx,[rdi+00000120] # Zero.
            //     MonsterHunterWorld.exe+228C4A7 - mov rdi,[rdi+00000120] # Attempted read.
            // The code that zero's these addresses looks like a shell of where they would be loaded. My assumption
            // is that it's compiled out and that this method of increasing the SSR resolution can't work.
            /*
            // Attempt to forcefully enable FULL_RES path for SSR.
            ssrFullRes1 = new Patch(lton(0x14228894D), [0x0F, 0x85, 0xB9, 0xAA, 0x30, 0x00]);
            ssrFullRes1_1 = new Patch(lton(0x14259340C), [0xC6, 0x81, 0x28, 0x02, 0x00, 0x00, 0x00, 0x90, 0x90, 0x90]);
            ssrFullRes2 = new Patch(lton(0x14228897D), [0x0F, 0x85, 0x99, 0xAA, 0x30, 0x00]);
            ssrFullRes2_1 = new Patch(lton(0x14259341C), [0xC6, 0x81, 0x30, 0x02, 0x00, 0x00, 0x00, 0x90, 0x90, 0x90]);
            ssrFullRes3 = new Patch(lton(0x1422889AD), [0x0F, 0x85, 0x79, 0xAA, 0x30, 0x00]);
            ssrFullRes3_1 = new Patch(lton(0x14259342C), [0xC6, 0x81, 0x2C, 0x02, 0x00, 0x00, 0x00, 0x90, 0x90, 0x90]);
            ssrFullRes4 = new Patch(lton(0x14259268C), [0x41, 0xC7, 0x86, 0x28, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0xC7, 0x86, 0x2C, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0xC7, 0x86, 0x30, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0xC7, 0x86, 0x34, 0x02, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x41, 0xC7, 0x86, 0x38, 0x02, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x41, 0xC6, 0x86, 0x3C, 0x02, 0x00, 0x00, 0x01]);
            */

            // SSLR resolution factor 0.5 -> 1.0 (not related to fSSLRFactor or fSSLRScale).
            ssrRes1 = new Patch(lton(0x1425926B8) + 0x9, [0x80]);
            ssrRes2 = new Patch(lton(0x1425934C0) + 0x8, [0x80]);
            // Skip mip mapping pass (part of _FULL_RES).
            ssrRes3 = new Patch(lton(0x142282B53), [0x31, 0xC0, 0x90, 0x90, 0x90]);

            // Depth mips resolution.
            ssrShr1 = new Patch(lton(0x14269DE47), [0x90, 0x90]);
            ssrShr2 = new Patch(lton(0x14269DE54), [0x90, 0x90]);
            ssrShr3 = new Patch(lton(0x14269E07A), [0x90, 0x90]);
            ssrShr4 = new Patch(lton(0x14269E080), [0x90, 0x90]);
            // Approximate depth mip resolution.
            ssrShr5 = new Patch(lton(0x14269DED3) + 0x2, [0x3]); // 4 -> 3
            ssrShr6 = new Patch(lton(0x14269DEDA) + 0x3, [0x3]);
            // Depth mips pass 1 dispatch dimensions.
            ssrSars1 = new Patch(lton(0x142282FD8) + 0x3, [0x3]); // 4 -> 3
            ssrSars2 = new Patch(lton(0x142282FE5) + 0x2, [0x3]);
            // Depth mips pass 2 iRegion parameter.
            ssrSars3 = new Patch(lton(0x142283014) + 0x3, [0x3]);
            ssrSars4 = new Patch(lton(0x142283018) + 0x3, [0x3]);
            ssrSars5 = new Patch(lton(0x14228301C) + 0x3, [0x3]);
            ssrSars6 = new Patch(lton(0x142283020) + 0x2, [0x3]);
            // Depth mips pass 2 dispatch dimensions.
            ssrSars7 = new Patch(lton(0x1422832B3) + 0x3, [0x3]);
            ssrSars8 = new Patch(lton(0x1422832C8) + 0x2, [0x3]);

            // Depth copy, for unknown use, viewport/scissor.
            ssrSars9 = new Patch(lton(0x1423C5809), [0x90, 0x90]);
            ssrSars10 = new Patch(lton(0x1423C5818), [0x90, 0x90]);
            ssrSars11 = new Patch(lton(0x1423C5824), [0x90, 0x90]);
            ssrSars12 = new Patch(lton(0x1423C5830), [0x90, 0x90]);
            ssrSars13 = new Patch(lton(0x1423C5ABC), [0x90, 0x90]);
            ssrSars14 = new Patch(lton(0x1423C5AF3), [0x90, 0x90]);

            // RayAppendBuffer dispatch dimensions, 4 -> 3 wasteful.
            //new Patch(lton(0x14228C323) + 0x3, [0x3]);
            //new Patch(lton(0x14228C32D) + 0x2, [0x3]);

            // Clear trace buffer, 8 -> 7 wasteful
            //new Patch(lton(0x14228C3F4) + 0x2, [0x7]);

            // Approximate mip resolution.
            ssrShr7 = new Patch(lton(0x142592EBA) + 0x2, [0x3]); // 4 -> 3
            ssrShr8 = new Patch(lton(0x142592ED0) + 0x2, [0x3]);
            // Mips pass 1 dispatch dimensions.
            ssrSars15 = new Patch(lton(0x142283626) + 0x3, [0x03]); // 4 -> 3
            ssrSars16 = new Patch(lton(0x142283633) + 0x2, [0x03]);
            // Mips pass 2 iRegion parameter.
            ssrSars17 = new Patch(lton(0x142283667) + 0x2, [0x03]);
            ssrSars18 = new Patch(lton(0x14228366A) + 0x3, [0x03]);
            ssrSars19 = new Patch(lton(0x14228366E) + 0x3, [0x03]);
            ssrSars20 = new Patch(lton(0x142283672) + 0x3, [0x03]);
            // Mips pass 2 dispatch dimensions.
            ssrSars21 = new Patch(lton(0x1422838E7) + 0x3, [0x03]);
            ssrSars22 = new Patch(lton(0x1422838FC) + 0x2, [0x03]);
            // Mips blur dispatch dimensions.
            ssrSars23 = new Patch(lton(0x1422839B0), [0x8D, 0x0E, 0x44, 0x8D, 0x76, 0x01, 0x90]);

            // Resolve pass, 4 -> 3 wasteful.
            //new Patch(lton(0x14228686D) + 0x3, [0x3]);
            //new Patch(lton(0x142286877) + 0x2, [0x3]);

            forceSSLRTemporalReset = new Patch(lton(0x14228CE53), [0xB9, 0x01, 0x00, 0x00, 0x00, 0x90, 0x90]);

            return new PluginData();
        }

        public void OnPreMain()
        {
            Config config = getConfig();
            PatchConfig patches = config.Patches;
#if SHADER_FEATURES
            fullResSSLR = patches.FullResolutionSSLR;
            if (fullResSSLR)
            {
                ssrRes1.Enable();
                ssrRes2.Enable();
                ssrShr1.Enable();
                ssrShr2.Enable();
                ssrShr3.Enable();
                ssrShr4.Enable();
                ssrShr5.Enable();
                ssrShr6.Enable();
                ssrShr7.Enable();
                ssrShr8.Enable();
                ssrSars1.Enable();
                ssrSars2.Enable();
                ssrSars3.Enable();
                ssrSars4.Enable();
                ssrSars5.Enable();
                ssrSars6.Enable();
                ssrSars7.Enable();
                ssrSars8.Enable();
                ssrSars9.Enable();
                ssrSars10.Enable();
                ssrSars11.Enable();
                ssrSars12.Enable();
                ssrSars13.Enable();
                ssrSars14.Enable();
                ssrSars15.Enable();
                ssrSars16.Enable();
                ssrSars17.Enable();
                ssrSars18.Enable();
                ssrSars19.Enable();
                ssrSars20.Enable();
                ssrSars21.Enable();
                ssrSars22.Enable();
                ssrSars23.Enable();
            }
#endif
            fullResVolumeBlur = patches.FullResolutionVolumeBlur;
            if (fullResVolumeBlur)
            {
                fullResVolumeBlurEnable();
            }
            higherVolumeQuality = patches.HigherThanHighestVolumeRendering;
            if (higherVolumeQuality)
            {
                value2ForVolumeQuality.Enable();
            }
            disableLODLimits = patches.DisableLODLimits;
            if (disableLODLimits)
            {
                disableLODLimitsEnable();
            }
            largerFoliageSwayRange = patches.LargerFoliageSwayRange;
            if (largerFoliageSwayRange)
            {
                addressHigherValueForFoliageSway.Enable();
            }
            disableReducedRateAnimations = patches.DisableReducedRateAnimations;
            if (disableReducedRateAnimations)
            {
                zeroFrameSkip.Enable();
            }
        }

        public void OnLoad()
        {
            sMhMain = SingletonManager.GetSingleton("sMhMain")!;
            sMhRender = SingletonManager.GetSingleton("sMhRender")!;
            sMhScene = SingletonManager.GetSingleton("sMhScene")!;
            sLightProbes = SingletonManager.GetSingleton("sLightProbes")!;
            foreach (Parameter param in sLightProbesParameters)
            {
                param.Update(sLightProbes!.Instance);
            }
            Config config = getConfig();
            if (config.SelectedGlobal == "")
            {
                config.SelectedGlobal = "Base";
            }
            selectedGlobal = config.SelectedGlobal;
            if (!config.Globals.ContainsKey(selectedGlobal))
            {
                config.Globals[selectedGlobal] = new List<Override>();
            }
            // config.Overrides shouldn't contain Global here.
            if (!config.Overrides.ContainsKey(globalStage))
            {
                config.Overrides.Add(globalStage, new List<Override>());
            }
            else
            {
                config.Overrides[globalStage].Clear();
            }
            foreach (Override ovG in config.Globals[selectedGlobal])
            {
                config.Overrides[globalStage].Add(ovG);
            }
            foreach (StageExt area in OrderedStages)
            {
                if (!config.Overrides.ContainsKey(area))
                {
                    config.Overrides.Add(area, new List<Override>());
                }
            }
            foreach (Override ovG in config.Overrides[globalStage])
            {
                ovG.Set();
            }
            foreach ((string name, List<Override> overrides) in config.Sets)
            {
                if (name == "")
                {
                    config.Sets.Remove(name);
                    break;
                }
            }
            saveConfig(config);
        }

        // It's hard to test, but I'm pretty sure just updating stepTime isn't enough for a higher rate to look right.
        // https://github.com/AsteriskAmpersand/CTC-MHW-Editor/blob/9ec6303042690478398801b1bb860a2d38298eee/structures/Ctc.py#L23
#if RESOURCE_ADJUSTMENT
        private bool adjustCtcParams = false;
        private float stepTimeFps = 60.0f;
        public void OnResourceLoad(Resource? resource, MtDti dti, string path, LoadFlags flags)
        {
            if (adjustCtcParams && resource != null && resource.FileExtension == "ctc")
            {
                Log.Info($"Attempting to increase physics update rate of {resource.FilePath} @ {resource.Instance:X}.");
                int numARecords = MemoryUtil.GetRef<int>(resource.Instance + 0xB8);
                nint aRecords = MemoryUtil.GetRef<nint>(resource.Instance + 0xF8);
                for (int i = 0; i < numARecords; i++)
                {
                    nint aRecord = aRecords + (0x50 * i);
                }
                MemoryUtil.GetRef<float>(resource.Instance + 0xC4) = 1.0f / stepTimeFps;
            }
        }
#endif

        public void OnUpdate(float deltaTime)
        {
            StageExt stage = currentStage;
            if (stage == StageExt.Global && previousStage != StageExt.Global)
            {
                HandleAreaChange(stage);
            }

            hqMode.Update(sMhScene!.Instance);

            foreach (Parameter param in lodParameters)
            {
                param.Update(sMhScene!.Instance);
            }

            foreach (Parameter param in snowParameters)
            {
                param.Update(sMhScene!.Instance);
            }

            foreach (Parameter param in passthroughParameters)
            {
                param.Update(sMhScene!.Instance);
            }

            foreach (Parameter param in shadowCascadeParameters)
            {
                param.Update(sMhScene!.Instance);
            }

            foreach (Parameter param in contactShadowParameters)
            {
                param.Update(sMhScene!.Instance);
            }

            foreach (Parameter param in ssaoParameters)
            {
                param.Update(sMhScene!.Instance);
            }

            foreach (Parameter param in sslrParameters)
            {
                param.Update(sMhScene!.Instance);
            }

            if (lightingObject != 0x0)
            {
                foreach (Parameter param in lightingParameters)
                {
                    param.Update(lightingObject);
                }
            }

            foreach (Parameter param in brightnessParameters)
            {
                param.Update(sMhRender!.Instance);
            }

            if (bloomObject != 0x0)
            {
                foreach (Parameter param in bloomParameters)
                {
                    param.Update(bloomObject);
                }
            }

            if (dofObject != 0x0)
            {
                foreach (Parameter param in dofParameters)
                {
                    param.Update(dofObject);
                }
            }

            if (motionBlurObject != 0x0)
            {
                foreach (Parameter param in motionBlurParameters)
                {
                    param.Update(motionBlurObject);
                }
            }

            if (waterWaveObject != 0x0)
            {
                foreach (Parameter param in waterWaveParameters)
                {
                    param.Update(waterWaveObject);
                }
            }

            if (fxaaObject != 0x0)
            {
                foreach (Parameter param in fxaaParameters)
                {
                    param.Update(fxaaObject);
                }
            }

            if (taaObject != 0x0)
            {
                foreach (Parameter param in taaParameters)
                {
                    param.Update(taaObject);
                }
            }
        }

        private void EvalSceneParamsHook(nint unknownPtr, nint unknownPtr2, int unknownInt, nint unknownPtr3)
        {
            foreach (Parameter param in broadAreaShadowParameters)
            {
                param.Update(sMhScene!.Instance, true);
            }
            evalSceneParams!.Original(unknownPtr, unknownPtr2, unknownInt, unknownPtr3);
        }

        private void UpdateCapsuleAOParamsHook(nint sceneObjectInternal)
        {
            updateCapsuleAoParams!.Original(sceneObjectInternal);
            foreach (Parameter param in capsuleLightParameters)
            {
                param.Update(sMhScene!.Instance, true);
            }
        }

        private void UpdateSSAOParamsHook(nint stackOffset)
        {
            updateSSAOParams!.Original(stackOffset);
            foreach (Parameter param in ssaoParameters)
            {
                param.Update(sMhScene!.Instance, true);
            }
        }

        private void UpdateSSLRParamsHook(nint stackOffset)
        {
            updateSSLRParams!.Original(stackOffset);
            foreach (Parameter param in sslrParameters)
            {
                param.Update(sMhScene!.Instance, true);
            }
        }

        private void UpdateLightingParamsHook(nint stackOffset, nint lightingObjectInternal)
        {
            updateLightingParams!.Original(stackOffset, lightingObjectInternal);
            if (lightingObject == lightingObjectInternal)
            {
                foreach (Parameter param in lightingParameters)
                {
                    param.Update(lightingObject, true);
                }
            }
        }

        private nint CreateLightingObjectHook()
        {
            lightingObject = createLightingObject!.Original();
            foreach (Parameter param in lightingParameters)
            {
                param.Update(lightingObject);
            }
            return lightingObject;
        }

        private nint DestroyLightingObjectHook(nint lightingObjectInternal, int unknownInt)
        {
            Assert(unknownInt == 1);
            if (lightingObject == lightingObjectInternal)
            {
                lightingObject = 0x0;
                foreach (Parameter param in lightingParameters)
                {
                    param.Update(lightingObject);
                }
            }
            return destroyLightingObject!.Original(lightingObjectInternal, unknownInt);
        }

        private void UpdateLutBlendHook(nint stackOffset, nint lightingObjectInternal)
        {
            updateLutBlend!.Original(stackOffset, lightingObjectInternal);
            if (lightingObject == lightingObjectInternal)
            {
                foreach (Parameter param in lightingParameters)
                {
                    param.Update(lightingObject, true);
                }
            }
        }

        private void UpdateLightProbesParamsHook(nint unknownPtr, int unknownInt)
        {
            updateLightProbesParams!.Original(unknownPtr, unknownInt);
            foreach (Parameter param in sLightProbesParameters)
            {
                param.Update(sLightProbes!.Instance);
            }
        }

        private nint CreateBloomObjectHook()
        {
            bloomObject = createBloomObject!.Original();
            foreach (Parameter param in bloomParameters)
            {
                param.Update(bloomObject);
            }
            return bloomObject;
        }

        private nint CreateBloomObject2Hook(nint unknownPtr)
        {
            bloomObject = createBloomObject2!.Original(unknownPtr);
            foreach (Parameter param in bloomParameters)
            {
                param.Update(bloomObject);
            }
            return bloomObject;
        }

        private nint DestroyBloomObjectHook(nint bloomObjectInternal, int unknownInt)
        {
            Assert(unknownInt == 1);
            if (bloomObject == bloomObjectInternal)
            {
                bloomObject = 0x0;
                foreach (Parameter param in bloomParameters)
                {
                    param.Update(bloomObject);
                }
            }
            return destroyBloomObject!.Original(bloomObjectInternal, unknownInt);
        }

        private nint CreateDofObjectHook()
        {
            dofObject = createDofObject!.Original();
            foreach (Parameter param in dofParameters)
            {
                param.Update(dofObject);
            }
            return dofObject;
        }

        private nint CreateDofObject2Hook(nint unknownPtr)
        {
            dofObject = createDofObject2!.Original(unknownPtr);
            foreach (Parameter param in dofParameters)
            {
                param.Update(dofObject);
            }
            return dofObject;
        }

        private nint DestroyDofObjectHook(nint dofObjectInternal, int unknownInt)
        {
            Assert(unknownInt == 1);
            if (dofObject == dofObjectInternal)
            {
                dofObject = 0x0;
                foreach (Parameter param in dofParameters)
                {
                    param.Update(dofObject);
                }
            }
            return destroyDofObject!.Original(dofObjectInternal, unknownInt);
        }

        private void UpdateDofParamsHook(nint unknownPtr)
        {
            updateDofParams!.Original(unknownPtr);
            foreach (Parameter param in dofParameters)
            {
                param.Update(dofObject, true);
            }
        }

        private nint CreateMotionBlurObjectHook()
        {
            motionBlurObject = createMotionBlurObject!.Original();
            foreach (Parameter param in motionBlurParameters)
            {
                param.Update(motionBlurObject);
            }
            return motionBlurObject;
        }

        private nint CreateMotionBlurObject2Hook(nint unknownPtr)
        {
            motionBlurObject = createMotionBlurObject2!.Original(unknownPtr);
            foreach (Parameter param in motionBlurParameters)
            {
                param.Update(motionBlurObject);
            }
            return motionBlurObject;
        }

        private nint DestroyMotionBlurObjectHook(nint motionBlurObjectInternal, int unknownInt)
        {
            Assert(unknownInt == 1);
            if (motionBlurObject == motionBlurObjectInternal)
            {
                motionBlurObject = 0x0;
                foreach (Parameter param in motionBlurParameters)
                {
                    param.Update(motionBlurObject);
                }
            }
            return destroyMotionBlurObject!.Original(motionBlurObjectInternal, unknownInt);
        }

        private void UpdateMotionBlurParamsHook(nint unknownPtr, nint unknownPtr2)
        {
            foreach (Parameter param in motionBlurParameters)
            {
                param.Update(motionBlurObject, true);
            }
            updateMotionBlurParams!.Original(unknownPtr, unknownPtr2);
        }

        private nint CreateSimpleSkyObjectHook(nint unknownPtr)
        {
            simpleSkyObject = createSimpleSkyObject!.Original(unknownPtr);
            foreach (Parameter param in simpleSkyParameters)
            {
                param.Update(simpleSkyObject);
            }
            return simpleSkyObject;
        }

        private nint DestroySimpleSkyObjectHook(nint simpleSkyObjectInternal, int unknownInt)
        {
            Assert(unknownInt == 1);
            if (simpleSkyObjectInternal == simpleSkyObject)
            {
                simpleSkyObject = 0x0;
                foreach (Parameter param in simpleSkyParameters)
                {
                    param.Update(simpleSkyObject);
                }
            }
            return destroySimpleSkyObject!.Original(simpleSkyObjectInternal, unknownInt);
        }

        private void RenderSimpleSkyHook(nint simpleSkyObjectInternal, nint unknownPtr)
        {
            foreach (Parameter param in simpleSkyParameters)
            {
                param.Update(simpleSkyObject, true);
            }
            renderSimpleSky!.Original(simpleSkyObjectInternal, unknownPtr);
        }

        private nint CreateFogObjectHook()
        {
            fogObject = createFogObject!.Original();
            foreach (Parameter param in fogParameters)
            {
                param.Update(fogObject);
            }
            return fogObject;
        }

        private nint CreateFogObject2Hook(nint unknownPtr)
        {
            fogObject = createFogObject2!.Original(unknownPtr);
            foreach (Parameter param in fogParameters)
            {
                param.Update(fogObject);
            }
            return fogObject;
        }

        private nint DestroyFogObjectHook(nint fogObjectInternal, int unknownInt)
        {
            Assert(unknownInt == 1);
            if (fogObject == fogObjectInternal)
            {
                fogObject = 0x0;
                foreach (Parameter param in fogParameters)
                {
                    param.Update(fogObject);
                }
            }
            return destroyFogObject!.Original(fogObjectInternal, unknownInt);
        }

        private void UpdateFogParamsHook(nint unknownPtr, int unknownInt)
        {
            updateFogParams!.Original(unknownPtr, unknownInt);
            foreach (Parameter param in fogParameters)
            {
                param.Update(fogObject, true);
            }
        }

        private nint CreateWaterWaveObjectHook(nint unknownPtr)
        {
            waterWaveObject = createWaterWaveObject!.Original(unknownPtr);
            foreach (Parameter param in waterWaveParameters)
            {
                param.Update(waterWaveObject);
            }
            return waterWaveObject;
        }

        private nint DestroyWaterWaveObjectHook(nint waterWaveObjectInternal, int unknownInt)
        {
            Assert(unknownInt == 1);
            if (waterWaveObjectInternal == waterWaveObject)
            {
                waterWaveObject = 0x0;
                foreach (Parameter param in waterWaveParameters)
                {
                    param.Update(waterWaveObject);
                }
            }
            return destroyWaterWaveObject!.Original(waterWaveObjectInternal, unknownInt);
        }

        private nint CreateFXAAObjectHook()
        {
            fxaaObject = createFXAAObject!.Original();
            foreach (Parameter param in fxaaParameters)
            {
                param.Update(fxaaObject);
            }
            return fxaaObject;
        }

        private nint CreateFXAAObject2Hook(nint unknownPtr)
        {
            fxaaObject = createFXAAObject2!.Original(unknownPtr);
            foreach (Parameter param in fxaaParameters)
            {
                param.Update(fxaaObject);
            }
            return fxaaObject;
        }

        private nint DestroyFXAAObjectHook(nint fxaaObjectInternal, int unknownInt)
        {
            Assert(unknownInt == 1);
            if (fxaaObject == fxaaObjectInternal)
            {
                fxaaObject = 0x0;
                foreach (Parameter param in fxaaParameters)
                {
                    param.Update(fxaaObject);
                }
            }
            return destroyFXAAObject!.Original(fxaaObjectInternal, unknownInt);
        }

        private nint CreateTAAObjectHook()
        {
            taaObject = createTAAObject!.Original();
            foreach (Parameter param in taaParameters)
            {
                param.Update(taaObject);
            }
            return taaObject;
        }

        private nint CreateTAAObject2Hook(nint unknownPtr)
        {
            taaObject = createTAAObject2!.Original(unknownPtr);
            foreach (Parameter param in taaParameters)
            {
                param.Update(taaObject);
            }
            return taaObject;
        }

        private nint DestroyTAAObjectHook(nint taaObjectInternal, int unknownInt)
        {
            Assert(unknownInt == 1);
            if (taaObject == taaObjectInternal)
            {
                taaObject = 0x0;
                foreach (Parameter param in taaParameters)
                {
                    param.Update(taaObject);
                }
            }
            return destroyTAAObject!.Original(taaObjectInternal, unknownInt);
        }

        private void UpdateShadowParamsHook(nint shadowParams, nint stackOffset)
        {
            bool isPrimary = MemoryUtil.Read<byte>(stackOffset + 0x1D) == 0x1;
            if (isPrimary)
            {
                foreach (Parameter param in shadowParameters2)
                {
                    param.Update(stackOffset, true);
                }
            }
            updateShadowParams!.Original(shadowParams, stackOffset);
        }

        private void StaticShadowParamsHook(nint shadowParamsStatic, nint shadowObjectInternal)
        {
            if (shadowObjectInternal == 0x0)
            {
                // Necessary to apply Broad Area Depth Bias overrides on first update.
                foreach (Parameter param in shadowParameters2)
                {
                    param.Update(shadowParamsStatic, true);
                }
            }
            staticShadowParams!.Original(shadowParamsStatic, shadowObjectInternal);
        }

        private void HandleSetChange(string prevSet, List<Override> globalOverrides, List<Override>? stageOverrides)
        {
            Config config = getConfig();
            if (prevSet != "")
            {
                List<Override> prevOverrides = config.Sets[prevSet];
                foreach (Override ovR in prevOverrides)
                {
                    bool superseded = ovR.Param != null && overridesContainsParam(externalOverrides.Values, ovR.Param);
                    if (!superseded)
                    {
                        ovR.Unset();
                        if (ovR.Param != null)
                        {
                            if (!(stageOverrides != null && setIfOverridesContainsParam(stageOverrides, ovR.Param)))
                            {
                                setIfOverridesContainsParam(globalOverrides, ovR.Param);
                            }
                        }
                    }
                }
            }
            if (selectedSet != "")
            {
                List<Override> newOverrides = config.Sets[selectedSet];
                foreach (Override ovN in newOverrides)
                {
                    bool superseded = ovN.Param != null && overridesContainsParam(externalOverrides.Values, ovN.Param);
                    if (!superseded)
                    {
                        if (ovN.Param != null)
                        {
                            if (!(stageOverrides != null && unsetIfOverridesContainsParam(stageOverrides, ovN.Param)))
                            {
                                unsetIfOverridesContainsParam(globalOverrides, ovN.Param);
                            }
                        }
                        ovN.Set();
                    }
                }
            }
        }

        private void HandleGlobalChange()
        {
            Config config = getConfig();

            // Unset current Global overrides.
            List<Override>? stageOverrides = maybeGetStageOverrides(config);
            List<Override> globalOverrides = config.Overrides[globalStage];
            foreach (Override ovG in globalOverrides)
            {
                bool superseded = selectedOverrideSuperseded(config, null, stageOverrides, ovG.Param);
                if (!superseded)
                {
                    ovG.Unset();
                }
            }

            // Drop current Global overrides.
            globalOverrides.Clear();

            // Rebuild from new selections.
            foreach (Override ovG in config.Globals[selectedGlobal])
            {
                globalOverrides.Add(ovG);
            }

            // Set new Global overrides.
            foreach (Override ovG in globalOverrides)
            {
                bool superseded = selectedOverrideSuperseded(config, null, stageOverrides, ovG.Param);
                if (!superseded)
                {
                    ovG.Set();
                }
            }
        }

        private void HandleAreaChange(StageExt stage)
        {
            Config config = getConfig();
            List<Override> prevOverrides = config.Overrides[previousStage];
            List<Override> globalOverrides = config.Overrides[globalStage];
            BeginTransition();
            if (previousStage != globalStage)
            {
                foreach (Override ovR in prevOverrides)
                {
                    bool superseded = stageOverrideSuperseded(config, ovR.Param);
                    if (!superseded)
                    {
                        ovR.Unset();
                        if (ovR.Param != null)
                        {
                            setIfOverridesContainsParam(globalOverrides, ovR.Param);
                        }
                    }
                }
            }
            if (!config.Overrides.ContainsKey(stage))
            {
                Log.Error($"Unknown stage: {stage}");
                stage = globalStage;
            }
            if (stage != globalStage)
            {
                List<Override> stageOverrides = config.Overrides[stage];
                foreach (Override ovS in stageOverrides)
                {
                    bool superseded = stageOverrideSuperseded(config, ovS.Param);
                    if (!superseded)
                    {
                        if (ovS.Param != null)
                        {
                            unsetIfOverridesContainsParam(globalOverrides, ovS.Param);
                        }
                        ovS.Set();
                    }
                }
            }
            EndTransition();
            previousStage = stage;
        }

        private void OnAreaChangeHook(nint unknownPtr)
        {
            onAreaChange!.Original(unknownPtr);
            StageExt stage = currentStage;
            if (stage == previousStage)
            {
                return;
            }
            HandleAreaChange(stage);
        }

        public void OnImGuiRender()
        {
            float width = ImGui.GetWindowWidth();
            width /= width / (600.0f * ImGui.GetIO().FontGlobalScale);

            ImGui.Text($"Current Stage: {StageToString(currentStage)}");
            ImGui.PushItemWidth(width * 0.35f);
            if (ImGui.BeginCombo("##Stage", StageToString(selectedStage), ImGuiComboFlags.HeightLarge))
            {
                foreach (StageExt area in OrderedStages)
                {
                    string name = StageToString(area);
                    bool isSelected = selectedStage == area;
                    if (ImGui.Selectable(name, isSelected))
                    {
                        selectedStage = area;
                    }
                    if (isSelected) ImGui.SetItemDefaultFocus();
                }
                ImGui.EndCombo();
            }
            ImGui.SameLine();
            Config config = getConfig();
            bool errorStage = !config.Overrides.ContainsKey(currentStage);
            if (errorStage)
            {
                ImGui.PushItemFlag(ImGuiItemFlags.Disabled, true);
                ImGui.PushStyleVar(ImGuiStyleVar.Alpha, ImGui.GetStyle().Alpha * 0.5f);
            }
            if (ImGui.Button("Current"))
            {
                selectedStage = currentStage;
            }
            if (errorStage)
            {
                ImGui.PopStyleVar();
                ImGui.PopItemFlag();
            }
            ImGui.SameLine();
            if (ImGui.Button("Global"))
            {
                selectedStage = globalStage;
            }

            bool selectedOrderChanged = false;
            List<Override> selectedOverrides = config.Overrides[selectedStage];
            if (ImGui.Button("Add override"))
            {
                Override ov = new Override();
                if (selectedStage == currentStage || selectedStage == globalStage)
                {
                    ov.Set(); // Empty override never superseded.
                }
                selectedOverrides.Add(ov);
                selectedOrderChanged = true;
            }
            List<Override>? stageOverrides = maybeGetStageOverrides(config);
            List<Override>? globalOverrides = null;
            if (selectedStage != globalStage)
            {
                globalOverrides = config.Overrides[globalStage];
            }
            else
            {
                ImGui.SameLine();
                string prevGlobal = selectedGlobal;
                ImGui.Text("Preset:");
                ImGui.SameLine();
                ImGui.SetCursorPos(ImGui.GetCursorPos() - new Vector2(5.0f, 0.0f));
                if (ImGui.BeginCombo("##Preset", selectedGlobal))
                {
                    foreach ((string name, List<Override> overrides) in config.Globals)
                    {
                        bool isSelected = name == selectedGlobal;
                        if (ImGui.Selectable(name, isSelected))
                        {
                            selectedGlobal = name;
                        }
                    }
                    ImGui.EndCombo();
                }
                if (prevGlobal != selectedGlobal)
                {
                    BeginTransition();
                    HandleGlobalChange();
                    EndTransition();
                    config.SelectedGlobal = selectedGlobal;
                    saveConfig(config);
                }
            }
            ImGui.PopItemWidth();
            for (int i = 0; i < selectedOverrides.Count; i++)
            {
                ImGui.PushID(i);
                Override ovS = selectedOverrides[i];
                bool superseded = selectedOverrideSuperseded(config, globalOverrides, stageOverrides, ovS.Param);
                bool requestRemove = ImGui.Button("X");
                ImGui.SameLine();
                bool requestUp = ImGui.Button("â–²");
                ImGui.SameLine();
                bool requestDown = ImGui.Button("â–¼");
                ImGui.SameLine();
                selectedOrderChanged |= requestRemove || requestUp || requestDown;
                if (requestDown && i < selectedOverrides.Count - 1)
                {
                    (selectedOverrides[i], selectedOverrides[i + 1]) = (selectedOverrides[i + 1], selectedOverrides[i]);
                }
                ovS.Draw(false, selectedOverrides, stageOverrides, globalOverrides, superseded, width);
                if (requestUp && i > 0)
                {
                    (selectedOverrides[i], selectedOverrides[i - 1]) = (selectedOverrides[i - 1], selectedOverrides[i]);
                }
                if (requestRemove)
                {
                    if (!superseded)
                    {
                        BeginTransition();
                        ovS.Unset();
                        if (ovS.Param != null && globalOverrides != null)
                        {
                            setIfOverridesContainsParam(globalOverrides, ovS.Param);
                        }
                        EndTransition();
                    }
                    selectedOverrides.RemoveAt(i);
                    i--;
                }

                ImGui.PopID();
            }
            if (ImGui.Button("Save"))
            {
                for (int i = 0; i < selectedOverrides.Count; i++)
                {
                    Override ovS = selectedOverrides[i];
                    if (ovS.Param == null)
                    {
                        selectedOverrides.RemoveAt(i);
                        i--;
                        continue;
                    }
                    ovS.Save();
                }
                saveConfig(config);
            }
            if (selectedOrderChanged)
            {
                if (selectedStage == globalStage)
                {
                    rebuildConfig(config, selectedOverrides);
                }
                configState |= SelectedNotSaved;
            }
            if ((configState & SelectedNotSaved) == SelectedNotSaved)
            {
                ImGui.SameLine();
                ImGui.PushStyleVar(ImGuiStyleVar.Alpha, ImGui.GetStyle().Alpha * 0.5f);
                ImGui.Text("(Not Saved)");
                ImGui.PopStyleVar();
            }

            ImGui.Separator();

            // From this point forward, we have to consider both globalOverrides and stageOverrides.
            globalOverrides = config.Overrides[globalStage];

            ImGui.PushID("Set");
            ImGui.Text("Quick Sets:");
            ImGui.PushItemWidth(width * 0.35f);
            string prevSet = selectedSet;
            if (ImGui.Button("+"))
            {
                string setName = "New Set";
                int setDup = 0;
                while (config.Sets.ContainsKey(setName))
                {
                    setDup++;
                    setName = $"New Set ({setDup})";
                }
                config.Sets[setName] = new List<Override>();
                selectedSet = setName;
            }
            ImGui.SameLine();
            if (renamingSet)
            {
                ImGui.PushItemFlag(ImGuiItemFlags.Disabled, true);
                ImGui.PushStyleVar(ImGuiStyleVar.Alpha, ImGui.GetStyle().Alpha * 0.5f);
            }
            if (ImGui.BeginCombo("##Set", selectedSet))
            {
                if (ImGui.Selectable("(None)", false))
                {
                    selectedSet = "";
                }
                foreach ((string name, List<Override> overrides) in config.Sets)
                {
                    bool isSelected = name == selectedSet;
                    if (ImGui.Selectable(name, isSelected))
                    {
                        selectedSet = name;
                    }
                }
                ImGui.EndCombo();
            }
            if (prevSet != selectedSet)
            {
                BeginTransition();
                HandleSetChange(prevSet, globalOverrides, stageOverrides);
                EndTransition();
            }
            if (renamingSet)
            {
                ImGui.PopStyleVar();
                ImGui.PopItemFlag();
            }
            ImGui.PopItemWidth();
            if (selectedSet != "")
            {
                ImGui.SameLine();
                ImGui.PushItemWidth(width * 0.2f);
                if (renamingSet)
                {
                    ImGui.InputText("##Set Name", ref typedSetName, 99);
                    ImGui.SameLine();
                    if (typedSetName == "")
                    {
                        ImGui.PushItemFlag(ImGuiItemFlags.Disabled, true);
                        ImGui.PushStyleVar(ImGuiStyleVar.Alpha, ImGui.GetStyle().Alpha * 0.5f);
                    }
                    if (ImGui.Button("Save"))
                    {
                        string setName = typedSetName;
                        if (setName != selectedSet)
                        {
                            int setDup = 0;
                            while (config.Sets.ContainsKey(setName))
                            {
                                setDup++;
                                setName = $"{typedSetName} ({setDup})";
                            }
                            List<Override> tmpOverrides = config.Sets[selectedSet];
                            config.Sets.Remove(selectedSet);
                            config.Sets[setName] = tmpOverrides;
                            selectedSet = setName;
                        }
                        renamingSet = false;
                    }
                    if (typedSetName == "")
                    {
                        ImGui.PopStyleVar();
                        ImGui.PopItemFlag();
                    }
                }
                else if (ImGui.Button("Rename"))
                {
                    renamingSet = true;
                    typedSetName = selectedSet;
                }
                ImGui.PopItemWidth();

                bool setOrderChanged = false;
                List<Override> setOverrides = config.Sets[selectedSet];
                if (ImGui.Button("Add override"))
                {
                    Override ov = new Override();
                    ov.Set(); // Empty override never superseded.
                    setOverrides.Add(ov);
                    setOrderChanged = true;
                }
                for (int i = 0; i < setOverrides.Count; i++)
                {
                    ImGui.PushID(i);
                    Override ovP = setOverrides[i];
                    bool superseded = ovP.Param != null && overridesContainsParam(externalOverrides.Values, ovP.Param);
                    bool requestRemove = ImGui.Button("X");
                    ImGui.SameLine();
                    bool requestUp = ImGui.Button("â–²");
                    ImGui.SameLine();
                    bool requestDown = ImGui.Button("â–¼");
                    ImGui.SameLine();
                    setOrderChanged |= requestRemove || requestUp || requestDown;
                    if (requestDown && i < setOverrides.Count - 1)
                    {
                        (setOverrides[i], setOverrides[i + 1]) = (setOverrides[i + 1], setOverrides[i]);
                    }
                    ovP.Draw(true, setOverrides, stageOverrides, globalOverrides, superseded, width);
                    if (requestUp && i > 0)
                    {
                        (setOverrides[i], setOverrides[i - 1]) = (setOverrides[i - 1], setOverrides[i]);
                    }
                    if (requestRemove)
                    {
                        if (!superseded)
                        {
                            BeginTransition();
                            ovP.Unset();
                            if (ovP.Param != null)
                            {
                                if (!(stageOverrides != null && setIfOverridesContainsParam(stageOverrides, ovP.Param)))
                                {
                                    setIfOverridesContainsParam(globalOverrides, ovP.Param);
                                }
                            }
                            EndTransition();
                        }
                        setOverrides.RemoveAt(i);
                        i--;
                    }
                    ImGui.PopID();
                }
                if (ImGui.Button("Save"))
                {
                    for (int i = 0; i < setOverrides.Count; i++)
                    {
                        Override ovP = setOverrides[i];
                        if (ovP.Param == null)
                        {
                            setOverrides.RemoveAt(i);
                            i--;
                            continue;
                        }
                        ovP.Save();
                    }
                    saveConfig(config);
                }
                if (setOrderChanged)
                {
                    configState |= SetNotSaved;
                }
                if ((configState & SetNotSaved) == SetNotSaved)
                {
                    ImGui.SameLine();
                    ImGui.PushStyleVar(ImGuiStyleVar.Alpha, ImGui.GetStyle().Alpha * 0.5f);
                    ImGui.Text("(Not Saved)");
                    ImGui.PopStyleVar();
                }
            }
            ImGui.PopID();

            ImGui.Separator();

            ImGui.PushID("External");
            ImGui.Text("External:");
            foreach (Override ovE in externalOverrides.Values)
            {
                ovE.Draw(false, null, null, null, false, width);
            }
            ImGui.PopID();

            ImGui.Separator();

            if (ImGui.CollapsingHeader("Patches"))
            {
                PatchConfig patches = config.Patches;

#if SHADER_FEATURES
                if (ImGui.Checkbox("Full Resolution Screen Space Reflections (Requires Restart)", ref fullResSSLR))
                {
                    patches.FullResolutionSSLR = fullResSSLR;
                    config.Patches = patches;
                    saveConfig(config);
                }
                if (ImGui.BeginItemTooltip())
                {
                    ImGui.Text("Restart Required");
                    ImGui.EndTooltip();
                }
#endif

                if (ImGui.Checkbox("Volume Rendering Full Resolution Blur Pass (Requires Area Change)", ref fullResVolumeBlur))
                {
                    if (fullResVolumeBlur)
                    {
                        fullResVolumeBlurEnable();
                    }
                    else
                    {
                        fullResVolumeBlurDisable();
                    }
                    patches.FullResolutionVolumeBlur = fullResVolumeBlur;
                    config.Patches = patches;
                    saveConfig(config);
                }
                if (ImGui.BeginItemTooltip())
                {
                    ImGui.Text("This can get rid of excessive aliasing when something is in front of a volumetric effect.\nMove to a different area for this to apply. It will stay applied after that.");
                    ImGui.EndTooltip();
                }

                if (ImGui.Checkbox("Higher Than \"Highest\" Volume Rendering Quality", ref higherVolumeQuality))
                {
                    if (higherVolumeQuality)
                    {
                        value2ForVolumeQuality.Enable();
                    }
                    else
                    {
                        value2ForVolumeQuality.Disable();
                    }
                    patches.HigherThanHighestVolumeRendering = higherVolumeQuality;
                    config.Patches = patches;
                    saveConfig(config);
                }
                if (ImGui.BeginItemTooltip())
                {
                    ImGui.Text("*Extremely Resource Intensive* Only noticeable effect is likely in areas that had visible breakup with Volume Rendering Quality: Highest.\nThis takes mostly the same path as Highest.");
                    ImGui.EndTooltip();
                }

                if (ImGui.Checkbox("Disable Player/Palico/NPC LOD Limit in Gameplay", ref disableLODLimits))
                {
                    if (disableLODLimits)
                    {
                        disableLODLimitsEnable();
                    }
                    else
                    {
                        disableLODLimitsDisable();
                    }
                    patches.DisableLODLimits = disableLODLimits;
                    config.Patches = patches;
                    saveConfig(config);
                }
                if (ImGui.BeginItemTooltip())
                {
                    ImGui.Text("This will make the default (gameplay) LOD limits equivalent to View Mode. Disabling the limit on:\n - Player Models & Shadows\n - Palico Models & Shadows\n - NPC Models & Shadows\n - Simple NPC Models & Shadows\nAlso equivalent to the settings applied in your room with the addition of disabled Simple NPC limits.");
                    ImGui.EndTooltip();
                }

                if (ImGui.Checkbox("Larger Foliage Sway Range", ref largerFoliageSwayRange))
                {
                    if (largerFoliageSwayRange)
                    {
                        addressHigherValueForFoliageSway.Enable();
                    }
                    else
                    {
                        addressHigherValueForFoliageSway.Disable();
                    }
                    patches.LargerFoliageSwayRange = largerFoliageSwayRange;
                    config.Patches = patches;
                    saveConfig(config);
                }
                if (ImGui.BeginItemTooltip())
                {
                    ImGui.Text("Increase the distance at which Foliage Sway is still applied to lower priority plants.");
                    ImGui.EndTooltip();
                }

                if (ImGui.Checkbox("Disable Reduced Rate Animations", ref disableReducedRateAnimations))
                {
                    if (disableReducedRateAnimations)
                    {
                        zeroFrameSkip.Enable();
                    }
                    else
                    {
                        zeroFrameSkip.Disable();
                    }
                    patches.DisableReducedRateAnimations = disableReducedRateAnimations;
                    config.Patches = patches;
                    saveConfig(config);
                }
                if (ImGui.BeginItemTooltip())
                {
                    ImGui.Text("Ignore the frame skip set on an animal's animation when are far from the camera.");
                    ImGui.EndTooltip();
                }
            }

            if (ImGui.CollapsingHeader("Lights"))
            {
                lights.DrawUI(width);
            }

            bool expanded = ImGui.CollapsingHeader("Parameters");
            if (ImGui.BeginItemTooltip())
            {
                ImGui.Text("(Original: X) may be inaccurate for various reasons, such as\n 1. The game set the parameter to the same value as an override from this mod.\n 2. The game is dynamically updating the parameter in a location unknown to this mod.");
                ImGui.EndTooltip();
            }
            if (expanded)
            {
                hqMode.Draw(width);

                ImGui.PushID("LOD");
                if (ImGui.CollapsingHeader("Level of Detail"))
                {
                    ImGui.Text($"Address: 0x{sMhScene!.Instance:X}");
                    foreach (Parameter param in lodParameters)
                    {
                        param.Draw(width);
                    }
                    foreach (Parameter param in snowParameters)
                    {
                        param.Draw(width);
                    }
                }
                ImGui.PopID();

                // MonsterHunterWorld.exe+1AB99E0 - mov rax,[MonsterHunterWorld.exe+500E180]
                nint shadowAddr = MemoryUtil.Read<nint>(0x14500E180);
                nint shadowObject = MemoryUtil.Read<nint>(shadowAddr + 0x4B0);
                shadowAddr += 0x5B0;
                ImGui.PushID("Shadows");
                if (ImGui.CollapsingHeader("Sunlight and Shadows"))
                {
                    shadowResParameter.Draw(width);
                    ImGui.Separator();
                    ImGui.Text($"shadowAddr: 0x{shadowAddr:X}, shadowObject: 0x{shadowObject:X}");
                    /*
                    if (ImGui.CollapsingHeader("Pass 1"))
                    {
                        ImGui.PushID("Pass1");
                        foreach (Parameter param in shadowParameters1)
                        {
                            param.Draw(width);
                        }
                        ImGui.PopID();
                    }
                    if (ImGui.CollapsingHeader("Pass 2"))
                    {
                        ImGui.PushID("Pass2");
                    */
                        foreach (Parameter param in shadowParameters2)
                        {
                            param.Draw(width);
                        }
                    /*
                        ImGui.PopID();
                    }
                    */
                    ImGui.Separator();
                    ImGui.Text($"Address: 0x{sMhScene!.Instance:X}");
                    foreach (Parameter param in shadowCascadeParameters)
                    {
                        param.Draw(width);
                    }
                }
                ImGui.PopID();

                ImGui.PushID("BroadAreaShadows");
                if (ImGui.CollapsingHeader("Broad Area Shadows"))
                {
                    ImGui.Text($"Address: 0x{sMhScene!.Instance:X}");
                    foreach (Parameter param in broadAreaShadowParameters)
                    {
                        param.Draw(width);
                    }
                }
                ImGui.PopID();

                ImGui.PushID("LightProbes");
                if (ImGui.CollapsingHeader("Light Probes"))
                {
                    ImGui.Text($"Address: 0x{sLightProbes!.Instance:X}");
                    foreach (Parameter param in sLightProbesParameters)
                    {
                        param.Draw(width);
                    }
                }
                ImGui.PopID();

                ImGui.PushID("ContactLight");
                if (ImGui.CollapsingHeader("Contact Light"))
                {
                    ImGui.Text($"Address: 0x{sMhScene!.Instance:X}");
                    foreach (Parameter param in contactShadowParameters)
                    {
                        param.Draw(width);
                    }
                    foreach (Parameter param in capsuleLightParameters)
                    {
                        param.Draw(width);
                    }
                }
                ImGui.PopID();

                ImGui.PushID("SSAO");
                if (ImGui.CollapsingHeader("Ambient Occlusion"))
                {
                    ImGui.Text($"Address: 0x{sMhScene!.Instance:X}");
                    foreach (Parameter param in ssaoParameters)
                    {
                        param.Draw(width);
                    }
                }
                ImGui.PopID();

                ImGui.PushID("SSLR");
                if (ImGui.CollapsingHeader("Reflections"))
                {
                    ImGui.Text($"Address: 0x{sMhScene!.Instance:X}");
                    foreach (Parameter param in sslrParameters)
                    {
                        param.Draw(width);
                    }
                }
                ImGui.PopID();

                ImGui.PushID("Passthrough");
                if (ImGui.CollapsingHeader("Passthrough"))
                {
                    ImGui.Text($"Address: 0x{sMhScene!.Instance:X}");
                    foreach (Parameter param in passthroughParameters)
                    {
                        param.Draw(width);
                    }
                }
                ImGui.PopID();

                ImGui.PushID("Lighting");
                if (ImGui.CollapsingHeader("Lighting"))
                {
                    ImGui.Text($"Address: 0x{lightingObject:X}");
                    if (lightingObject != 0x0)
                    {
                        if (ImGui.CollapsingHeader("LUTs"))
                        {
                            nint lutBlendTexture = MemoryUtil.Read<nint>(lightingObject + 0x1C0);
                            ImGui.Text($"LUT Blend: 0x{lutBlendTexture:X}");
                            nint lutMap0 = MemoryUtil.Read<nint>(lightingObject + 0x1A8);
                            if (lutMap0 != 0x0)
                            {
                                luts.DrawUI(lutMap0, lightingObject, 0, width);
                            }
                            nint lutMap1 = MemoryUtil.Read<nint>(lightingObject + 0x1B0);
                            if (lutMap1 != 0x0)
                            {
                                luts.DrawUI(lutMap1, lightingObject, 1, width);
                            }
                        }
                        foreach (Parameter param in lightingParameters)
                        {
                            param.Draw(width);
                        }
                    }
                    ImGui.Separator();
                    ImGui.Text($"Address: 0x{sMhRender!.Instance:X}");
                    foreach (Parameter param in brightnessParameters)
                    {
                        param.Draw(width);
                    }
                }
                ImGui.PopID();

                ImGui.PushID("Bloom");
                if (ImGui.CollapsingHeader("Bloom"))
                {
                    ImGui.Text($"Address: 0x{bloomObject:X}");
                    if (bloomObject != 0x0)
                    {
                        foreach (Parameter param in bloomParameters)
                        {
                            param.Draw(width);
                        }
                    }
                }
                ImGui.PopID();

                ImGui.PushID("DepthOfField");
                if (ImGui.CollapsingHeader("Depth of Field"))
                {
                    ImGui.Text($"Address: 0x{dofObject:X}");
                    if (dofObject != 0x0)
                    {
                        foreach (Parameter param in dofParameters)
                        {
                            param.Draw(width);
                        }
                    }
                }
                ImGui.PopID();

                ImGui.PushID("MotionBlur");
                if (ImGui.CollapsingHeader("Motion Blur"))
                {
                    ImGui.Text($"Address: 0x{motionBlurObject:X}");
                    if (motionBlurObject != 0x0)
                    {
                        foreach (Parameter param in motionBlurParameters)
                        {
                            param.Draw(width);
                        }
                    }
                }
                ImGui.PopID();

                ImGui.PushID("Sky");
                if (ImGui.CollapsingHeader("Sky"))
                {
                    ImGui.Text($"Address: 0x{simpleSkyObject:X}");
                    if (simpleSkyObject != 0x0)
                    {
                        foreach (Parameter param in simpleSkyParameters)
                        {
                            param.Draw(width);
                        }
                    }
                }
                ImGui.PopID();

                ImGui.PushID("Fog");
                if (ImGui.CollapsingHeader("Fog"))
                {
                    ImGui.Text($"Address: 0x{fogObject:X}");
                    if (fogObject != 0x0)
                    {
                        foreach (Parameter param in fogParameters)
                        {
                            param.Draw(width);
                        }
                    }
                }
                ImGui.PopID();

                ImGui.PushID("WaterWave");
                if (ImGui.CollapsingHeader("Water Waves"))
                {
                    ImGui.Text($"Address: 0x{waterWaveObject:X}");
                    if (waterWaveObject != 0x0)
                    {
                        foreach (Parameter param in waterWaveParameters)
                        {
                            param.Draw(width);
                        }
                    }
                }
                ImGui.PopID();

                ImGui.PushID("FXAA");
                if (ImGui.CollapsingHeader("FXAA"))
                {
                    ImGui.Text($"Address: 0x{fxaaObject:X}");
                    if (fxaaObject != 0x0)
                    {
                        foreach (Parameter param in fxaaParameters)
                        {
                            param.Draw(width);
                        }
                    }
                }
                ImGui.PopID();

                ImGui.PushID("TAA");
                if (ImGui.CollapsingHeader("TAA"))
                {
                    ImGui.Text($"Address: 0x{taaObject:X}");
                    if (taaObject != 0x0)
                    {
                        foreach (Parameter param in taaParameters)
                        {
                            param.Draw(width);
                        }
                    }
                }
                ImGui.PopID();

                ImGui.Separator();
            }

            if (ImGui.CollapsingHeader("DEBUG"))
            {
                ImGui.Checkbox("Globally Ignore Parameter Min/Max", ref ignoreMinMax);
                if (ImGui.BeginItemTooltip())
                {
                    ImGui.Text("Some min/max values are set to avoid crashes, so be warned.");
                    ImGui.EndTooltip();
                }

                if (ImGui.CollapsingHeader("Tests"))
                {
                    if (ImGui.Checkbox("Skip Mip Mapping for SSLR", ref skipSSLRMipMapping))
                    {
                        if (skipSSLRMipMapping)
                        {
                            ssrRes3.Enable();
                        }
                        else
                        {
                            ssrRes3.Disable();
                        }
                    }

                    if (ImGui.Checkbox("Continous SSLR Temporal Reset", ref continousSSLRTemporalReset))
                    {
                        if (continousSSLRTemporalReset)
                        {
                            forceSSLRTemporalReset.Enable();
                        }
                        else
                        {
                            forceSSLRTemporalReset.Disable();
                        }
                    }
                    if (ImGui.BeginItemTooltip())
                    {
                        ImGui.Text("Don't reference tBlendMap in SSLR resolve.");
                        ImGui.EndTooltip();
                    }

                    lights.DrawDebug(width);

                    ImGui.Separator();
                }

                ImGui.PushItemWidth(width * 0.15f);
                ImGui.Text($"FPS: {MemoryUtil.GetRef<float>(sMhMain!.Instance + 0x68)}");
                ImGui.Text($"Delta Time: {MemoryUtil.GetRef<float>(sMhMain!.Instance + 0x94)}");
                // Locations taken from MHW-DTI-Dumps/wip_dump_15_20_00.h.
                ImGui.InputFloat("Simulation FPS", ref MemoryUtil.GetRef<float>(sMhMain!.Instance + 0x58));
                if (ImGui.BeginItemTooltip())
                {
                    ImGui.Text("This does not apply to jiggle physics.");
                    ImGui.EndTooltip();
                }
                ImGui.InputFloat("Max FPS", ref MemoryUtil.GetRef<float>(sMhMain!.Instance + 0x5C));
                ImGui.PopItemWidth();
            }
        }

#if SHADER_FEATURES
        private static bool replaceShaderFromFile(ShaderInfo *info, string path)
        {
            if (!System.IO.File.Exists(path))
            {
                Log.Warn($"File not found: {path}.");
                return false;
            }
            byte[] shaderData;
            try
            {
                shaderData = System.IO.File.ReadAllBytes(path);
            }
            catch (Exception)
            {
                Log.Error($"Failed to read: {path}.");
                return false;
            }
            info->Replacement.Length = shaderData.Length;
            info->Replacement.Source = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement<byte>(shaderData, 0);
            return true;
        }

        private const string shaderPath = "nativePC/plugins/CSharp/Shaders";
        private bool shadersLoadedOnce = false;
        public unsafe void OnCreateShader(ShaderInfo *info)
        {
            string hash = new string(info->DxbcHash);
            if (hash == "0c3dacbd-32c175d5-10d80d04-cce7e689")
            {
                if (replaceShaderFromFile(info, $"{shaderPath}/alpha_as_luma.hlsl"))
                {
                    info->Replacement.Type = ShaderSourceType.HLSL;
                    Log.Info("Alpha as luma shader replaced.");
                }
            }
            else if (hash == "9ff245fb-4fd555e0-04d0ef15-84609fe1")
            {
                if (replaceShaderFromFile(info, $"{shaderPath}/fxaa_max_quality.hlsl"))
                {
                    info->Replacement.Type = ShaderSourceType.HLSL;
                    Log.Info("FXAA shader replaced.");
                }
            }
            else if (!shadersLoadedOnce && hash == "2e4e18fd-6ea5eeae-2de3d65c-26ab36dd")
            {
                if (replaceShaderFromFile(info, $"{shaderPath}/volume_upsample1.shdr"))
                {
                    info->Replacement.Type = ShaderSourceType.Binary;
                    Log.Info("Volume upsample shader 1 replaced.");
                }
            }
            else if (!shadersLoadedOnce && hash == "e2c8c13e-45bc99b2-4c3d7699-3d66188e")
            {
                if (replaceShaderFromFile(info, $"{shaderPath}/volume_upsample2.shdr"))
                {
                    info->Replacement.Type = ShaderSourceType.Binary;
                    Log.Info("Volume upsample shader 2 replaced.");
                }
                // This allows us to A/B using the volume rendering value 2 switch.
                //shadersLoadedOnce = true;
            }
            /*
            else if (hash == "8cf2a107-ecde214b-9939b350-7b2af1a7")
            {
                if (replaceShaderFromFile(info, $"{shaderPath}/cube_only.shdr"))
                {
                    info->Replacement.Type = ShaderSourceType.Binary;
                    Log.Info("Cube Only shader replaced.");
                }
            }
            */
            else if (hash == "2eed1f00-e24d1b19-9d521064-17b9a586")
            {
                if (replaceShaderFromFile(info, $"{shaderPath}/body_skin.shdr"))
                {
                    info->Replacement.Type = ShaderSourceType.Binary;
                    Log.Info("Body skin shader replaced.");
                }
            }
            else if (hash == "8e5e3c09-ebe77ee4-ba1cb659-d25bc7bf")
            {
                if (replaceShaderFromFile(info, $"{shaderPath}/face.shdr"))
                {
                    info->Replacement.Type = ShaderSourceType.Binary;
                    Log.Info("Face shader replaced.");
                }
            }
            /*
            else if (hash == "18a797dc-9458d333-59e6dff0-9790fcea")
            {
                if (replaceShaderFromFile(info, $"{shaderPath}/sssss.shdr"))
                {
                    info->Replacement.Type = ShaderSourceType.Binary;
                    Log.Info("SSSSS shader replaced.");
                }
            }
            */
            /*
            else if (hash == "ca33bab6-2119df84-41786a69-404471cd")
            {
                if (replaceShaderFromFile(info, $"{shaderPath}/color_grading.shdr"))
                {
                    info->Replacement.Type = ShaderSourceType.Binary;
                    Log.Info("Color grading shader replaced.");
                }
            }
            */
            if (fullResSSLR)
            {
                if (hash == "4b722c0e-8e787cd5-5eaf5e6c-09782f91")
                {
                    if (replaceShaderFromFile(info, $"{shaderPath}/sslr_depth_mips.shdr"))
                    {
                        info->Replacement.Type = ShaderSourceType.Binary;
                        Log.Info("SSLR depth mips shader replaced.");
                    }
                }
                else if (hash == "5abc7a51-f182e7d6-14d2f897-6f851c0b")
                {
                    if (replaceShaderFromFile(info, $"{shaderPath}/sslr_trace.shdr"))
                    {
                        info->Replacement.Type = ShaderSourceType.Binary;
                        Log.Info("SSLR trace shader replaced.");
                    }
                }
                else if (hash == "d7e47ffe-82572c64-795c4698-341e5b91")
                {
                    if (replaceShaderFromFile(info, $"{shaderPath}/sslr_mips.shdr"))
                    {
                        info->Replacement.Type = ShaderSourceType.Binary;
                        Log.Info("SSLR mips shader replaced.");
                    }
                }
                else if (hash == "b21dd223-98ab56ae-918264e6-eb6e8ee4")
                {
                    if (replaceShaderFromFile(info, $"{shaderPath}/sslr_resolve.shdr"))
                    {
                        info->Replacement.Type = ShaderSourceType.Binary;
                        Log.Info("SSLR resolve shader replaced.");
                    }
                }
                else if (hash == "8703f55f-6c22fba7-1ef876f1-4767379e")
                {
                    if (replaceShaderFromFile(info, $"{shaderPath}/sslr_resolve_no_jitter.shdr"))
                    {
                        info->Replacement.Type = ShaderSourceType.Binary;
                        Log.Info("SSLR resolve no jitter shader replaced.");
                    }
                }
                else if (hash == "a9372f22-05154267-13f583e1-b08ffd75")
                {
                    if (replaceShaderFromFile(info, $"{shaderPath}/sslr_resolve_no_dither.shdr"))
                    {
                        info->Replacement.Type = ShaderSourceType.Binary;
                        Log.Info("SSLR resolve no dither shader replaced.");
                    }
                }
                else if (hash == "77e20ce4-0538a5f1-908ba0a3-55821b0f")
                {
                    if (replaceShaderFromFile(info, $"{shaderPath}/sslr_resolve_no_jitter_no_dither.shdr"))
                    {
                        info->Replacement.Type = ShaderSourceType.Binary;
                        Log.Info("SSLR resolve no jitter or dither shader replaced.");
                    }
                }
            }
            else
            {
                if (hash == "8703f55f-6c22fba7-1ef876f1-4767379e")
                {
                    if (replaceShaderFromFile(info, $"{shaderPath}/sslr_resolve_no_jitter_min_only.shdr"))
                    {
                        info->Replacement.Type = ShaderSourceType.Binary;
                        Log.Info("SSLR resolve no jitter shader replaced.");
                    }
                }
            }
        }
#endif
    }
}