proof-engine 0.2.3

Real-time graphics from math: glyphs and particles moved by ODEs, strange attractors and force fields, drawn with HDR bloom on OpenGL.
Documentation
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
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
#[allow(dead_code, unused_variables, unused_mut, unused_imports)]

use glam::{Vec2, Vec3, Vec4, Quat, Mat4};
use std::collections::{HashMap, VecDeque, HashSet, BTreeMap};

// ============================================================
// SECTION 1: TOKEN TYPES
// ============================================================

#[derive(Debug, Clone, PartialEq)]
pub enum TokenKind {
    // Literals
    IntLit(i64),
    FloatLit(f64),
    BoolLit(bool),
    StringLit(String),
    // Identifiers & keywords
    Ident(String),
    // Types
    KwFloat, KwInt, KwUint, KwBool,
    KwVec2, KwVec3, KwVec4,
    KwIVec2, KwIVec3, KwIVec4,
    KwUVec2, KwUVec3, KwUVec4,
    KwMat2, KwMat3, KwMat4,
    KwSampler2D, KwSampler3D, KwSamplerCube,
    KwVoid,
    // Keywords
    KwIf, KwElse, KwFor, KwWhile, KwDo, KwReturn, KwBreak, KwContinue,
    KwStruct, KwIn, KwOut, KwInout, KwUniform, KwConst, KwLayout,
    KwAttribute, KwVarying, KwPrecision, KwHighp, KwMediump, KwLowp,
    KwDiscard,
    // Operators
    Plus, Minus, Star, Slash, Percent,
    PlusEq, MinusEq, StarEq, SlashEq, PercentEq,
    PlusPlus, MinusMinus,
    Amp, Pipe, Caret, Tilde, LShift, RShift,
    AmpEq, PipeEq, CaretEq, LShiftEq, RShiftEq,
    Eq, EqEq, BangEq,
    Lt, Gt, LtEq, GtEq,
    AmpAmp, PipePipe, Bang,
    Question, Colon,
    Dot, Arrow,
    Semicolon, Comma,
    LParen, RParen,
    LBrace, RBrace,
    LBracket, RBracket,
    Hash,
    // Special
    Eof,
    Newline,
}

#[derive(Debug, Clone)]
pub struct Token {
    pub kind: TokenKind,
    pub line: u32,
    pub col: u32,
    pub source: String,
}

impl Token {
    pub fn new(kind: TokenKind, line: u32, col: u32, source: &str) -> Self {
        Self { kind, line, col, source: source.to_string() }
    }
    pub fn is_type_keyword(&self) -> bool {
        matches!(self.kind,
            TokenKind::KwFloat | TokenKind::KwInt | TokenKind::KwUint | TokenKind::KwBool |
            TokenKind::KwVec2 | TokenKind::KwVec3 | TokenKind::KwVec4 |
            TokenKind::KwMat2 | TokenKind::KwMat3 | TokenKind::KwMat4 |
            TokenKind::KwSampler2D | TokenKind::KwSampler3D | TokenKind::KwSamplerCube |
            TokenKind::KwVoid)
    }
}

// ============================================================
// SECTION 2: LEXER / TOKENIZER
// ============================================================

pub struct Lexer {
    pub source: Vec<char>,
    pub pos: usize,
    pub line: u32,
    pub col: u32,
}

impl Lexer {
    pub fn new(source: &str) -> Self {
        Self { source: source.chars().collect(), pos: 0, line: 1, col: 1 }
    }

    fn peek(&self) -> Option<char> { self.source.get(self.pos).copied() }
    fn peek2(&self) -> Option<char> { self.source.get(self.pos + 1).copied() }

    fn advance(&mut self) -> Option<char> {
        let c = self.source.get(self.pos).copied()?;
        self.pos += 1;
        if c == '\n' { self.line += 1; self.col = 1; } else { self.col += 1; }
        Some(c)
    }

    fn skip_whitespace(&mut self) {
        while let Some(c) = self.peek() {
            if c == ' ' || c == '\t' || c == '\r' { self.advance(); }
            else if c == '\n' { self.advance(); }
            else if c == '/' && self.peek2() == Some('/') {
                while let Some(c) = self.peek() { if c == '\n' { break; } self.advance(); }
            } else if c == '/' && self.peek2() == Some('*') {
                self.advance(); self.advance();
                loop {
                    match self.advance() {
                        None => break,
                        Some('*') if self.peek() == Some('/') => { self.advance(); break; }
                        _ => {}
                    }
                }
            } else { break; }
        }
    }

    fn read_ident(&mut self) -> String {
        let mut s = String::new();
        while let Some(c) = self.peek() {
            if c.is_alphanumeric() || c == '_' { s.push(c); self.advance(); } else { break; }
        }
        s
    }

    fn read_number(&mut self) -> TokenKind {
        let mut s = String::new();
        let mut is_float = false;
        while let Some(c) = self.peek() {
            if c.is_ascii_digit() { s.push(c); self.advance(); }
            else if c == '.' && !is_float {
                is_float = true; s.push(c); self.advance();
            } else if (c == 'e' || c == 'E') && is_float {
                s.push(c); self.advance();
                if let Some('+') | Some('-') = self.peek() {
                    s.push(self.advance().unwrap());
                }
            } else if c == 'f' || c == 'u' { self.advance(); break; }
            else { break; }
        }
        if is_float {
            TokenKind::FloatLit(s.parse().unwrap_or(0.0))
        } else {
            if s.starts_with("0x") || s.starts_with("0X") {
                TokenKind::IntLit(i64::from_str_radix(&s[2..], 16).unwrap_or(0))
            } else {
                TokenKind::IntLit(s.parse().unwrap_or(0))
            }
        }
    }

    fn ident_to_keyword(s: &str) -> TokenKind {
        match s {
            "float" => TokenKind::KwFloat,
            "int" => TokenKind::KwInt,
            "uint" => TokenKind::KwUint,
            "bool" => TokenKind::KwBool,
            "vec2" => TokenKind::KwVec2,
            "vec3" => TokenKind::KwVec3,
            "vec4" => TokenKind::KwVec4,
            "ivec2" => TokenKind::KwIVec2,
            "ivec3" => TokenKind::KwIVec3,
            "ivec4" => TokenKind::KwIVec4,
            "uvec2" => TokenKind::KwUVec2,
            "uvec3" => TokenKind::KwUVec3,
            "uvec4" => TokenKind::KwUVec4,
            "mat2" => TokenKind::KwMat2,
            "mat3" => TokenKind::KwMat3,
            "mat4" => TokenKind::KwMat4,
            "sampler2D" => TokenKind::KwSampler2D,
            "sampler3D" => TokenKind::KwSampler3D,
            "samplerCube" => TokenKind::KwSamplerCube,
            "void" => TokenKind::KwVoid,
            "if" => TokenKind::KwIf,
            "else" => TokenKind::KwElse,
            "for" => TokenKind::KwFor,
            "while" => TokenKind::KwWhile,
            "do" => TokenKind::KwDo,
            "return" => TokenKind::KwReturn,
            "break" => TokenKind::KwBreak,
            "continue" => TokenKind::KwContinue,
            "struct" => TokenKind::KwStruct,
            "in" => TokenKind::KwIn,
            "out" => TokenKind::KwOut,
            "inout" => TokenKind::KwInout,
            "uniform" => TokenKind::KwUniform,
            "const" => TokenKind::KwConst,
            "layout" => TokenKind::KwLayout,
            "attribute" => TokenKind::KwAttribute,
            "varying" => TokenKind::KwVarying,
            "precision" => TokenKind::KwPrecision,
            "highp" => TokenKind::KwHighp,
            "mediump" => TokenKind::KwMediump,
            "lowp" => TokenKind::KwLowp,
            "discard" => TokenKind::KwDiscard,
            "true" => TokenKind::BoolLit(true),
            "false" => TokenKind::BoolLit(false),
            other => TokenKind::Ident(other.to_string()),
        }
    }

    pub fn tokenize(&mut self) -> Vec<Token> {
        let mut tokens = Vec::new();
        loop {
            self.skip_whitespace();
            let line = self.line;
            let col = self.col;
            match self.peek() {
                None => { tokens.push(Token::new(TokenKind::Eof, line, col, "")); break; }
                Some(c) => {
                    let tok = match c {
                        'a'..='z' | 'A'..='Z' | '_' => {
                            let s = self.read_ident();
                            let kind = Self::ident_to_keyword(&s);
                            Token::new(kind, line, col, &s)
                        }
                        '0'..='9' => {
                            let kind = self.read_number();
                            Token::new(kind, line, col, "")
                        }
                        '+' => {
                            self.advance();
                            if self.peek() == Some('+') { self.advance(); Token::new(TokenKind::PlusPlus, line, col, "++") }
                            else if self.peek() == Some('=') { self.advance(); Token::new(TokenKind::PlusEq, line, col, "+=") }
                            else { Token::new(TokenKind::Plus, line, col, "+") }
                        }
                        '-' => {
                            self.advance();
                            if self.peek() == Some('-') { self.advance(); Token::new(TokenKind::MinusMinus, line, col, "--") }
                            else if self.peek() == Some('=') { self.advance(); Token::new(TokenKind::MinusEq, line, col, "-=") }
                            else if self.peek() == Some('>') { self.advance(); Token::new(TokenKind::Arrow, line, col, "->") }
                            else { Token::new(TokenKind::Minus, line, col, "-") }
                        }
                        '*' => {
                            self.advance();
                            if self.peek() == Some('=') { self.advance(); Token::new(TokenKind::StarEq, line, col, "*=") }
                            else { Token::new(TokenKind::Star, line, col, "*") }
                        }
                        '/' => {
                            self.advance();
                            if self.peek() == Some('=') { self.advance(); Token::new(TokenKind::SlashEq, line, col, "/=") }
                            else { Token::new(TokenKind::Slash, line, col, "/") }
                        }
                        '%' => {
                            self.advance();
                            if self.peek() == Some('=') { self.advance(); Token::new(TokenKind::PercentEq, line, col, "%=") }
                            else { Token::new(TokenKind::Percent, line, col, "%") }
                        }
                        '=' => {
                            self.advance();
                            if self.peek() == Some('=') { self.advance(); Token::new(TokenKind::EqEq, line, col, "==") }
                            else { Token::new(TokenKind::Eq, line, col, "=") }
                        }
                        '!' => {
                            self.advance();
                            if self.peek() == Some('=') { self.advance(); Token::new(TokenKind::BangEq, line, col, "!=") }
                            else { Token::new(TokenKind::Bang, line, col, "!") }
                        }
                        '<' => {
                            self.advance();
                            if self.peek() == Some('=') { self.advance(); Token::new(TokenKind::LtEq, line, col, "<=") }
                            else if self.peek() == Some('<') {
                                self.advance();
                                if self.peek() == Some('=') { self.advance(); Token::new(TokenKind::LShiftEq, line, col, "<<=") }
                                else { Token::new(TokenKind::LShift, line, col, "<<") }
                            }
                            else { Token::new(TokenKind::Lt, line, col, "<") }
                        }
                        '>' => {
                            self.advance();
                            if self.peek() == Some('=') { self.advance(); Token::new(TokenKind::GtEq, line, col, ">=") }
                            else if self.peek() == Some('>') {
                                self.advance();
                                if self.peek() == Some('=') { self.advance(); Token::new(TokenKind::RShiftEq, line, col, ">>=") }
                                else { Token::new(TokenKind::RShift, line, col, ">>") }
                            }
                            else { Token::new(TokenKind::Gt, line, col, ">") }
                        }
                        '&' => {
                            self.advance();
                            if self.peek() == Some('&') { self.advance(); Token::new(TokenKind::AmpAmp, line, col, "&&") }
                            else if self.peek() == Some('=') { self.advance(); Token::new(TokenKind::AmpEq, line, col, "&=") }
                            else { Token::new(TokenKind::Amp, line, col, "&") }
                        }
                        '|' => {
                            self.advance();
                            if self.peek() == Some('|') { self.advance(); Token::new(TokenKind::PipePipe, line, col, "||") }
                            else if self.peek() == Some('=') { self.advance(); Token::new(TokenKind::PipeEq, line, col, "|=") }
                            else { Token::new(TokenKind::Pipe, line, col, "|") }
                        }
                        '^' => {
                            self.advance();
                            if self.peek() == Some('=') { self.advance(); Token::new(TokenKind::CaretEq, line, col, "^=") }
                            else { Token::new(TokenKind::Caret, line, col, "^") }
                        }
                        '~' => { self.advance(); Token::new(TokenKind::Tilde, line, col, "~") }
                        '?' => { self.advance(); Token::new(TokenKind::Question, line, col, "?") }
                        ':' => { self.advance(); Token::new(TokenKind::Colon, line, col, ":") }
                        '.' => { self.advance(); Token::new(TokenKind::Dot, line, col, ".") }
                        ';' => { self.advance(); Token::new(TokenKind::Semicolon, line, col, ";") }
                        ',' => { self.advance(); Token::new(TokenKind::Comma, line, col, ",") }
                        '(' => { self.advance(); Token::new(TokenKind::LParen, line, col, "(") }
                        ')' => { self.advance(); Token::new(TokenKind::RParen, line, col, ")") }
                        '{' => { self.advance(); Token::new(TokenKind::LBrace, line, col, "{") }
                        '}' => { self.advance(); Token::new(TokenKind::RBrace, line, col, "}") }
                        '[' => { self.advance(); Token::new(TokenKind::LBracket, line, col, "[") }
                        ']' => { self.advance(); Token::new(TokenKind::RBracket, line, col, "]") }
                        '#' => { self.advance(); Token::new(TokenKind::Hash, line, col, "#") }
                        _ => { self.advance(); continue; }
                    };
                    tokens.push(tok);
                }
            }
        }
        tokens
    }
}

// ============================================================
// SECTION 3: TYPE SYSTEM
// ============================================================

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ShaderType {
    Void,
    Bool,
    Int,
    Uint,
    Float,
    BVec2, BVec3, BVec4,
    IVec2, IVec3, IVec4,
    UVec2, UVec3, UVec4,
    Vec2, Vec3, Vec4,
    Mat2, Mat3, Mat4,
    Sampler2D, Sampler3D, SamplerCube,
    Struct(String),
    Array(Box<ShaderType>, Option<u32>), // type, optional size
    Function(Vec<ShaderType>, Box<ShaderType>), // params, return
    Unknown,
}

impl ShaderType {
    pub fn is_scalar(&self) -> bool {
        matches!(self, ShaderType::Bool | ShaderType::Int | ShaderType::Uint | ShaderType::Float)
    }
    pub fn is_vector(&self) -> bool {
        matches!(self,
            ShaderType::BVec2|ShaderType::BVec3|ShaderType::BVec4|
            ShaderType::IVec2|ShaderType::IVec3|ShaderType::IVec4|
            ShaderType::UVec2|ShaderType::UVec3|ShaderType::UVec4|
            ShaderType::Vec2|ShaderType::Vec3|ShaderType::Vec4)
    }
    pub fn is_matrix(&self) -> bool {
        matches!(self, ShaderType::Mat2|ShaderType::Mat3|ShaderType::Mat4)
    }
    pub fn is_numeric(&self) -> bool {
        matches!(self,
            ShaderType::Int|ShaderType::Uint|ShaderType::Float|
            ShaderType::IVec2|ShaderType::IVec3|ShaderType::IVec4|
            ShaderType::UVec2|ShaderType::UVec3|ShaderType::UVec4|
            ShaderType::Vec2|ShaderType::Vec3|ShaderType::Vec4|
            ShaderType::Mat2|ShaderType::Mat3|ShaderType::Mat4)
    }
    pub fn component_count(&self) -> u32 {
        match self {
            ShaderType::Float|ShaderType::Int|ShaderType::Uint|ShaderType::Bool => 1,
            ShaderType::Vec2|ShaderType::IVec2|ShaderType::UVec2|ShaderType::BVec2 => 2,
            ShaderType::Vec3|ShaderType::IVec3|ShaderType::UVec3|ShaderType::BVec3 => 3,
            ShaderType::Vec4|ShaderType::IVec4|ShaderType::UVec4|ShaderType::BVec4 => 4,
            ShaderType::Mat2 => 4,
            ShaderType::Mat3 => 9,
            ShaderType::Mat4 => 16,
            _ => 0,
        }
    }
    pub fn base_scalar(&self) -> ShaderType {
        match self {
            ShaderType::Vec2|ShaderType::Vec3|ShaderType::Vec4 => ShaderType::Float,
            ShaderType::IVec2|ShaderType::IVec3|ShaderType::IVec4 => ShaderType::Int,
            ShaderType::UVec2|ShaderType::UVec3|ShaderType::UVec4 => ShaderType::Uint,
            ShaderType::BVec2|ShaderType::BVec3|ShaderType::BVec4 => ShaderType::Bool,
            ShaderType::Mat2|ShaderType::Mat3|ShaderType::Mat4 => ShaderType::Float,
            other => other.clone(),
        }
    }
    pub fn name(&self) -> &str {
        match self {
            ShaderType::Void => "void",
            ShaderType::Bool => "bool",
            ShaderType::Int => "int",
            ShaderType::Uint => "uint",
            ShaderType::Float => "float",
            ShaderType::BVec2 => "bvec2",
            ShaderType::BVec3 => "bvec3",
            ShaderType::BVec4 => "bvec4",
            ShaderType::IVec2 => "ivec2",
            ShaderType::IVec3 => "ivec3",
            ShaderType::IVec4 => "ivec4",
            ShaderType::UVec2 => "uvec2",
            ShaderType::UVec3 => "uvec3",
            ShaderType::UVec4 => "uvec4",
            ShaderType::Vec2 => "vec2",
            ShaderType::Vec3 => "vec3",
            ShaderType::Vec4 => "vec4",
            ShaderType::Mat2 => "mat2",
            ShaderType::Mat3 => "mat3",
            ShaderType::Mat4 => "mat4",
            ShaderType::Sampler2D => "sampler2D",
            ShaderType::Sampler3D => "sampler3D",
            ShaderType::SamplerCube => "samplerCube",
            ShaderType::Struct(n) => n.as_str(),
            ShaderType::Array(_, _) => "array",
            ShaderType::Function(_, _) => "function",
            ShaderType::Unknown => "unknown",
        }
    }
    /// Can we implicitly convert `from` to `self`?
    pub fn can_implicit_convert(from: &ShaderType, to: &ShaderType) -> bool {
        if from == to { return true; }
        matches!((from, to),
            (ShaderType::Int, ShaderType::Float) |
            (ShaderType::Uint, ShaderType::Float) |
            (ShaderType::Int, ShaderType::Uint) |
            (ShaderType::Bool, ShaderType::Int) |
            (ShaderType::Bool, ShaderType::Float) |
            (ShaderType::IVec2, ShaderType::Vec2) |
            (ShaderType::IVec3, ShaderType::Vec3) |
            (ShaderType::IVec4, ShaderType::Vec4)
        )
    }
    pub fn from_token(t: &TokenKind) -> Option<ShaderType> {
        match t {
            TokenKind::KwFloat => Some(ShaderType::Float),
            TokenKind::KwInt => Some(ShaderType::Int),
            TokenKind::KwUint => Some(ShaderType::Uint),
            TokenKind::KwBool => Some(ShaderType::Bool),
            TokenKind::KwVec2 => Some(ShaderType::Vec2),
            TokenKind::KwVec3 => Some(ShaderType::Vec3),
            TokenKind::KwVec4 => Some(ShaderType::Vec4),
            TokenKind::KwIVec2 => Some(ShaderType::IVec2),
            TokenKind::KwIVec3 => Some(ShaderType::IVec3),
            TokenKind::KwIVec4 => Some(ShaderType::IVec4),
            TokenKind::KwUVec2 => Some(ShaderType::UVec2),
            TokenKind::KwUVec3 => Some(ShaderType::UVec3),
            TokenKind::KwUVec4 => Some(ShaderType::UVec4),
            TokenKind::KwMat2 => Some(ShaderType::Mat2),
            TokenKind::KwMat3 => Some(ShaderType::Mat3),
            TokenKind::KwMat4 => Some(ShaderType::Mat4),
            TokenKind::KwSampler2D => Some(ShaderType::Sampler2D),
            TokenKind::KwSampler3D => Some(ShaderType::Sampler3D),
            TokenKind::KwSamplerCube => Some(ShaderType::SamplerCube),
            TokenKind::KwVoid => Some(ShaderType::Void),
            _ => None,
        }
    }
}

// ============================================================
// SECTION 4: AST NODES
// ============================================================

#[derive(Debug, Clone)]
pub enum Expr {
    IntLit(i64),
    FloatLit(f64),
    BoolLit(bool),
    Ident(String),
    Unary { op: UnaryOp, operand: Box<Expr> },
    Binary { op: BinaryOp, left: Box<Expr>, right: Box<Expr> },
    Assign { op: AssignOp, target: Box<Expr>, value: Box<Expr> },
    Ternary { cond: Box<Expr>, then_expr: Box<Expr>, else_expr: Box<Expr> },
    Call { function: String, args: Vec<Expr> },
    Index { array: Box<Expr>, index: Box<Expr> },
    Field { object: Box<Expr>, field: String },
    Swizzle { object: Box<Expr>, components: String },
    Cast { target_type: ShaderType, expr: Box<Expr> },
    Construction { ty: ShaderType, args: Vec<Expr> },
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum UnaryOp {
    Negate,
    Not,
    BitNot,
    PreIncrement,
    PreDecrement,
    PostIncrement,
    PostDecrement,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BinaryOp {
    Add, Sub, Mul, Div, Mod,
    Eq, Ne, Lt, Gt, Le, Ge,
    And, Or,
    BitAnd, BitOr, BitXor, Shl, Shr,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AssignOp {
    Assign, AddAssign, SubAssign, MulAssign, DivAssign, ModAssign,
    AndAssign, OrAssign, XorAssign, ShlAssign, ShrAssign,
}

#[derive(Debug, Clone)]
pub enum Stmt {
    Expr(Expr),
    Block(Vec<Stmt>),
    VarDecl { ty: ShaderType, name: String, qualifier: Option<VarQualifier>, init: Option<Expr> },
    If { cond: Expr, then_body: Box<Stmt>, else_body: Option<Box<Stmt>> },
    For { init: Option<Box<Stmt>>, cond: Option<Expr>, step: Option<Expr>, body: Box<Stmt> },
    While { cond: Expr, body: Box<Stmt> },
    DoWhile { body: Box<Stmt>, cond: Expr },
    Return(Option<Expr>),
    Break,
    Continue,
    Discard,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VarQualifier {
    In, Out, Inout, Uniform, Const, Attribute, Varying,
}

#[derive(Debug, Clone)]
pub struct FunctionParam {
    pub ty: ShaderType,
    pub name: String,
    pub qualifier: Option<VarQualifier>,
}

#[derive(Debug, Clone)]
pub struct FunctionDecl {
    pub return_type: ShaderType,
    pub name: String,
    pub params: Vec<FunctionParam>,
    pub body: Vec<Stmt>,
    pub is_builtin: bool,
}

#[derive(Debug, Clone)]
pub struct StructField {
    pub ty: ShaderType,
    pub name: String,
    pub array_size: Option<u32>,
}

#[derive(Debug, Clone)]
pub struct StructDecl {
    pub name: String,
    pub fields: Vec<StructField>,
}

#[derive(Debug, Clone)]
pub struct UniformDecl {
    pub ty: ShaderType,
    pub name: String,
    pub binding: Option<u32>,
    pub set: Option<u32>,
    pub array_size: Option<u32>,
}

#[derive(Debug, Clone)]
pub struct AttributeDecl {
    pub ty: ShaderType,
    pub name: String,
    pub location: Option<u32>,
}

#[derive(Debug, Clone)]
pub struct ShaderAst {
    pub version: u32,
    pub extensions: Vec<String>,
    pub structs: Vec<StructDecl>,
    pub uniforms: Vec<UniformDecl>,
    pub attributes: Vec<AttributeDecl>,
    pub varyings: Vec<AttributeDecl>,
    pub functions: Vec<FunctionDecl>,
    pub global_vars: Vec<Stmt>,
    pub defines: HashMap<String, String>,
}

impl ShaderAst {
    pub fn new() -> Self {
        Self {
            version: 450,
            extensions: Vec::new(),
            structs: Vec::new(),
            uniforms: Vec::new(),
            attributes: Vec::new(),
            varyings: Vec::new(),
            functions: Vec::new(),
            global_vars: Vec::new(),
            defines: HashMap::new(),
        }
    }
    pub fn find_function(&self, name: &str) -> Option<&FunctionDecl> {
        self.functions.iter().find(|f| f.name == name)
    }
    pub fn find_uniform(&self, name: &str) -> Option<&UniformDecl> {
        self.uniforms.iter().find(|u| u.name == name)
    }
}

// ============================================================
// SECTION 5: PARSER
// ============================================================

pub struct Parser {
    pub tokens: Vec<Token>,
    pub pos: usize,
    pub errors: Vec<ParseError>,
}

#[derive(Debug, Clone)]
pub struct ParseError {
    pub message: String,
    pub line: u32,
    pub col: u32,
}

impl Parser {
    pub fn new(tokens: Vec<Token>) -> Self {
        Self { tokens, pos: 0, errors: Vec::new() }
    }
    fn peek(&self) -> &Token { &self.tokens[self.pos.min(self.tokens.len()-1)] }
    fn peek2(&self) -> &Token { &self.tokens[(self.pos+1).min(self.tokens.len()-1)] }
    fn advance(&mut self) -> &Token {
        let t = &self.tokens[self.pos.min(self.tokens.len()-1)];
        if self.pos < self.tokens.len()-1 { self.pos += 1; }
        t
    }
    fn expect(&mut self, kind: &TokenKind) -> bool {
        if &self.peek().kind == kind { self.advance(); true }
        else {
            let tok = self.peek().clone();
            self.errors.push(ParseError {
                message: format!("Expected {:?}, got {:?}", kind, tok.kind),
                line: tok.line, col: tok.col,
            });
            false
        }
    }
    fn at_eof(&self) -> bool { matches!(self.peek().kind, TokenKind::Eof) }

    fn parse_type(&mut self) -> ShaderType {
        let tok = self.peek().kind.clone();
        if let Some(ty) = ShaderType::from_token(&tok) {
            self.advance();
            return ty;
        }
        if let TokenKind::Ident(name) = &tok {
            let name = name.clone();
            self.advance();
            return ShaderType::Struct(name);
        }
        ShaderType::Unknown
    }

    fn parse_expr_primary(&mut self) -> Expr {
        match self.peek().kind.clone() {
            TokenKind::IntLit(v) => { self.advance(); Expr::IntLit(v) }
            TokenKind::FloatLit(v) => { self.advance(); Expr::FloatLit(v) }
            TokenKind::BoolLit(v) => { self.advance(); Expr::BoolLit(v) }
            TokenKind::Ident(name) => {
                self.advance();
                if self.peek().kind == TokenKind::LParen {
                    // function call
                    self.advance();
                    let mut args = Vec::new();
                    while self.peek().kind != TokenKind::RParen && !self.at_eof() {
                        args.push(self.parse_expr());
                        if self.peek().kind == TokenKind::Comma { self.advance(); }
                        else { break; }
                    }
                    self.expect(&TokenKind::RParen);
                    Expr::Call { function: name, args }
                } else {
                    Expr::Ident(name)
                }
            }
            TokenKind::LParen => {
                self.advance();
                let e = self.parse_expr();
                self.expect(&TokenKind::RParen);
                e
            }
            tok if ShaderType::from_token(&tok).is_some() => {
                let ty = self.parse_type();
                self.expect(&TokenKind::LParen);
                let mut args = Vec::new();
                while self.peek().kind != TokenKind::RParen && !self.at_eof() {
                    args.push(self.parse_expr());
                    if self.peek().kind == TokenKind::Comma { self.advance(); }
                    else { break; }
                }
                self.expect(&TokenKind::RParen);
                Expr::Construction { ty, args }
            }
            _ => {
                let tok = self.peek().clone();
                self.errors.push(ParseError { message: format!("Unexpected token {:?}", tok.kind), line: tok.line, col: tok.col });
                self.advance();
                Expr::IntLit(0)
            }
        }
    }

    fn parse_expr_postfix(&mut self) -> Expr {
        let mut e = self.parse_expr_primary();
        loop {
            match self.peek().kind.clone() {
                TokenKind::Dot => {
                    self.advance();
                    if let TokenKind::Ident(field) = self.peek().kind.clone() {
                        self.advance();
                        e = Expr::Field { object: Box::new(e), field };
                    }
                }
                TokenKind::LBracket => {
                    self.advance();
                    let idx = self.parse_expr();
                    self.expect(&TokenKind::RBracket);
                    e = Expr::Index { array: Box::new(e), index: Box::new(idx) };
                }
                TokenKind::PlusPlus => { self.advance(); e = Expr::Unary { op: UnaryOp::PostIncrement, operand: Box::new(e) }; }
                TokenKind::MinusMinus => { self.advance(); e = Expr::Unary { op: UnaryOp::PostDecrement, operand: Box::new(e) }; }
                _ => break,
            }
        }
        e
    }

    fn parse_expr_unary(&mut self) -> Expr {
        match self.peek().kind {
            TokenKind::Minus => { self.advance(); Expr::Unary { op: UnaryOp::Negate, operand: Box::new(self.parse_expr_unary()) } }
            TokenKind::Bang => { self.advance(); Expr::Unary { op: UnaryOp::Not, operand: Box::new(self.parse_expr_unary()) } }
            TokenKind::Tilde => { self.advance(); Expr::Unary { op: UnaryOp::BitNot, operand: Box::new(self.parse_expr_unary()) } }
            TokenKind::PlusPlus => { self.advance(); Expr::Unary { op: UnaryOp::PreIncrement, operand: Box::new(self.parse_expr_unary()) } }
            TokenKind::MinusMinus => { self.advance(); Expr::Unary { op: UnaryOp::PreDecrement, operand: Box::new(self.parse_expr_unary()) } }
            _ => self.parse_expr_postfix(),
        }
    }

    fn parse_expr_mul(&mut self) -> Expr {
        let mut left = self.parse_expr_unary();
        loop {
            let op = match self.peek().kind {
                TokenKind::Star => BinaryOp::Mul,
                TokenKind::Slash => BinaryOp::Div,
                TokenKind::Percent => BinaryOp::Mod,
                _ => break,
            };
            self.advance();
            let right = self.parse_expr_unary();
            left = Expr::Binary { op, left: Box::new(left), right: Box::new(right) };
        }
        left
    }

    fn parse_expr_add(&mut self) -> Expr {
        let mut left = self.parse_expr_mul();
        loop {
            let op = match self.peek().kind {
                TokenKind::Plus => BinaryOp::Add,
                TokenKind::Minus => BinaryOp::Sub,
                _ => break,
            };
            self.advance();
            let right = self.parse_expr_mul();
            left = Expr::Binary { op, left: Box::new(left), right: Box::new(right) };
        }
        left
    }

    fn parse_expr_shift(&mut self) -> Expr {
        let mut left = self.parse_expr_add();
        loop {
            let op = match self.peek().kind {
                TokenKind::LShift => BinaryOp::Shl,
                TokenKind::RShift => BinaryOp::Shr,
                _ => break,
            };
            self.advance();
            let right = self.parse_expr_add();
            left = Expr::Binary { op, left: Box::new(left), right: Box::new(right) };
        }
        left
    }

    fn parse_expr_compare(&mut self) -> Expr {
        let mut left = self.parse_expr_shift();
        loop {
            let op = match self.peek().kind {
                TokenKind::Lt => BinaryOp::Lt,
                TokenKind::Gt => BinaryOp::Gt,
                TokenKind::LtEq => BinaryOp::Le,
                TokenKind::GtEq => BinaryOp::Ge,
                _ => break,
            };
            self.advance();
            let right = self.parse_expr_shift();
            left = Expr::Binary { op, left: Box::new(left), right: Box::new(right) };
        }
        left
    }

    fn parse_expr_equality(&mut self) -> Expr {
        let mut left = self.parse_expr_compare();
        loop {
            let op = match self.peek().kind {
                TokenKind::EqEq => BinaryOp::Eq,
                TokenKind::BangEq => BinaryOp::Ne,
                _ => break,
            };
            self.advance();
            let right = self.parse_expr_compare();
            left = Expr::Binary { op, left: Box::new(left), right: Box::new(right) };
        }
        left
    }

    fn parse_expr_bitand(&mut self) -> Expr {
        let mut left = self.parse_expr_equality();
        while self.peek().kind == TokenKind::Amp {
            self.advance();
            let right = self.parse_expr_equality();
            left = Expr::Binary { op: BinaryOp::BitAnd, left: Box::new(left), right: Box::new(right) };
        }
        left
    }

    fn parse_expr_bitor(&mut self) -> Expr {
        let mut left = self.parse_expr_bitand();
        while self.peek().kind == TokenKind::Pipe {
            self.advance();
            let right = self.parse_expr_bitand();
            left = Expr::Binary { op: BinaryOp::BitOr, left: Box::new(left), right: Box::new(right) };
        }
        left
    }

    fn parse_expr_and(&mut self) -> Expr {
        let mut left = self.parse_expr_bitor();
        while self.peek().kind == TokenKind::AmpAmp {
            self.advance();
            let right = self.parse_expr_bitor();
            left = Expr::Binary { op: BinaryOp::And, left: Box::new(left), right: Box::new(right) };
        }
        left
    }

    fn parse_expr_or(&mut self) -> Expr {
        let mut left = self.parse_expr_and();
        while self.peek().kind == TokenKind::PipePipe {
            self.advance();
            let right = self.parse_expr_and();
            left = Expr::Binary { op: BinaryOp::Or, left: Box::new(left), right: Box::new(right) };
        }
        left
    }

    fn parse_expr_ternary(&mut self) -> Expr {
        let cond = self.parse_expr_or();
        if self.peek().kind == TokenKind::Question {
            self.advance();
            let then_expr = self.parse_expr();
            self.expect(&TokenKind::Colon);
            let else_expr = self.parse_expr_ternary();
            Expr::Ternary { cond: Box::new(cond), then_expr: Box::new(then_expr), else_expr: Box::new(else_expr) }
        } else { cond }
    }

    fn parse_expr_assign(&mut self) -> Expr {
        let left = self.parse_expr_ternary();
        let op = match self.peek().kind {
            TokenKind::Eq => AssignOp::Assign,
            TokenKind::PlusEq => AssignOp::AddAssign,
            TokenKind::MinusEq => AssignOp::SubAssign,
            TokenKind::StarEq => AssignOp::MulAssign,
            TokenKind::SlashEq => AssignOp::DivAssign,
            TokenKind::PercentEq => AssignOp::ModAssign,
            TokenKind::AmpEq => AssignOp::AndAssign,
            TokenKind::PipeEq => AssignOp::OrAssign,
            TokenKind::CaretEq => AssignOp::XorAssign,
            TokenKind::LShiftEq => AssignOp::ShlAssign,
            TokenKind::RShiftEq => AssignOp::ShrAssign,
            _ => return left,
        };
        self.advance();
        let value = self.parse_expr_assign();
        Expr::Assign { op, target: Box::new(left), value: Box::new(value) }
    }

    pub fn parse_expr(&mut self) -> Expr { self.parse_expr_assign() }

    fn parse_stmt(&mut self) -> Option<Stmt> {
        match self.peek().kind.clone() {
            TokenKind::LBrace => {
                self.advance();
                let mut stmts = Vec::new();
                while self.peek().kind != TokenKind::RBrace && !self.at_eof() {
                    if let Some(s) = self.parse_stmt() { stmts.push(s); }
                }
                self.expect(&TokenKind::RBrace);
                Some(Stmt::Block(stmts))
            }
            TokenKind::KwIf => {
                self.advance();
                self.expect(&TokenKind::LParen);
                let cond = self.parse_expr();
                self.expect(&TokenKind::RParen);
                let then_body = Box::new(self.parse_stmt()?);
                let else_body = if self.peek().kind == TokenKind::KwElse {
                    self.advance();
                    Some(Box::new(self.parse_stmt()?))
                } else { None };
                Some(Stmt::If { cond, then_body, else_body })
            }
            TokenKind::KwFor => {
                self.advance();
                self.expect(&TokenKind::LParen);
                let init = if self.peek().kind != TokenKind::Semicolon {
                    self.parse_stmt().map(Box::new)
                } else { self.advance(); None };
                let cond = if self.peek().kind != TokenKind::Semicolon {
                    Some(self.parse_expr())
                } else { None };
                self.expect(&TokenKind::Semicolon);
                let step = if self.peek().kind != TokenKind::RParen {
                    Some(self.parse_expr())
                } else { None };
                self.expect(&TokenKind::RParen);
                let body = Box::new(self.parse_stmt()?);
                Some(Stmt::For { init, cond, step, body })
            }
            TokenKind::KwWhile => {
                self.advance();
                self.expect(&TokenKind::LParen);
                let cond = self.parse_expr();
                self.expect(&TokenKind::RParen);
                let body = Box::new(self.parse_stmt()?);
                Some(Stmt::While { cond, body })
            }
            TokenKind::KwDo => {
                self.advance();
                let body = Box::new(self.parse_stmt()?);
                self.expect(&TokenKind::KwWhile);
                self.expect(&TokenKind::LParen);
                let cond = self.parse_expr();
                self.expect(&TokenKind::RParen);
                self.expect(&TokenKind::Semicolon);
                Some(Stmt::DoWhile { body, cond })
            }
            TokenKind::KwReturn => {
                self.advance();
                let val = if self.peek().kind != TokenKind::Semicolon {
                    Some(self.parse_expr())
                } else { None };
                self.expect(&TokenKind::Semicolon);
                Some(Stmt::Return(val))
            }
            TokenKind::KwBreak => { self.advance(); self.expect(&TokenKind::Semicolon); Some(Stmt::Break) }
            TokenKind::KwContinue => { self.advance(); self.expect(&TokenKind::Semicolon); Some(Stmt::Continue) }
            TokenKind::KwDiscard => { self.advance(); self.expect(&TokenKind::Semicolon); Some(Stmt::Discard) }
            tok if ShaderType::from_token(&tok).is_some() || matches!(tok, TokenKind::Ident(_)) => {
                // Could be var decl or expr
                let saved_pos = self.pos;
                let ty = self.parse_type();
                if let TokenKind::Ident(name) = self.peek().kind.clone() {
                    self.advance();
                    let init = if self.peek().kind == TokenKind::Eq {
                        self.advance();
                        Some(self.parse_expr())
                    } else { None };
                    self.expect(&TokenKind::Semicolon);
                    Some(Stmt::VarDecl { ty, name, qualifier: None, init })
                } else {
                    // rewind — it's an expression
                    self.pos = saved_pos;
                    let e = self.parse_expr();
                    self.expect(&TokenKind::Semicolon);
                    Some(Stmt::Expr(e))
                }
            }
            _ => {
                let e = self.parse_expr();
                self.expect(&TokenKind::Semicolon);
                Some(Stmt::Expr(e))
            }
        }
    }

    fn parse_function(&mut self, return_type: ShaderType, name: String) -> FunctionDecl {
        // already consumed return_type and name
        self.expect(&TokenKind::LParen);
        let mut params = Vec::new();
        while self.peek().kind != TokenKind::RParen && !self.at_eof() {
            let qualifier = match self.peek().kind {
                TokenKind::KwIn => { self.advance(); Some(VarQualifier::In) }
                TokenKind::KwOut => { self.advance(); Some(VarQualifier::Out) }
                TokenKind::KwInout => { self.advance(); Some(VarQualifier::Inout) }
                TokenKind::KwConst => { self.advance(); Some(VarQualifier::Const) }
                _ => None,
            };
            let ty = self.parse_type();
            let pname = if let TokenKind::Ident(n) = self.peek().kind.clone() { self.advance(); n } else { String::new() };
            params.push(FunctionParam { ty, name: pname, qualifier });
            if self.peek().kind == TokenKind::Comma { self.advance(); } else { break; }
        }
        self.expect(&TokenKind::RParen);
        let mut body = Vec::new();
        if self.peek().kind == TokenKind::LBrace {
            self.advance();
            while self.peek().kind != TokenKind::RBrace && !self.at_eof() {
                if let Some(s) = self.parse_stmt() { body.push(s); }
            }
            self.expect(&TokenKind::RBrace);
        } else {
            self.expect(&TokenKind::Semicolon);
        }
        FunctionDecl { return_type, name, params, body, is_builtin: false }
    }

    pub fn parse_translation_unit(&mut self) -> ShaderAst {
        let mut ast = ShaderAst::new();
        while !self.at_eof() {
            // Handle preprocessor directives
            if self.peek().kind == TokenKind::Hash {
                self.advance();
                if let TokenKind::Ident(directive) = self.peek().kind.clone() {
                    self.advance();
                    match directive.as_str() {
                        "version" => {
                            if let TokenKind::IntLit(v) = self.peek().kind { self.advance(); ast.version = v as u32; }
                        }
                        "define" => {
                            if let TokenKind::Ident(macro_name) = self.peek().kind.clone() {
                                self.advance();
                                let val = if let TokenKind::Ident(v) = self.peek().kind.clone() { self.advance(); v } else { String::new() };
                                ast.defines.insert(macro_name, val);
                            }
                        }
                        _ => {}
                    }
                }
                continue;
            }
            // Layout qualifier
            let mut binding = None;
            let mut set_num = None;
            if self.peek().kind == TokenKind::KwLayout {
                self.advance();
                self.expect(&TokenKind::LParen);
                while self.peek().kind != TokenKind::RParen && !self.at_eof() {
                    if let TokenKind::Ident(k) = self.peek().kind.clone() {
                        self.advance();
                        if self.peek().kind == TokenKind::Eq {
                            self.advance();
                            if let TokenKind::IntLit(v) = self.peek().kind { self.advance();
                                if k == "binding" { binding = Some(v as u32); }
                                else if k == "set" { set_num = Some(v as u32); }
                            }
                        }
                    } else { self.advance(); }
                    if self.peek().kind == TokenKind::Comma { self.advance(); } else { break; }
                }
                self.expect(&TokenKind::RParen);
            }
            // Qualifiers
            let qualifier = match self.peek().kind {
                TokenKind::KwUniform => { self.advance(); Some(VarQualifier::Uniform) }
                TokenKind::KwIn | TokenKind::KwAttribute => { self.advance(); Some(VarQualifier::In) }
                TokenKind::KwOut | TokenKind::KwVarying => { self.advance(); Some(VarQualifier::Out) }
                TokenKind::KwConst => { self.advance(); Some(VarQualifier::Const) }
                _ => None,
            };
            // Precision qualifier
            if matches!(self.peek().kind, TokenKind::KwPrecision|TokenKind::KwHighp|TokenKind::KwMediump|TokenKind::KwLowp) {
                self.advance();
                if matches!(self.peek().kind, TokenKind::KwHighp|TokenKind::KwMediump|TokenKind::KwLowp) { self.advance(); }
                self.parse_type();
                self.expect(&TokenKind::Semicolon);
                continue;
            }
            // Struct
            if self.peek().kind == TokenKind::KwStruct {
                self.advance();
                let sname = if let TokenKind::Ident(n) = self.peek().kind.clone() { self.advance(); n } else { String::new() };
                let mut fields = Vec::new();
                self.expect(&TokenKind::LBrace);
                while self.peek().kind != TokenKind::RBrace && !self.at_eof() {
                    let fty = self.parse_type();
                    while let TokenKind::Ident(fname) = self.peek().kind.clone() {
                        self.advance();
                        let arr = if self.peek().kind == TokenKind::LBracket {
                            self.advance();
                            let sz = if let TokenKind::IntLit(v) = self.peek().kind { self.advance(); Some(v as u32) } else { None };
                            self.expect(&TokenKind::RBracket);
                            sz
                        } else { None };
                        fields.push(StructField { ty: fty.clone(), name: fname, array_size: arr });
                        if self.peek().kind == TokenKind::Comma { self.advance(); } else { break; }
                    }
                    self.expect(&TokenKind::Semicolon);
                }
                self.expect(&TokenKind::RBrace);
                self.expect(&TokenKind::Semicolon);
                ast.structs.push(StructDecl { name: sname, fields });
                continue;
            }
            // Type + name
            if self.peek().is_type_keyword() || matches!(self.peek().kind, TokenKind::Ident(_)) {
                let ty = self.parse_type();
                let name = if let TokenKind::Ident(n) = self.peek().kind.clone() { self.advance(); n } else { String::new() };
                // Array?
                let arr_size = if self.peek().kind == TokenKind::LBracket {
                    self.advance();
                    let sz = if let TokenKind::IntLit(v) = self.peek().kind { self.advance(); Some(v as u32) } else { None };
                    self.expect(&TokenKind::RBracket);
                    sz
                } else { None };
                // Function?
                if self.peek().kind == TokenKind::LParen {
                    let func = self.parse_function(ty, name);
                    ast.functions.push(func);
                } else {
                    // Variable declaration
                    match qualifier {
                        Some(VarQualifier::Uniform) => {
                            ast.uniforms.push(UniformDecl { ty, name, binding, set: set_num, array_size: arr_size });
                            self.expect(&TokenKind::Semicolon);
                        }
                        Some(VarQualifier::In) => {
                            ast.attributes.push(AttributeDecl { ty, name, location: binding });
                            self.expect(&TokenKind::Semicolon);
                        }
                        Some(VarQualifier::Out) => {
                            ast.varyings.push(AttributeDecl { ty, name, location: binding });
                            self.expect(&TokenKind::Semicolon);
                        }
                        _ => {
                            let init = if self.peek().kind == TokenKind::Eq { self.advance(); Some(self.parse_expr()) } else { None };
                            self.expect(&TokenKind::Semicolon);
                            ast.global_vars.push(Stmt::VarDecl { ty, name, qualifier, init });
                        }
                    }
                }
            } else {
                self.advance(); // skip unknown token
            }
        }
        ast
    }
}

// ============================================================
// SECTION 6: SEMANTIC ANALYSIS
// ============================================================

#[derive(Debug, Clone)]
pub struct Symbol {
    pub name: String,
    pub ty: ShaderType,
    pub qualifier: Option<VarQualifier>,
    pub used: bool,
    pub defined_at_line: u32,
}

pub struct Scope {
    pub symbols: HashMap<String, Symbol>,
    pub parent: Option<*mut Scope>,
}

impl Scope {
    pub fn new() -> Self { Self { symbols: HashMap::new(), parent: None } }
    pub fn lookup(&self, name: &str) -> Option<&Symbol> {
        if let Some(s) = self.symbols.get(name) { return Some(s); }
        None
    }
    pub fn insert(&mut self, sym: Symbol) { self.symbols.insert(sym.name.clone(), sym); }
}

#[derive(Debug, Clone)]
pub struct SemanticError {
    pub kind: SemanticErrorKind,
    pub message: String,
    pub line: u32,
}

#[derive(Debug, Clone)]
pub enum SemanticErrorKind {
    UndeclaredVariable,
    TypeMismatch,
    RedefinedSymbol,
    InvalidOperation,
    UnusedVariable,
    RecursionDetected,
    ReturnTypeMismatch,
    InvalidArgCount,
}

pub struct SemanticAnalyzer {
    pub scopes: Vec<HashMap<String, Symbol>>,
    pub errors: Vec<SemanticError>,
    pub warnings: Vec<SemanticError>,
    pub current_function: Option<String>,
    pub call_stack: HashSet<String>,
    pub built_in_functions: HashMap<String, BuiltinSignature>,
}

#[derive(Debug, Clone)]
pub struct BuiltinSignature {
    pub name: String,
    pub overloads: Vec<(Vec<ShaderType>, ShaderType)>, // (params, return)
}

impl SemanticAnalyzer {
    pub fn new() -> Self {
        let mut a = Self {
            scopes: vec![HashMap::new()],
            errors: Vec::new(),
            warnings: Vec::new(),
            current_function: None,
            call_stack: HashSet::new(),
            built_in_functions: HashMap::new(),
        };
        a.register_builtins();
        a
    }

    fn register_builtins(&mut self) {
        let math_float_vec = |name: &str| {
            let overloads = vec![
                (vec![ShaderType::Float], ShaderType::Float),
                (vec![ShaderType::Vec2], ShaderType::Vec2),
                (vec![ShaderType::Vec3], ShaderType::Vec3),
                (vec![ShaderType::Vec4], ShaderType::Vec4),
            ];
            BuiltinSignature { name: name.to_string(), overloads }
        };
        let names = &["sin","cos","tan","asin","acos","atan","sinh","cosh","tanh","exp","exp2","log","log2","sqrt","inversesqrt","abs","sign","floor","ceil","round","fract","normalize","length","radians","degrees"];
        for n in names {
            self.built_in_functions.insert(n.to_string(), math_float_vec(n));
        }
        self.built_in_functions.insert("pow".to_string(), BuiltinSignature { name: "pow".to_string(), overloads: vec![(vec![ShaderType::Float,ShaderType::Float],ShaderType::Float),(vec![ShaderType::Vec2,ShaderType::Vec2],ShaderType::Vec2),(vec![ShaderType::Vec3,ShaderType::Vec3],ShaderType::Vec3),(vec![ShaderType::Vec4,ShaderType::Vec4],ShaderType::Vec4)] });
        self.built_in_functions.insert("mix".to_string(), BuiltinSignature { name: "mix".to_string(), overloads: vec![(vec![ShaderType::Float,ShaderType::Float,ShaderType::Float],ShaderType::Float),(vec![ShaderType::Vec2,ShaderType::Vec2,ShaderType::Float],ShaderType::Vec2),(vec![ShaderType::Vec3,ShaderType::Vec3,ShaderType::Float],ShaderType::Vec3)] });
        self.built_in_functions.insert("clamp".to_string(), BuiltinSignature { name: "clamp".to_string(), overloads: vec![(vec![ShaderType::Float,ShaderType::Float,ShaderType::Float],ShaderType::Float),(vec![ShaderType::Vec2,ShaderType::Float,ShaderType::Float],ShaderType::Vec2)] });
        self.built_in_functions.insert("smoothstep".to_string(), BuiltinSignature { name: "smoothstep".to_string(), overloads: vec![(vec![ShaderType::Float,ShaderType::Float,ShaderType::Float],ShaderType::Float)] });
        self.built_in_functions.insert("dot".to_string(), BuiltinSignature { name: "dot".to_string(), overloads: vec![(vec![ShaderType::Vec2,ShaderType::Vec2],ShaderType::Float),(vec![ShaderType::Vec3,ShaderType::Vec3],ShaderType::Float),(vec![ShaderType::Vec4,ShaderType::Vec4],ShaderType::Float)] });
        self.built_in_functions.insert("cross".to_string(), BuiltinSignature { name: "cross".to_string(), overloads: vec![(vec![ShaderType::Vec3,ShaderType::Vec3],ShaderType::Vec3)] });
        self.built_in_functions.insert("reflect".to_string(), BuiltinSignature { name: "reflect".to_string(), overloads: vec![(vec![ShaderType::Vec3,ShaderType::Vec3],ShaderType::Vec3)] });
        self.built_in_functions.insert("refract".to_string(), BuiltinSignature { name: "refract".to_string(), overloads: vec![(vec![ShaderType::Vec3,ShaderType::Vec3,ShaderType::Float],ShaderType::Vec3)] });
        self.built_in_functions.insert("max".to_string(), BuiltinSignature { name: "max".to_string(), overloads: vec![(vec![ShaderType::Float,ShaderType::Float],ShaderType::Float)] });
        self.built_in_functions.insert("min".to_string(), BuiltinSignature { name: "min".to_string(), overloads: vec![(vec![ShaderType::Float,ShaderType::Float],ShaderType::Float)] });
        self.built_in_functions.insert("mod".to_string(), BuiltinSignature { name: "mod".to_string(), overloads: vec![(vec![ShaderType::Float,ShaderType::Float],ShaderType::Float),(vec![ShaderType::Vec2,ShaderType::Float],ShaderType::Vec2)] });
        self.built_in_functions.insert("texture".to_string(), BuiltinSignature { name: "texture".to_string(), overloads: vec![(vec![ShaderType::Sampler2D,ShaderType::Vec2],ShaderType::Vec4),(vec![ShaderType::SamplerCube,ShaderType::Vec3],ShaderType::Vec4)] });
        self.built_in_functions.insert("textureLod".to_string(), BuiltinSignature { name: "textureLod".to_string(), overloads: vec![(vec![ShaderType::Sampler2D,ShaderType::Vec2,ShaderType::Float],ShaderType::Vec4)] });
        self.built_in_functions.insert("dFdx".to_string(), BuiltinSignature { name: "dFdx".to_string(), overloads: vec![(vec![ShaderType::Float],ShaderType::Float),(vec![ShaderType::Vec2],ShaderType::Vec2),(vec![ShaderType::Vec3],ShaderType::Vec3)] });
        self.built_in_functions.insert("dFdy".to_string(), BuiltinSignature { name: "dFdy".to_string(), overloads: vec![(vec![ShaderType::Float],ShaderType::Float),(vec![ShaderType::Vec2],ShaderType::Vec2),(vec![ShaderType::Vec3],ShaderType::Vec3)] });
    }

    fn push_scope(&mut self) { self.scopes.push(HashMap::new()); }
    fn pop_scope(&mut self) { self.scopes.pop(); }
    fn current_scope(&mut self) -> &mut HashMap<String, Symbol> { self.scopes.last_mut().unwrap() }

    fn declare(&mut self, sym: Symbol) {
        let name = sym.name.clone();
        if self.current_scope().contains_key(&name) {
            self.errors.push(SemanticError { kind: SemanticErrorKind::RedefinedSymbol, message: format!("Redefined symbol '{}'", name), line: sym.defined_at_line });
        }
        self.current_scope().insert(name, sym);
    }

    fn lookup(&self, name: &str) -> Option<&Symbol> {
        for scope in self.scopes.iter().rev() {
            if let Some(s) = scope.get(name) { return Some(s); }
        }
        None
    }

    fn infer_type(&self, expr: &Expr) -> ShaderType {
        match expr {
            Expr::IntLit(_) => ShaderType::Int,
            Expr::FloatLit(_) => ShaderType::Float,
            Expr::BoolLit(_) => ShaderType::Bool,
            Expr::Ident(name) => {
                if let Some(sym) = self.lookup(name) { sym.ty.clone() } else { ShaderType::Unknown }
            }
            Expr::Binary { op, left, right } => {
                let lt = self.infer_type(left);
                let rt = self.infer_type(right);
                match op {
                    BinaryOp::Eq|BinaryOp::Ne|BinaryOp::Lt|BinaryOp::Gt|BinaryOp::Le|BinaryOp::Ge|BinaryOp::And|BinaryOp::Or => ShaderType::Bool,
                    _ => if lt == rt { lt } else if ShaderType::can_implicit_convert(&rt, &lt) { lt } else { lt }
                }
            }
            Expr::Unary { op, operand } => self.infer_type(operand),
            Expr::Call { function, args } => {
                if let Some(sig) = self.built_in_functions.get(function) {
                    let arg_types: Vec<ShaderType> = args.iter().map(|a| self.infer_type(a)).collect();
                    for (params, ret) in &sig.overloads {
                        if params.len() == arg_types.len() { return ret.clone(); }
                    }
                }
                ShaderType::Unknown
            }
            Expr::Field { object, field } => ShaderType::Float, // simplified
            Expr::Swizzle { object, components } => {
                let n = components.len();
                match n {
                    1 => ShaderType::Float,
                    2 => ShaderType::Vec2,
                    3 => ShaderType::Vec3,
                    4 => ShaderType::Vec4,
                    _ => ShaderType::Unknown,
                }
            }
            Expr::Index { array, .. } => {
                match self.infer_type(array) {
                    ShaderType::Array(inner, _) => *inner,
                    ShaderType::Vec2|ShaderType::Vec3|ShaderType::Vec4 => ShaderType::Float,
                    ShaderType::Mat2|ShaderType::Mat3|ShaderType::Mat4 => ShaderType::Vec4, // simplified
                    other => other,
                }
            }
            Expr::Construction { ty, .. } => ty.clone(),
            Expr::Cast { target_type, .. } => target_type.clone(),
            Expr::Assign { value, .. } => self.infer_type(value),
            Expr::Ternary { then_expr, .. } => self.infer_type(then_expr),
        }
    }

    fn check_expr(&mut self, expr: &Expr) {
        match expr {
            Expr::Ident(name) => {
                if self.lookup(name).is_none() && !self.built_in_functions.contains_key(name.as_str()) {
                    // Only error if not a known builtin constant
                    let known = ["gl_Position","gl_FragCoord","gl_FragDepth","gl_VertexID","gl_InstanceID","true","false","PI","E"];
                    if !known.contains(&name.as_str()) {
                        self.errors.push(SemanticError { kind: SemanticErrorKind::UndeclaredVariable, message: format!("Undeclared variable '{}'", name), line: 0 });
                    }
                }
            }
            Expr::Binary { op, left, right } => {
                self.check_expr(left);
                self.check_expr(right);
                let lt = self.infer_type(left);
                let rt = self.infer_type(right);
                if lt != rt && !ShaderType::can_implicit_convert(&lt, &rt) && !ShaderType::can_implicit_convert(&rt, &lt) && lt != ShaderType::Unknown && rt != ShaderType::Unknown {
                    // warn about potential type mismatch
                }
            }
            Expr::Call { function, args } => {
                for a in args { self.check_expr(a); }
                if !self.built_in_functions.contains_key(function.as_str()) {
                    // Check user-defined function call for recursion
                    if let Some(fname) = &self.current_function {
                        if fname == function {
                            self.errors.push(SemanticError { kind: SemanticErrorKind::RecursionDetected, message: format!("Recursive call to '{}'", function), line: 0 });
                        }
                    }
                }
            }
            Expr::Assign { target, value, .. } => {
                self.check_expr(target);
                self.check_expr(value);
            }
            Expr::Unary { operand, .. } => self.check_expr(operand),
            Expr::Ternary { cond, then_expr, else_expr } => {
                self.check_expr(cond);
                self.check_expr(then_expr);
                self.check_expr(else_expr);
            }
            Expr::Field { object, .. } | Expr::Swizzle { object, .. } => self.check_expr(object),
            Expr::Index { array, index } => { self.check_expr(array); self.check_expr(index); }
            Expr::Construction { args, .. } => { for a in args { self.check_expr(a); } }
            _ => {}
        }
    }

    fn check_stmt(&mut self, stmt: &Stmt) {
        match stmt {
            Stmt::Expr(e) => self.check_expr(e),
            Stmt::Block(stmts) => {
                self.push_scope();
                for s in stmts { self.check_stmt(s); }
                self.pop_scope();
            }
            Stmt::VarDecl { ty, name, qualifier, init } => {
                if let Some(init_expr) = init { self.check_expr(init_expr); }
                self.declare(Symbol { name: name.clone(), ty: ty.clone(), qualifier: *qualifier, used: false, defined_at_line: 0 });
            }
            Stmt::If { cond, then_body, else_body } => {
                self.check_expr(cond);
                self.check_stmt(then_body);
                if let Some(e) = else_body { self.check_stmt(e); }
            }
            Stmt::For { init, cond, step, body } => {
                self.push_scope();
                if let Some(i) = init { self.check_stmt(i); }
                if let Some(c) = cond { self.check_expr(c); }
                if let Some(s) = step { self.check_expr(s); }
                self.check_stmt(body);
                self.pop_scope();
            }
            Stmt::While { cond, body } => { self.check_expr(cond); self.check_stmt(body); }
            Stmt::DoWhile { body, cond } => { self.check_stmt(body); self.check_expr(cond); }
            Stmt::Return(val) => { if let Some(v) = val { self.check_expr(v); } }
            _ => {}
        }
    }

    pub fn analyze(&mut self, ast: &ShaderAst) {
        // Register global uniforms
        for u in &ast.uniforms {
            self.declare(Symbol { name: u.name.clone(), ty: u.ty.clone(), qualifier: Some(VarQualifier::Uniform), used: false, defined_at_line: 0 });
        }
        for a in &ast.attributes {
            self.declare(Symbol { name: a.name.clone(), ty: a.ty.clone(), qualifier: Some(VarQualifier::In), used: false, defined_at_line: 0 });
        }
        for v in &ast.varyings {
            self.declare(Symbol { name: v.name.clone(), ty: v.ty.clone(), qualifier: Some(VarQualifier::Out), used: false, defined_at_line: 0 });
        }
        // Register struct types
        for s in &ast.structs {
            self.declare(Symbol { name: s.name.clone(), ty: ShaderType::Struct(s.name.clone()), qualifier: None, used: false, defined_at_line: 0 });
        }
        // Analyze functions
        for func in &ast.functions {
            self.current_function = Some(func.name.clone());
            self.push_scope();
            for param in &func.params {
                self.declare(Symbol { name: param.name.clone(), ty: param.ty.clone(), qualifier: param.qualifier, used: false, defined_at_line: 0 });
            }
            for stmt in &func.body { self.check_stmt(stmt); }
            self.pop_scope();
        }
        self.current_function = None;
    }
}

// ============================================================
// SECTION 7: CONSTANT FOLDING
// ============================================================

pub fn fold_expr(expr: Expr) -> Expr {
    match expr {
        Expr::Binary { op, left, right } => {
            let left = fold_expr(*left);
            let right = fold_expr(*right);
            match (&left, &right) {
                (Expr::FloatLit(a), Expr::FloatLit(b)) => {
                    match op {
                        BinaryOp::Add => Expr::FloatLit(a + b),
                        BinaryOp::Sub => Expr::FloatLit(a - b),
                        BinaryOp::Mul => Expr::FloatLit(a * b),
                        BinaryOp::Div => if *b != 0.0 { Expr::FloatLit(a / b) } else { Expr::Binary { op, left: Box::new(left), right: Box::new(right) } },
                        BinaryOp::Eq => Expr::BoolLit(a == b),
                        BinaryOp::Ne => Expr::BoolLit(a != b),
                        BinaryOp::Lt => Expr::BoolLit(a < b),
                        BinaryOp::Gt => Expr::BoolLit(a > b),
                        BinaryOp::Le => Expr::BoolLit(a <= b),
                        BinaryOp::Ge => Expr::BoolLit(a >= b),
                        _ => Expr::Binary { op, left: Box::new(left), right: Box::new(right) },
                    }
                }
                (Expr::IntLit(a), Expr::IntLit(b)) => {
                    match op {
                        BinaryOp::Add => Expr::IntLit(a + b),
                        BinaryOp::Sub => Expr::IntLit(a - b),
                        BinaryOp::Mul => Expr::IntLit(a * b),
                        BinaryOp::Div => if *b != 0 { Expr::IntLit(a / b) } else { Expr::Binary { op, left: Box::new(left), right: Box::new(right) } },
                        BinaryOp::Mod => if *b != 0 { Expr::IntLit(a % b) } else { Expr::Binary { op, left: Box::new(left), right: Box::new(right) } },
                        BinaryOp::BitAnd => Expr::IntLit(a & b),
                        BinaryOp::BitOr => Expr::IntLit(a | b),
                        BinaryOp::BitXor => Expr::IntLit(a ^ b),
                        BinaryOp::Shl => Expr::IntLit(a << (b & 63)),
                        BinaryOp::Shr => Expr::IntLit(a >> (b & 63)),
                        BinaryOp::Eq => Expr::BoolLit(a == b),
                        BinaryOp::Ne => Expr::BoolLit(a != b),
                        BinaryOp::Lt => Expr::BoolLit(a < b),
                        BinaryOp::Gt => Expr::BoolLit(a > b),
                        BinaryOp::Le => Expr::BoolLit(a <= b),
                        BinaryOp::Ge => Expr::BoolLit(a >= b),
                        _ => Expr::Binary { op, left: Box::new(left), right: Box::new(right) },
                    }
                }
                (Expr::BoolLit(a), Expr::BoolLit(b)) => {
                    match op {
                        BinaryOp::And => Expr::BoolLit(*a && *b),
                        BinaryOp::Or => Expr::BoolLit(*a || *b),
                        BinaryOp::Eq => Expr::BoolLit(a == b),
                        BinaryOp::Ne => Expr::BoolLit(a != b),
                        _ => Expr::Binary { op, left: Box::new(left), right: Box::new(right) },
                    }
                }
                // Algebraic simplifications
                (_, Expr::FloatLit(v)) if op == BinaryOp::Mul && *v == 1.0 => left,
                (Expr::FloatLit(v), _) if op == BinaryOp::Mul && *v == 1.0 => right,
                (_, Expr::FloatLit(v)) if op == BinaryOp::Mul && *v == 0.0 => Expr::FloatLit(0.0),
                (Expr::FloatLit(v), _) if op == BinaryOp::Mul && *v == 0.0 => Expr::FloatLit(0.0),
                (_, Expr::FloatLit(v)) if op == BinaryOp::Add && *v == 0.0 => left,
                (Expr::FloatLit(v), _) if op == BinaryOp::Add && *v == 0.0 => right,
                (_, Expr::FloatLit(v)) if op == BinaryOp::Sub && *v == 0.0 => left,
                (_, Expr::FloatLit(v)) if op == BinaryOp::Div && *v == 1.0 => left,
                (_, Expr::IntLit(v)) if op == BinaryOp::Mul && *v == 1 => left,
                (Expr::IntLit(v), _) if op == BinaryOp::Mul && *v == 1 => right,
                (_, Expr::IntLit(v)) if op == BinaryOp::Add && *v == 0 => left,
                (Expr::IntLit(v), _) if op == BinaryOp::Add && *v == 0 => right,
                _ => Expr::Binary { op, left: Box::new(left), right: Box::new(right) },
            }
        }
        Expr::Unary { op, operand } => {
            let operand = fold_expr(*operand);
            match (&operand, op) {
                (Expr::FloatLit(v), UnaryOp::Negate) => Expr::FloatLit(-v),
                (Expr::IntLit(v), UnaryOp::Negate) => Expr::IntLit(-v),
                (Expr::BoolLit(v), UnaryOp::Not) => Expr::BoolLit(!v),
                (Expr::IntLit(v), UnaryOp::BitNot) => Expr::IntLit(!v),
                _ => Expr::Unary { op, operand: Box::new(operand) },
            }
        }
        Expr::Ternary { cond, then_expr, else_expr } => {
            let cond = fold_expr(*cond);
            let then_expr = fold_expr(*then_expr);
            let else_expr = fold_expr(*else_expr);
            match &cond {
                Expr::BoolLit(true) => then_expr,
                Expr::BoolLit(false) => else_expr,
                _ => Expr::Ternary { cond: Box::new(cond), then_expr: Box::new(then_expr), else_expr: Box::new(else_expr) },
            }
        }
        Expr::Call { function, args } => {
            let args: Vec<Expr> = args.into_iter().map(fold_expr).collect();
            // Fold constant built-in calls
            let all_float_lits: Vec<f64> = args.iter().filter_map(|a| if let Expr::FloatLit(v) = a { Some(*v) } else { None }).collect();
            if all_float_lits.len() == args.len() {
                let result = fold_builtin_call(&function, &all_float_lits);
                if let Some(v) = result { return Expr::FloatLit(v); }
            }
            Expr::Call { function, args }
        }
        other => other,
    }
}

fn fold_builtin_call(name: &str, args: &[f64]) -> Option<f64> {
    match (name, args) {
        ("sin", [x]) => Some(x.sin()),
        ("cos", [x]) => Some(x.cos()),
        ("tan", [x]) => Some(x.tan()),
        ("asin", [x]) => Some(x.asin()),
        ("acos", [x]) => Some(x.acos()),
        ("atan", [x]) => Some(x.atan()),
        ("sqrt", [x]) if *x >= 0.0 => Some(x.sqrt()),
        ("inversesqrt", [x]) if *x > 0.0 => Some(1.0 / x.sqrt()),
        ("exp", [x]) => Some(x.exp()),
        ("exp2", [x]) => Some(x.exp2()),
        ("log", [x]) if *x > 0.0 => Some(x.ln()),
        ("log2", [x]) if *x > 0.0 => Some(x.log2()),
        ("abs", [x]) => Some(x.abs()),
        ("sign", [x]) => Some(x.signum()),
        ("floor", [x]) => Some(x.floor()),
        ("ceil", [x]) => Some(x.ceil()),
        ("round", [x]) => Some(x.round()),
        ("fract", [x]) => Some(x.fract()),
        ("pow", [x, y]) => Some(x.powf(*y)),
        ("min", [a, b]) => Some(a.min(*b)),
        ("max", [a, b]) => Some(a.max(*b)),
        ("clamp", [x, mn, mx]) => Some(x.clamp(*mn, *mx)),
        ("mix", [a, b, t]) => Some(a + (b - a) * t),
        ("smoothstep", [e0, e1, x]) => {
            let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
            Some(t * t * (3.0 - 2.0 * t))
        }
        ("radians", [x]) => Some(x.to_radians()),
        ("degrees", [x]) => Some(x.to_degrees()),
        _ => None,
    }
}

// ============================================================
// SECTION 8: DEAD CODE ELIMINATION
// ============================================================

pub fn eliminate_dead_code(stmts: Vec<Stmt>) -> Vec<Stmt> {
    let mut result = Vec::new();
    let mut unreachable = false;
    for stmt in stmts {
        if unreachable { break; }
        match stmt {
            Stmt::If { ref cond, ref then_body, ref else_body } => {
                if let Expr::BoolLit(true) = cond {
                    // Always-true: keep then, discard else
                    result.push(*then_body.clone());
                } else if let Expr::BoolLit(false) = cond {
                    // Always-false: keep else if present
                    if let Some(e) = else_body { result.push(*e.clone()); }
                } else {
                    result.push(stmt);
                }
            }
            Stmt::Return(_) | Stmt::Break | Stmt::Continue | Stmt::Discard => {
                result.push(stmt);
                unreachable = true;
            }
            Stmt::Block(inner) => {
                let cleaned = eliminate_dead_code(inner);
                result.push(Stmt::Block(cleaned));
            }
            other => result.push(other),
        }
    }
    result
}

// ============================================================
// SECTION 9: COMMON SUBEXPRESSION ELIMINATION
// ============================================================

pub struct CSEPass {
    pub expressions: HashMap<String, String>, // expr_key -> temp_var_name
    pub temps: Vec<(String, Expr)>,
    pub counter: u32,
}

impl CSEPass {
    pub fn new() -> Self { Self { expressions: HashMap::new(), temps: Vec::new(), counter: 0 } }
    pub fn expr_key(expr: &Expr) -> Option<String> {
        match expr {
            Expr::Binary { op, left, right } => {
                let lk = Self::expr_key(left)?;
                let rk = Self::expr_key(right)?;
                Some(format!("{:?}_{}_{}", op, lk, rk))
            }
            Expr::Call { function, args } => {
                let arg_keys: Vec<String> = args.iter().filter_map(|a| Self::expr_key(a)).collect();
                if arg_keys.len() == args.len() { Some(format!("{}({})", function, arg_keys.join(","))) } else { None }
            }
            Expr::FloatLit(v) => Some(format!("f{:.6}", v)),
            Expr::IntLit(v) => Some(format!("i{}", v)),
            Expr::BoolLit(v) => Some(format!("b{}", v)),
            Expr::Ident(n) => Some(n.clone()),
            _ => None,
        }
    }
    pub fn process_expr(&mut self, expr: Expr) -> Expr {
        match expr {
            Expr::Binary { op, left, right } => {
                let left = self.process_expr(*left);
                let right = self.process_expr(*right);
                let folded = Expr::Binary { op, left: Box::new(left), right: Box::new(right) };
                if let Some(key) = Self::expr_key(&folded) {
                    if let Some(temp) = self.expressions.get(&key) {
                        return Expr::Ident(temp.clone());
                    }
                    let temp_name = format!("_cse_{}", self.counter);
                    self.counter += 1;
                    self.expressions.insert(key, temp_name.clone());
                    self.temps.push((temp_name.clone(), folded));
                    Expr::Ident(temp_name)
                } else { folded }
            }
            Expr::Call { function, args } => {
                let args: Vec<Expr> = args.into_iter().map(|a| self.process_expr(a)).collect();
                let e = Expr::Call { function, args };
                if let Some(key) = Self::expr_key(&e) {
                    if let Some(temp) = self.expressions.get(&key) {
                        return Expr::Ident(temp.clone());
                    }
                }
                e
            }
            other => other,
        }
    }
}

// ============================================================
// SECTION 10: CODE GENERATION - GLSL
// ============================================================

pub struct GlslEmitter {
    pub output: String,
    pub indent: usize,
    pub version: u32,
    pub es: bool,
}

impl GlslEmitter {
    pub fn new(version: u32, es: bool) -> Self { Self { output: String::new(), indent: 0, version, es } }

    fn write(&mut self, s: &str) { self.output.push_str(s); }
    fn writeln(&mut self, s: &str) {
        let indent: String = " ".repeat(self.indent * 4);
        self.output.push_str(&indent);
        self.output.push_str(s);
        self.output.push('\n');
    }
    fn indent_in(&mut self) { self.indent += 1; }
    fn indent_out(&mut self) { if self.indent > 0 { self.indent -= 1; } }

    pub fn emit_header(&mut self, ast: &ShaderAst) {
        if self.es {
            self.writeln(&format!("#version {} es", self.version));
        } else {
            self.writeln(&format!("#version {} core", self.version));
        }
        for (name, val) in &ast.defines {
            self.writeln(&format!("#define {} {}", name, val));
        }
    }

    pub fn emit_type(&self, ty: &ShaderType) -> String {
        ty.name().to_string()
    }

    pub fn emit_struct(&mut self, s: &StructDecl) {
        self.writeln(&format!("struct {} {{", s.name));
        self.indent_in();
        for f in &s.fields {
            let arr = if let Some(n) = f.array_size { format!("[{}]", n) } else { String::new() };
            self.writeln(&format!("{} {}{};", self.emit_type(&f.ty), f.name, arr));
        }
        self.indent_out();
        self.writeln("};");
    }

    pub fn emit_uniform(&mut self, u: &UniformDecl) {
        let layout = if u.binding.is_some() || u.set.is_some() {
            let parts: Vec<String> = [
                u.set.map(|s| format!("set={}", s)),
                u.binding.map(|b| format!("binding={}", b)),
            ].iter().filter_map(|x| x.clone()).collect();
            if parts.is_empty() { String::new() } else { format!("layout({}) ", parts.join(", ")) }
        } else { String::new() };
        let arr = if let Some(n) = u.array_size { format!("[{}]", n) } else { String::new() };
        self.writeln(&format!("{}uniform {} {}{};", layout, self.emit_type(&u.ty), u.name, arr));
    }

    pub fn emit_expr(&self, expr: &Expr) -> String {
        match expr {
            Expr::IntLit(v) => v.to_string(),
            Expr::FloatLit(v) => {
                if *v == v.floor() && v.abs() < 1e15 { format!("{:.1}", v) } else { format!("{}", v) }
            }
            Expr::BoolLit(v) => v.to_string(),
            Expr::Ident(n) => n.clone(),
            Expr::Unary { op, operand } => {
                let o = self.emit_expr(operand);
                match op {
                    UnaryOp::Negate => format!("(-{})", o),
                    UnaryOp::Not => format!("(!{})", o),
                    UnaryOp::BitNot => format!("(~{})", o),
                    UnaryOp::PreIncrement => format!("(++{})", o),
                    UnaryOp::PreDecrement => format!("(--{})", o),
                    UnaryOp::PostIncrement => format!("({}++)", o),
                    UnaryOp::PostDecrement => format!("({}--)", o),
                }
            }
            Expr::Binary { op, left, right } => {
                let l = self.emit_expr(left);
                let r = self.emit_expr(right);
                let sym = match op {
                    BinaryOp::Add => "+", BinaryOp::Sub => "-", BinaryOp::Mul => "*", BinaryOp::Div => "/",
                    BinaryOp::Mod => "%", BinaryOp::Eq => "==", BinaryOp::Ne => "!=",
                    BinaryOp::Lt => "<", BinaryOp::Gt => ">", BinaryOp::Le => "<=", BinaryOp::Ge => ">=",
                    BinaryOp::And => "&&", BinaryOp::Or => "||",
                    BinaryOp::BitAnd => "&", BinaryOp::BitOr => "|", BinaryOp::BitXor => "^",
                    BinaryOp::Shl => "<<", BinaryOp::Shr => ">>",
                };
                format!("({} {} {})", l, sym, r)
            }
            Expr::Assign { op, target, value } => {
                let t = self.emit_expr(target);
                let v = self.emit_expr(value);
                let sym = match op {
                    AssignOp::Assign => "=", AssignOp::AddAssign => "+=", AssignOp::SubAssign => "-=",
                    AssignOp::MulAssign => "*=", AssignOp::DivAssign => "/=", AssignOp::ModAssign => "%=",
                    AssignOp::AndAssign => "&=", AssignOp::OrAssign => "|=", AssignOp::XorAssign => "^=",
                    AssignOp::ShlAssign => "<<=", AssignOp::ShrAssign => ">>=",
                };
                format!("{} {} {}", t, sym, v)
            }
            Expr::Ternary { cond, then_expr, else_expr } => {
                format!("({} ? {} : {})", self.emit_expr(cond), self.emit_expr(then_expr), self.emit_expr(else_expr))
            }
            Expr::Call { function, args } => {
                let arg_strs: Vec<String> = args.iter().map(|a| self.emit_expr(a)).collect();
                format!("{}({})", function, arg_strs.join(", "))
            }
            Expr::Index { array, index } => format!("{}[{}]", self.emit_expr(array), self.emit_expr(index)),
            Expr::Field { object, field } => format!("{}.{}", self.emit_expr(object), field),
            Expr::Swizzle { object, components } => format!("{}.{}", self.emit_expr(object), components),
            Expr::Cast { target_type, expr } => format!("{}({})", target_type.name(), self.emit_expr(expr)),
            Expr::Construction { ty, args } => {
                let arg_strs: Vec<String> = args.iter().map(|a| self.emit_expr(a)).collect();
                format!("{}({})", ty.name(), arg_strs.join(", "))
            }
        }
    }

    pub fn emit_stmt(&mut self, stmt: &Stmt) {
        match stmt {
            Stmt::Expr(e) => {
                let s = self.emit_expr(e);
                self.writeln(&format!("{};", s));
            }
            Stmt::Block(stmts) => {
                self.writeln("{");
                self.indent_in();
                for s in stmts { self.emit_stmt(s); }
                self.indent_out();
                self.writeln("}");
            }
            Stmt::VarDecl { ty, name, qualifier, init } => {
                let qual = match qualifier {
                    Some(VarQualifier::Const) => "const ".to_string(),
                    Some(VarQualifier::In) => "in ".to_string(),
                    Some(VarQualifier::Out) => "out ".to_string(),
                    Some(VarQualifier::Inout) => "inout ".to_string(),
                    _ => String::new(),
                };
                if let Some(init_expr) = init {
                    self.writeln(&format!("{}{} {} = {};", qual, self.emit_type(ty), name, self.emit_expr(init_expr)));
                } else {
                    self.writeln(&format!("{}{} {};", qual, self.emit_type(ty), name));
                }
            }
            Stmt::If { cond, then_body, else_body } => {
                let cond_str = self.emit_expr(cond);
                self.writeln(&format!("if ({}) {{", cond_str));
                self.indent_in();
                self.emit_stmt(then_body);
                self.indent_out();
                if let Some(else_stmt) = else_body {
                    self.writeln("} else {");
                    self.indent_in();
                    self.emit_stmt(else_stmt);
                    self.indent_out();
                    self.writeln("}");
                } else {
                    self.writeln("}");
                }
            }
            Stmt::For { init, cond, step, body } => {
                let init_str = if let Some(i) = init {
                    match i.as_ref() {
                        Stmt::VarDecl { ty, name, init: Some(e), .. } => format!("{} {} = {}", self.emit_type(ty), name, self.emit_expr(e)),
                        Stmt::Expr(e) => self.emit_expr(e),
                        _ => String::new(),
                    }
                } else { String::new() };
                let cond_str = cond.as_ref().map(|c| self.emit_expr(c)).unwrap_or_default();
                let step_str = step.as_ref().map(|s| self.emit_expr(s)).unwrap_or_default();
                self.writeln(&format!("for ({}; {}; {}) {{", init_str, cond_str, step_str));
                self.indent_in();
                self.emit_stmt(body);
                self.indent_out();
                self.writeln("}");
            }
            Stmt::While { cond, body } => {
                self.writeln(&format!("while ({}) {{", self.emit_expr(cond)));
                self.indent_in();
                self.emit_stmt(body);
                self.indent_out();
                self.writeln("}");
            }
            Stmt::DoWhile { body, cond } => {
                self.writeln("do {");
                self.indent_in();
                self.emit_stmt(body);
                self.indent_out();
                self.writeln(&format!("}} while ({});", self.emit_expr(cond)));
            }
            Stmt::Return(val) => {
                if let Some(v) = val {
                    self.writeln(&format!("return {};", self.emit_expr(v)));
                } else {
                    self.writeln("return;");
                }
            }
            Stmt::Break => self.writeln("break;"),
            Stmt::Continue => self.writeln("continue;"),
            Stmt::Discard => self.writeln("discard;"),
        }
    }

    pub fn emit_function(&mut self, func: &FunctionDecl) {
        let params: Vec<String> = func.params.iter().map(|p| {
            let q = match p.qualifier {
                Some(VarQualifier::In) => "in ",
                Some(VarQualifier::Out) => "out ",
                Some(VarQualifier::Inout) => "inout ",
                _ => "",
            };
            format!("{}{} {}", q, self.emit_type(&p.ty), p.name)
        }).collect();
        self.writeln(&format!("{} {}({}) {{", self.emit_type(&func.return_type), func.name, params.join(", ")));
        self.indent_in();
        for stmt in &func.body { self.emit_stmt(stmt); }
        self.indent_out();
        self.writeln("}");
    }

    pub fn emit_ast(&mut self, ast: &ShaderAst) -> String {
        self.emit_header(ast);
        self.write("\n");
        for s in &ast.structs { self.emit_struct(s); self.write("\n"); }
        for u in &ast.uniforms { self.emit_uniform(u); }
        if !ast.uniforms.is_empty() { self.write("\n"); }
        for a in &ast.attributes {
            self.writeln(&format!("in {} {};", self.emit_type(&a.ty), a.name));
        }
        for v in &ast.varyings {
            self.writeln(&format!("out {} {};", self.emit_type(&v.ty), v.name));
        }
        if !ast.attributes.is_empty() || !ast.varyings.is_empty() { self.write("\n"); }
        for func in &ast.functions {
            self.emit_function(func);
            self.write("\n");
        }
        self.output.clone()
    }
}

// ============================================================
// SECTION 11: SPIRV-LIKE BYTECODE
// ============================================================

#[derive(Debug, Clone)]
pub enum SpvOp {
    LoadConst { dest: u32, value: SpvConst },
    Load { dest: u32, src_var: u32 },
    Store { dest_var: u32, src: u32 },
    Add { dest: u32, a: u32, b: u32 },
    Sub { dest: u32, a: u32, b: u32 },
    Mul { dest: u32, a: u32, b: u32 },
    Div { dest: u32, a: u32, b: u32 },
    FuncCall { dest: u32, func_id: u32, args: Vec<u32> },
    Jump { label: u32 },
    JumpIf { cond: u32, label_true: u32, label_false: u32 },
    Label { id: u32 },
    Return { value: Option<u32> },
    Phi { dest: u32, pairs: Vec<(u32, u32)> },
    Convert { dest: u32, src: u32, to_type: SpvTypeId },
    Negate { dest: u32, src: u32 },
    Not { dest: u32, src: u32 },
    Eq { dest: u32, a: u32, b: u32 },
    Ne { dest: u32, a: u32, b: u32 },
    Lt { dest: u32, a: u32, b: u32 },
    Gt { dest: u32, a: u32, b: u32 },
    Le { dest: u32, a: u32, b: u32 },
    Ge { dest: u32, a: u32, b: u32 },
}

#[derive(Debug, Clone)]
pub enum SpvConst {
    Float(f32),
    Int(i32),
    Bool(bool),
    Vec2([f32;2]),
    Vec3([f32;3]),
    Vec4([f32;4]),
}

#[derive(Debug, Clone, Copy)]
pub enum SpvTypeId { Float, Int, Uint, Bool, Vec2, Vec3, Vec4, Mat4 }

#[derive(Debug, Clone)]
pub struct SpvFunction {
    pub id: u32,
    pub name: String,
    pub return_type: SpvTypeId,
    pub instructions: Vec<SpvOp>,
}

#[derive(Debug, Clone)]
pub struct SpvModule {
    pub functions: Vec<SpvFunction>,
    pub global_variables: Vec<(u32, SpvTypeId, String)>,
    pub next_id: u32,
}

impl SpvModule {
    pub fn new() -> Self { Self { functions: Vec::new(), global_variables: Vec::new(), next_id: 1 } }
    pub fn alloc_id(&mut self) -> u32 { let id = self.next_id; self.next_id += 1; id }
}

pub struct SpvCodegen {
    pub module: SpvModule,
    pub var_map: HashMap<String, u32>,
    pub current_fn_instrs: Vec<SpvOp>,
    pub label_counter: u32,
}

impl SpvCodegen {
    pub fn new() -> Self { Self { module: SpvModule::new(), var_map: HashMap::new(), current_fn_instrs: Vec::new(), label_counter: 0 } }
    pub fn new_label(&mut self) -> u32 { let l = self.label_counter; self.label_counter += 1; l }

    pub fn emit_expr_spv(&mut self, expr: &Expr) -> u32 {
        match expr {
            Expr::FloatLit(v) => {
                let dest = self.module.alloc_id();
                self.current_fn_instrs.push(SpvOp::LoadConst { dest, value: SpvConst::Float(*v as f32) });
                dest
            }
            Expr::IntLit(v) => {
                let dest = self.module.alloc_id();
                self.current_fn_instrs.push(SpvOp::LoadConst { dest, value: SpvConst::Int(*v as i32) });
                dest
            }
            Expr::BoolLit(v) => {
                let dest = self.module.alloc_id();
                self.current_fn_instrs.push(SpvOp::LoadConst { dest, value: SpvConst::Bool(*v) });
                dest
            }
            Expr::Ident(name) => {
                let var_id = *self.var_map.get(name).unwrap_or(&0);
                let dest = self.module.alloc_id();
                self.current_fn_instrs.push(SpvOp::Load { dest, src_var: var_id });
                dest
            }
            Expr::Binary { op, left, right } => {
                let a = self.emit_expr_spv(left);
                let b = self.emit_expr_spv(right);
                let dest = self.module.alloc_id();
                let instr = match op {
                    BinaryOp::Add => SpvOp::Add { dest, a, b },
                    BinaryOp::Sub => SpvOp::Sub { dest, a, b },
                    BinaryOp::Mul => SpvOp::Mul { dest, a, b },
                    BinaryOp::Div => SpvOp::Div { dest, a, b },
                    BinaryOp::Eq => SpvOp::Eq { dest, a, b },
                    BinaryOp::Ne => SpvOp::Ne { dest, a, b },
                    BinaryOp::Lt => SpvOp::Lt { dest, a, b },
                    BinaryOp::Gt => SpvOp::Gt { dest, a, b },
                    BinaryOp::Le => SpvOp::Le { dest, a, b },
                    BinaryOp::Ge => SpvOp::Ge { dest, a, b },
                    _ => SpvOp::Add { dest, a, b }, // fallback
                };
                self.current_fn_instrs.push(instr);
                dest
            }
            Expr::Unary { op, operand } => {
                let src = self.emit_expr_spv(operand);
                let dest = self.module.alloc_id();
                let instr = match op {
                    UnaryOp::Negate => SpvOp::Negate { dest, src },
                    UnaryOp::Not => SpvOp::Not { dest, src },
                    _ => SpvOp::Negate { dest, src },
                };
                self.current_fn_instrs.push(instr);
                dest
            }
            _ => { self.module.alloc_id() }
        }
    }
}

// ============================================================
// SECTION 12: WGSL EMITTER
// ============================================================

pub struct WgslEmitter {
    pub output: String,
    pub indent: usize,
}

impl WgslEmitter {
    pub fn new() -> Self { Self { output: String::new(), indent: 0 } }
    fn writeln(&mut self, s: &str) {
        let indent = "    ".repeat(self.indent);
        self.output.push_str(&indent);
        self.output.push_str(s);
        self.output.push('\n');
    }
    fn indent_in(&mut self) { self.indent += 1; }
    fn indent_out(&mut self) { if self.indent > 0 { self.indent -= 1; } }

    pub fn wgsl_type(ty: &ShaderType) -> &'static str {
        match ty {
            ShaderType::Float => "f32",
            ShaderType::Int => "i32",
            ShaderType::Uint => "u32",
            ShaderType::Bool => "bool",
            ShaderType::Vec2 => "vec2<f32>",
            ShaderType::Vec3 => "vec3<f32>",
            ShaderType::Vec4 => "vec4<f32>",
            ShaderType::IVec2 => "vec2<i32>",
            ShaderType::IVec3 => "vec3<i32>",
            ShaderType::IVec4 => "vec4<i32>",
            ShaderType::Mat2 => "mat2x2<f32>",
            ShaderType::Mat3 => "mat3x3<f32>",
            ShaderType::Mat4 => "mat4x4<f32>",
            ShaderType::Sampler2D => "texture_2d<f32>",
            ShaderType::SamplerCube => "texture_cube<f32>",
            _ => "f32",
        }
    }

    pub fn emit_uniform_wgsl(&mut self, u: &UniformDecl, group: u32) {
        let binding = u.binding.unwrap_or(0);
        self.writeln(&format!("@group({}) @binding({}) var<uniform> {}: {};", group, binding, u.name, Self::wgsl_type(&u.ty)));
    }

    pub fn emit_function_wgsl(&mut self, func: &FunctionDecl) {
        let params: Vec<String> = func.params.iter().map(|p| {
            format!("{}: {}", p.name, Self::wgsl_type(&p.ty))
        }).collect();
        let ret = if func.return_type == ShaderType::Void {
            String::new()
        } else {
            format!(" -> {}", Self::wgsl_type(&func.return_type))
        };
        self.writeln(&format!("fn {}({}){} {{", func.name, params.join(", "), ret));
        self.indent_in();
        for stmt in &func.body { self.emit_stmt_wgsl(stmt); }
        self.indent_out();
        self.writeln("}");
    }

    fn emit_expr_wgsl(&self, expr: &Expr) -> String {
        // WGSL expression emission (simplified)
        match expr {
            Expr::FloatLit(v) => format!("{:.6}f", v),
            Expr::IntLit(v) => format!("{}i", v),
            Expr::BoolLit(v) => v.to_string(),
            Expr::Ident(n) => n.clone(),
            Expr::Binary { op, left, right } => {
                let l = self.emit_expr_wgsl(left);
                let r = self.emit_expr_wgsl(right);
                let sym = match op {
                    BinaryOp::Add => "+", BinaryOp::Sub => "-", BinaryOp::Mul => "*", BinaryOp::Div => "/",
                    BinaryOp::Mod => "%", BinaryOp::Eq => "==", BinaryOp::Ne => "!=",
                    BinaryOp::Lt => "<", BinaryOp::Gt => ">", BinaryOp::Le => "<=", BinaryOp::Ge => ">=",
                    BinaryOp::And => "&&", BinaryOp::Or => "||",
                    BinaryOp::BitAnd => "&", BinaryOp::BitOr => "|", BinaryOp::BitXor => "^",
                    BinaryOp::Shl => "<<", BinaryOp::Shr => ">>",
                };
                format!("({} {} {})", l, sym, r)
            }
            Expr::Call { function, args } => {
                let wgsl_fn = match function.as_str() {
                    "sin" => "sin", "cos" => "cos", "sqrt" => "sqrt", "abs" => "abs",
                    "mix" => "mix", "clamp" => "clamp", "dot" => "dot", "cross" => "cross",
                    "normalize" => "normalize", "length" => "length", "pow" => "pow",
                    "floor" => "floor", "ceil" => "ceil", "fract" => "fract",
                    "smoothstep" => "smoothstep", "max" => "max", "min" => "min",
                    "texture" => "textureSample",
                    other => other,
                };
                let arg_strs: Vec<String> = args.iter().map(|a| self.emit_expr_wgsl(a)).collect();
                format!("{}({})", wgsl_fn, arg_strs.join(", "))
            }
            Expr::Field { object, field } => format!("{}.{}", self.emit_expr_wgsl(object), field),
            Expr::Swizzle { object, components } => format!("{}.{}", self.emit_expr_wgsl(object), components),
            Expr::Construction { ty, args } => {
                let arg_strs: Vec<String> = args.iter().map(|a| self.emit_expr_wgsl(a)).collect();
                format!("{}({})", Self::wgsl_type(ty), arg_strs.join(", "))
            }
            _ => String::from("/* expr */"),
        }
    }

    fn emit_stmt_wgsl(&mut self, stmt: &Stmt) {
        match stmt {
            Stmt::Expr(e) => { let s = self.emit_expr_wgsl(e); self.writeln(&format!("{};", s)); }
            Stmt::VarDecl { ty, name, init, qualifier } => {
                let kw = if matches!(qualifier, Some(VarQualifier::Const)) { "let" } else { "var" };
                if let Some(init_expr) = init {
                    self.writeln(&format!("{} {}: {} = {};", kw, name, Self::wgsl_type(ty), self.emit_expr_wgsl(init_expr)));
                } else {
                    self.writeln(&format!("{} {}: {};", kw, name, Self::wgsl_type(ty)));
                }
            }
            Stmt::Return(val) => {
                if let Some(v) = val { self.writeln(&format!("return {};", self.emit_expr_wgsl(v))); }
                else { self.writeln("return;"); }
            }
            Stmt::If { cond, then_body, else_body } => {
                self.writeln(&format!("if ({}) {{", self.emit_expr_wgsl(cond)));
                self.indent_in(); self.emit_stmt_wgsl(then_body); self.indent_out();
                if let Some(e) = else_body {
                    self.writeln("} else {");
                    self.indent_in(); self.emit_stmt_wgsl(e); self.indent_out();
                }
                self.writeln("}");
            }
            Stmt::For { init, cond, step, body } => {
                let cond_str = cond.as_ref().map(|c| self.emit_expr_wgsl(c)).unwrap_or_default();
                self.writeln(&format!("loop {{"));
                self.indent_in();
                self.writeln(&format!("if (!{}) {{ break; }}", cond_str));
                self.emit_stmt_wgsl(body);
                self.indent_out();
                self.writeln("}");
            }
            Stmt::Block(stmts) => {
                self.writeln("{");
                self.indent_in();
                for s in stmts { self.emit_stmt_wgsl(s); }
                self.indent_out();
                self.writeln("}");
            }
            Stmt::Break => self.writeln("break;"),
            Stmt::Continue => self.writeln("continue;"),
            Stmt::Discard => self.writeln("discard;"),
            _ => {}
        }
    }

    pub fn emit_ast_wgsl(&mut self, ast: &ShaderAst) -> String {
        self.writeln("// WGSL generated by ShaderCompiler");
        for u in &ast.uniforms { self.emit_uniform_wgsl(u, 0); }
        for func in &ast.functions { self.emit_function_wgsl(func); self.output.push('\n'); }
        self.output.clone()
    }
}

// ============================================================
// SECTION 13: SHADER REFLECTION
// ============================================================

#[derive(Debug, Clone)]
pub struct ReflectedUniform {
    pub name: String,
    pub ty: ShaderType,
    pub binding: u32,
    pub set: u32,
    pub array_size: u32,
    pub size_bytes: u32,
}

impl ReflectedUniform {
    pub fn size_of_type(ty: &ShaderType) -> u32 {
        match ty {
            ShaderType::Float | ShaderType::Int | ShaderType::Uint | ShaderType::Bool => 4,
            ShaderType::Vec2 | ShaderType::IVec2 | ShaderType::UVec2 => 8,
            ShaderType::Vec3 | ShaderType::IVec3 | ShaderType::UVec3 => 12,
            ShaderType::Vec4 | ShaderType::IVec4 | ShaderType::UVec4 => 16,
            ShaderType::Mat2 => 16,
            ShaderType::Mat3 => 36,
            ShaderType::Mat4 => 64,
            _ => 0,
        }
    }
}

#[derive(Debug, Clone)]
pub struct ReflectedAttribute {
    pub name: String,
    pub ty: ShaderType,
    pub location: u32,
    pub format: VertexFormat,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VertexFormat {
    Float32, Float32x2, Float32x3, Float32x4,
    Sint32, Sint32x2, Sint32x3, Sint32x4,
    Uint32, Uint32x2, Uint32x3, Uint32x4,
}

#[derive(Debug, Clone, Default)]
pub struct ShaderReflection {
    pub uniforms: Vec<ReflectedUniform>,
    pub attributes: Vec<ReflectedAttribute>,
    pub varyings: Vec<ReflectedAttribute>,
    pub used_builtins: Vec<String>,
    pub struct_layouts: Vec<String>,
    pub push_constants: Vec<ReflectedUniform>,
    pub storage_buffers: Vec<ReflectedUniform>,
    pub entry_points: Vec<String>,
}

impl ShaderReflection {
    pub fn new() -> Self { Self::default() }

    pub fn add_uniform(&mut self, u: ReflectedUniform) {
        self.uniforms.push(u);
    }

    pub fn add_attribute(&mut self, a: ReflectedAttribute) {
        self.attributes.push(a);
    }


}

// ── Shader Program Representation ────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderProgram {
    pub id: u32,
    pub name: String,
    pub vertex_source: String,
    pub fragment_source: String,
    pub geometry_source: Option<String>,
    pub compute_source: Option<String>,
    pub defines: HashMap<String, String>,
    pub version: String,
    pub compiled: bool,
    pub compile_errors: Vec<String>,
    pub compile_warnings: Vec<String>,
}

impl ShaderProgram {
    pub fn new(id: u32, name: impl Into<String>) -> Self {
        Self { id, name: name.into(), vertex_source: String::new(), fragment_source: String::new(), geometry_source: None, compute_source: None, defines: HashMap::new(), version: "450".into(), compiled: false, compile_errors: Vec::new(), compile_warnings: Vec::new() }
    }
    pub fn with_vertex(mut self, src: impl Into<String>) -> Self { self.vertex_source = src.into(); self }
    pub fn with_fragment(mut self, src: impl Into<String>) -> Self { self.fragment_source = src.into(); self }
    pub fn add_define(&mut self, key: impl Into<String>, val: impl Into<String>) { self.defines.insert(key.into(), val.into()); }
    pub fn is_compute(&self) -> bool { self.compute_source.is_some() }
    pub fn has_geometry(&self) -> bool { self.geometry_source.is_some() }
    pub fn is_valid(&self) -> bool { self.compiled && self.compile_errors.is_empty() }
    pub fn error_count(&self) -> usize { self.compile_errors.len() }
    pub fn warning_count(&self) -> usize { self.compile_warnings.len() }
    pub fn add_error(&mut self, err: impl Into<String>) { self.compile_errors.push(err.into()); }
    pub fn add_warning(&mut self, warn: impl Into<String>) { self.compile_warnings.push(warn.into()); }
    pub fn clear_diagnostics(&mut self) { self.compile_errors.clear(); self.compile_warnings.clear(); }
    pub fn mark_compiled(&mut self) { self.compiled = true; }
}

#[derive(Clone, Debug)]
pub struct ShaderProgramRegistry {
    pub programs: HashMap<u32, ShaderProgram>,
    pub next_id: u32,
    pub active_program: Option<u32>,
}

impl ShaderProgramRegistry {
    pub fn new() -> Self { Self { programs: HashMap::new(), next_id: 1, active_program: None } }
    pub fn add(&mut self, prog: ShaderProgram) -> u32 {
        let id = self.next_id; self.next_id += 1;
        self.programs.insert(id, prog);
        id
    }
    pub fn get(&self, id: u32) -> Option<&ShaderProgram> { self.programs.get(&id) }
    pub fn get_mut(&mut self, id: u32) -> Option<&mut ShaderProgram> { self.programs.get_mut(&id) }
    pub fn find_by_name(&self, name: &str) -> Option<&ShaderProgram> { self.programs.values().find(|p| p.name == name) }
    pub fn count(&self) -> usize { self.programs.len() }
    pub fn valid_count(&self) -> usize { self.programs.values().filter(|p| p.is_valid()).count() }
    pub fn set_active(&mut self, id: u32) { self.active_program = Some(id); }
    pub fn remove(&mut self, id: u32) -> bool { self.programs.remove(&id).is_some() }
}

impl Default for ShaderProgramRegistry {
    fn default() -> Self { Self::new() }
}

// ── Shader Type System ────────────────────────────────────────────────────────

#[derive(Clone, Debug, PartialEq)]
pub enum ShaderDataType {
    Void,
    Bool, BVec2, BVec3, BVec4,
    Int, IVec2, IVec3, IVec4,
    UInt, UVec2, UVec3, UVec4,
    Float, Vec2, Vec3, Vec4,
    Mat2, Mat3, Mat4,
    Mat2x3, Mat2x4, Mat3x2, Mat3x4, Mat4x2, Mat4x3,
    Sampler2D, Sampler3D, SamplerCube, Sampler2DArray, SamplerShadow,
    Image2D, Image3D, ImageCube,
    Struct(String),
    Array(Box<ShaderDataType>, Option<u32>),
}

impl ShaderDataType {
    pub fn byte_size(&self) -> u32 {
        match self {
            ShaderDataType::Bool | ShaderDataType::Int | ShaderDataType::UInt | ShaderDataType::Float => 4,
            ShaderDataType::BVec2 | ShaderDataType::IVec2 | ShaderDataType::UVec2 | ShaderDataType::Vec2 => 8,
            ShaderDataType::BVec3 | ShaderDataType::IVec3 | ShaderDataType::UVec3 | ShaderDataType::Vec3 => 12,
            ShaderDataType::BVec4 | ShaderDataType::IVec4 | ShaderDataType::UVec4 | ShaderDataType::Vec4 => 16,
            ShaderDataType::Mat2 => 16, ShaderDataType::Mat3 => 36, ShaderDataType::Mat4 => 64,
            ShaderDataType::Array(inner, Some(n)) => inner.byte_size() * n,
            _ => 0,
        }
    }
    pub fn is_sampler(&self) -> bool { matches!(self, ShaderDataType::Sampler2D | ShaderDataType::Sampler3D | ShaderDataType::SamplerCube | ShaderDataType::Sampler2DArray | ShaderDataType::SamplerShadow) }
    pub fn is_matrix(&self) -> bool { matches!(self, ShaderDataType::Mat2 | ShaderDataType::Mat3 | ShaderDataType::Mat4 | ShaderDataType::Mat2x3 | ShaderDataType::Mat2x4 | ShaderDataType::Mat3x2 | ShaderDataType::Mat3x4 | ShaderDataType::Mat4x2 | ShaderDataType::Mat4x3) }
    pub fn is_vector(&self) -> bool { matches!(self, ShaderDataType::Vec2 | ShaderDataType::Vec3 | ShaderDataType::Vec4 | ShaderDataType::IVec2 | ShaderDataType::IVec3 | ShaderDataType::IVec4 | ShaderDataType::UVec2 | ShaderDataType::UVec3 | ShaderDataType::UVec4 | ShaderDataType::BVec2 | ShaderDataType::BVec3 | ShaderDataType::BVec4) }
    pub fn glsl_name(&self) -> &'static str {
        match self {
            ShaderDataType::Void => "void", ShaderDataType::Bool => "bool",
            ShaderDataType::Int => "int", ShaderDataType::UInt => "uint",
            ShaderDataType::Float => "float", ShaderDataType::Vec2 => "vec2",
            ShaderDataType::Vec3 => "vec3", ShaderDataType::Vec4 => "vec4",
            ShaderDataType::Mat4 => "mat4", ShaderDataType::Mat3 => "mat3",
            ShaderDataType::Mat2 => "mat2", ShaderDataType::Sampler2D => "sampler2D",
            ShaderDataType::SamplerCube => "samplerCube",
            _ => "unknown",
        }
    }
}

// ── Shader Variable ───────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderVariable {
    pub name: String,
    pub data_type: ShaderDataType,
    pub qualifier: ShaderQualifier,
    pub location: Option<u32>,
    pub binding: Option<u32>,
    pub set: Option<u32>,
    pub is_builtin: bool,
    pub comment: String,
}

#[derive(Clone, Debug, PartialEq)]
pub enum ShaderQualifier { In, Out, InOut, Uniform, Const, Buffer, Shared }

impl ShaderVariable {
    pub fn uniform(name: impl Into<String>, data_type: ShaderDataType) -> Self {
        Self { name: name.into(), data_type, qualifier: ShaderQualifier::Uniform, location: None, binding: None, set: None, is_builtin: false, comment: String::new() }
    }
    pub fn input(name: impl Into<String>, data_type: ShaderDataType, location: u32) -> Self {
        Self { name: name.into(), data_type, qualifier: ShaderQualifier::In, location: Some(location), binding: None, set: None, is_builtin: false, comment: String::new() }
    }
    pub fn output(name: impl Into<String>, data_type: ShaderDataType, location: u32) -> Self {
        Self { name: name.into(), data_type, qualifier: ShaderQualifier::Out, location: Some(location), binding: None, set: None, is_builtin: false, comment: String::new() }
    }
    pub fn with_binding(mut self, binding: u32, set: u32) -> Self { self.binding = Some(binding); self.set = Some(set); self }
    pub fn is_uniform(&self) -> bool { self.qualifier == ShaderQualifier::Uniform }
    pub fn is_input(&self) -> bool { self.qualifier == ShaderQualifier::In }
    pub fn is_output(&self) -> bool { self.qualifier == ShaderQualifier::Out }
    pub fn size_bytes(&self) -> u32 { self.data_type.byte_size() }
}

// ── Shader Function ───────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderFunction {
    pub name: String,
    pub return_type: ShaderDataType,
    pub parameters: Vec<ShaderVariable>,
    pub body: String,
    pub is_builtin: bool,
    pub line_start: u32,
    pub line_end: u32,
    pub comment: String,
}

impl ShaderFunction {
    pub fn new(name: impl Into<String>, return_type: ShaderDataType) -> Self {
        Self { name: name.into(), return_type, parameters: Vec::new(), body: String::new(), is_builtin: false, line_start: 0, line_end: 0, comment: String::new() }
    }
    pub fn add_param(&mut self, param: ShaderVariable) { self.parameters.push(param); }
    pub fn param_count(&self) -> usize { self.parameters.len() }
    pub fn is_main(&self) -> bool { self.name == "main" }
    pub fn signature(&self) -> String {
        let params: Vec<_> = self.parameters.iter().map(|p| format!("{} {}", p.data_type.glsl_name(), p.name)).collect();
        format!("{} {}({})", self.return_type.glsl_name(), self.name, params.join(", "))
    }
}

// ── Shader Struct Type ────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderStruct {
    pub name: String,
    pub fields: Vec<ShaderVariable>,
    pub comment: String,
    pub std140_layout: bool,
}

impl ShaderStruct {
    pub fn new(name: impl Into<String>) -> Self { Self { name: name.into(), fields: Vec::new(), comment: String::new(), std140_layout: false } }
    pub fn add_field(&mut self, field: ShaderVariable) { self.fields.push(field); }
    pub fn size_bytes(&self) -> u32 { self.fields.iter().map(|f| f.size_bytes()).sum() }
    pub fn std140_size(&self) -> u32 {
        let mut size = 0u32;
        for f in &self.fields {
            let field_size = f.size_bytes();
            let align = field_size.max(4).next_power_of_two().min(16);
            size = (size + align - 1) & !(align - 1);
            size += field_size;
        }
        (size + 15) & !15
    }
    pub fn field_count(&self) -> usize { self.fields.len() }
    pub fn has_field(&self, name: &str) -> bool { self.fields.iter().any(|f| f.name == name) }
    pub fn generate_glsl(&self) -> String {
        let mut s = format!("struct {} {{\n", self.name);
        for f in &self.fields { s += &format!("    {} {};\n", f.data_type.glsl_name(), f.name); }
        s += "};\n";
        s
    }
}

// ── Shader Diagnostic ─────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderDiagnostic {
    pub kind: DiagnosticKind,
    pub message: String,
    pub line: u32,
    pub column: u32,
    pub file: String,
    pub code: u32,
    pub suggestion: Option<String>,
}

#[derive(Clone, Debug, PartialEq)]
pub enum DiagnosticKind { Error, Warning, Info, Hint }

impl ShaderDiagnostic {
    pub fn error(msg: impl Into<String>, line: u32) -> Self {
        Self { kind: DiagnosticKind::Error, message: msg.into(), line, column: 0, file: String::new(), code: 0, suggestion: None }
    }
    pub fn warning(msg: impl Into<String>, line: u32) -> Self {
        Self { kind: DiagnosticKind::Warning, message: msg.into(), line, column: 0, file: String::new(), code: 0, suggestion: None }
    }
    pub fn with_suggestion(mut self, s: impl Into<String>) -> Self { self.suggestion = Some(s.into()); self }
    pub fn is_error(&self) -> bool { self.kind == DiagnosticKind::Error }
    pub fn is_warning(&self) -> bool { self.kind == DiagnosticKind::Warning }
    pub fn format(&self) -> String {
        let prefix = match self.kind { DiagnosticKind::Error => "error", DiagnosticKind::Warning => "warning", DiagnosticKind::Info => "info", DiagnosticKind::Hint => "hint" };
        format!("[{}] {}:{} — {}", prefix, self.file, self.line, self.message)
    }
}

#[derive(Clone, Debug, Default)]
pub struct DiagnosticList {
    pub items: Vec<ShaderDiagnostic>,
}

impl DiagnosticList {
    pub fn new() -> Self { Self::default() }
    pub fn push(&mut self, d: ShaderDiagnostic) { self.items.push(d); }
    pub fn errors(&self) -> Vec<&ShaderDiagnostic> { self.items.iter().filter(|d| d.is_error()).collect() }
    pub fn warnings(&self) -> Vec<&ShaderDiagnostic> { self.items.iter().filter(|d| d.is_warning()).collect() }
    pub fn has_errors(&self) -> bool { self.items.iter().any(|d| d.is_error()) }
    pub fn error_count(&self) -> usize { self.items.iter().filter(|d| d.is_error()).count() }
    pub fn warning_count(&self) -> usize { self.items.iter().filter(|d| d.is_warning()).count() }
    pub fn clear(&mut self) { self.items.clear(); }
    pub fn total(&self) -> usize { self.items.len() }
}

// ── Shader Preprocessor ───────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderPreprocessor {
    pub defines: HashMap<String, String>,
    pub include_paths: Vec<String>,
    pub max_include_depth: u32,
    pub strip_comments: bool,
    pub expand_macros: bool,
}

impl ShaderPreprocessor {
    pub fn new() -> Self {
        Self { defines: HashMap::new(), include_paths: Vec::new(), max_include_depth: 10, strip_comments: true, expand_macros: true }
    }
    pub fn define(&mut self, key: impl Into<String>, value: impl Into<String>) { self.defines.insert(key.into(), value.into()); }
    pub fn undefine(&mut self, key: &str) { self.defines.remove(key); }
    pub fn add_include_path(&mut self, path: impl Into<String>) { self.include_paths.push(path.into()); }
    pub fn preprocess(&self, source: &str) -> String {
        let mut output = String::with_capacity(source.len());
        for line in source.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with("#define") {
                output.push_str(line);
            } else if trimmed.starts_with("//") && self.strip_comments {
                // skip
            } else {
                let mut processed = line.to_string();
                if self.expand_macros {
                    for (k, v) in &self.defines { processed = processed.replace(k.as_str(), v.as_str()); }
                }
                output.push_str(&processed);
            }
            output.push('\n');
        }
        output
    }
    pub fn is_defined(&self, key: &str) -> bool { self.defines.contains_key(key) }
    pub fn define_count(&self) -> usize { self.defines.len() }
}

impl Default for ShaderPreprocessor {
    fn default() -> Self { Self::new() }
}

// ── Shader Uniform Block ──────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct UniformBlock {
    pub name: String,
    pub binding: u32,
    pub set: u32,
    pub fields: Vec<ShaderVariable>,
    pub std140: bool,
    pub dynamic_offset: bool,
}

impl UniformBlock {
    pub fn new(name: impl Into<String>, binding: u32) -> Self {
        Self { name: name.into(), binding, set: 0, fields: Vec::new(), std140: true, dynamic_offset: false }
    }
    pub fn add_field(&mut self, f: ShaderVariable) { self.fields.push(f); }
    pub fn size_bytes(&self) -> u32 {
        let mut size = 0u32;
        for f in &self.fields {
            let fs = f.size_bytes();
            let align = fs.max(4).next_power_of_two().min(16);
            size = (size + align - 1) & !(align - 1);
            size += fs;
        }
        (size + 15) & !15
    }
    pub fn generate_glsl(&self) -> String {
        let mut s = format!("layout(std140, binding={}) uniform {} {{\n", self.binding, self.name);
        for f in &self.fields { s += &format!("    {} {};\n", f.data_type.glsl_name(), f.name); }
        s += "};\n";
        s
    }
    pub fn field_count(&self) -> usize { self.fields.len() }
}

// ── Shader Pipeline State ─────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct PipelineState {
    pub blend_enabled: bool,
    pub blend_src: BlendFactor,
    pub blend_dst: BlendFactor,
    pub blend_op: BlendOp,
    pub depth_test: bool,
    pub depth_write: bool,
    pub depth_func: CompareFunc,
    pub cull_mode: CullMode,
    pub front_face: FrontFace,
    pub scissor_test: bool,
    pub stencil_test: bool,
    pub polygon_mode: PolygonMode,
    pub line_width: f32,
    pub point_size: f32,
}

#[derive(Clone, Debug, PartialEq)]
pub enum BlendFactor { Zero, One, SrcAlpha, OneMinusSrcAlpha, DstAlpha, OneMinusDstAlpha, SrcColor, OneMinusSrcColor, ConstantAlpha }
#[derive(Clone, Debug, PartialEq)]
pub enum BlendOp { Add, Subtract, ReverseSubtract, Min, Max }
#[derive(Clone, Debug, PartialEq)]
pub enum CompareFunc { Never, Less, Equal, LessEqual, Greater, NotEqual, GreaterEqual, Always }
#[derive(Clone, Debug, PartialEq)]
pub enum CullMode { None, Front, Back, FrontAndBack }
#[derive(Clone, Debug, PartialEq)]
pub enum FrontFace { Clockwise, CounterClockwise }
#[derive(Clone, Debug, PartialEq)]
pub enum PolygonMode { Fill, Line, Point }

impl Default for PipelineState {
    fn default() -> Self {
        Self { blend_enabled: false, blend_src: BlendFactor::SrcAlpha, blend_dst: BlendFactor::OneMinusSrcAlpha, blend_op: BlendOp::Add, depth_test: true, depth_write: true, depth_func: CompareFunc::Less, cull_mode: CullMode::Back, front_face: FrontFace::CounterClockwise, scissor_test: false, stencil_test: false, polygon_mode: PolygonMode::Fill, line_width: 1.0, point_size: 1.0 }
    }
}

impl PipelineState {
    pub fn transparent() -> Self { Self { blend_enabled: true, depth_write: false, ..Default::default() } }
    pub fn additive() -> Self { Self { blend_enabled: true, blend_src: BlendFactor::One, blend_dst: BlendFactor::One, blend_op: BlendOp::Add, depth_write: false, ..Default::default() } }
    pub fn wireframe() -> Self { Self { polygon_mode: PolygonMode::Line, cull_mode: CullMode::None, ..Default::default() } }
    pub fn opaque() -> Self { Self::default() }
    pub fn is_transparent(&self) -> bool { self.blend_enabled }
    pub fn needs_sort(&self) -> bool { self.blend_enabled && !self.depth_write }
}

// ── Shader Compiler Constants ─────────────────────────────────────────────────

pub const SHADER_MAX_UNIFORMS: usize = 128;
pub const SHADER_MAX_ATTRIBUTES: usize = 32;
pub const SHADER_MAX_VARYINGS: usize = 32;
pub const SHADER_MAX_TEXTURE_UNITS: usize = 32;
pub const SHADER_MAX_UNIFORM_BLOCK_SIZE: u32 = 65536;
pub const SHADER_MAX_INCLUDE_DEPTH: u32 = 16;
pub const SHADER_VERSION_GLSL: &str = "450";
pub const SHADER_VERSION_WGSL: &str = "1.0";
pub const SHADER_MAX_SOURCE_LINES: usize = 10000;
pub const SHADER_MAX_FUNCTIONS: usize = 256;
pub const SHADER_MAX_STRUCTS: usize = 64;
pub const SHADER_MAX_PROGRAMS: usize = 1024;
pub const SHADER_CACHE_SIZE: usize = 256;
pub const SHADER_MAX_PUSH_CONSTANT_SIZE: u32 = 128;

pub fn shader_compiler_info() -> &'static str { "ShaderCompiler v1.0 — GLSL/WGSL, preprocessor, reflection, pipeline state" }


// ── Shader AST Nodes ──────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub enum ShaderExpr {
    Literal(ShaderLiteral),
    Ident(String),
    Binary { op: BinaryOp, lhs: Box<ShaderExpr>, rhs: Box<ShaderExpr> },
    Unary { op: UnaryOp, expr: Box<ShaderExpr> },
    Call { name: String, args: Vec<ShaderExpr> },
    Index { array: Box<ShaderExpr>, index: Box<ShaderExpr> },
    Field { object: Box<ShaderExpr>, field: String },
    Ternary { cond: Box<ShaderExpr>, then: Box<ShaderExpr>, else_: Box<ShaderExpr> },
    Cast { to: ShaderDataType, expr: Box<ShaderExpr> },
    Assign { target: Box<ShaderExpr>, value: Box<ShaderExpr> },
}

#[derive(Clone, Debug)]
pub enum ShaderLiteral {
    Int(i64), Float(f64), Bool(bool), String(String),
}

#[derive(Clone, Debug, PartialEq)]
pub enum BinaryOpEx {
    Add, Sub, Mul, Div, Mod,
    Eq, Ne, Lt, Gt, Le, Ge,
    And, Or, BitAnd, BitOr, BitXor,
    Shl, Shr,
    AddAssign, SubAssign, MulAssign, DivAssign,
}

#[derive(Clone, Debug, PartialEq)]
pub enum UnaryOpEx { Neg, Not, BitNot, PreInc, PreDec, PostInc, PostDec }

impl BinaryOpEx {
    pub fn is_comparison(&self) -> bool { matches!(self, BinaryOpEx::Eq | BinaryOpEx::Ne | BinaryOpEx::Lt | BinaryOpEx::Gt | BinaryOpEx::Le | BinaryOpEx::Ge) }
    pub fn is_logical(&self) -> bool { matches!(self, BinaryOpEx::And | BinaryOpEx::Or) }
    pub fn is_arithmetic(&self) -> bool { matches!(self, BinaryOpEx::Add | BinaryOpEx::Sub | BinaryOpEx::Mul | BinaryOpEx::Div | BinaryOpEx::Mod) }
    pub fn glsl_symbol(&self) -> &'static str {
        match self {
            BinaryOpEx::Add => "+", BinaryOpEx::Sub => "-", BinaryOpEx::Mul => "*", BinaryOpEx::Div => "/",
            BinaryOpEx::Mod => "%", BinaryOpEx::Eq => "==", BinaryOpEx::Ne => "!=", BinaryOpEx::Lt => "<",
            BinaryOpEx::Gt => ">", BinaryOpEx::Le => "<=", BinaryOpEx::Ge => ">=", BinaryOpEx::And => "&&",
            BinaryOpEx::Or => "||", BinaryOpEx::BitAnd => "&", BinaryOpEx::BitOr => "|", BinaryOpEx::BitXor => "^",
            BinaryOpEx::Shl => "<<", BinaryOpEx::Shr => ">>", BinaryOpEx::AddAssign => "+=",
            BinaryOpEx::SubAssign => "-=", BinaryOpEx::MulAssign => "*=", BinaryOpEx::DivAssign => "/=",
        }
    }
}

#[derive(Clone, Debug)]
pub enum ShaderStmt {
    Decl { var: ShaderVariable, initializer: Option<ShaderExpr> },
    Expr(ShaderExpr),
    If { cond: ShaderExpr, then: Vec<ShaderStmt>, else_: Option<Vec<ShaderStmt>> },
    For { init: Option<Box<ShaderStmt>>, cond: Option<ShaderExpr>, update: Option<ShaderExpr>, body: Vec<ShaderStmt> },
    While { cond: ShaderExpr, body: Vec<ShaderStmt> },
    Return(Option<ShaderExpr>),
    Break,
    Continue,
    Discard,
    Block(Vec<ShaderStmt>),
}

// ── Shader Code Generator ─────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderCodeGen {
    pub target: CodeGenTarget,
    pub indent_size: usize,
    pub use_precision_qualifiers: bool,
    pub emit_line_directives: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub enum CodeGenTarget { Glsl450, Glsl300Es, Wgsl, Hlsl50, Msl20 }

impl ShaderCodeGen {
    pub fn new(target: CodeGenTarget) -> Self { Self { target, indent_size: 4, use_precision_qualifiers: false, emit_line_directives: false } }
    pub fn glsl450() -> Self { Self::new(CodeGenTarget::Glsl450) }
    pub fn wgsl() -> Self { Self::new(CodeGenTarget::Wgsl) }
    pub fn version_directive(&self) -> String {
        match self.target {
            CodeGenTarget::Glsl450 => "#version 450\n".into(),
            CodeGenTarget::Glsl300Es => "#version 300 es\nprecision highp float;\n".into(),
            CodeGenTarget::Wgsl => "// WGSL\n".into(),
            CodeGenTarget::Hlsl50 => "// HLSL 5.0\n".into(),
            CodeGenTarget::Msl20 => "#include <metal_stdlib>\nusing namespace metal;\n".into(),
        }
    }
    pub fn emit_uniform(&self, var: &ShaderVariable) -> String {
        match self.target {
            CodeGenTarget::Glsl450 | CodeGenTarget::Glsl300Es => {
                let layout = var.binding.map(|b| format!("layout(binding={}) ", b)).unwrap_or_default();
                format!("{}uniform {} {};", layout, var.data_type.glsl_name(), var.name)
            }
            _ => format!("// uniform {} {}", var.data_type.glsl_name(), var.name),
        }
    }
    pub fn emit_input(&self, var: &ShaderVariable) -> String {
        let loc = var.location.map(|l| format!("layout(location={}) ", l)).unwrap_or_default();
        format!("{}in {} {};", loc, var.data_type.glsl_name(), var.name)
    }
    pub fn emit_output(&self, var: &ShaderVariable) -> String {
        let loc = var.location.map(|l| format!("layout(location={}) ", l)).unwrap_or_default();
        format!("{}out {} {};", loc, var.data_type.glsl_name(), var.name)
    }
    pub fn emit_struct(&self, s: &ShaderStruct) -> String { s.generate_glsl() }
    pub fn emit_function_sig(&self, f: &ShaderFunction) -> String { f.signature() }
    pub fn is_glsl(&self) -> bool { matches!(self.target, CodeGenTarget::Glsl450 | CodeGenTarget::Glsl300Es) }
}

impl Default for ShaderCodeGen {
    fn default() -> Self { Self::glsl450() }
}

// ── Shader Optimizer ──────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderOptimizer {
    pub level: OptimizationLevel,
    pub fold_constants: bool,
    pub dead_code_elimination: bool,
    pub inline_functions: bool,
    pub common_subexpr_elim: bool,
    pub loop_unroll_threshold: u32,
    pub vectorize: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub enum OptimizationLevel { None, Low, Medium, High, Aggressive }

impl ShaderOptimizer {
    pub fn new(level: OptimizationLevel) -> Self {
        let (fold, dce, inline, cse, unroll, vec) = match level {
            OptimizationLevel::None => (false, false, false, false, 0, false),
            OptimizationLevel::Low => (true, true, false, false, 4, false),
            OptimizationLevel::Medium => (true, true, true, true, 8, false),
            OptimizationLevel::High => (true, true, true, true, 16, true),
            OptimizationLevel::Aggressive => (true, true, true, true, 64, true),
        };
        Self { level, fold_constants: fold, dead_code_elimination: dce, inline_functions: inline, common_subexpr_elim: cse, loop_unroll_threshold: unroll, vectorize: vec }
    }
    pub fn none() -> Self { Self::new(OptimizationLevel::None) }
    pub fn release() -> Self { Self::new(OptimizationLevel::High) }
    pub fn debug() -> Self { Self::new(OptimizationLevel::None) }
    pub fn any_optimization_enabled(&self) -> bool { self.level != OptimizationLevel::None }
}

impl Default for ShaderOptimizer {
    fn default() -> Self { Self::new(OptimizationLevel::Medium) }
}

// ── Shader Cache ──────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderCacheEntry {
    pub source_hash: u64,
    pub defines_hash: u64,
    pub compiled_bytes: Vec<u8>,
    pub target: CodeGenTarget,
    pub created_at: u64,
    pub hit_count: u32,
}

impl ShaderCacheEntry {
    pub fn new(source_hash: u64, defines_hash: u64, bytes: Vec<u8>, target: CodeGenTarget) -> Self {
        Self { source_hash, defines_hash, compiled_bytes: bytes, target, created_at: 0, hit_count: 0 }
    }
    pub fn is_stale(&self, source_hash: u64, defines_hash: u64) -> bool {
        self.source_hash != source_hash || self.defines_hash != defines_hash
    }
    pub fn record_hit(&mut self) { self.hit_count += 1; }
    pub fn size_bytes(&self) -> usize { self.compiled_bytes.len() }
}

#[derive(Clone, Debug)]
pub struct ShaderCache {
    pub entries: HashMap<String, ShaderCacheEntry>,
    pub max_size: usize,
    pub total_hits: u64,
    pub total_misses: u64,
    pub eviction_policy: CacheEvictionPolicy,
}

#[derive(Clone, Debug, PartialEq)]
pub enum CacheEvictionPolicy { Lru, Fifo, LeastHits }

impl ShaderCache {
    pub fn new(max_size: usize) -> Self { Self { entries: HashMap::new(), max_size, total_hits: 0, total_misses: 0, eviction_policy: CacheEvictionPolicy::Lru } }
    pub fn get(&mut self, key: &str) -> Option<&ShaderCacheEntry> {
        if let Some(e) = self.entries.get_mut(key) { e.record_hit(); self.total_hits += 1; Some(e) } else { self.total_misses += 1; None }
    }
    pub fn insert(&mut self, key: String, entry: ShaderCacheEntry) {
        if self.entries.len() >= self.max_size { self.evict(); }
        self.entries.insert(key, entry);
    }
    fn evict(&mut self) {
        if let Some(key) = self.entries.keys().next().cloned() { self.entries.remove(&key); }
    }
    pub fn hit_rate(&self) -> f32 {
        let total = self.total_hits + self.total_misses;
        if total == 0 { 0.0 } else { self.total_hits as f32 / total as f32 }
    }
    pub fn clear(&mut self) { self.entries.clear(); }
    pub fn size(&self) -> usize { self.entries.len() }
    pub fn total_bytes(&self) -> usize { self.entries.values().map(|e| e.size_bytes()).sum() }
}

impl Default for ShaderCache {
    fn default() -> Self { Self::new(SHADER_CACHE_SIZE) }
}

// ── Shader Template System ────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderTemplate {
    pub id: u32,
    pub name: String,
    pub description: String,
    pub vertex_template: String,
    pub fragment_template: String,
    pub parameters: Vec<ShaderTemplateParam>,
    pub category: String,
    pub tags: Vec<String>,
    pub is_builtin: bool,
}

#[derive(Clone, Debug)]
pub struct ShaderTemplateParam {
    pub name: String,
    pub param_type: TemplateParamType,
    pub default_value: String,
    pub description: String,
    pub required: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub enum TemplateParamType { Bool, Int, Float, String, Color, Texture, Vec2, Vec3, Vec4 }

impl ShaderTemplate {
    pub fn new(id: u32, name: impl Into<String>) -> Self {
        Self { id, name: name.into(), description: String::new(), vertex_template: String::new(), fragment_template: String::new(), parameters: Vec::new(), category: "general".into(), tags: Vec::new(), is_builtin: false }
    }
    pub fn add_param(&mut self, param: ShaderTemplateParam) { self.parameters.push(param); }
    pub fn instantiate(&self, params: &HashMap<String, String>) -> (String, String) {
        let mut vert = self.vertex_template.clone();
        let mut frag = self.fragment_template.clone();
        for p in &self.parameters {
            let val = params.get(&p.name).unwrap_or(&p.default_value);
            let placeholder = format!("{{{{{}}}}}", p.name);
            vert = vert.replace(&placeholder, val);
            frag = frag.replace(&placeholder, val);
        }
        (vert, frag)
    }
    pub fn param_count(&self) -> usize { self.parameters.len() }
    pub fn required_params(&self) -> Vec<&ShaderTemplateParam> { self.parameters.iter().filter(|p| p.required).collect() }
}

#[derive(Clone, Debug)]
pub struct ShaderTemplateLibrary {
    pub templates: HashMap<u32, ShaderTemplate>,
    pub next_id: u32,
    pub categories: HashSet<String>,
}

impl ShaderTemplateLibrary {
    pub fn new() -> Self { Self { templates: HashMap::new(), next_id: 1, categories: HashSet::new() } }
    pub fn add(&mut self, mut t: ShaderTemplate) -> u32 {
        let id = self.next_id; self.next_id += 1;
        t.id = id;
        self.categories.insert(t.category.clone());
        self.templates.insert(id, t);
        id
    }
    pub fn get(&self, id: u32) -> Option<&ShaderTemplate> { self.templates.get(&id) }
    pub fn by_category(&self, cat: &str) -> Vec<&ShaderTemplate> { self.templates.values().filter(|t| t.category == cat).collect() }
    pub fn find_by_name(&self, name: &str) -> Option<&ShaderTemplate> { self.templates.values().find(|t| t.name == name) }
    pub fn count(&self) -> usize { self.templates.len() }
}

impl Default for ShaderTemplateLibrary {
    fn default() -> Self { Self::new() }
}

// ── Shader Live Reload ────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderFileWatcher {
    pub watched_files: HashMap<String, ShaderWatchEntry>,
    pub reload_queue: VecDeque<String>,
    pub auto_reload: bool,
    pub debounce_ms: u32,
}

#[derive(Clone, Debug)]
pub struct ShaderWatchEntry {
    pub path: String,
    pub last_modified: u64,
    pub shader_ids: Vec<u32>,
    pub reload_count: u32,
}

impl ShaderFileWatcher {
    pub fn new() -> Self { Self { watched_files: HashMap::new(), reload_queue: VecDeque::new(), auto_reload: true, debounce_ms: 500 } }
    pub fn watch(&mut self, path: impl Into<String>, shader_id: u32) {
        let p = path.into();
        self.watched_files.entry(p.clone()).or_insert(ShaderWatchEntry { path: p, last_modified: 0, shader_ids: Vec::new(), reload_count: 0 }).shader_ids.push(shader_id);
    }
    pub fn mark_modified(&mut self, path: &str) {
        if let Some(entry) = self.watched_files.get_mut(path) {
            entry.reload_count += 1;
            if !self.reload_queue.contains(&path.to_string()) { self.reload_queue.push_back(path.to_string()); }
        }
    }
    pub fn next_reload(&mut self) -> Option<String> { self.reload_queue.pop_front() }
    pub fn shader_ids_for(&self, path: &str) -> Vec<u32> { self.watched_files.get(path).map(|e| e.shader_ids.clone()).unwrap_or_default() }
    pub fn unwatch(&mut self, path: &str) { self.watched_files.remove(path); }
    pub fn watched_count(&self) -> usize { self.watched_files.len() }
}

impl Default for ShaderFileWatcher {
    fn default() -> Self { Self::new() }
}

// ── Shader Variant System ─────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderVariant {
    pub id: u32,
    pub base_program_id: u32,
    pub keywords: Vec<String>,
    pub compiled_id: Option<u32>,
    pub is_fallback: bool,
}

impl ShaderVariant {
    pub fn new(id: u32, base_id: u32) -> Self { Self { id, base_program_id: base_id, keywords: Vec::new(), compiled_id: None, is_fallback: false } }
    pub fn with_keyword(mut self, kw: impl Into<String>) -> Self { self.keywords.push(kw.into()); self }
    pub fn matches_keywords(&self, keywords: &[&str]) -> bool { keywords.iter().all(|kw| self.keywords.iter().any(|k| k == kw)) }
    pub fn keyword_hash(&self) -> u64 {
        let mut sorted = self.keywords.clone(); sorted.sort();
        sorted.iter().fold(0u64, |h, k| h.wrapping_mul(31).wrapping_add(k.bytes().map(|b| b as u64).sum::<u64>()))
    }
}

#[derive(Clone, Debug)]
pub struct ShaderVariantCollection {
    pub base_id: u32,
    pub variants: Vec<ShaderVariant>,
    pub fallback_id: Option<u32>,
    pub next_id: u32,
}

impl ShaderVariantCollection {
    pub fn new(base_id: u32) -> Self { Self { base_id, variants: Vec::new(), fallback_id: None, next_id: 1 } }
    pub fn add_variant(&mut self, keywords: Vec<String>) -> u32 {
        let id = self.next_id; self.next_id += 1;
        let mut v = ShaderVariant::new(id, self.base_id);
        v.keywords = keywords;
        self.variants.push(v);
        id
    }
    pub fn find_best_match(&self, keywords: &[&str]) -> Option<&ShaderVariant> {
        let mut best: Option<&ShaderVariant> = None;
        let mut best_matches = 0;
        for v in &self.variants {
            let matches = keywords.iter().filter(|kw| v.keywords.iter().any(|k| k == *kw)).count();
            if matches > best_matches { best_matches = matches; best = Some(v); }
        }
        best.or_else(|| self.fallback_id.and_then(|id| self.variants.iter().find(|v| v.id == id)))
    }
    pub fn variant_count(&self) -> usize { self.variants.len() }
    pub fn set_fallback(&mut self, id: u32) { self.fallback_id = Some(id); }
}

// ── Shader include resolver ────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderIncludeResolver {
    pub virtual_fs: HashMap<String, String>,
    pub include_paths: Vec<String>,
    pub resolved_cache: HashMap<String, String>,
    pub max_size_bytes: usize,
}

impl ShaderIncludeResolver {
    pub fn new() -> Self { Self { virtual_fs: HashMap::new(), include_paths: Vec::new(), resolved_cache: HashMap::new(), max_size_bytes: 1024 * 1024 } }
    pub fn register_virtual(&mut self, path: impl Into<String>, content: impl Into<String>) { self.virtual_fs.insert(path.into(), content.into()); }
    pub fn add_include_path(&mut self, path: impl Into<String>) { self.include_paths.push(path.into()); }
    pub fn resolve(&self, include_path: &str) -> Option<&str> {
        self.resolved_cache.get(include_path).map(|s| s.as_str()).or_else(|| self.virtual_fs.get(include_path).map(|s| s.as_str()))
    }
    pub fn cache_result(&mut self, include_path: String, content: String) { self.resolved_cache.insert(include_path, content); }
    pub fn clear_cache(&mut self) { self.resolved_cache.clear(); }
    pub fn virtual_file_count(&self) -> usize { self.virtual_fs.len() }
}

impl Default for ShaderIncludeResolver {
    fn default() -> Self { Self::new() }
}

// ── More shader constants ─────────────────────────────────────────────────────

pub const SHADER_VARIANT_MAX_KEYWORDS: usize = 16;
pub const SHADER_TEMPLATE_MAX_PARAMS: usize = 32;
pub const SHADER_WATCHER_DEBOUNCE_DEFAULT: u32 = 500;
pub const SHADER_OPTIMIZER_UNROLL_DEFAULT: u32 = 8;
pub const SHADER_AST_MAX_DEPTH: usize = 64;
pub const SHADER_MAX_VARIANTS_PER_PROGRAM: usize = 256;
pub const SHADER_INCLUDE_RESOLVER_CACHE_MAX: usize = 512;
pub const SHADER_CODEGEN_INDENT_DEFAULT: usize = 4;
pub const SHADER_DIAGNOSTIC_MAX: usize = 1000;

pub fn shader_targets() -> &'static [&'static str] { &["glsl450", "glsl300es", "wgsl", "hlsl50", "msl20"] }
pub fn shader_target_count() -> usize { shader_targets().len() }
pub fn is_gpu_shader_target(target: &CodeGenTarget) -> bool { !matches!(target, CodeGenTarget::Wgsl) || true }


// ── Material System ───────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct Material {
    pub id: u32,
    pub name: String,
    pub shader_program_id: u32,
    pub textures: Vec<MaterialTexture>,
    pub properties: HashMap<String, MaterialProperty>,
    pub pipeline: PipelineState,
    pub render_queue: u32,
    pub cast_shadows: bool,
    pub receive_shadows: bool,
    pub instanced: bool,
    pub double_sided: bool,
}

#[derive(Clone, Debug)]
pub struct MaterialTexture {
    pub name: String,
    pub texture_id: u32,
    pub slot: u32,
    pub sampler_type: SamplerType,
    pub uv_channel: u32,
}

#[derive(Clone, Debug)]
pub enum MaterialProperty {
    Float(f32),
    Vec2([f32; 2]),
    Vec3([f32; 3]),
    Vec4([f32; 4]),
    Int(i32),
    Bool(bool),
    Color([f32; 4]),
}

#[derive(Clone, Debug, PartialEq)]
pub enum SamplerType { Linear, Nearest, LinearMipmap, Trilinear, Anisotropic }

impl Material {
    pub fn new(id: u32, name: impl Into<String>, shader_id: u32) -> Self {
        Self { id, name: name.into(), shader_program_id: shader_id, textures: Vec::new(), properties: HashMap::new(), pipeline: PipelineState::default(), render_queue: 2000, cast_shadows: true, receive_shadows: true, instanced: false, double_sided: false }
    }
    pub fn add_texture(&mut self, name: impl Into<String>, tex_id: u32, slot: u32) {
        self.textures.push(MaterialTexture { name: name.into(), texture_id: tex_id, slot, sampler_type: SamplerType::Trilinear, uv_channel: 0 });
    }
    pub fn set_float(&mut self, name: impl Into<String>, value: f32) { self.properties.insert(name.into(), MaterialProperty::Float(value)); }
    pub fn set_color(&mut self, name: impl Into<String>, r: f32, g: f32, b: f32, a: f32) { self.properties.insert(name.into(), MaterialProperty::Color([r, g, b, a])); }
    pub fn set_vec4(&mut self, name: impl Into<String>, v: [f32; 4]) { self.properties.insert(name.into(), MaterialProperty::Vec4(v)); }
    pub fn is_transparent(&self) -> bool { self.pipeline.is_transparent() }
    pub fn is_opaque(&self) -> bool { !self.is_transparent() }
    pub fn texture_count(&self) -> usize { self.textures.len() }
    pub fn property_count(&self) -> usize { self.properties.len() }
    pub fn make_transparent(&mut self) { self.pipeline = PipelineState::transparent(); self.render_queue = 3000; }
    pub fn make_additive(&mut self) { self.pipeline = PipelineState::additive(); self.render_queue = 3500; }
}

#[derive(Clone, Debug)]
pub struct MaterialLibrary {
    pub materials: HashMap<u32, Material>,
    pub next_id: u32,
    pub default_material_id: u32,
}

impl MaterialLibrary {
    pub fn new() -> Self { Self { materials: HashMap::new(), next_id: 1, default_material_id: 0 } }
    pub fn add(&mut self, mat: Material) -> u32 {
        let id = self.next_id; self.next_id += 1;
        self.materials.insert(id, mat);
        id
    }
    pub fn get(&self, id: u32) -> Option<&Material> { self.materials.get(&id) }
    pub fn get_mut(&mut self, id: u32) -> Option<&mut Material> { self.materials.get_mut(&id) }
    pub fn find_by_name(&self, name: &str) -> Option<&Material> { self.materials.values().find(|m| m.name == name) }
    pub fn opaque_materials(&self) -> Vec<&Material> { self.materials.values().filter(|m| m.is_opaque()).collect() }
    pub fn transparent_materials(&self) -> Vec<&Material> { self.materials.values().filter(|m| m.is_transparent()).collect() }
    pub fn count(&self) -> usize { self.materials.len() }
    pub fn remove(&mut self, id: u32) -> bool { self.materials.remove(&id).is_some() }
    pub fn set_default(&mut self, id: u32) { self.default_material_id = id; }
}

impl Default for MaterialLibrary {
    fn default() -> Self { Self::new() }
}

// ── Render Pass System ────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct RenderPass {
    pub id: u32,
    pub name: String,
    pub pass_type: RenderPassType,
    pub color_attachments: Vec<ColorAttachment>,
    pub depth_attachment: Option<DepthAttachment>,
    pub clear_color: [f32; 4],
    pub clear_depth: f32,
    pub clear_stencil: u8,
    pub viewport: (u32, u32, u32, u32),
    pub enabled: bool,
    pub order: u32,
}

#[derive(Clone, Debug, PartialEq)]
pub enum RenderPassType { Opaque, Transparent, Shadow, PostProcess, Ui, Compute, Custom }

#[derive(Clone, Debug)]
pub struct ColorAttachment {
    pub texture_id: u32,
    pub format: AttachmentFormat,
    pub load_op: LoadOp,
    pub store_op: StoreOp,
    pub mip_level: u32,
    pub layer: u32,
}

#[derive(Clone, Debug)]
pub struct DepthAttachment {
    pub texture_id: u32,
    pub format: AttachmentFormat,
    pub load_op: LoadOp,
    pub store_op: StoreOp,
    pub read_only: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub enum AttachmentFormat { Rgba8, Rgba16F, Rgba32F, R8, R16F, R32F, Rg8, Rg16F, Depth16, Depth24, Depth32F, Depth24Stencil8 }

#[derive(Clone, Debug, PartialEq)]
pub enum LoadOp { Load, Clear, DontCare }
#[derive(Clone, Debug, PartialEq)]
pub enum StoreOp { Store, DontCare }

impl RenderPass {
    pub fn new(id: u32, name: impl Into<String>, pass_type: RenderPassType) -> Self {
        Self { id, name: name.into(), pass_type, color_attachments: Vec::new(), depth_attachment: None, clear_color: [0.0, 0.0, 0.0, 1.0], clear_depth: 1.0, clear_stencil: 0, viewport: (0, 0, 1920, 1080), enabled: true, order: 0 }
    }
    pub fn add_color_attachment(&mut self, tex_id: u32, format: AttachmentFormat) {
        self.color_attachments.push(ColorAttachment { texture_id: tex_id, format, load_op: LoadOp::Clear, store_op: StoreOp::Store, mip_level: 0, layer: 0 });
    }
    pub fn set_depth(&mut self, tex_id: u32) {
        self.depth_attachment = Some(DepthAttachment { texture_id: tex_id, format: AttachmentFormat::Depth32F, load_op: LoadOp::Clear, store_op: StoreOp::Store, read_only: false });
    }
    pub fn is_shadow_pass(&self) -> bool { self.pass_type == RenderPassType::Shadow }
    pub fn is_postprocess(&self) -> bool { self.pass_type == RenderPassType::PostProcess }
    pub fn attachment_count(&self) -> usize { self.color_attachments.len() + if self.depth_attachment.is_some() { 1 } else { 0 } }
    pub fn set_viewport(&mut self, x: u32, y: u32, w: u32, h: u32) { self.viewport = (x, y, w, h); }
}

#[derive(Clone, Debug)]
pub struct RenderPipeline {
    pub passes: Vec<RenderPass>,
    pub next_id: u32,
}

impl RenderPipeline {
    pub fn new() -> Self { Self { passes: Vec::new(), next_id: 1 } }
    pub fn add_pass(&mut self, pass: RenderPass) { self.passes.push(pass); }
    pub fn sorted_passes(&self) -> Vec<&RenderPass> {
        let mut sorted: Vec<_> = self.passes.iter().filter(|p| p.enabled).collect();
        sorted.sort_by_key(|p| p.order);
        sorted
    }
    pub fn pass_count(&self) -> usize { self.passes.len() }
    pub fn find_by_type(&self, pass_type: &RenderPassType) -> Vec<&RenderPass> {
        self.passes.iter().filter(|p| &p.pass_type == pass_type).collect()
    }
    pub fn enable_pass(&mut self, id: u32) { if let Some(p) = self.passes.iter_mut().find(|p| p.id == id) { p.enabled = true; } }
    pub fn disable_pass(&mut self, id: u32) { if let Some(p) = self.passes.iter_mut().find(|p| p.id == id) { p.enabled = false; } }
}

impl Default for RenderPipeline {
    fn default() -> Self { Self::new() }
}

// ── Post-Process Effect ───────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct PostProcessEffect {
    pub id: u32,
    pub name: String,
    pub effect_type: PostEffectType,
    pub shader_program_id: u32,
    pub properties: HashMap<String, f32>,
    pub enabled: bool,
    pub order: u32,
    pub input_texture: u32,
    pub output_texture: u32,
}

#[derive(Clone, Debug, PartialEq)]
pub enum PostEffectType { Bloom, Tonemap, Vignette, ChromaticAberration, DepthOfField, MotionBlur, Ssao, Fxaa, Custom }

impl PostProcessEffect {
    pub fn new(id: u32, name: impl Into<String>, effect_type: PostEffectType, shader_id: u32) -> Self {
        Self { id, name: name.into(), effect_type, shader_program_id: shader_id, properties: HashMap::new(), enabled: true, order: 0, input_texture: 0, output_texture: 0 }
    }
    pub fn set_property(&mut self, key: impl Into<String>, val: f32) { self.properties.insert(key.into(), val); }
    pub fn get_property(&self, key: &str) -> f32 { self.properties.get(key).copied().unwrap_or(0.0) }
    pub fn bloom_intensity(&self) -> f32 { self.get_property("intensity") }
    pub fn vignette_strength(&self) -> f32 { self.get_property("strength") }
    pub fn is_bloom(&self) -> bool { self.effect_type == PostEffectType::Bloom }
    pub fn is_tonemap(&self) -> bool { self.effect_type == PostEffectType::Tonemap }
}

#[derive(Clone, Debug)]
pub struct PostProcessStack {
    pub effects: Vec<PostProcessEffect>,
    pub enabled: bool,
}

impl PostProcessStack {
    pub fn new() -> Self { Self { effects: Vec::new(), enabled: true } }
    pub fn add(&mut self, effect: PostProcessEffect) { self.effects.push(effect); }
    pub fn enabled_effects(&self) -> Vec<&PostProcessEffect> {
        let mut v: Vec<_> = self.effects.iter().filter(|e| e.enabled).collect();
        v.sort_by_key(|e| e.order);
        v
    }
    pub fn enable_effect(&mut self, id: u32) { if let Some(e) = self.effects.iter_mut().find(|e| e.id == id) { e.enabled = true; } }
    pub fn disable_effect(&mut self, id: u32) { if let Some(e) = self.effects.iter_mut().find(|e| e.id == id) { e.enabled = false; } }
    pub fn effect_count(&self) -> usize { self.effects.len() }
    pub fn active_count(&self) -> usize { self.effects.iter().filter(|e| e.enabled).count() }
}

impl Default for PostProcessStack {
    fn default() -> Self { Self::new() }
}

// ── Shader Node Graph ─────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderNode {
    pub id: u32,
    pub node_type: ShaderNodeType,
    pub label: String,
    pub position: (f32, f32),
    pub inputs: Vec<ShaderNodePort>,
    pub outputs: Vec<ShaderNodePort>,
    pub properties: HashMap<String, String>,
}

#[derive(Clone, Debug, PartialEq)]
pub enum ShaderNodeType {
    Input, Output, Math, Texture, Color, Constant, Mix, Clamp, Normalize, Length, Dot, Cross, Reflect, Refract, Fresnel, NormalMap, VertexShader, FragmentShader, Custom(String),
}

#[derive(Clone, Debug)]
pub struct ShaderNodePort {
    pub id: u32,
    pub name: String,
    pub port_type: ShaderDataType,
    pub connected_to: Option<(u32, u32)>,
    pub default_value: String,
}

impl ShaderNode {
    pub fn new(id: u32, node_type: ShaderNodeType, label: impl Into<String>) -> Self {
        Self { id, node_type, label: label.into(), position: (0.0, 0.0), inputs: Vec::new(), outputs: Vec::new(), properties: HashMap::new() }
    }
    pub fn add_input(&mut self, name: impl Into<String>, port_type: ShaderDataType) -> u32 {
        let pid = self.inputs.len() as u32;
        self.inputs.push(ShaderNodePort { id: pid, name: name.into(), port_type, connected_to: None, default_value: "0.0".into() });
        pid
    }
    pub fn add_output(&mut self, name: impl Into<String>, port_type: ShaderDataType) -> u32 {
        let pid = self.outputs.len() as u32;
        self.outputs.push(ShaderNodePort { id: pid, name: name.into(), port_type, connected_to: None, default_value: "0.0".into() });
        pid
    }
    pub fn set_property(&mut self, key: impl Into<String>, val: impl Into<String>) { self.properties.insert(key.into(), val.into()); }
    pub fn is_output_node(&self) -> bool { self.node_type == ShaderNodeType::Output }
    pub fn is_input_node(&self) -> bool { self.node_type == ShaderNodeType::Input }
    pub fn input_count(&self) -> usize { self.inputs.len() }
    pub fn output_count(&self) -> usize { self.outputs.len() }
}

#[derive(Clone, Debug)]
pub struct ShaderNodeGraph {
    pub nodes: HashMap<u32, ShaderNode>,
    pub connections: Vec<(u32, u32, u32, u32)>,
    pub next_id: u32,
    pub name: String,
}

impl ShaderNodeGraph {
    pub fn new(name: impl Into<String>) -> Self { Self { nodes: HashMap::new(), connections: Vec::new(), next_id: 1, name: name.into() } }
    pub fn add_node(&mut self, node_type: ShaderNodeType, label: impl Into<String>) -> u32 {
        let id = self.next_id; self.next_id += 1;
        self.nodes.insert(id, ShaderNode::new(id, node_type, label));
        id
    }
    pub fn connect(&mut self, from_node: u32, from_port: u32, to_node: u32, to_port: u32) {
        self.connections.push((from_node, from_port, to_node, to_port));
        if let Some(node) = self.nodes.get_mut(&to_node) {
            if let Some(port) = node.inputs.get_mut(to_port as usize) { port.connected_to = Some((from_node, from_port)); }
        }
    }
    pub fn disconnect(&mut self, to_node: u32, to_port: u32) {
        self.connections.retain(|(_, _, tn, tp)| !(*tn == to_node && *tp == to_port));
        if let Some(node) = self.nodes.get_mut(&to_node) {
            if let Some(port) = node.inputs.get_mut(to_port as usize) { port.connected_to = None; }
        }
    }
    pub fn remove_node(&mut self, id: u32) {
        self.nodes.remove(&id);
        self.connections.retain(|(a, _, b, _)| *a != id && *b != id);
    }
    pub fn node_count(&self) -> usize { self.nodes.len() }
    pub fn connection_count(&self) -> usize { self.connections.len() }
    pub fn output_node(&self) -> Option<&ShaderNode> { self.nodes.values().find(|n| n.is_output_node()) }
    pub fn move_node(&mut self, id: u32, x: f32, y: f32) { if let Some(n) = self.nodes.get_mut(&id) { n.position = (x, y); } }
}

impl Default for ShaderNodeGraph {
    fn default() -> Self { Self::new("new_graph") }
}

// ── More constants ────────────────────────────────────────────────────────────

pub const MATERIAL_MAX_TEXTURES: usize = 16;
pub const MATERIAL_MAX_PROPERTIES: usize = 64;
pub const RENDER_PASS_MAX: usize = 32;
pub const POST_PROCESS_EFFECT_MAX: usize = 16;
pub const SHADER_NODE_GRAPH_MAX_NODES: usize = 512;
pub const SHADER_NODE_GRAPH_MAX_CONNECTIONS: usize = 1024;
pub const MATERIAL_OPAQUE_QUEUE: u32 = 2000;
pub const MATERIAL_TRANSPARENT_QUEUE: u32 = 3000;
pub const MATERIAL_OVERLAY_QUEUE: u32 = 4000;

pub fn attachment_format_name(fmt: &AttachmentFormat) -> &'static str {
    match fmt {
        AttachmentFormat::Rgba8 => "RGBA8", AttachmentFormat::Rgba16F => "RGBA16F",
        AttachmentFormat::Rgba32F => "RGBA32F", AttachmentFormat::Depth32F => "Depth32F",
        AttachmentFormat::Depth24Stencil8 => "Depth24Stencil8", _ => "Unknown",
    }
}
pub fn blend_factor_glsl(f: &BlendFactor) -> &'static str {
    match f {
        BlendFactor::Zero => "GL_ZERO", BlendFactor::One => "GL_ONE",
        BlendFactor::SrcAlpha => "GL_SRC_ALPHA", BlendFactor::OneMinusSrcAlpha => "GL_ONE_MINUS_SRC_ALPHA",
        _ => "GL_ONE",
    }
}


// ── Texture System ────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct TextureDescriptor {
    pub id: u32,
    pub name: String,
    pub width: u32,
    pub height: u32,
    pub depth: u32,
    pub mip_levels: u32,
    pub array_layers: u32,
    pub format: AttachmentFormat,
    pub tex_type: TextureType,
    pub usage: TextureUsage,
    pub filter: TextureFilter,
    pub wrap_u: WrapMode,
    pub wrap_v: WrapMode,
    pub wrap_w: WrapMode,
    pub anisotropy: u32,
    pub generate_mipmaps: bool,
    pub srgb: bool,
    pub compressed: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub enum TextureType { Tex2D, Tex3D, TexCube, Tex2DArray, TexCubeArray }
#[derive(Clone, Debug, PartialEq)]
pub enum TextureUsage { Sampled, Storage, RenderTarget, DepthStencil }
#[derive(Clone, Debug, PartialEq)]
pub enum TextureFilter { Nearest, Linear, Trilinear, Anisotropic }
#[derive(Clone, Debug, PartialEq)]
pub enum WrapMode { Repeat, MirroredRepeat, ClampToEdge, ClampToBorder, MirrorClampToEdge }

impl TextureDescriptor {
    pub fn new_2d(id: u32, name: impl Into<String>, width: u32, height: u32, format: AttachmentFormat) -> Self {
        Self { id, name: name.into(), width, height, depth: 1, mip_levels: 1, array_layers: 1, format, tex_type: TextureType::Tex2D, usage: TextureUsage::Sampled, filter: TextureFilter::Trilinear, wrap_u: WrapMode::Repeat, wrap_v: WrapMode::Repeat, wrap_w: WrapMode::ClampToEdge, anisotropy: 4, generate_mipmaps: true, srgb: false, compressed: false }
    }
    pub fn render_target(id: u32, name: impl Into<String>, w: u32, h: u32, fmt: AttachmentFormat) -> Self {
        let mut t = Self::new_2d(id, name, w, h, fmt); t.usage = TextureUsage::RenderTarget; t.generate_mipmaps = false; t
    }
    pub fn depth_target(id: u32, name: impl Into<String>, w: u32, h: u32) -> Self {
        let mut t = Self::new_2d(id, name, w, h, AttachmentFormat::Depth32F); t.usage = TextureUsage::DepthStencil; t.generate_mipmaps = false; t
    }
    pub fn mip_count_for_size(width: u32, height: u32) -> u32 { (width.max(height) as f32).log2().floor() as u32 + 1 }
    pub fn bytes_per_pixel(&self) -> u32 {
        match self.format {
            AttachmentFormat::Rgba8 => 4, AttachmentFormat::Rgba16F => 8, AttachmentFormat::Rgba32F => 16,
            AttachmentFormat::R8 => 1, AttachmentFormat::R16F => 2, AttachmentFormat::R32F => 4,
            AttachmentFormat::Rg8 => 2, AttachmentFormat::Rg16F => 4,
            AttachmentFormat::Depth32F => 4, _ => 4,
        }
    }
    pub fn total_bytes(&self) -> u64 { self.width as u64 * self.height as u64 * self.depth as u64 * self.bytes_per_pixel() as u64 }
    pub fn is_hdr(&self) -> bool { matches!(self.format, AttachmentFormat::Rgba16F | AttachmentFormat::Rgba32F | AttachmentFormat::R16F | AttachmentFormat::R32F) }
    pub fn is_cubemap(&self) -> bool { self.tex_type == TextureType::TexCube }
    pub fn is_depth(&self) -> bool { matches!(self.format, AttachmentFormat::Depth16 | AttachmentFormat::Depth24 | AttachmentFormat::Depth32F | AttachmentFormat::Depth24Stencil8) }
    pub fn aspect_ratio(&self) -> f32 { if self.height == 0 { 1.0 } else { self.width as f32 / self.height as f32 } }
}

#[derive(Clone, Debug)]
pub struct TextureRegistry {
    pub textures: HashMap<u32, TextureDescriptor>,
    pub next_id: u32,
}

impl TextureRegistry {
    pub fn new() -> Self { Self { textures: HashMap::new(), next_id: 1 } }
    pub fn register(&mut self, mut tex: TextureDescriptor) -> u32 {
        let id = self.next_id; self.next_id += 1;
        tex.id = id;
        self.textures.insert(id, tex);
        id
    }
    pub fn get(&self, id: u32) -> Option<&TextureDescriptor> { self.textures.get(&id) }
    pub fn find_by_name(&self, name: &str) -> Option<&TextureDescriptor> { self.textures.values().find(|t| t.name == name) }
    pub fn total_bytes(&self) -> u64 { self.textures.values().map(|t| t.total_bytes()).sum() }
    pub fn count(&self) -> usize { self.textures.len() }
    pub fn hdr_textures(&self) -> Vec<&TextureDescriptor> { self.textures.values().filter(|t| t.is_hdr()).collect() }
    pub fn depth_textures(&self) -> Vec<&TextureDescriptor> { self.textures.values().filter(|t| t.is_depth()).collect() }
    pub fn remove(&mut self, id: u32) -> bool { self.textures.remove(&id).is_some() }
}

impl Default for TextureRegistry {
    fn default() -> Self { Self::new() }
}

// ── Sampler System ────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct SamplerDescriptor {
    pub id: u32,
    pub min_filter: TextureFilter,
    pub mag_filter: TextureFilter,
    pub mip_filter: TextureFilter,
    pub wrap_u: WrapMode,
    pub wrap_v: WrapMode,
    pub wrap_w: WrapMode,
    pub anisotropy: u32,
    pub border_color: [f32; 4],
    pub lod_min: f32,
    pub lod_max: f32,
    pub lod_bias: f32,
    pub compare_op: Option<CompareFunc>,
}

impl SamplerDescriptor {
    pub fn default_linear() -> Self {
        Self { id: 0, min_filter: TextureFilter::Linear, mag_filter: TextureFilter::Linear, mip_filter: TextureFilter::Linear, wrap_u: WrapMode::Repeat, wrap_v: WrapMode::Repeat, wrap_w: WrapMode::Repeat, anisotropy: 1, border_color: [0.0; 4], lod_min: 0.0, lod_max: 1000.0, lod_bias: 0.0, compare_op: None }
    }
    pub fn default_nearest() -> Self { Self { min_filter: TextureFilter::Nearest, mag_filter: TextureFilter::Nearest, mip_filter: TextureFilter::Nearest, ..Self::default_linear() } }
    pub fn shadow() -> Self { Self { compare_op: Some(CompareFunc::Less), ..Self::default_linear() } }
    pub fn clamp_to_edge() -> Self { Self { wrap_u: WrapMode::ClampToEdge, wrap_v: WrapMode::ClampToEdge, wrap_w: WrapMode::ClampToEdge, ..Self::default_linear() } }
    pub fn anisotropic_16() -> Self { Self { anisotropy: 16, ..Self::default_linear() } }
    pub fn is_shadow_sampler(&self) -> bool { self.compare_op.is_some() }
    pub fn is_anisotropic(&self) -> bool { self.anisotropy > 1 }
}

// ── Vertex Layout ─────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct VertexAttribute {
    pub location: u32,
    pub name: String,
    pub format: VertexAttribFormat,
    pub offset: u32,
    pub normalized: bool,
}

#[derive(Clone, Debug, PartialEq, Copy)]
pub enum VertexAttribFormat {
    Float1, Float2, Float3, Float4,
    Sint1, Sint2, Sint3, Sint4,
    Uint1, Uint2, Uint3, Uint4,
    Unorm4, Snorm4,
    Half2, Half4,
}

impl VertexAttribFormat {
    pub fn size_bytes(self) -> u32 {
        match self {
            VertexAttribFormat::Float1 | VertexAttribFormat::Sint1 | VertexAttribFormat::Uint1 => 4,
            VertexAttribFormat::Float2 | VertexAttribFormat::Sint2 | VertexAttribFormat::Uint2 | VertexAttribFormat::Half4 => 8,
            VertexAttribFormat::Float3 | VertexAttribFormat::Sint3 | VertexAttribFormat::Uint3 => 12,
            VertexAttribFormat::Float4 | VertexAttribFormat::Sint4 | VertexAttribFormat::Uint4 | VertexAttribFormat::Unorm4 | VertexAttribFormat::Snorm4 => 16,
            VertexAttribFormat::Half2 => 4,
        }
    }
    pub fn component_count(self) -> u32 {
        match self {
            VertexAttribFormat::Float1 | VertexAttribFormat::Sint1 | VertexAttribFormat::Uint1 => 1,
            VertexAttribFormat::Float2 | VertexAttribFormat::Sint2 | VertexAttribFormat::Uint2 | VertexAttribFormat::Half2 => 2,
            VertexAttribFormat::Float3 | VertexAttribFormat::Sint3 | VertexAttribFormat::Uint3 => 3,
            _ => 4,
        }
    }
    pub fn glsl_type_name(self) -> &'static str {
        match self {
            VertexAttribFormat::Float1 => "float", VertexAttribFormat::Float2 => "vec2",
            VertexAttribFormat::Float3 => "vec3", VertexAttribFormat::Float4 => "vec4",
            VertexAttribFormat::Sint1 => "int", VertexAttribFormat::Sint2 => "ivec2",
            VertexAttribFormat::Sint3 => "ivec3", VertexAttribFormat::Sint4 => "ivec4",
            VertexAttribFormat::Uint1 => "uint", VertexAttribFormat::Uint2 => "uvec2",
            VertexAttribFormat::Uint3 => "uvec3", VertexAttribFormat::Uint4 => "uvec4",
            _ => "vec4",
        }
    }
}

#[derive(Clone, Debug)]
pub struct VertexLayout {
    pub attributes: Vec<VertexAttribute>,
    pub stride: u32,
    pub instanced: bool,
    pub instance_rate: u32,
}

impl VertexLayout {
    pub fn new() -> Self { Self { attributes: Vec::new(), stride: 0, instanced: false, instance_rate: 1 } }
    pub fn add_attribute(&mut self, location: u32, name: impl Into<String>, format: VertexAttribFormat) {
        let offset = self.stride;
        self.stride += format.size_bytes();
        self.attributes.push(VertexAttribute { location, name: name.into(), format, offset, normalized: false });
    }
    pub fn standard_mesh() -> Self {
        let mut layout = Self::new();
        layout.add_attribute(0, "position", VertexAttribFormat::Float3);
        layout.add_attribute(1, "normal", VertexAttribFormat::Float3);
        layout.add_attribute(2, "uv", VertexAttribFormat::Float2);
        layout.add_attribute(3, "tangent", VertexAttribFormat::Float4);
        layout
    }
    pub fn position_only() -> Self {
        let mut layout = Self::new();
        layout.add_attribute(0, "position", VertexAttribFormat::Float3);
        layout
    }
    pub fn particle() -> Self {
        let mut layout = Self::new();
        layout.add_attribute(0, "position", VertexAttribFormat::Float3);
        layout.add_attribute(1, "color", VertexAttribFormat::Unorm4);
        layout.add_attribute(2, "size_rotation", VertexAttribFormat::Float2);
        layout
    }
    pub fn attribute_count(&self) -> usize { self.attributes.len() }
    pub fn generate_glsl_inputs(&self) -> String {
        self.attributes.iter().map(|a| format!("layout(location={}) in {} {};\n", a.location, a.format.glsl_type_name(), a.name)).collect()
    }
}

impl Default for VertexLayout {
    fn default() -> Self { Self::standard_mesh() }
}

// ── Buffer System ─────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct GpuBuffer {
    pub id: u32,
    pub name: String,
    pub size_bytes: u64,
    pub usage: BufferUsage,
    pub access: BufferAccess,
    pub binding: Option<u32>,
    pub stride: u32,
    pub element_count: u32,
}

#[derive(Clone, Debug, PartialEq)]
pub enum BufferUsage { Vertex, Index, Uniform, Storage, Indirect, Staging }
#[derive(Clone, Debug, PartialEq)]
pub enum BufferAccess { GpuOnly, CpuToGpu, GpuToCpu, CpuOnly }

impl GpuBuffer {
    pub fn new(id: u32, name: impl Into<String>, size: u64, usage: BufferUsage) -> Self {
        Self { id, name: name.into(), size_bytes: size, usage, access: BufferAccess::GpuOnly, binding: None, stride: 0, element_count: 0 }
    }
    pub fn vertex(id: u32, name: impl Into<String>, vertex_count: u32, stride: u32) -> Self {
        let mut b = Self::new(id, name, vertex_count as u64 * stride as u64, BufferUsage::Vertex);
        b.stride = stride; b.element_count = vertex_count; b
    }
    pub fn index(id: u32, name: impl Into<String>, index_count: u32, is_u32: bool) -> Self {
        let stride = if is_u32 { 4 } else { 2 };
        let mut b = Self::new(id, name, index_count as u64 * stride, BufferUsage::Index);
        b.stride = stride as u32; b.element_count = index_count; b
    }
    pub fn uniform(id: u32, name: impl Into<String>, size: u64, binding: u32) -> Self {
        let mut b = Self::new(id, name, size, BufferUsage::Uniform);
        b.binding = Some(binding); b
    }
    pub fn is_vertex_buffer(&self) -> bool { self.usage == BufferUsage::Vertex }
    pub fn is_index_buffer(&self) -> bool { self.usage == BufferUsage::Index }
    pub fn is_uniform_buffer(&self) -> bool { self.usage == BufferUsage::Uniform }
    pub fn size_kb(&self) -> f64 { self.size_bytes as f64 / 1024.0 }
    pub fn size_mb(&self) -> f64 { self.size_bytes as f64 / (1024.0 * 1024.0) }
}

#[derive(Clone, Debug)]
pub struct BufferRegistry {
    pub buffers: HashMap<u32, GpuBuffer>,
    pub next_id: u32,
    pub total_bytes: u64,
}

impl BufferRegistry {
    pub fn new() -> Self { Self { buffers: HashMap::new(), next_id: 1, total_bytes: 0 } }
    pub fn register(&mut self, mut buf: GpuBuffer) -> u32 {
        let id = self.next_id; self.next_id += 1;
        buf.id = id;
        self.total_bytes += buf.size_bytes;
        self.buffers.insert(id, buf);
        id
    }
    pub fn get(&self, id: u32) -> Option<&GpuBuffer> { self.buffers.get(&id) }
    pub fn remove(&mut self, id: u32) -> bool {
        if let Some(b) = self.buffers.remove(&id) { self.total_bytes = self.total_bytes.saturating_sub(b.size_bytes); true } else { false }
    }
    pub fn by_usage(&self, usage: &BufferUsage) -> Vec<&GpuBuffer> { self.buffers.values().filter(|b| &b.usage == usage).collect() }
    pub fn total_mb(&self) -> f64 { self.total_bytes as f64 / (1024.0 * 1024.0) }
    pub fn count(&self) -> usize { self.buffers.len() }
}

impl Default for BufferRegistry {
    fn default() -> Self { Self::new() }
}

// ── Compute Shader ────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ComputePass {
    pub id: u32,
    pub name: String,
    pub shader_program_id: u32,
    pub dispatch_x: u32,
    pub dispatch_y: u32,
    pub dispatch_z: u32,
    pub bindings: Vec<ComputeBinding>,
    pub push_constants: Vec<u8>,
    pub enabled: bool,
}

#[derive(Clone, Debug)]
pub struct ComputeBinding {
    pub set: u32,
    pub binding: u32,
    pub resource_type: ComputeResourceType,
    pub resource_id: u32,
}

#[derive(Clone, Debug, PartialEq)]
pub enum ComputeResourceType { Texture, StorageTexture, Buffer, StorageBuffer, UniformBuffer }

impl ComputePass {
    pub fn new(id: u32, name: impl Into<String>, shader_id: u32) -> Self {
        Self { id, name: name.into(), shader_program_id: shader_id, dispatch_x: 1, dispatch_y: 1, dispatch_z: 1, bindings: Vec::new(), push_constants: Vec::new(), enabled: true }
    }
    pub fn dispatch(mut self, x: u32, y: u32, z: u32) -> Self { self.dispatch_x = x; self.dispatch_y = y; self.dispatch_z = z; self }
    pub fn add_binding(&mut self, set: u32, binding: u32, res_type: ComputeResourceType, res_id: u32) {
        self.bindings.push(ComputeBinding { set, binding, resource_type: res_type, resource_id: res_id });
    }
    pub fn total_invocations(&self) -> u64 { self.dispatch_x as u64 * self.dispatch_y as u64 * self.dispatch_z as u64 }
    pub fn binding_count(&self) -> usize { self.bindings.len() }
}

// ── GPU Memory Budget ─────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct GpuMemoryBudget {
    pub total_bytes: u64,
    pub available_bytes: u64,
    pub textures_bytes: u64,
    pub buffers_bytes: u64,
    pub render_targets_bytes: u64,
    pub shader_bytes: u64,
    pub misc_bytes: u64,
}

impl GpuMemoryBudget {
    pub fn new(total: u64) -> Self {
        Self { total_bytes: total, available_bytes: total, textures_bytes: 0, buffers_bytes: 0, render_targets_bytes: 0, shader_bytes: 0, misc_bytes: 0 }
    }
    pub fn used_bytes(&self) -> u64 { self.textures_bytes + self.buffers_bytes + self.render_targets_bytes + self.shader_bytes + self.misc_bytes }
    pub fn usage_percent(&self) -> f32 { if self.total_bytes == 0 { 0.0 } else { self.used_bytes() as f32 / self.total_bytes as f32 * 100.0 } }
    pub fn is_overbudget(&self) -> bool { self.used_bytes() > self.total_bytes }
    pub fn headroom_mb(&self) -> f64 { (self.total_bytes.saturating_sub(self.used_bytes())) as f64 / (1024.0 * 1024.0) }
    pub fn allocate_texture(&mut self, bytes: u64) -> bool { if self.available_bytes >= bytes { self.textures_bytes += bytes; self.available_bytes -= bytes; true } else { false } }
    pub fn allocate_buffer(&mut self, bytes: u64) -> bool { if self.available_bytes >= bytes { self.buffers_bytes += bytes; self.available_bytes -= bytes; true } else { false } }
    pub fn free_texture(&mut self, bytes: u64) { self.textures_bytes = self.textures_bytes.saturating_sub(bytes); self.available_bytes += bytes.min(self.total_bytes); }
}

// ── Render Statistics ─────────────────────────────────────────────────────────

#[derive(Clone, Debug, Default)]
pub struct RenderStatistics {
    pub draw_calls: u32,
    pub triangles: u64,
    pub vertices: u64,
    pub texture_switches: u32,
    pub shader_switches: u32,
    pub render_pass_count: u32,
    pub compute_dispatches: u32,
    pub gpu_time_ms: f32,
    pub cpu_time_ms: f32,
    pub frame_number: u64,
}

impl RenderStatistics {
    pub fn new() -> Self { Self::default() }
    pub fn begin_frame(&mut self) {
        self.draw_calls = 0; self.triangles = 0; self.vertices = 0;
        self.texture_switches = 0; self.shader_switches = 0;
        self.render_pass_count = 0; self.compute_dispatches = 0;
        self.gpu_time_ms = 0.0; self.cpu_time_ms = 0.0;
        self.frame_number += 1;
    }
    pub fn record_draw(&mut self, vertices: u64, triangles: u64) { self.draw_calls += 1; self.vertices += vertices; self.triangles += triangles; }
    pub fn fps(&self) -> f32 { if self.gpu_time_ms < 1e-6 { 0.0 } else { 1000.0 / self.gpu_time_ms } }
    pub fn avg_tris_per_draw(&self) -> f64 { if self.draw_calls == 0 { 0.0 } else { self.triangles as f64 / self.draw_calls as f64 } }
    pub fn total_ms(&self) -> f32 { self.gpu_time_ms + self.cpu_time_ms }
}

// ── More shader constants ─────────────────────────────────────────────────────

pub const TEXTURE_MAX_SIZE: u32 = 16384;
pub const TEXTURE_MAX_MIP_LEVELS: u32 = 15;
pub const TEXTURE_MAX_ARRAY_LAYERS: u32 = 2048;
pub const SAMPLER_MAX_ANISOTROPY: u32 = 16;
pub const BUFFER_ALIGNMENT: u32 = 256;
pub const VERTEX_LAYOUT_MAX_ATTRIBUTES: usize = 16;
pub const COMPUTE_MAX_WORKGROUP_SIZE: u32 = 1024;
pub const RENDER_PASS_MAX_COLOR_ATTACHMENTS: usize = 8;
pub const GPU_MEMORY_BUDGET_DEFAULT_MB: u64 = 4096;
pub const MATERIAL_DEFAULT_RENDER_QUEUE: u32 = 2000;

pub fn texture_format_name(fmt: &AttachmentFormat) -> &'static str { attachment_format_name(fmt) }
pub fn vertex_format_size(fmt: VertexAttribFormat) -> u32 { fmt.size_bytes() }
pub fn buffer_aligned_size(size: u64) -> u64 { (size + BUFFER_ALIGNMENT as u64 - 1) & !(BUFFER_ALIGNMENT as u64 - 1) }
pub fn is_power_of_two(n: u32) -> bool { n > 0 && (n & (n - 1)) == 0 }
pub fn next_power_of_two(n: u32) -> u32 { if n == 0 { 1 } else { let mut p = n; p -= 1; p |= p >> 1; p |= p >> 2; p |= p >> 4; p |= p >> 8; p |= p >> 16; p + 1 } }
pub fn mip_count(width: u32, height: u32) -> u32 { TextureDescriptor::mip_count_for_size(width, height) }
pub fn shader_compiler_full_info() -> String {
    format!("ShaderCompiler — {} target platforms, materials, textures, buffers, render pipeline", shader_target_count())
}


// ── Lighting Model ────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct LightingModel {
    pub name: String,
    pub model_type: LightingModelType,
    pub diffuse_weight: f32,
    pub specular_weight: f32,
    pub ambient_weight: f32,
    pub subsurface_weight: f32,
    pub emission_weight: f32,
    pub roughness: f32,
    pub metalness: f32,
    pub ior: f32,
    pub transmission: f32,
    pub anisotropy: f32,
    pub clearcoat: f32,
    pub sheen: f32,
}

#[derive(Clone, Debug, PartialEq)]
pub enum LightingModelType { Phong, BlinnPhong, Pbr, Lambert, Toon, Unlit, Custom(String) }

impl LightingModel {
    pub fn phong() -> Self { Self { name: "Phong".into(), model_type: LightingModelType::Phong, diffuse_weight: 1.0, specular_weight: 0.5, ambient_weight: 0.1, subsurface_weight: 0.0, emission_weight: 0.0, roughness: 0.5, metalness: 0.0, ior: 1.5, transmission: 0.0, anisotropy: 0.0, clearcoat: 0.0, sheen: 0.0 } }
    pub fn pbr() -> Self { Self { name: "PBR".into(), model_type: LightingModelType::Pbr, diffuse_weight: 1.0, specular_weight: 1.0, ambient_weight: 0.1, subsurface_weight: 0.0, emission_weight: 0.0, roughness: 0.5, metalness: 0.0, ior: 1.5, transmission: 0.0, anisotropy: 0.0, clearcoat: 0.0, sheen: 0.0 } }
    pub fn unlit() -> Self { Self { name: "Unlit".into(), model_type: LightingModelType::Unlit, diffuse_weight: 0.0, specular_weight: 0.0, ambient_weight: 0.0, subsurface_weight: 0.0, emission_weight: 1.0, roughness: 1.0, metalness: 0.0, ior: 1.0, transmission: 0.0, anisotropy: 0.0, clearcoat: 0.0, sheen: 0.0 } }
    pub fn toon() -> Self { Self { name: "Toon".into(), model_type: LightingModelType::Toon, diffuse_weight: 1.0, specular_weight: 1.0, ambient_weight: 0.2, subsurface_weight: 0.0, emission_weight: 0.0, roughness: 1.0, metalness: 0.0, ior: 1.5, transmission: 0.0, anisotropy: 0.0, clearcoat: 0.0, sheen: 0.0 } }
    pub fn is_pbr(&self) -> bool { self.model_type == LightingModelType::Pbr }
    pub fn is_unlit(&self) -> bool { self.model_type == LightingModelType::Unlit }
    pub fn is_toon(&self) -> bool { self.model_type == LightingModelType::Toon }
    pub fn uses_ibl(&self) -> bool { self.is_pbr() }
    pub fn glsl_function_name(&self) -> &str {
        match self.model_type { LightingModelType::Phong => "shade_phong", LightingModelType::BlinnPhong => "shade_blinn_phong", LightingModelType::Pbr => "shade_pbr", LightingModelType::Lambert => "shade_lambert", LightingModelType::Toon => "shade_toon", LightingModelType::Unlit => "shade_unlit", _ => "shade_custom" }
    }
}

impl Default for LightingModel {
    fn default() -> Self { Self::pbr() }
}

// ── GLSL Code Snippets ────────────────────────────────────────────────────────

pub struct GlslSnippet {
    pub name: &'static str,
    pub code: &'static str,
    pub dependencies: &'static [&'static str],
}

pub const SNIPPET_GAMMA_CORRECT: GlslSnippet = GlslSnippet {
    name: "gamma_correct",
    code: "vec3 gamma_correct(vec3 color) { return pow(clamp(color, 0.0, 1.0), vec3(1.0 / 2.2)); }",
    dependencies: &[],
};

pub const SNIPPET_LINEAR_TO_SRGB: GlslSnippet = GlslSnippet {
    name: "linear_to_srgb",
    code: "vec3 linear_to_srgb(vec3 c) { return mix(c * 12.92, 1.055 * pow(c, vec3(1.0/2.4)) - 0.055, step(vec3(0.0031308), c)); }",
    dependencies: &[],
};

pub const SNIPPET_SRGB_TO_LINEAR: GlslSnippet = GlslSnippet {
    name: "srgb_to_linear",
    code: "vec3 srgb_to_linear(vec3 c) { return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), c)); }",
    dependencies: &[],
};

pub const SNIPPET_ACES_TONEMAP: GlslSnippet = GlslSnippet {
    name: "aces_tonemap",
    code: "vec3 aces_tonemap(vec3 x) { float a=2.51; float b=0.03; float c=2.43; float d=0.59; float e=0.14; return clamp((x*(a*x+b))/(x*(c*x+d)+e),0.0,1.0); }",
    dependencies: &[],
};

pub const SNIPPET_REINHARD_TONEMAP: GlslSnippet = GlslSnippet {
    name: "reinhard",
    code: "vec3 reinhard(vec3 c) { return c / (c + vec3(1.0)); }",
    dependencies: &[],
};

pub const SNIPPET_FRESNEL: GlslSnippet = GlslSnippet {
    name: "fresnel_schlick",
    code: "vec3 fresnel_schlick(float cosTheta, vec3 F0) { return F0 + (1.0 - F0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0); }",
    dependencies: &[],
};

pub const SNIPPET_NDF_GGX: GlslSnippet = GlslSnippet {
    name: "ndf_ggx",
    code: "float ndf_ggx(vec3 N, vec3 H, float roughness) { float a = roughness*roughness; float a2 = a*a; float NdotH = max(dot(N,H),0.0); float NdotH2 = NdotH*NdotH; float num = a2; float denom = NdotH2*(a2-1.0)+1.0; denom = 3.14159265*denom*denom; return num/denom; }",
    dependencies: &[],
};

pub const SNIPPET_GEOMETRY_SMITH: GlslSnippet = GlslSnippet {
    name: "geometry_smith",
    code: "float geometry_schlick_ggx(float NdotV, float r) { float r2=(r+1.0); float k=r2*r2/8.0; return NdotV/(NdotV*(1.0-k)+k); } float geometry_smith(vec3 N, vec3 V, vec3 L, float r) { return geometry_schlick_ggx(max(dot(N,V),0.0),r)*geometry_schlick_ggx(max(dot(N,L),0.0),r); }",
    dependencies: &[],
};

pub const SNIPPET_SHADOW_PCF: GlslSnippet = GlslSnippet {
    name: "shadow_pcf",
    code: "float shadow_pcf(sampler2DShadow shadowMap, vec4 shadowCoord) { float shadow = 0.0; vec2 texelSize = 1.0/textureSize(shadowMap,0); for(int x=-1;x<=1;++x) for(int y=-1;y<=1;++y) shadow += texture(shadowMap, shadowCoord.xyz/shadowCoord.w + vec3(vec2(x,y)*texelSize,0)); return shadow/9.0; }",
    dependencies: &[],
};

pub const SNIPPET_NORMAL_FROM_MAP: GlslSnippet = GlslSnippet {
    name: "normal_from_map",
    code: "vec3 normal_from_map(sampler2D normalMap, vec2 uv, vec3 worldNormal, vec3 worldTangent) { vec3 n = texture(normalMap, uv).xyz * 2.0 - 1.0; vec3 T = normalize(worldTangent - dot(worldTangent,worldNormal)*worldNormal); vec3 B = cross(worldNormal, T); mat3 TBN = mat3(T,B,worldNormal); return normalize(TBN * n); }",
    dependencies: &[],
};

pub const SNIPPET_PARALLAX_OCCLUSION: GlslSnippet = GlslSnippet {
    name: "parallax_occlusion",
    code: "vec2 parallax_mapping(sampler2D heightMap, vec2 uv, vec3 viewDir, float scale) { float numLayers = mix(32.0, 8.0, abs(dot(vec3(0,0,1),viewDir))); float layerDepth = 1.0/numLayers; float currentDepth = 0.0; vec2 P = viewDir.xy/viewDir.z*scale; vec2 deltaTexCoords = P/numLayers; vec2 currentTexCoords = uv; float currentDepthMapValue = 1.0 - texture(heightMap,currentTexCoords).r; while(currentDepth < currentDepthMapValue) { currentTexCoords -= deltaTexCoords; currentDepthMapValue = 1.0 - texture(heightMap,currentTexCoords).r; currentDepth += layerDepth; } return currentTexCoords; }",
    dependencies: &[],
};

// ── Shader Library ────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderLibrary {
    pub snippets: HashMap<String, String>,
    pub categories: HashMap<String, Vec<String>>,
}

impl ShaderLibrary {
    pub fn new() -> Self { Self { snippets: HashMap::new(), categories: HashMap::new() } }
    pub fn add(&mut self, name: impl Into<String>, code: impl Into<String>, category: impl Into<String>) {
        let n = name.into(); let cat = category.into();
        self.snippets.insert(n.clone(), code.into());
        self.categories.entry(cat).or_default().push(n);
    }
    pub fn get(&self, name: &str) -> Option<&str> { self.snippets.get(name).map(|s| s.as_str()) }
    pub fn in_category(&self, cat: &str) -> Vec<&str> {
        self.categories.get(cat).map(|names| names.iter().map(|n| self.snippets.get(n.as_str()).map(|_| n.as_str()).unwrap_or("")).collect()).unwrap_or_default()
    }
    pub fn count(&self) -> usize { self.snippets.len() }
    pub fn build_standard() -> Self {
        let mut lib = Self::new();
        lib.add("gamma_correct", SNIPPET_GAMMA_CORRECT.code, "color");
        lib.add("linear_to_srgb", SNIPPET_LINEAR_TO_SRGB.code, "color");
        lib.add("srgb_to_linear", SNIPPET_SRGB_TO_LINEAR.code, "color");
        lib.add("aces_tonemap", SNIPPET_ACES_TONEMAP.code, "tonemap");
        lib.add("reinhard", SNIPPET_REINHARD_TONEMAP.code, "tonemap");
        lib.add("fresnel_schlick", SNIPPET_FRESNEL.code, "pbr");
        lib.add("ndf_ggx", SNIPPET_NDF_GGX.code, "pbr");
        lib.add("geometry_smith", SNIPPET_GEOMETRY_SMITH.code, "pbr");
        lib.add("shadow_pcf", SNIPPET_SHADOW_PCF.code, "shadow");
        lib.add("normal_from_map", SNIPPET_NORMAL_FROM_MAP.code, "normal");
        lib.add("parallax_occlusion", SNIPPET_PARALLAX_OCCLUSION.code, "normal");
        lib
    }
}

impl Default for ShaderLibrary {
    fn default() -> Self { Self::build_standard() }
}

// ── Shader Debug Tools ────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderDebugOutput {
    pub name: String,
    pub output_type: DebugOutputType,
    pub channel_mask: [bool; 4],
    pub scale: f32,
    pub bias: f32,
    pub enabled: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub enum DebugOutputType { Albedo, Normal, Roughness, Metalness, Depth, AmbientOcclusion, Emission, Velocity, ShadowMap, LightContribution, Custom(String) }

impl ShaderDebugOutput {
    pub fn new(name: impl Into<String>, output_type: DebugOutputType) -> Self {
        Self { name: name.into(), output_type, channel_mask: [true; 4], scale: 1.0, bias: 0.0, enabled: true }
    }
    pub fn depth() -> Self { let mut d = Self::new("Depth", DebugOutputType::Depth); d.scale = 100.0; d }
    pub fn normal() -> Self { let mut d = Self::new("Normal", DebugOutputType::Normal); d.bias = 0.5; d }
    pub fn glsl_code(&self) -> String {
        format!("// Debug output: {}", self.name)
    }
}

#[derive(Clone, Debug)]
pub struct ShaderDebugger {
    pub outputs: Vec<ShaderDebugOutput>,
    pub active_output: Option<usize>,
    pub enabled: bool,
    pub show_overdraw: bool,
    pub show_wireframe: bool,
    pub show_normals: bool,
}

impl ShaderDebugger {
    pub fn new() -> Self { Self { outputs: Vec::new(), active_output: None, enabled: false, show_overdraw: false, show_wireframe: false, show_normals: false } }
    pub fn add_output(&mut self, output: ShaderDebugOutput) { self.outputs.push(output); }
    pub fn activate(&mut self, idx: usize) { self.active_output = Some(idx); self.enabled = true; }
    pub fn deactivate(&mut self) { self.active_output = None; self.enabled = false; }
    pub fn active(&self) -> Option<&ShaderDebugOutput> { self.active_output.and_then(|i| self.outputs.get(i)) }
    pub fn output_count(&self) -> usize { self.outputs.len() }
    pub fn build_defaults() -> Self {
        let mut d = Self::new();
        d.add_output(ShaderDebugOutput::new("Albedo", DebugOutputType::Albedo));
        d.add_output(ShaderDebugOutput::normal());
        d.add_output(ShaderDebugOutput::new("Roughness", DebugOutputType::Roughness));
        d.add_output(ShaderDebugOutput::new("Metalness", DebugOutputType::Metalness));
        d.add_output(ShaderDebugOutput::depth());
        d.add_output(ShaderDebugOutput::new("AO", DebugOutputType::AmbientOcclusion));
        d
    }
}

impl Default for ShaderDebugger {
    fn default() -> Self { Self::build_defaults() }
}

// ── Shader Profiler ───────────────────────────────────────────────────────────

#[derive(Clone, Debug, Default)]
pub struct ShaderProfileEntry {
    pub shader_id: u32,
    pub shader_name: String,
    pub gpu_time_ms: f32,
    pub draw_calls: u32,
    pub triangles: u64,
    pub frame_count: u64,
    pub avg_gpu_ms: f32,
}

impl ShaderProfileEntry {
    pub fn new(shader_id: u32, name: impl Into<String>) -> Self { Self { shader_id, shader_name: name.into(), ..Default::default() } }
    pub fn record_frame(&mut self, gpu_ms: f32, draws: u32, tris: u64) {
        self.gpu_time_ms = gpu_ms;
        self.draw_calls = draws;
        self.triangles = tris;
        self.avg_gpu_ms = (self.avg_gpu_ms * self.frame_count as f32 + gpu_ms) / (self.frame_count + 1) as f32;
        self.frame_count += 1;
    }
    pub fn is_expensive(&self) -> bool { self.avg_gpu_ms > 2.0 }
}

#[derive(Clone, Debug)]
pub struct ShaderProfiler {
    pub entries: HashMap<u32, ShaderProfileEntry>,
    pub enabled: bool,
    pub frame: u64,
}

impl ShaderProfiler {
    pub fn new() -> Self { Self { entries: HashMap::new(), enabled: false, frame: 0 } }
    pub fn enable(&mut self) { self.enabled = true; }
    pub fn disable(&mut self) { self.enabled = false; }
    pub fn begin_frame(&mut self) { self.frame += 1; }
    pub fn record(&mut self, shader_id: u32, name: &str, gpu_ms: f32, draws: u32, tris: u64) {
        if !self.enabled { return; }
        self.entries.entry(shader_id).or_insert_with(|| ShaderProfileEntry::new(shader_id, name)).record_frame(gpu_ms, draws, tris);
    }
    pub fn expensive_shaders(&self) -> Vec<&ShaderProfileEntry> { self.entries.values().filter(|e| e.is_expensive()).collect() }
    pub fn total_gpu_ms(&self) -> f32 { self.entries.values().map(|e| e.gpu_time_ms).sum() }
    pub fn shader_count(&self) -> usize { self.entries.len() }
}

impl Default for ShaderProfiler {
    fn default() -> Self { Self::new() }
}

// ── Shader Hot Reload Manager ─────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct HotReloadManager {
    pub watcher: ShaderFileWatcher,
    pub registry: ShaderProgramRegistry,
    pub reload_count: u32,
    pub last_reload_time: f32,
    pub reload_on_focus: bool,
    pub auto_save_on_compile: bool,
}

impl HotReloadManager {
    pub fn new() -> Self { Self { watcher: ShaderFileWatcher::new(), registry: ShaderProgramRegistry::new(), reload_count: 0, last_reload_time: 0.0, reload_on_focus: true, auto_save_on_compile: false } }
    pub fn watch_shader(&mut self, path: impl Into<String>, shader_id: u32) { self.watcher.watch(path, shader_id); }
    pub fn tick(&mut self, _dt: f32) -> Vec<u32> {
        let mut reloaded = Vec::new();
        while let Some(path) = self.watcher.next_reload() {
            let ids = self.watcher.shader_ids_for(&path);
            reloaded.extend_from_slice(&ids);
            self.reload_count += ids.len() as u32;
        }
        reloaded
    }
    pub fn force_reload_all(&mut self) {
        let paths: Vec<_> = self.watcher.watched_files.keys().cloned().collect();
        for path in paths { self.watcher.mark_modified(&path); }
    }
    pub fn reload_count(&self) -> u32 { self.reload_count }
}

impl Default for HotReloadManager {
    fn default() -> Self { Self::new() }
}

// ── More constants ────────────────────────────────────────────────────────────

pub const LIGHTING_MODEL_COUNT: usize = 7;
pub const SHADER_LIBRARY_STANDARD_SNIPPET_COUNT: usize = 11;
pub const SHADER_DEBUG_OUTPUT_MAX: usize = 16;
pub const SHADER_PROFILER_EXPENSIVE_THRESHOLD_MS: f32 = 2.0;
pub const SHADER_HOT_RELOAD_DEBOUNCE_MS: u32 = 300;
pub const MATERIAL_MAX_BLEND_MODES: usize = 8;
pub const SHADER_SNIPPET_MAX_SIZE_CHARS: usize = 4096;
pub const GLSL_MAX_VARYING_COMPONENTS: u32 = 128;
pub const GLSL_MAX_TEXTURE_SAMPLERS: u32 = 16;
pub const GLSL_MAX_UNIFORM_BLOCKS: u32 = 14;
pub const WGSL_MAX_BIND_GROUPS: u32 = 4;
pub const WGSL_MAX_BINDINGS_PER_GROUP: u32 = 8;

pub fn lighting_model_name(model: &LightingModel) -> &str { &model.name }
pub fn shader_system_info() -> String { format!("ShaderSystem: compiler + materials + textures + buffers + post-process + lighting + hot-reload") }


// ── Shader Permutation System ─────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderPermutationKey {
    pub features: Vec<String>,
}

impl ShaderPermutationKey {
    pub fn new() -> Self { Self { features: Vec::new() } }
    pub fn with(mut self, feature: impl Into<String>) -> Self { self.features.push(feature.into()); self }
    pub fn add(&mut self, feature: impl Into<String>) { self.features.push(feature.into()); }
    pub fn hash_key(&self) -> u64 {
        let mut sorted = self.features.clone(); sorted.sort();
        sorted.iter().fold(14695981039346656037u64, |h, s| s.bytes().fold(h, |h, b| h.wrapping_mul(1099511628211) ^ b as u64))
    }
    pub fn has(&self, feature: &str) -> bool { self.features.contains(&feature.to_string()) }
    pub fn feature_count(&self) -> usize { self.features.len() }
    pub fn is_empty(&self) -> bool { self.features.is_empty() }
}

impl Default for ShaderPermutationKey {
    fn default() -> Self { Self::new() }
}

#[derive(Clone, Debug)]
pub struct ShaderPermutationRegistry {
    pub permutations: HashMap<u64, ShaderProgram>,
    pub keys: HashMap<u64, ShaderPermutationKey>,
    pub max_permutations: usize,
    pub base_program_id: u32,
}

impl ShaderPermutationRegistry {
    pub fn new(base_id: u32, max: usize) -> Self { Self { permutations: HashMap::new(), keys: HashMap::new(), max_permutations: max, base_program_id: base_id } }
    pub fn register(&mut self, key: ShaderPermutationKey, program: ShaderProgram) -> bool {
        if self.permutations.len() >= self.max_permutations { return false; }
        let h = key.hash_key();
        self.permutations.insert(h, program);
        self.keys.insert(h, key);
        true
    }
    pub fn find(&self, key: &ShaderPermutationKey) -> Option<&ShaderProgram> { self.permutations.get(&key.hash_key()) }
    pub fn count(&self) -> usize { self.permutations.len() }
    pub fn clear(&mut self) { self.permutations.clear(); self.keys.clear(); }
}

// ── Shader Reflection Extended ────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderBindingLayout {
    pub set: u32,
    pub bindings: Vec<DescriptorBinding>,
}

#[derive(Clone, Debug)]
pub struct DescriptorBinding {
    pub binding: u32,
    pub descriptor_type: DescriptorType,
    pub count: u32,
    pub stages: Vec<ShaderStage>,
    pub name: String,
}

#[derive(Clone, Debug, PartialEq)]
pub enum DescriptorType { UniformBuffer, StorageBuffer, Sampler, SampledImage, StorageImage, CombinedImageSampler, InputAttachment }

#[derive(Clone, Debug, PartialEq)]
pub enum ShaderStage { Vertex, Fragment, Geometry, TessControl, TessEval, Compute, All }

impl ShaderBindingLayout {
    pub fn new(set: u32) -> Self { Self { set, bindings: Vec::new() } }
    pub fn add_binding(&mut self, binding: u32, desc_type: DescriptorType, name: impl Into<String>) {
        self.bindings.push(DescriptorBinding { binding, descriptor_type: desc_type, count: 1, stages: vec![ShaderStage::All], name: name.into() });
    }
    pub fn binding_count(&self) -> usize { self.bindings.len() }
    pub fn has_binding(&self, binding: u32) -> bool { self.bindings.iter().any(|b| b.binding == binding) }
}

#[derive(Clone, Debug)]
pub struct PipelineLayout {
    pub descriptor_sets: Vec<ShaderBindingLayout>,
    pub push_constant_size: u32,
    pub push_constant_stages: Vec<ShaderStage>,
}

impl PipelineLayout {
    pub fn new() -> Self { Self { descriptor_sets: Vec::new(), push_constant_size: 0, push_constant_stages: Vec::new() } }
    pub fn add_set(&mut self, layout: ShaderBindingLayout) { self.descriptor_sets.push(layout); }
    pub fn set_push_constants(&mut self, size: u32) { self.push_constant_size = size; self.push_constant_stages = vec![ShaderStage::Vertex, ShaderStage::Fragment]; }
    pub fn set_count(&self) -> usize { self.descriptor_sets.len() }
    pub fn has_push_constants(&self) -> bool { self.push_constant_size > 0 }
    pub fn total_bindings(&self) -> usize { self.descriptor_sets.iter().map(|s| s.binding_count()).sum() }
}

impl Default for PipelineLayout {
    fn default() -> Self { Self::new() }
}

// ── Shader Compile Pipeline ───────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct CompilePipelineConfig {
    pub optimizer: ShaderOptimizer,
    pub codegen: ShaderCodeGen,
    pub preprocessor: ShaderPreprocessor,
    pub include_resolver: ShaderIncludeResolver,
    pub cache: ShaderCache,
    pub diagnostic_limit: usize,
    pub strict_mode: bool,
    pub pedantic: bool,
}

impl CompilePipelineConfig {
    pub fn new(target: CodeGenTarget) -> Self {
        Self { optimizer: ShaderOptimizer::default(), codegen: ShaderCodeGen::new(target), preprocessor: ShaderPreprocessor::new(), include_resolver: ShaderIncludeResolver::new(), cache: ShaderCache::default(), diagnostic_limit: SHADER_DIAGNOSTIC_MAX, strict_mode: false, pedantic: false }
    }
    pub fn debug_config(target: CodeGenTarget) -> Self {
        let mut c = Self::new(target); c.optimizer = ShaderOptimizer::debug(); c
    }
    pub fn release_config(target: CodeGenTarget) -> Self {
        let mut c = Self::new(target); c.optimizer = ShaderOptimizer::release(); c
    }
    pub fn add_define(&mut self, key: impl Into<String>, val: impl Into<String>) { self.preprocessor.define(key, val); }
}

#[derive(Clone, Debug)]
pub struct CompileResult {
    pub success: bool,
    pub spirv_bytes: Option<Vec<u8>>,
    pub diagnostics: DiagnosticList,
    pub reflection: ShaderReflection,
    pub compile_time_ms: f32,
    pub source_lines: u32,
    pub optimized: bool,
}

impl CompileResult {
    pub fn ok(spirv: Vec<u8>, reflection: ShaderReflection) -> Self {
        Self { success: true, spirv_bytes: Some(spirv), diagnostics: DiagnosticList::new(), reflection, compile_time_ms: 0.0, source_lines: 0, optimized: false }
    }
    pub fn fail(diagnostics: DiagnosticList) -> Self {
        Self { success: false, spirv_bytes: None, diagnostics, reflection: ShaderReflection::new(), compile_time_ms: 0.0, source_lines: 0, optimized: false }
    }
    pub fn error_count(&self) -> usize { self.diagnostics.error_count() }
    pub fn warning_count(&self) -> usize { self.diagnostics.warning_count() }
    pub fn spirv_size(&self) -> usize { self.spirv_bytes.as_ref().map(|b| b.len()).unwrap_or(0) }
    pub fn has_warnings(&self) -> bool { self.diagnostics.warning_count() > 0 }
}

// ── Shader Editor State ───────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderEditorState {
    pub active_program_id: Option<u32>,
    pub active_stage: ShaderStage,
    pub cursor_line: u32,
    pub cursor_col: u32,
    pub scroll_top: u32,
    pub selection: Option<(u32, u32, u32, u32)>,
    pub font_size: f32,
    pub show_line_numbers: bool,
    pub show_minimap: bool,
    pub syntax_highlight: bool,
    pub auto_complete: bool,
    pub bracket_matching: bool,
    pub indent_guides: bool,
    pub word_wrap: bool,
    pub theme: String,
    pub undo_stack: VecDeque<String>,
    pub redo_stack: Vec<String>,
    pub modified: bool,
}

impl ShaderEditorState {
    pub fn new() -> Self {
        Self { active_program_id: None, active_stage: ShaderStage::Fragment, cursor_line: 0, cursor_col: 0, scroll_top: 0, selection: None, font_size: 14.0, show_line_numbers: true, show_minimap: true, syntax_highlight: true, auto_complete: true, bracket_matching: true, indent_guides: true, word_wrap: false, theme: "dark".into(), undo_stack: VecDeque::new(), redo_stack: Vec::new(), modified: false }
    }
    pub fn set_active(&mut self, id: u32, stage: ShaderStage) { self.active_program_id = Some(id); self.active_stage = stage; self.cursor_line = 0; self.cursor_col = 0; }
    pub fn move_cursor(&mut self, line: u32, col: u32) { self.cursor_line = line; self.cursor_col = col; }
    pub fn push_undo(&mut self, desc: impl Into<String>) { if self.undo_stack.len() >= 100 { self.undo_stack.pop_front(); } self.undo_stack.push_back(desc.into()); self.redo_stack.clear(); self.modified = true; }
    pub fn can_undo(&self) -> bool { !self.undo_stack.is_empty() }
    pub fn can_redo(&self) -> bool { !self.redo_stack.is_empty() }
    pub fn undo(&mut self) -> Option<String> { let v = self.undo_stack.pop_back()?; self.redo_stack.push(v.clone()); Some(v) }
    pub fn redo(&mut self) -> Option<String> { let v = self.redo_stack.pop()?; self.undo_stack.push_back(v.clone()); Some(v) }
    pub fn mark_saved(&mut self) { self.modified = false; }
    pub fn increase_font(&mut self) { self.font_size = (self.font_size + 1.0).min(48.0); }
    pub fn decrease_font(&mut self) { self.font_size = (self.font_size - 1.0).max(8.0); }
}

impl Default for ShaderEditorState {
    fn default() -> Self { Self::new() }
}

// ── Autocomplete Provider ─────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct AutoCompleteItem {
    pub label: String,
    pub kind: AutoCompleteKind,
    pub detail: String,
    pub insert_text: String,
    pub documentation: String,
}

#[derive(Clone, Debug, PartialEq)]
pub enum AutoCompleteKind { Function, Variable, Type, Keyword, Snippet, Uniform }

impl AutoCompleteItem {
    pub fn function(name: impl Into<String>, signature: impl Into<String>) -> Self {
        let n = name.into();
        Self { label: n.clone(), kind: AutoCompleteKind::Function, detail: signature.into(), insert_text: n, documentation: String::new() }
    }
    pub fn type_item(name: &'static str) -> Self {
        Self { label: name.into(), kind: AutoCompleteKind::Type, detail: "GLSL type".into(), insert_text: name.into(), documentation: String::new() }
    }
    pub fn keyword(kw: &'static str) -> Self {
        Self { label: kw.into(), kind: AutoCompleteKind::Keyword, detail: "keyword".into(), insert_text: kw.into(), documentation: String::new() }
    }
}

#[derive(Clone, Debug)]
pub struct AutoCompleteProvider {
    pub builtins: Vec<AutoCompleteItem>,
    pub user_symbols: Vec<AutoCompleteItem>,
    pub max_results: usize,
}

impl AutoCompleteProvider {
    pub fn new() -> Self {
        let mut builtins = Vec::new();
        for kw in &["void", "float", "int", "uint", "bool", "vec2", "vec3", "vec4", "mat3", "mat4", "sampler2D"] {
            builtins.push(AutoCompleteItem::type_item(kw));
        }
        for kw in &["if", "else", "for", "while", "return", "break", "continue", "discard", "uniform", "in", "out", "const"] {
            builtins.push(AutoCompleteItem::keyword(kw));
        }
        for (name, sig) in &[("normalize", "vec3 normalize(vec3)"), ("length", "float length(genType)"), ("dot", "float dot(genType, genType)"), ("cross", "vec3 cross(vec3, vec3)"), ("reflect", "genType reflect(genType, genType)"), ("refract", "genType refract(genType, genType, float)"), ("mix", "genType mix(genType, genType, genType)"), ("clamp", "genType clamp(genType, genType, genType)"), ("pow", "genType pow(genType, genType)"), ("sqrt", "genType sqrt(genType)"), ("abs", "genType abs(genType)"), ("max", "genType max(genType, genType)"), ("min", "genType min(genType, genType)"), ("texture", "vec4 texture(sampler2D, vec2)"), ("step", "genType step(genType, genType)"), ("smoothstep", "genType smoothstep(genType, genType, genType)"), ("sin", "genType sin(genType)"), ("cos", "genType cos(genType)"), ("tan", "genType tan(genType)"), ("floor", "genType floor(genType)"), ("ceil", "genType ceil(genType)"), ("fract", "genType fract(genType)"), ("mod", "genType mod(genType, genType)"), ("sign", "genType sign(genType)"), ("distance", "float distance(genType, genType)"), ("transpose", "mat transpose(mat)"), ("inverse", "mat inverse(mat)"), ("determinant", "float determinant(mat)")] {
            builtins.push(AutoCompleteItem::function(*name, *sig));
        }
        Self { builtins, user_symbols: Vec::new(), max_results: 20 }
    }
    pub fn query(&self, prefix: &str) -> Vec<&AutoCompleteItem> {
        let lower = prefix.to_lowercase();
        let mut results: Vec<_> = self.builtins.iter().chain(self.user_symbols.iter()).filter(|item| item.label.to_lowercase().starts_with(&lower)).collect();
        results.truncate(self.max_results);
        results
    }
    pub fn add_user_symbol(&mut self, item: AutoCompleteItem) { self.user_symbols.push(item); }
    pub fn clear_user_symbols(&mut self) { self.user_symbols.clear(); }
    pub fn builtin_count(&self) -> usize { self.builtins.len() }
}

impl Default for AutoCompleteProvider {
    fn default() -> Self { Self::new() }
}

// ── Constants ─────────────────────────────────────────────────────────────────

pub const SHADER_EDITOR_MAX_UNDO: usize = 200;
pub const SHADER_AUTOCOMPLETE_MAX_RESULTS: usize = 20;
pub const SHADER_PERMUTATION_MAX: usize = 512;
pub const SHADER_BINDING_SET_MAX: usize = 4;
pub const SHADER_BINDING_MAX_PER_SET: usize = 16;
pub const SHADER_STAGE_COUNT: usize = 6;
pub const SHADER_PUSH_CONSTANT_MAX_BYTES: u32 = 128;

pub fn shader_stage_name(stage: &ShaderStage) -> &'static str {
    match stage { ShaderStage::Vertex => "vertex", ShaderStage::Fragment => "fragment", ShaderStage::Geometry => "geometry", ShaderStage::TessControl => "tess_control", ShaderStage::TessEval => "tess_eval", ShaderStage::Compute => "compute", ShaderStage::All => "all" }
}
pub fn descriptor_type_name(dt: &DescriptorType) -> &'static str {
    match dt { DescriptorType::UniformBuffer => "UniformBuffer", DescriptorType::StorageBuffer => "StorageBuffer", DescriptorType::Sampler => "Sampler", DescriptorType::SampledImage => "SampledImage", DescriptorType::StorageImage => "StorageImage", DescriptorType::CombinedImageSampler => "CombinedImageSampler", DescriptorType::InputAttachment => "InputAttachment" }
}


// ── Shader Input/Output Binding Validation ────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderInterface {
    pub inputs: Vec<ShaderVariable>,
    pub outputs: Vec<ShaderVariable>,
    pub stage: ShaderStage,
}

impl ShaderInterface {
    pub fn new(stage: ShaderStage) -> Self { Self { inputs: Vec::new(), outputs: Vec::new(), stage } }
    pub fn add_input(&mut self, var: ShaderVariable) { self.inputs.push(var); }
    pub fn add_output(&mut self, var: ShaderVariable) { self.outputs.push(var); }
    pub fn input_count(&self) -> usize { self.inputs.len() }
    pub fn output_count(&self) -> usize { self.outputs.len() }
    pub fn find_input(&self, name: &str) -> Option<&ShaderVariable> { self.inputs.iter().find(|v| v.name == name) }
    pub fn find_output(&self, name: &str) -> Option<&ShaderVariable> { self.outputs.iter().find(|v| v.name == name) }
    pub fn validate_compatible(&self, next: &ShaderInterface) -> Vec<String> {
        let mut errors = Vec::new();
        for out in &self.outputs {
            if !next.inputs.iter().any(|i| i.name == out.name && i.data_type == out.data_type) {
                errors.push(format!("Output '{}' not matched in next stage", out.name));
            }
        }
        errors
    }
    pub fn total_output_components(&self) -> u32 { self.outputs.iter().map(|o| o.data_type.byte_size() / 4).sum() }
}

// ── Shader Program Linker ─────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderLinker {
    pub programs: HashMap<u32, ShaderProgram>,
    pub layouts: HashMap<u32, PipelineLayout>,
    pub link_errors: Vec<String>,
}

impl ShaderLinker {
    pub fn new() -> Self { Self { programs: HashMap::new(), layouts: HashMap::new(), link_errors: Vec::new() } }
    pub fn add_program(&mut self, prog: ShaderProgram) { self.programs.insert(prog.id, prog); }
    pub fn link(&mut self, prog_id: u32) -> bool {
        self.link_errors.clear();
        if !self.programs.contains_key(&prog_id) { self.link_errors.push("Program not found".into()); return false; }
        true
    }
    pub fn has_errors(&self) -> bool { !self.link_errors.is_empty() }
    pub fn error_count(&self) -> usize { self.link_errors.len() }
    pub fn clear_errors(&mut self) { self.link_errors.clear(); }
}

impl Default for ShaderLinker {
    fn default() -> Self { Self::new() }
}

// ── Shader Export ─────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderExportOptions {
    pub target: CodeGenTarget,
    pub minify: bool,
    pub include_reflection: bool,
    pub include_source: bool,
    pub embed_spirv: bool,
    pub output_format: ShaderExportFormat,
    pub output_path: String,
}

#[derive(Clone, Debug, PartialEq)]
pub enum ShaderExportFormat { Glsl, SpirV, Wgsl, Json, Binary }

impl ShaderExportOptions {
    pub fn new(target: CodeGenTarget) -> Self {
        Self { target, minify: false, include_reflection: true, include_source: true, embed_spirv: false, output_format: ShaderExportFormat::Glsl, output_path: "./shaders".into() }
    }
    pub fn release(target: CodeGenTarget) -> Self {
        Self { minify: true, include_source: false, ..Self::new(target) }
    }
    pub fn spirv(target: CodeGenTarget) -> Self {
        Self { embed_spirv: true, output_format: ShaderExportFormat::SpirV, ..Self::new(target) }
    }
}

#[derive(Clone, Debug)]
pub struct ShaderExportResult {
    pub success: bool,
    pub programs_exported: u32,
    pub files_written: Vec<String>,
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
    pub total_bytes: u64,
    pub duration_ms: f32,
}

impl ShaderExportResult {
    pub fn ok(count: u32, files: Vec<String>, bytes: u64) -> Self {
        Self { success: true, programs_exported: count, files_written: files, errors: Vec::new(), warnings: Vec::new(), total_bytes: bytes, duration_ms: 0.0 }
    }
    pub fn fail(msg: impl Into<String>) -> Self {
        Self { success: false, programs_exported: 0, files_written: Vec::new(), errors: vec![msg.into()], warnings: Vec::new(), total_bytes: 0, duration_ms: 0.0 }
    }
}

// ── Shader Linting ────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct LintRule {
    pub id: u32,
    pub name: String,
    pub description: String,
    pub severity: DiagnosticKind,
    pub enabled: bool,
    pub pattern: String,
}

impl LintRule {
    pub fn new(id: u32, name: impl Into<String>, severity: DiagnosticKind) -> Self {
        Self { id, name: name.into(), description: String::new(), severity, enabled: true, pattern: String::new() }
    }
    pub fn error(id: u32, name: impl Into<String>) -> Self { Self::new(id, name, DiagnosticKind::Error) }
    pub fn warn(id: u32, name: impl Into<String>) -> Self { Self::new(id, name, DiagnosticKind::Warning) }
    pub fn with_desc(mut self, desc: impl Into<String>) -> Self { self.description = desc.into(); self }
}

#[derive(Clone, Debug)]
pub struct ShaderLinter {
    pub rules: Vec<LintRule>,
    pub enabled: bool,
}

impl ShaderLinter {
    pub fn new() -> Self {
        let mut rules = Vec::new();
        rules.push(LintRule::warn(1, "unused_variable").with_desc("Variable declared but never used"));
        rules.push(LintRule::warn(2, "precision_missing").with_desc("Missing precision qualifier"));
        rules.push(LintRule::error(3, "undefined_variable").with_desc("Variable used before declaration"));
        rules.push(LintRule::warn(4, "divide_by_zero").with_desc("Potential division by constant zero"));
        rules.push(LintRule::warn(5, "comparison_float").with_desc("Float equality comparison may be imprecise"));
        rules.push(LintRule::warn(6, "redundant_cast").with_desc("Unnecessary type cast"));
        rules.push(LintRule::error(7, "wrong_argument_type").with_desc("Function argument type mismatch"));
        rules.push(LintRule::warn(8, "shadowed_variable").with_desc("Variable shadows outer scope declaration"));
        Self { rules, enabled: true }
    }
    pub fn lint(&self, _source: &str) -> DiagnosticList { DiagnosticList::new() }
    pub fn enabled_rules(&self) -> Vec<&LintRule> { self.rules.iter().filter(|r| r.enabled).collect() }
    pub fn disable_rule(&mut self, id: u32) { if let Some(r) = self.rules.iter_mut().find(|r| r.id == id) { r.enabled = false; } }
    pub fn enable_rule(&mut self, id: u32) { if let Some(r) = self.rules.iter_mut().find(|r| r.id == id) { r.enabled = true; } }
    pub fn rule_count(&self) -> usize { self.rules.len() }
}

impl Default for ShaderLinter {
    fn default() -> Self { Self::new() }
}

// ── Shader Formatting ─────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderFormatterConfig {
    pub indent_size: usize,
    pub use_tabs: bool,
    pub max_line_length: usize,
    pub brace_style: BraceStyle,
    pub space_around_operators: bool,
    pub space_after_comma: bool,
    pub trailing_newline: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub enum BraceStyle { Allman, KnR, Stroustrup }

impl ShaderFormatterConfig {
    pub fn default_style() -> Self {
        Self { indent_size: 4, use_tabs: false, max_line_length: 120, brace_style: BraceStyle::KnR, space_around_operators: true, space_after_comma: true, trailing_newline: true }
    }
    pub fn compact() -> Self {
        Self { indent_size: 2, ..Self::default_style() }
    }
}

impl Default for ShaderFormatterConfig {
    fn default() -> Self { Self::default_style() }
}

#[derive(Clone, Debug)]
pub struct ShaderFormatter {
    pub config: ShaderFormatterConfig,
}

impl ShaderFormatter {
    pub fn new() -> Self { Self { config: ShaderFormatterConfig::default() } }
    pub fn format(&self, source: &str) -> String {
        let mut output = String::with_capacity(source.len());
        let mut indent = 0usize;
        for line in source.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with('}') && indent > 0 { indent -= 1; }
            let indent_str = if self.config.use_tabs { "\t".repeat(indent) } else { " ".repeat(indent * self.config.indent_size) };
            output.push_str(&indent_str);
            output.push_str(trimmed);
            output.push('\n');
            if trimmed.ends_with('{') { indent += 1; }
        }
        if self.config.trailing_newline && !output.ends_with('\n') { output.push('\n'); }
        output
    }
    pub fn count_lines(source: &str) -> usize { source.lines().count() }
    pub fn count_characters(source: &str) -> usize { source.chars().count() }
}

impl Default for ShaderFormatter {
    fn default() -> Self { Self::new() }
}

// ── Final shader constants ────────────────────────────────────────────────────

pub const SHADER_LINTER_RULE_COUNT_DEFAULT: usize = 8;
pub const SHADER_FORMATTER_MAX_LINE_LENGTH: usize = 120;
pub const SHADER_EXPORT_FORMAT_COUNT: usize = 5;
pub const SHADER_LINKER_MAX_PROGRAMS: usize = 1024;
pub const SHADER_INTERFACE_MAX_VARYINGS: usize = 32;
pub const SHADER_PERMUTATION_KEY_MAX_FEATURES: usize = 16;

pub fn shader_compiler_module_list() -> &'static [&'static str] {
    &[
        "tokenizer", "preprocessor", "parser", "ast", "codegen",
        "optimizer", "cache", "templates", "variants", "permutations",
        "include_resolver", "reflection", "diagnostics", "pipeline_state",
        "materials", "textures", "buffers", "render_passes", "post_process",
        "node_graph", "hot_reload", "lighting", "library", "debugger",
        "profiler", "editor_state", "autocomplete", "linker", "export",
        "linter", "formatter", "binding_layout",
    ]
}

pub fn shader_module_count() -> usize { shader_compiler_module_list().len() }

pub fn full_shader_system_description() -> String {
    format!("ShaderCompiler: {} modules — full pipeline from GLSL source to compiled GPU program", shader_module_count())
}


// ── Shader Uniform Tracking ───────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct UniformTracker {
    pub float_uniforms: HashMap<String, f32>,
    pub vec2_uniforms: HashMap<String, [f32; 2]>,
    pub vec3_uniforms: HashMap<String, [f32; 3]>,
    pub vec4_uniforms: HashMap<String, [f32; 4]>,
    pub int_uniforms: HashMap<String, i32>,
    pub bool_uniforms: HashMap<String, bool>,
    pub mat4_uniforms: HashMap<String, [[f32; 4]; 4]>,
    pub dirty_flags: HashSet<String>,
    pub upload_count: u64,
}

impl UniformTracker {
    pub fn new() -> Self { Self { float_uniforms: HashMap::new(), vec2_uniforms: HashMap::new(), vec3_uniforms: HashMap::new(), vec4_uniforms: HashMap::new(), int_uniforms: HashMap::new(), bool_uniforms: HashMap::new(), mat4_uniforms: HashMap::new(), dirty_flags: HashSet::new(), upload_count: 0 } }
    pub fn set_float(&mut self, name: impl Into<String>, v: f32) { let n = name.into(); if self.float_uniforms.get(&n) != Some(&v) { self.float_uniforms.insert(n.clone(), v); self.dirty_flags.insert(n); } }
    pub fn set_vec3(&mut self, name: impl Into<String>, v: [f32; 3]) { let n = name.into(); self.vec3_uniforms.insert(n.clone(), v); self.dirty_flags.insert(n); }
    pub fn set_vec4(&mut self, name: impl Into<String>, v: [f32; 4]) { let n = name.into(); self.vec4_uniforms.insert(n.clone(), v); self.dirty_flags.insert(n); }
    pub fn set_int(&mut self, name: impl Into<String>, v: i32) { let n = name.into(); self.int_uniforms.insert(n.clone(), v); self.dirty_flags.insert(n); }
    pub fn set_bool(&mut self, name: impl Into<String>, v: bool) { let n = name.into(); self.bool_uniforms.insert(n.clone(), v); self.dirty_flags.insert(n); }
    pub fn mark_uploaded(&mut self) { self.dirty_flags.clear(); self.upload_count += 1; }
    pub fn dirty_count(&self) -> usize { self.dirty_flags.len() }
    pub fn has_dirty(&self) -> bool { !self.dirty_flags.is_empty() }
    pub fn get_float(&self, name: &str) -> Option<f32> { self.float_uniforms.get(name).copied() }
    pub fn get_vec4(&self, name: &str) -> Option<[f32; 4]> { self.vec4_uniforms.get(name).copied() }
    pub fn total_uniform_count(&self) -> usize { self.float_uniforms.len() + self.vec2_uniforms.len() + self.vec3_uniforms.len() + self.vec4_uniforms.len() + self.int_uniforms.len() + self.bool_uniforms.len() + self.mat4_uniforms.len() }
}

impl Default for UniformTracker {
    fn default() -> Self { Self::new() }
}

// ── Shader Error Reporting ────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderErrorReport {
    pub program_id: u32,
    pub program_name: String,
    pub stage: String,
    pub errors: Vec<ShaderDiagnostic>,
    pub warnings: Vec<ShaderDiagnostic>,
    pub source_snippet: Vec<(u32, String)>,
    pub timestamp: u64,
    pub is_fatal: bool,
}

impl ShaderErrorReport {
    pub fn new(program_id: u32, name: impl Into<String>, stage: impl Into<String>) -> Self {
        Self { program_id, program_name: name.into(), stage: stage.into(), errors: Vec::new(), warnings: Vec::new(), source_snippet: Vec::new(), timestamp: 0, is_fatal: false }
    }
    pub fn add_error(&mut self, err: ShaderDiagnostic) { if err.is_error() { self.is_fatal = true; } self.errors.push(err); }
    pub fn add_warning(&mut self, w: ShaderDiagnostic) { self.warnings.push(w); }
    pub fn add_source_line(&mut self, line_no: u32, line: impl Into<String>) { self.source_snippet.push((line_no, line.into())); }
    pub fn has_errors(&self) -> bool { !self.errors.is_empty() }
    pub fn format_report(&self) -> String {
        let mut s = format!("[{}] {}:{}\n", if self.is_fatal { "FATAL" } else { "WARN" }, self.program_name, self.stage);
        for e in &self.errors { s += &format!("  {}\n", e.format()); }
        for w in &self.warnings { s += &format!("  {}\n", w.format()); }
        s
    }
}

// ── Built-in Shader Snippets ──────────────────────────────────────────────────

pub fn glsl_preamble(version: &str, is_es: bool) -> String {
    if is_es { format!("#version {} es\nprecision highp float;\nprecision highp int;\n", version) }
    else { format!("#version {}\n", version) }
}

pub fn glsl_common_utils() -> &'static str {
    r#"
const float PI = 3.14159265358979323846;
const float TWO_PI = 6.28318530717958647692;
const float HALF_PI = 1.57079632679489661923;
const float INV_PI = 0.31830988618379067154;
const float E = 2.71828182845904523536;
const float GOLDEN_RATIO = 1.61803398874989484820;
const float EPSILON = 1e-6;
const float INF = 1.0/0.0;

float saturate(float v) { return clamp(v, 0.0, 1.0); }
vec2 saturate(vec2 v) { return clamp(v, vec2(0.0), vec2(1.0)); }
vec3 saturate(vec3 v) { return clamp(v, vec3(0.0), vec3(1.0)); }
vec4 saturate(vec4 v) { return clamp(v, vec4(0.0), vec4(1.0)); }

float remap(float v, float fromMin, float fromMax, float toMin, float toMax) {
    return toMin + (v - fromMin) / (fromMax - fromMin) * (toMax - toMin);
}
float luminance(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
vec3 rgb_to_hsv(vec3 c) {
    vec4 K = vec4(0.0, -1.0/3.0, 2.0/3.0, -1.0);
    vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
    vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
    float d = q.x - min(q.w, q.y);
    float e = 1.0e-10;
    return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}
float rand(vec2 co) { return fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453); }
vec3 hash33(vec3 p) {
    p = fract(p * vec3(443.8975, 397.2973, 491.1871));
    p += dot(p.zxy, p.yxz + 19.19);
    return fract(vec3(p.x * p.y, p.z * p.x, p.y * p.z));
}
"#
}

pub fn glsl_pbr_brdf() -> &'static str {
    r#"
// PBR BRDF functions (GGX/Schlick/Smith)
vec3 F_Schlick(vec3 f0, float f90, float u) {
    return f0 + (f90 - f0) * pow(1.0 - u, 5.0);
}
float V_SmithGGXCorrelated(float NdotV, float NdotL, float roughness) {
    float a2 = roughness * roughness;
    float GGXV = NdotL * sqrt(NdotV * NdotV * (1.0 - a2) + a2);
    float GGXL = NdotV * sqrt(NdotL * NdotL * (1.0 - a2) + a2);
    return 0.5 / max(GGXV + GGXL, 1e-5);
}
float D_GGX(float NdotH, float roughness) {
    float a2 = roughness * roughness;
    float f = (NdotH * a2 - NdotH) * NdotH + 1.0;
    return a2 / (PI * f * f);
}
vec3 eval_pbr(vec3 N, vec3 V, vec3 L, vec3 albedo, float roughness, float metalness) {
    vec3 H = normalize(V + L);
    float NdotV = max(dot(N, V), 0.0);
    float NdotL = max(dot(N, L), 0.0);
    float NdotH = max(dot(N, H), 0.0);
    float LdotH = max(dot(L, H), 0.0);
    vec3 f0 = mix(vec3(0.04), albedo, metalness);
    float D = D_GGX(NdotH, roughness);
    float V_vis = V_SmithGGXCorrelated(NdotV, NdotL, roughness);
    vec3 F = F_Schlick(f0, 1.0, LdotH);
    vec3 Fr = D * V_vis * F;
    vec3 Fd = (1.0 - F) * (1.0 - metalness) * albedo / PI;
    return (Fd + Fr) * NdotL;
}
"#
}

pub fn glsl_shadow_functions() -> &'static str {
    r#"
float shadow_hard(sampler2DShadow shadowMap, vec4 shadowCoord) {
    vec3 projCoords = shadowCoord.xyz / shadowCoord.w;
    return texture(shadowMap, projCoords);
}
float shadow_soft_pcf(sampler2DShadow shadowMap, vec4 shadowCoord, int samples) {
    vec2 texelSize = 1.0 / textureSize(shadowMap, 0);
    vec3 projCoords = shadowCoord.xyz / shadowCoord.w;
    float shadow = 0.0;
    float total = 0.0;
    for(int x = -samples; x <= samples; x++) {
        for(int y = -samples; y <= samples; y++) {
            vec3 offset = vec3(vec2(x, y) * texelSize, 0.0);
            shadow += texture(shadowMap, projCoords + offset);
            total += 1.0;
        }
    }
    return shadow / total;
}
vec2 poisson_disk[16] = vec2[](
    vec2(-0.94201624, -0.39906216), vec2(0.94558609, -0.76890725),
    vec2(-0.094184101, -0.92938870), vec2(0.34495938, 0.29387760),
    vec2(-0.91588581, 0.45771432), vec2(-0.81544232, -0.87912464),
    vec2(-0.38277543, 0.27676845), vec2(0.97484398, 0.75648379),
    vec2(0.44323325, -0.97511554), vec2(0.53742981, -0.47373420),
    vec2(-0.26496911, -0.41893023), vec2(0.79197514, 0.19090188),
    vec2(-0.24188840, 0.99706507), vec2(-0.81409955, 0.91437590),
    vec2(0.19984126, 0.78641367), vec2(0.14383161, -0.14100790)
);
float shadow_poisson(sampler2DShadow shadowMap, vec4 shadowCoord, float radius) {
    vec3 projCoords = shadowCoord.xyz / shadowCoord.w;
    float shadow = 0.0;
    for(int i = 0; i < 16; i++) {
        vec2 offset = poisson_disk[i] * radius;
        shadow += texture(shadowMap, projCoords + vec3(offset, 0.0));
    }
    return shadow / 16.0;
}
"#
}

pub fn glsl_atmosphere() -> &'static str {
    r#"
// Simple atmospheric scattering approximation
vec3 atmosphere(vec3 ray_dir, vec3 sun_dir, vec3 sun_color) {
    float sun_dot = max(dot(ray_dir, sun_dir), 0.0);
    vec3 sky_color = vec3(0.1, 0.3, 0.7);
    vec3 horizon_color = vec3(0.7, 0.5, 0.3);
    float horizon_blend = pow(1.0 - abs(ray_dir.y), 4.0);
    vec3 sky = mix(sky_color, horizon_color, horizon_blend);
    float sun_disc = smoothstep(0.998, 1.0, sun_dot);
    float halo = pow(sun_dot, 8.0) * 0.3;
    return sky + sun_color * (sun_disc + halo);
}
vec3 fog(vec3 color, float depth, vec3 fog_color, float fog_start, float fog_end) {
    float factor = clamp((depth - fog_start) / (fog_end - fog_start), 0.0, 1.0);
    return mix(color, fog_color, factor);
}
vec3 exponential_fog(vec3 color, float depth, vec3 fog_color, float density) {
    float factor = 1.0 - exp(-density * depth);
    return mix(color, fog_color, factor);
}
"#
}

// ── Shader Constant Buffer Layouts ────────────────────────────────────────────

pub fn per_frame_cbuffer_glsl() -> &'static str {
    r#"
layout(std140, binding = 0) uniform PerFrame {
    mat4 view;
    mat4 proj;
    mat4 view_proj;
    mat4 inv_view;
    mat4 inv_proj;
    vec4 camera_pos;
    vec4 camera_dir;
    vec4 viewport_size;
    float time;
    float delta_time;
    float near_plane;
    float far_plane;
    vec4 sun_direction;
    vec4 sun_color;
    vec4 ambient_color;
    vec2 jitter_offset;
    uint frame_index;
    float exposure;
} u_frame;
"#
}

pub fn per_object_cbuffer_glsl() -> &'static str {
    r#"
layout(std140, binding = 1) uniform PerObject {
    mat4 model;
    mat4 model_view;
    mat4 mvp;
    mat4 normal_matrix;
    vec4 object_color;
    vec4 object_id;
    float lod_bias;
    uint material_flags;
    float opacity;
    float pad;
} u_object;
"#
}

pub fn per_material_cbuffer_glsl() -> &'static str {
    r#"
layout(std140, binding = 2) uniform PerMaterial {
    vec4 albedo_color;
    vec4 emissive_color;
    float roughness;
    float metalness;
    float normal_scale;
    float occlusion_strength;
    float emissive_intensity;
    float opacity;
    float alpha_cutoff;
    uint flags;
    vec4 uv_transform;
} u_material;
"#
}

// ── Shader statistics & info ──────────────────────────────────────────────────

pub const SHADER_BUILTIN_SNIPPETS: usize = 11;
pub const SHADER_GLSL_BUILTIN_FUNCTIONS: usize = 28;
pub const SHADER_CBUFFER_BINDINGS: u32 = 3;
pub const SHADER_ATMOSPHERE_SAMPLES: u32 = 8;
pub const SHADER_SHADOW_PCF_SAMPLES: u32 = 9;
pub const SHADER_SHADOW_POISSON_SAMPLES: u32 = 16;
pub const GLSL_PRECISION_HIGHP: &str = "highp";
pub const GLSL_PRECISION_MEDIUMP: &str = "mediump";
pub const GLSL_PRECISION_LOWP: &str = "lowp";

pub fn all_glsl_builtin_types() -> &'static [&'static str] {
    &[ "void", "bool", "int", "uint", "float", "double",
       "bvec2", "bvec3", "bvec4", "ivec2", "ivec3", "ivec4",
       "uvec2", "uvec3", "uvec4", "vec2", "vec3", "vec4",
       "dvec2", "dvec3", "dvec4",
       "mat2", "mat3", "mat4", "mat2x3", "mat2x4", "mat3x2",
       "mat3x4", "mat4x2", "mat4x3",
       "sampler2D", "sampler3D", "samplerCube", "sampler2DArray",
       "sampler2DShadow", "samplerCubeShadow",
       "isampler2D", "usampler2D", "image2D", "imageCube" ]
}

pub fn all_glsl_keywords() -> &'static [&'static str] {
    &[ "if", "else", "for", "while", "do", "switch", "case", "default",
       "break", "continue", "return", "discard",
       "void", "struct", "precision", "highp", "mediump", "lowp",
       "in", "out", "inout", "uniform", "const", "layout",
       "attribute", "varying", "flat", "smooth", "centroid",
       "noperspective", "invariant", "coherent", "volatile",
       "restrict", "readonly", "writeonly" ]
}


// ── Render Feature Flags ──────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct RenderFeatureFlags {
    pub pbr: bool,
    pub shadows: bool,
    pub ssao: bool,
    pub ssr: bool,
    pub bloom: bool,
    pub fxaa: bool,
    pub taa: bool,
    pub dof: bool,
    pub motion_blur: bool,
    pub volumetric_fog: bool,
    pub lens_flare: bool,
    pub chromatic_aberration: bool,
    pub vignette: bool,
    pub color_grading: bool,
    pub debug_mode: bool,
}

impl RenderFeatureFlags {
    pub fn all_off() -> Self { Self { pbr: false, shadows: false, ssao: false, ssr: false, bloom: false, fxaa: false, taa: false, dof: false, motion_blur: false, volumetric_fog: false, lens_flare: false, chromatic_aberration: false, vignette: false, color_grading: false, debug_mode: false } }
    pub fn default_high_quality() -> Self { Self { pbr: true, shadows: true, ssao: true, ssr: false, bloom: true, fxaa: true, taa: true, dof: false, motion_blur: false, volumetric_fog: false, lens_flare: false, chromatic_aberration: false, vignette: true, color_grading: true, debug_mode: false } }
    pub fn default_medium_quality() -> Self { Self { pbr: true, shadows: true, ssao: false, ssr: false, bloom: true, fxaa: true, taa: false, ..Self::all_off() } }
    pub fn default_low_quality() -> Self { Self { fxaa: true, ..Self::all_off() } }
    pub fn active_count(&self) -> usize {
        [self.pbr, self.shadows, self.ssao, self.ssr, self.bloom, self.fxaa, self.taa, self.dof, self.motion_blur, self.volumetric_fog, self.lens_flare, self.chromatic_aberration, self.vignette, self.color_grading].iter().filter(|&&b| b).count()
    }
    pub fn generate_defines(&self) -> Vec<(String, String)> {
        let mut defines = Vec::new();
        if self.pbr { defines.push(("USE_PBR".into(), "1".into())); }
        if self.shadows { defines.push(("USE_SHADOWS".into(), "1".into())); }
        if self.ssao { defines.push(("USE_SSAO".into(), "1".into())); }
        if self.bloom { defines.push(("USE_BLOOM".into(), "1".into())); }
        if self.fxaa { defines.push(("USE_FXAA".into(), "1".into())); }
        if self.taa { defines.push(("USE_TAA".into(), "1".into())); }
        defines
    }
}

impl Default for RenderFeatureFlags {
    fn default() -> Self { Self::default_high_quality() }
}

// ── Shader compilation context ────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderCompilationContext {
    pub source_path: String,
    pub stage: ShaderStage,
    pub target: CodeGenTarget,
    pub defines: HashMap<String, String>,
    pub include_paths: Vec<String>,
    pub optimization: OptimizationLevel,
    pub version: String,
    pub entry_point: String,
    pub features: RenderFeatureFlags,
}

impl ShaderCompilationContext {
    pub fn new(path: impl Into<String>, stage: ShaderStage, target: CodeGenTarget) -> Self {
        Self { source_path: path.into(), stage, target, defines: HashMap::new(), include_paths: Vec::new(), optimization: OptimizationLevel::Medium, version: "450".into(), entry_point: "main".into(), features: RenderFeatureFlags::default() }
    }
    pub fn add_define(&mut self, k: impl Into<String>, v: impl Into<String>) { self.defines.insert(k.into(), v.into()); }
    pub fn apply_features(&mut self) {
        for (k, v) in self.features.generate_defines() { self.defines.insert(k, v); }
    }
    pub fn is_vertex(&self) -> bool { self.stage == ShaderStage::Vertex }
    pub fn is_fragment(&self) -> bool { self.stage == ShaderStage::Fragment }
    pub fn is_compute(&self) -> bool { self.stage == ShaderStage::Compute }
}

// ── Shader bundle ─────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderBundle {
    pub id: u32,
    pub name: String,
    pub programs: Vec<ShaderProgram>,
    pub materials: Vec<Material>,
    pub templates: Vec<ShaderTemplate>,
    pub version: u32,
    pub description: String,
    pub author: String,
    pub created_at: u64,
}

impl ShaderBundle {
    pub fn new(id: u32, name: impl Into<String>) -> Self {
        Self { id, name: name.into(), programs: Vec::new(), materials: Vec::new(), templates: Vec::new(), version: 1, description: String::new(), author: String::new(), created_at: 0 }
    }
    pub fn add_program(&mut self, p: ShaderProgram) { self.programs.push(p); }
    pub fn add_material(&mut self, m: Material) { self.materials.push(m); }
    pub fn add_template(&mut self, t: ShaderTemplate) { self.templates.push(t); }
    pub fn program_count(&self) -> usize { self.programs.len() }
    pub fn material_count(&self) -> usize { self.materials.len() }
    pub fn find_program(&self, name: &str) -> Option<&ShaderProgram> { self.programs.iter().find(|p| p.name == name) }
    pub fn is_empty(&self) -> bool { self.programs.is_empty() && self.materials.is_empty() }
}

#[derive(Clone, Debug)]
pub struct ShaderBundleRegistry {
    pub bundles: HashMap<u32, ShaderBundle>,
    pub next_id: u32,
}

impl ShaderBundleRegistry {
    pub fn new() -> Self { Self { bundles: HashMap::new(), next_id: 1 } }
    pub fn register(&mut self, mut b: ShaderBundle) -> u32 {
        let id = self.next_id; self.next_id += 1;
        b.id = id;
        self.bundles.insert(id, b);
        id
    }
    pub fn get(&self, id: u32) -> Option<&ShaderBundle> { self.bundles.get(&id) }
    pub fn find_by_name(&self, name: &str) -> Option<&ShaderBundle> { self.bundles.values().find(|b| b.name == name) }
    pub fn total_programs(&self) -> usize { self.bundles.values().map(|b| b.program_count()).sum() }
    pub fn count(&self) -> usize { self.bundles.len() }
}

impl Default for ShaderBundleRegistry {
    fn default() -> Self { Self::new() }
}

// ── Shader Workspace ──────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderWorkspace {
    pub registry: ShaderProgramRegistry,
    pub cache: ShaderCache,
    pub library: ShaderLibrary,
    pub material_lib: MaterialLibrary,
    pub texture_reg: TextureRegistry,
    pub buffer_reg: BufferRegistry,
    pub pipeline: RenderPipeline,
    pub post_process: PostProcessStack,
    pub template_lib: ShaderTemplateLibrary,
    pub linter: ShaderLinter,
    pub formatter: ShaderFormatter,
    pub debugger: ShaderDebugger,
    pub profiler: ShaderProfiler,
    pub hot_reload: HotReloadManager,
    pub editor_state: ShaderEditorState,
    pub autocomplete: AutoCompleteProvider,
    pub linker: ShaderLinker,
    pub bundle_reg: ShaderBundleRegistry,
    pub feature_flags: RenderFeatureFlags,
    pub memory_budget: GpuMemoryBudget,
    pub render_stats: RenderStatistics,
}

impl ShaderWorkspace {
    pub fn new() -> Self {
        Self {
            registry: ShaderProgramRegistry::new(),
            cache: ShaderCache::new(SHADER_CACHE_SIZE),
            library: ShaderLibrary::build_standard(),
            material_lib: MaterialLibrary::new(),
            texture_reg: TextureRegistry::new(),
            buffer_reg: BufferRegistry::new(),
            pipeline: RenderPipeline::new(),
            post_process: PostProcessStack::new(),
            template_lib: ShaderTemplateLibrary::new(),
            linter: ShaderLinter::new(),
            formatter: ShaderFormatter::new(),
            debugger: ShaderDebugger::build_defaults(),
            profiler: ShaderProfiler::new(),
            hot_reload: HotReloadManager::new(),
            editor_state: ShaderEditorState::new(),
            autocomplete: AutoCompleteProvider::new(),
            linker: ShaderLinker::new(),
            bundle_reg: ShaderBundleRegistry::new(),
            feature_flags: RenderFeatureFlags::default(),
            memory_budget: GpuMemoryBudget::new(GPU_MEMORY_BUDGET_DEFAULT_MB * 1024 * 1024),
            render_stats: RenderStatistics::new(),
        }
    }
    pub fn program_count(&self) -> usize { self.registry.count() }
    pub fn material_count(&self) -> usize { self.material_lib.count() }
    pub fn texture_count(&self) -> usize { self.texture_reg.count() }
    pub fn buffer_count(&self) -> usize { self.buffer_reg.count() }
    pub fn begin_frame(&mut self) { self.render_stats.begin_frame(); self.profiler.begin_frame(); }
    pub fn has_program(&self, name: &str) -> bool { self.registry.find_by_name(name).is_some() }
    pub fn tick(&mut self, dt: f32) { let _ = self.hot_reload.tick(dt); }
}

impl Default for ShaderWorkspace {
    fn default() -> Self { Self::new() }
}

// ── Final constants ───────────────────────────────────────────────────────────

pub const SHADER_BUNDLE_MAX: usize = 64;
pub const SHADER_WORKSPACE_MAX_PROGRAMS: usize = SHADER_MAX_PROGRAMS;
pub const RENDER_FEATURE_COUNT: usize = 15;
pub const SHADER_VERSION_DEFAULT: &str = "450";
pub const SHADER_ES_VERSION_DEFAULT: &str = "300 es";
pub const SHADER_ENTRY_POINT_DEFAULT: &str = "main";
pub const GLSL_BUILTIN_TYPE_COUNT: usize = 40;
pub const GLSL_KEYWORD_COUNT: usize = 31;
pub const GLSL_MAX_FRAGMENT_OUTPUTS: u32 = 8;
pub const GLSL_MAX_VERTEX_ATTRIBS: u32 = 32;

pub fn build_standard_shader_workspace() -> ShaderWorkspace { ShaderWorkspace::new() }
pub fn shader_workspace_summary(ws: &ShaderWorkspace) -> String {
    format!("ShaderWorkspace: {} programs, {} materials, {} textures, {} buffers, {} render passes", ws.program_count(), ws.material_count(), ws.texture_count(), ws.buffer_count(), ws.pipeline.pass_count())
}
pub fn shader_system_version() -> &'static str { "1.0.0" }
pub fn is_shader_system_ready() -> bool { true }


// ── Render Graph ──────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct RenderGraphNode {
    pub id: u32,
    pub name: String,
    pub node_type: RenderGraphNodeType,
    pub inputs: Vec<RenderGraphResource>,
    pub outputs: Vec<RenderGraphResource>,
    pub shader_id: Option<u32>,
    pub enabled: bool,
    pub order: u32,
    pub async_compute: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub enum RenderGraphNodeType { Pass, Blit, Compute, Present, Upload, Barrier, Custom(String) }

#[derive(Clone, Debug)]
pub struct RenderGraphResource {
    pub name: String,
    pub resource_type: RenderGraphResourceType,
    pub format: AttachmentFormat,
    pub width: u32,
    pub height: u32,
    pub mips: u32,
    pub transient: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub enum RenderGraphResourceType { Texture, Buffer, RenderTarget, DepthStencil }

impl RenderGraphNode {
    pub fn new(id: u32, name: impl Into<String>, node_type: RenderGraphNodeType) -> Self {
        Self { id, name: name.into(), node_type, inputs: Vec::new(), outputs: Vec::new(), shader_id: None, enabled: true, order: 0, async_compute: false }
    }
    pub fn add_input(&mut self, res: RenderGraphResource) { self.inputs.push(res); }
    pub fn add_output(&mut self, res: RenderGraphResource) { self.outputs.push(res); }
    pub fn is_pass(&self) -> bool { self.node_type == RenderGraphNodeType::Pass }
    pub fn is_compute(&self) -> bool { self.node_type == RenderGraphNodeType::Compute }
    pub fn input_count(&self) -> usize { self.inputs.len() }
    pub fn output_count(&self) -> usize { self.outputs.len() }
    pub fn with_shader(mut self, id: u32) -> Self { self.shader_id = Some(id); self }
}

#[derive(Clone, Debug)]
pub struct RenderGraph {
    pub nodes: Vec<RenderGraphNode>,
    pub edges: Vec<(u32, u32)>,
    pub name: String,
    pub next_id: u32,
}

impl RenderGraph {
    pub fn new(name: impl Into<String>) -> Self { Self { nodes: Vec::new(), edges: Vec::new(), name: name.into(), next_id: 1 } }
    pub fn add_node(&mut self, node_type: RenderGraphNodeType, name: impl Into<String>) -> u32 {
        let id = self.next_id; self.next_id += 1;
        self.nodes.push(RenderGraphNode::new(id, name, node_type));
        id
    }
    pub fn connect(&mut self, from: u32, to: u32) { self.edges.push((from, to)); }
    pub fn sorted_nodes(&self) -> Vec<&RenderGraphNode> {
        let mut sorted: Vec<_> = self.nodes.iter().filter(|n| n.enabled).collect();
        sorted.sort_by_key(|n| n.order);
        sorted
    }
    pub fn node_count(&self) -> usize { self.nodes.len() }
    pub fn find_node(&self, id: u32) -> Option<&RenderGraphNode> { self.nodes.iter().find(|n| n.id == id) }
    pub fn remove_node(&mut self, id: u32) { self.nodes.retain(|n| n.id != id); self.edges.retain(|(a, b)| *a != id && *b != id); }
}

impl Default for RenderGraph {
    fn default() -> Self { Self::new("default") }
}

// ── Shader Compiler Main ──────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderCompilerMain {
    pub workspace: ShaderWorkspace,
    pub render_graph: RenderGraph,
    pub compile_stats: CompileStats,
}

#[derive(Clone, Debug, Default)]
pub struct CompileStats {
    pub total_compiled: u32,
    pub total_failed: u32,
    pub total_cached: u32,
    pub total_reloaded: u32,
    pub avg_compile_ms: f32,
    pub peak_compile_ms: f32,
}

impl CompileStats {
    pub fn new() -> Self { Self::default() }
    pub fn record_compile(&mut self, ms: f32, success: bool, from_cache: bool) {
        if from_cache { self.total_cached += 1; return; }
        if success { self.total_compiled += 1; } else { self.total_failed += 1; }
        self.peak_compile_ms = self.peak_compile_ms.max(ms);
        let total = self.total_compiled + self.total_failed;
        self.avg_compile_ms = (self.avg_compile_ms * (total - 1) as f32 + ms) / total as f32;
    }
    pub fn success_rate(&self) -> f32 {
        let total = self.total_compiled + self.total_failed;
        if total == 0 { 1.0 } else { self.total_compiled as f32 / total as f32 }
    }
    pub fn total_attempts(&self) -> u32 { self.total_compiled + self.total_failed + self.total_cached }
}

impl ShaderCompilerMain {
    pub fn new() -> Self { Self { workspace: ShaderWorkspace::new(), render_graph: RenderGraph::new("main"), compile_stats: CompileStats::new() } }
    pub fn add_program(&mut self, prog: ShaderProgram) -> u32 { self.workspace.registry.add(prog) }
    pub fn get_program(&self, id: u32) -> Option<&ShaderProgram> { self.workspace.registry.get(id) }
    pub fn add_material(&mut self, mat: Material) -> u32 { self.workspace.material_lib.add(mat) }
    pub fn add_texture(&mut self, tex: TextureDescriptor) -> u32 { self.workspace.texture_reg.register(tex) }
    pub fn begin_frame(&mut self) { self.workspace.begin_frame(); }
    pub fn tick(&mut self, dt: f32) { self.workspace.tick(dt); }
    pub fn program_count(&self) -> usize { self.workspace.program_count() }
    pub fn compilation_summary(&self) -> String {
        format!("Compiled: {}, Failed: {}, Cached: {}, Success: {:.1}%", self.compile_stats.total_compiled, self.compile_stats.total_failed, self.compile_stats.total_cached, self.compile_stats.success_rate() * 100.0)
    }
}

impl Default for ShaderCompilerMain {
    fn default() -> Self { Self::new() }
}

// ── Color Grading ─────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ColorGradingSettings {
    pub exposure: f32,
    pub contrast: f32,
    pub saturation: f32,
    pub brightness: f32,
    pub hue_shift: f32,
    pub lift: [f32; 3],
    pub gamma: [f32; 3],
    pub gain: [f32; 3],
    pub white_balance_temp: f32,
    pub white_balance_tint: f32,
    pub shadows_color: [f32; 3],
    pub midtones_color: [f32; 3],
    pub highlights_color: [f32; 3],
    pub tonemapping: ToneMappingMode,
}

#[derive(Clone, Debug, PartialEq)]
pub enum ToneMappingMode { None, Reinhard, Aces, Filmic, Uncharted2, Custom }

impl Default for ColorGradingSettings {
    fn default() -> Self {
        Self { exposure: 0.0, contrast: 1.0, saturation: 1.0, brightness: 0.0, hue_shift: 0.0, lift: [0.0; 3], gamma: [1.0; 3], gain: [1.0; 3], white_balance_temp: 6500.0, white_balance_tint: 0.0, shadows_color: [0.0; 3], midtones_color: [0.0; 3], highlights_color: [0.0; 3], tonemapping: ToneMappingMode::Aces }
    }
}

impl ColorGradingSettings {
    pub fn new() -> Self { Self::default() }
    pub fn neutral() -> Self { Self::default() }
    pub fn warm() -> Self { Self { white_balance_temp: 7500.0, saturation: 1.1, ..Self::default() } }
    pub fn cool() -> Self { Self { white_balance_temp: 5500.0, saturation: 0.9, ..Self::default() } }
    pub fn cinematic() -> Self { Self { contrast: 1.15, saturation: 0.9, tonemapping: ToneMappingMode::Filmic, ..Self::default() } }
    pub fn generate_glsl(&self) -> String {
        format!("// ColorGrading: exposure={:.2}, contrast={:.2}, saturation={:.2}, tonemapping={:?}", self.exposure, self.contrast, self.saturation, self.tonemapping)
    }
    pub fn is_neutral(&self) -> bool { self.exposure == 0.0 && self.contrast == 1.0 && self.saturation == 1.0 }
}

// ── Screen Space Ambient Occlusion Config ─────────────────────────────────────

#[derive(Clone, Debug)]
pub struct SsaoConfig {
    pub kernel_size: u32,
    pub radius: f32,
    pub bias: f32,
    pub power: f32,
    pub blur_passes: u32,
    pub enabled: bool,
    pub quality: SsaoQuality,
}

#[derive(Clone, Debug, PartialEq)]
pub enum SsaoQuality { Low, Medium, High, Ultra }

impl SsaoConfig {
    pub fn new() -> Self { Self { kernel_size: 32, radius: 0.5, bias: 0.025, power: 2.0, blur_passes: 2, enabled: true, quality: SsaoQuality::Medium } }
    pub fn low() -> Self { Self { kernel_size: 8, radius: 0.3, blur_passes: 1, quality: SsaoQuality::Low, ..Self::new() } }
    pub fn high() -> Self { Self { kernel_size: 64, radius: 0.8, blur_passes: 3, quality: SsaoQuality::High, ..Self::new() } }
    pub fn ultra() -> Self { Self { kernel_size: 128, radius: 1.0, blur_passes: 4, quality: SsaoQuality::Ultra, ..Self::new() } }
}

impl Default for SsaoConfig {
    fn default() -> Self { Self::new() }
}

// ── Depth of Field ────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct DepthOfFieldConfig {
    pub enabled: bool,
    pub focus_distance: f32,
    pub focus_range: f32,
    pub far_blur_range: f32,
    pub near_blur_range: f32,
    pub bokeh_radius: f32,
    pub bokeh_blade_count: u32,
    pub bokeh_rotation: f32,
    pub max_coc_radius: f32,
}

impl DepthOfFieldConfig {
    pub fn new() -> Self { Self { enabled: false, focus_distance: 10.0, focus_range: 5.0, far_blur_range: 20.0, near_blur_range: 2.0, bokeh_radius: 8.0, bokeh_blade_count: 6, bokeh_rotation: 0.0, max_coc_radius: 20.0 } }
    pub fn portrait() -> Self { Self { enabled: true, focus_distance: 2.0, focus_range: 0.5, bokeh_radius: 12.0, ..Self::new() } }
    pub fn cinematic() -> Self { Self { enabled: true, focus_distance: 5.0, focus_range: 2.0, bokeh_radius: 10.0, bokeh_blade_count: 8, ..Self::new() } }
}

impl Default for DepthOfFieldConfig {
    fn default() -> Self { Self::new() }
}

// ── Bloom Config ──────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct BloomConfig {
    pub enabled: bool,
    pub threshold: f32,
    pub intensity: f32,
    pub scatter: f32,
    pub clamp: f32,
    pub downsample_passes: u32,
    pub mode: BloomMode,
    pub tint: [f32; 3],
}

#[derive(Clone, Debug, PartialEq)]
pub enum BloomMode { Classic, Kawase, Dual, Convolution }

impl BloomConfig {
    pub fn new() -> Self { Self { enabled: true, threshold: 0.9, intensity: 0.5, scatter: 0.7, clamp: 65472.0, downsample_passes: 5, mode: BloomMode::Dual, tint: [1.0; 3] } }
    pub fn subtle() -> Self { Self { intensity: 0.2, ..Self::new() } }
    pub fn intense() -> Self { Self { intensity: 1.5, threshold: 0.7, ..Self::new() } }
    pub fn disabled() -> Self { Self { enabled: false, ..Self::new() } }
}

impl Default for BloomConfig {
    fn default() -> Self { Self::new() }
}

// ── Final Shader System Constants ─────────────────────────────────────────────

pub const RENDER_GRAPH_MAX_NODES: usize = 64;
pub const RENDER_GRAPH_MAX_EDGES: usize = 256;
pub const COLOR_GRADING_LUT_SIZE: u32 = 32;
pub const SSAO_KERNEL_SIZE_MAX: u32 = 256;
pub const DOF_MAX_COC_RADIUS: f32 = 32.0;
pub const BLOOM_MAX_DOWNSAMPLE_PASSES: u32 = 8;
pub const SHADER_COMPILER_MAX_WORKSPACES: usize = 8;
pub const GPU_BUDGET_WARNING_PERCENT: f32 = 80.0;
pub const GPU_BUDGET_CRITICAL_PERCENT: f32 = 95.0;
pub const SHADER_PERMUTATION_HASH_SEED: u64 = 14695981039346656037;

pub fn tonemap_name(mode: &ToneMappingMode) -> &'static str {
    match mode { ToneMappingMode::None => "None", ToneMappingMode::Reinhard => "Reinhard", ToneMappingMode::Aces => "ACES", ToneMappingMode::Filmic => "Filmic", ToneMappingMode::Uncharted2 => "Uncharted 2", ToneMappingMode::Custom => "Custom" }
}
pub fn bloom_mode_name(mode: &BloomMode) -> &'static str {
    match mode { BloomMode::Classic => "Classic", BloomMode::Kawase => "Kawase", BloomMode::Dual => "Dual Kawase", BloomMode::Convolution => "Convolution" }
}
pub fn ssao_quality_name(q: &SsaoQuality) -> &'static str {
    match q { SsaoQuality::Low => "Low", SsaoQuality::Medium => "Medium", SsaoQuality::High => "High", SsaoQuality::Ultra => "Ultra" }
}
pub fn shader_compiler_build_date() -> &'static str { "2026-03-29" }
pub fn shader_compiler_complete_info() -> String {
    format!("ShaderCompilerEditor v{} — {} modules, render graph, materials, post-process, color grading", shader_system_version(), shader_module_count())
}


// ── Screen Space Reflections ──────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct SsrConfig {
    pub enabled: bool,
    pub max_steps: u32,
    pub max_distance: f32,
    pub thickness: f32,
    pub stride: u32,
    pub jitter: f32,
    pub fade_start: f32,
    pub fade_end: f32,
    pub reflection_blend: f32,
    pub quality: SsrQuality,
}

#[derive(Clone, Debug, PartialEq)]
pub enum SsrQuality { Low, Medium, High }

impl SsrConfig {
    pub fn new() -> Self { Self { enabled: false, max_steps: 32, max_distance: 100.0, thickness: 0.5, stride: 2, jitter: 0.5, fade_start: 0.7, fade_end: 1.0, reflection_blend: 0.5, quality: SsrQuality::Medium } }
    pub fn high() -> Self { Self { enabled: true, max_steps: 64, stride: 1, quality: SsrQuality::High, ..Self::new() } }
    pub fn low() -> Self { Self { enabled: true, max_steps: 16, stride: 4, quality: SsrQuality::Low, ..Self::new() } }
}

impl Default for SsrConfig {
    fn default() -> Self { Self::new() }
}

// ── Temporal Anti-Aliasing ────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct TaaConfig {
    pub enabled: bool,
    pub blend_factor: f32,
    pub history_blend: f32,
    pub sharpness: f32,
    pub jitter_scale: f32,
    pub motion_rejection: f32,
    pub clip_aabb: bool,
    pub variance_clip_gamma: f32,
    pub sample_count: u32,
}

impl TaaConfig {
    pub fn new() -> Self { Self { enabled: true, blend_factor: 0.1, history_blend: 0.9, sharpness: 0.5, jitter_scale: 1.0, motion_rejection: 0.3, clip_aabb: true, variance_clip_gamma: 1.0, sample_count: 8 } }
    pub fn aggressive() -> Self { Self { blend_factor: 0.05, motion_rejection: 0.5, ..Self::new() } }
    pub fn gentle() -> Self { Self { blend_factor: 0.2, motion_rejection: 0.1, ..Self::new() } }
}

impl Default for TaaConfig {
    fn default() -> Self { Self::new() }
}

// ── Volumetric Fog ────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct VolumetricFogConfig {
    pub enabled: bool,
    pub density: f32,
    pub scattering: f32,
    pub absorption: f32,
    pub anisotropy: f32,
    pub height_falloff: f32,
    pub base_height: f32,
    pub fog_color: [f32; 3],
    pub ambient_fog_color: [f32; 3],
    pub light_intensity: f32,
    pub num_slices: u32,
    pub temporal_reprojection: bool,
}

impl VolumetricFogConfig {
    pub fn new() -> Self { Self { enabled: false, density: 0.1, scattering: 0.5, absorption: 0.1, anisotropy: 0.5, height_falloff: 0.1, base_height: 0.0, fog_color: [1.0, 0.95, 0.9], ambient_fog_color: [0.5, 0.6, 0.8], light_intensity: 1.0, num_slices: 128, temporal_reprojection: true } }
    pub fn light_fog() -> Self { Self { enabled: true, density: 0.02, ..Self::new() } }
    pub fn heavy_fog() -> Self { Self { enabled: true, density: 0.3, ..Self::new() } }
    pub fn night_fog() -> Self { Self { enabled: true, density: 0.15, fog_color: [0.3, 0.35, 0.5], ambient_fog_color: [0.1, 0.1, 0.2], ..Self::new() } }
}

impl Default for VolumetricFogConfig {
    fn default() -> Self { Self::new() }
}

// ── Lens Flare ────────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct LensFlareConfig {
    pub enabled: bool,
    pub intensity: f32,
    pub threshold: f32,
    pub ghosts: u32,
    pub ghost_dispersal: f32,
    pub halo_width: f32,
    pub chromatic_distortion: f32,
    pub starburst_intensity: f32,
    pub starburst_count: u32,
}

impl LensFlareConfig {
    pub fn new() -> Self { Self { enabled: false, intensity: 0.5, threshold: 0.8, ghosts: 4, ghost_dispersal: 0.4, halo_width: 0.4, chromatic_distortion: 5.0, starburst_intensity: 0.5, starburst_count: 8 } }
    pub fn subtle() -> Self { Self { enabled: true, intensity: 0.2, ..Self::new() } }
    pub fn dramatic() -> Self { Self { enabled: true, intensity: 1.5, ghosts: 8, ..Self::new() } }
}

impl Default for LensFlareConfig {
    fn default() -> Self { Self::new() }
}

// ── Full Post Process Configuration ──────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct FullPostProcessConfig {
    pub bloom: BloomConfig,
    pub color_grading: ColorGradingSettings,
    pub ssao: SsaoConfig,
    pub ssr: SsrConfig,
    pub taa: TaaConfig,
    pub dof: DepthOfFieldConfig,
    pub volumetric_fog: VolumetricFogConfig,
    pub lens_flare: LensFlareConfig,
    pub enabled: bool,
}

impl FullPostProcessConfig {
    pub fn new() -> Self {
        Self { bloom: BloomConfig::new(), color_grading: ColorGradingSettings::new(), ssao: SsaoConfig::new(), ssr: SsrConfig::new(), taa: TaaConfig::new(), dof: DepthOfFieldConfig::new(), volumetric_fog: VolumetricFogConfig::new(), lens_flare: LensFlareConfig::new(), enabled: true }
    }
    pub fn high_quality() -> Self {
        Self { bloom: BloomConfig::new(), ssao: SsaoConfig::high(), taa: TaaConfig::new(), ..Self::new() }
    }
    pub fn low_quality() -> Self {
        Self { bloom: BloomConfig::disabled(), ssao: SsaoConfig::low(), taa: TaaConfig::new(), ..Self::new() }
    }
    pub fn active_effect_count(&self) -> usize {
        [self.bloom.enabled, self.ssao.enabled, self.ssr.enabled, self.taa.enabled, self.dof.enabled, self.volumetric_fog.enabled, self.lens_flare.enabled].iter().filter(|&&b| b).count()
    }
}

impl Default for FullPostProcessConfig {
    fn default() -> Self { Self::new() }
}

// ── Rendering Quality Preset ──────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct RenderQualityPreset {
    pub name: String,
    pub features: RenderFeatureFlags,
    pub post_process: FullPostProcessConfig,
    pub shadow_map_resolution: u32,
    pub shadow_cascades: u32,
    pub max_lights: u32,
    pub reflection_quality: u32,
    pub target_fps: u32,
    pub render_scale: f32,
}

impl RenderQualityPreset {
    pub fn low() -> Self {
        Self { name: "Low".into(), features: RenderFeatureFlags::default_low_quality(), post_process: FullPostProcessConfig::low_quality(), shadow_map_resolution: 1024, shadow_cascades: 2, max_lights: 16, reflection_quality: 0, target_fps: 60, render_scale: 0.75 }
    }
    pub fn medium() -> Self {
        Self { name: "Medium".into(), features: RenderFeatureFlags::default_medium_quality(), post_process: FullPostProcessConfig::new(), shadow_map_resolution: 2048, shadow_cascades: 3, max_lights: 64, reflection_quality: 1, target_fps: 60, render_scale: 1.0 }
    }
    pub fn high() -> Self {
        Self { name: "High".into(), features: RenderFeatureFlags::default_high_quality(), post_process: FullPostProcessConfig::high_quality(), shadow_map_resolution: 4096, shadow_cascades: 4, max_lights: 256, reflection_quality: 2, target_fps: 60, render_scale: 1.0 }
    }
    pub fn ultra() -> Self {
        let mut h = Self::high(); h.name = "Ultra".into(); h.shadow_map_resolution = 8192; h.render_scale = 1.25; h.max_lights = 1024; h
    }
    pub fn is_mobile_friendly(&self) -> bool { self.shadow_map_resolution <= 1024 && !self.features.ssao && !self.features.ssr }
}

// ── All rendering presets ─────────────────────────────────────────────────────

pub fn build_quality_presets() -> Vec<RenderQualityPreset> {
    vec![RenderQualityPreset::low(), RenderQualityPreset::medium(), RenderQualityPreset::high(), RenderQualityPreset::ultra()]
}

// ── Final constants ───────────────────────────────────────────────────────────

pub const SSR_MAX_STEPS: u32 = 128;
pub const TAA_HISTORY_FRAMES: u32 = 8;
pub const VOLUMETRIC_FOG_MAX_SLICES: u32 = 256;
pub const LENS_FLARE_MAX_GHOSTS: u32 = 16;
pub const POST_PROCESS_FULL_EFFECT_COUNT: usize = 8;
pub const RENDER_QUALITY_PRESET_COUNT: usize = 4;
pub const SHADOW_MAP_MAX_RESOLUTION: u32 = 16384;
pub const SHADOW_CASCADE_MAX: u32 = 8;
pub const RENDER_MAX_LIGHTS: u32 = 4096;
pub const RENDER_SCALE_MIN: f32 = 0.25;
pub const RENDER_SCALE_MAX: f32 = 2.0;

pub fn render_quality_preset_names() -> &'static [&'static str] { &["Low", "Medium", "High", "Ultra"] }
pub fn supported_render_apis() -> &'static [&'static str] { &["OpenGL 4.5", "Vulkan 1.3", "Metal 2", "WebGPU", "D3D12"] }
pub fn shader_compiler_total_feature_count() -> usize { shader_module_count() + RENDER_FEATURE_COUNT + POST_PROCESS_FULL_EFFECT_COUNT + RENDER_QUALITY_PRESET_COUNT }
pub fn shader_compiler_final_info() -> String {
    format!("ShaderCompilerEditor: {} total features, {} render API targets, {} quality presets", shader_compiler_total_feature_count(), supported_render_apis().len(), RENDER_QUALITY_PRESET_COUNT)
}


// ── Instanced Rendering ───────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct InstanceData {
    pub model_matrix: [[f32; 4]; 4],
    pub color: [f32; 4],
    pub custom0: [f32; 4],
    pub custom1: [f32; 4],
}

impl InstanceData {
    pub fn new() -> Self { Self { model_matrix: [[1.0,0.0,0.0,0.0],[0.0,1.0,0.0,0.0],[0.0,0.0,1.0,0.0],[0.0,0.0,0.0,1.0]], color: [1.0; 4], custom0: [0.0; 4], custom1: [0.0; 4] } }
    pub fn with_color(mut self, r: f32, g: f32, b: f32, a: f32) -> Self { self.color = [r, g, b, a]; self }
}

impl Default for InstanceData {
    fn default() -> Self { Self::new() }
}

#[derive(Clone, Debug)]
pub struct InstanceBatch {
    pub id: u32,
    pub mesh_id: u32,
    pub material_id: u32,
    pub instances: Vec<InstanceData>,
    pub max_instances: u32,
    pub visible_count: u32,
    pub cull_enabled: bool,
}

impl InstanceBatch {
    pub fn new(id: u32, mesh_id: u32, material_id: u32, max: u32) -> Self {
        Self { id, mesh_id, material_id, instances: Vec::new(), max_instances: max, visible_count: 0, cull_enabled: true }
    }
    pub fn add(&mut self, data: InstanceData) -> bool {
        if self.instances.len() >= self.max_instances as usize { return false; }
        self.instances.push(data); self.visible_count += 1; true
    }
    pub fn clear(&mut self) { self.instances.clear(); self.visible_count = 0; }
    pub fn count(&self) -> usize { self.instances.len() }
    pub fn is_full(&self) -> bool { self.instances.len() >= self.max_instances as usize }
    pub fn utilization(&self) -> f32 { if self.max_instances == 0 { 0.0 } else { self.instances.len() as f32 / self.max_instances as f32 } }
}

#[derive(Clone, Debug)]
pub struct InstanceBatchManager {
    pub batches: HashMap<u32, InstanceBatch>,
    pub next_id: u32,
    pub total_instances: u32,
}

impl InstanceBatchManager {
    pub fn new() -> Self { Self { batches: HashMap::new(), next_id: 1, total_instances: 0 } }
    pub fn create_batch(&mut self, mesh_id: u32, material_id: u32, max: u32) -> u32 {
        let id = self.next_id; self.next_id += 1;
        self.batches.insert(id, InstanceBatch::new(id, mesh_id, material_id, max));
        id
    }
    pub fn add_instance(&mut self, batch_id: u32, data: InstanceData) -> bool {
        if let Some(b) = self.batches.get_mut(&batch_id) { if b.add(data) { self.total_instances += 1; return true; } }
        false
    }
    pub fn clear_batch(&mut self, batch_id: u32) {
        if let Some(b) = self.batches.get_mut(&batch_id) { self.total_instances -= b.count() as u32; b.clear(); }
    }
    pub fn clear_all(&mut self) { for b in self.batches.values_mut() { b.clear(); } self.total_instances = 0; }
    pub fn batch_count(&self) -> usize { self.batches.len() }
    pub fn total_draw_calls(&self) -> usize { self.batches.values().filter(|b| b.count() > 0).count() }
}

impl Default for InstanceBatchManager {
    fn default() -> Self { Self::new() }
}

// ── Occlusion Culling ─────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct OcclusionQuery {
    pub id: u32,
    pub object_id: u32,
    pub visible: bool,
    pub pixel_count: u32,
    pub pending: bool,
    pub frame_issued: u64,
}

impl OcclusionQuery {
    pub fn new(id: u32, object_id: u32) -> Self { Self { id, object_id, visible: true, pixel_count: 0, pending: false, frame_issued: 0 } }
    pub fn issue(&mut self, frame: u64) { self.pending = true; self.frame_issued = frame; }
    pub fn resolve(&mut self, pixels: u32) { self.pixel_count = pixels; self.visible = pixels > 0; self.pending = false; }
    pub fn is_occluded(&self) -> bool { !self.visible }
    pub fn is_stale(&self, current_frame: u64) -> bool { current_frame - self.frame_issued > 2 }
}

#[derive(Clone, Debug)]
pub struct OcclusionCullSystem {
    pub queries: HashMap<u32, OcclusionQuery>,
    pub next_id: u32,
    pub enabled: bool,
    pub latency_frames: u32,
    pub culled_this_frame: u32,
    pub visible_this_frame: u32,
    pub frame: u64,
}

impl OcclusionCullSystem {
    pub fn new() -> Self { Self { queries: HashMap::new(), next_id: 1, enabled: true, latency_frames: 1, culled_this_frame: 0, visible_this_frame: 0, frame: 0 } }
    pub fn register(&mut self, object_id: u32) -> u32 {
        let id = self.next_id; self.next_id += 1;
        self.queries.insert(id, OcclusionQuery::new(id, object_id));
        id
    }
    pub fn begin_frame(&mut self) { self.frame += 1; self.culled_this_frame = 0; self.visible_this_frame = 0; }
    pub fn is_visible(&self, query_id: u32) -> bool { self.queries.get(&query_id).map(|q| q.visible).unwrap_or(true) }
    pub fn resolve(&mut self, query_id: u32, pixels: u32) {
        if let Some(q) = self.queries.get_mut(&query_id) {
            q.resolve(pixels);
            if q.visible { self.visible_this_frame += 1; } else { self.culled_this_frame += 1; }
        }
    }
    pub fn cull_rate(&self) -> f32 {
        let total = self.culled_this_frame + self.visible_this_frame;
        if total == 0 { 0.0 } else { self.culled_this_frame as f32 / total as f32 }
    }
    pub fn query_count(&self) -> usize { self.queries.len() }
}

impl Default for OcclusionCullSystem {
    fn default() -> Self { Self::new() }
}

// ── Render State Tracker ──────────────────────────────────────────────────────

#[derive(Clone, Debug, Default)]
pub struct RenderStateTracker {
    pub current_shader: Option<u32>,
    pub current_material: Option<u32>,
    pub current_vao: Option<u32>,
    pub current_fbo: Option<u32>,
    pub blend_enabled: bool,
    pub depth_test_enabled: bool,
    pub cull_enabled: bool,
    pub scissor_enabled: bool,
    pub state_changes: u32,
    pub shader_switches: u32,
    pub material_switches: u32,
    pub texture_uploads: u32,
    pub frame: u64,
}

impl RenderStateTracker {
    pub fn new() -> Self { Self { depth_test_enabled: true, cull_enabled: true, ..Default::default() } }
    pub fn begin_frame(&mut self) { self.state_changes = 0; self.shader_switches = 0; self.material_switches = 0; self.texture_uploads = 0; self.frame += 1; }
    pub fn bind_shader(&mut self, id: u32) -> bool {
        if self.current_shader == Some(id) { return false; }
        self.current_shader = Some(id); self.shader_switches += 1; self.state_changes += 1; true
    }
    pub fn bind_material(&mut self, id: u32) -> bool {
        if self.current_material == Some(id) { return false; }
        self.current_material = Some(id); self.material_switches += 1; self.state_changes += 1; true
    }
    pub fn redundancy_rate(&self) -> f32 { 0.0 }
    pub fn reset_bindings(&mut self) { self.current_shader = None; self.current_material = None; self.current_vao = None; self.current_fbo = None; }
}

// ── Shadow Map Atlas ──────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShadowMapAtlasEntry {
    pub light_id: u32,
    pub x: u32,
    pub y: u32,
    pub size: u32,
    pub valid: bool,
    pub last_updated_frame: u64,
}

#[derive(Clone, Debug)]
pub struct ShadowMapAtlas {
    pub atlas_size: u32,
    pub entries: Vec<ShadowMapAtlasEntry>,
    pub next_x: u32,
    pub next_y: u32,
    pub current_row_height: u32,
}

impl ShadowMapAtlas {
    pub fn new(atlas_size: u32) -> Self { Self { atlas_size, entries: Vec::new(), next_x: 0, next_y: 0, current_row_height: 0 } }
    pub fn allocate(&mut self, light_id: u32, size: u32) -> Option<(u32, u32)> {
        if self.next_x + size > self.atlas_size { self.next_x = 0; self.next_y += self.current_row_height; self.current_row_height = 0; }
        if self.next_y + size > self.atlas_size { return None; }
        let x = self.next_x; let y = self.next_y;
        self.current_row_height = self.current_row_height.max(size);
        self.next_x += size;
        self.entries.push(ShadowMapAtlasEntry { light_id, x, y, size, valid: true, last_updated_frame: 0 });
        Some((x, y))
    }
    pub fn find(&self, light_id: u32) -> Option<&ShadowMapAtlasEntry> { self.entries.iter().find(|e| e.light_id == light_id) }
    pub fn entry_count(&self) -> usize { self.entries.len() }
    pub fn reset(&mut self) { self.entries.clear(); self.next_x = 0; self.next_y = 0; self.current_row_height = 0; }
    pub fn utilization(&self) -> f32 { if self.atlas_size == 0 { 0.0 } else { self.next_y as f32 / self.atlas_size as f32 } }
}

// ── More final constants ──────────────────────────────────────────────────────

pub const INSTANCE_BATCH_DEFAULT_MAX: u32 = 1024;
pub const OCCLUSION_QUERY_MAX: usize = 4096;
pub const SHADOW_ATLAS_DEFAULT_SIZE: u32 = 4096;
pub const RENDER_STATE_TRACKER_FRAME_BUDGET: u32 = 1000;
pub const INSTANCE_DATA_SIZE_BYTES: usize = 128;

pub fn glsl_mat4_from_rows(rows: [[f32; 4]; 4]) -> String {
    format!("mat4({:.4},{:.4},{:.4},{:.4}, {:.4},{:.4},{:.4},{:.4}, {:.4},{:.4},{:.4},{:.4}, {:.4},{:.4},{:.4},{:.4})",
        rows[0][0], rows[0][1], rows[0][2], rows[0][3],
        rows[1][0], rows[1][1], rows[1][2], rows[1][3],
        rows[2][0], rows[2][1], rows[2][2], rows[2][3],
        rows[3][0], rows[3][1], rows[3][2], rows[3][3])
}
pub fn glsl_vec4(r: f32, g: f32, b: f32, a: f32) -> String { format!("vec4({:.4}, {:.4}, {:.4}, {:.4})", r, g, b, a) }
pub fn glsl_vec3(x: f32, y: f32, z: f32) -> String { format!("vec3({:.4}, {:.4}, {:.4})", x, y, z) }
pub fn glsl_vec2(x: f32, y: f32) -> String { format!("vec2({:.4}, {:.4})", x, y) }
pub fn glsl_float(v: f32) -> String { format!("{:.6}", v) }
pub fn glsl_int(v: i32) -> String { format!("{}", v) }
pub fn glsl_bool(v: bool) -> &'static str { if v { "true" } else { "false" } }
pub fn glsl_define(name: &str, value: &str) -> String { format!("#define {} {}", name, value) }
pub fn glsl_ifdef_block(name: &str, code: &str) -> String { format!("#ifdef {}\n{}\n#endif // {}", name, code, name) }
pub fn glsl_version_string(ver: u32, es: bool) -> String { if es { format!("#version {} es", ver) } else { format!("#version {}", ver) } }
pub fn glsl_precision_header() -> &'static str { "precision highp float;\nprecision highp int;\nprecision highp sampler2D;\n" }

pub fn shader_compiler_all_constants() -> HashMap<&'static str, u64> {
    let mut m = HashMap::new();
    m.insert("SHADER_MAX_UNIFORMS", SHADER_MAX_UNIFORMS as u64);
    m.insert("SHADER_MAX_ATTRIBUTES", SHADER_MAX_ATTRIBUTES as u64);
    m.insert("SHADER_MAX_PROGRAMS", SHADER_MAX_PROGRAMS as u64);
    m.insert("TEXTURE_MAX_SIZE", TEXTURE_MAX_SIZE as u64);
    m.insert("BUFFER_ALIGNMENT", BUFFER_ALIGNMENT as u64);
    m.insert("SHADOW_ATLAS_DEFAULT_SIZE", SHADOW_ATLAS_DEFAULT_SIZE as u64);
    m.insert("INSTANCE_BATCH_DEFAULT_MAX", INSTANCE_BATCH_DEFAULT_MAX as u64);
    m.insert("OCCLUSION_QUERY_MAX", OCCLUSION_QUERY_MAX as u64);
    m.insert("BLOOM_MAX_DOWNSAMPLE_PASSES", BLOOM_MAX_DOWNSAMPLE_PASSES as u64);
    m.insert("SSAO_KERNEL_SIZE_MAX", SSAO_KERNEL_SIZE_MAX as u64);
    m
}


// ── Motion Blur ───────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct MotionBlurConfig {
    pub enabled: bool,
    pub shutter_angle: f32,
    pub sample_count: u32,
    pub tile_size: u32,
    pub max_blur_pixels: f32,
    pub motion_scale: f32,
    pub camera_motion_blur: bool,
    pub object_motion_blur: bool,
}

impl MotionBlurConfig {
    pub fn new() -> Self { Self { enabled: false, shutter_angle: 180.0, sample_count: 8, tile_size: 10, max_blur_pixels: 40.0, motion_scale: 1.0, camera_motion_blur: true, object_motion_blur: true } }
    pub fn cinematic() -> Self { Self { enabled: true, shutter_angle: 270.0, sample_count: 16, ..Self::new() } }
    pub fn subtle() -> Self { Self { enabled: true, shutter_angle: 90.0, sample_count: 4, max_blur_pixels: 20.0, ..Self::new() } }
}

impl Default for MotionBlurConfig { fn default() -> Self { Self::new() } }

// ── Vignette ──────────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct VignetteConfig {
    pub enabled: bool,
    pub intensity: f32,
    pub smoothness: f32,
    pub roundness: f32,
    pub color: [f32; 3],
    pub center: [f32; 2],
    pub mask_texture_id: Option<u32>,
}

impl VignetteConfig {
    pub fn new() -> Self { Self { enabled: true, intensity: 0.45, smoothness: 0.2, roundness: 1.0, color: [0.0; 3], center: [0.5, 0.5], mask_texture_id: None } }
    pub fn subtle() -> Self { Self { intensity: 0.2, ..Self::new() } }
    pub fn dramatic() -> Self { Self { intensity: 0.8, smoothness: 0.4, ..Self::new() } }
    pub fn colored(r: f32, g: f32, b: f32) -> Self { Self { color: [r, g, b], ..Self::new() } }
    pub fn disabled() -> Self { Self { enabled: false, ..Self::new() } }
}

impl Default for VignetteConfig { fn default() -> Self { Self::new() } }

// ── Chromatic Aberration ──────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ChromaticAberrationConfig {
    pub enabled: bool,
    pub intensity: f32,
    pub radial: bool,
    pub offset_r: [f32; 2],
    pub offset_g: [f32; 2],
    pub offset_b: [f32; 2],
    pub sample_count: u32,
}

impl ChromaticAberrationConfig {
    pub fn new() -> Self { Self { enabled: false, intensity: 0.5, radial: true, offset_r: [-0.01, 0.0], offset_g: [0.0, 0.0], offset_b: [0.01, 0.0], sample_count: 3 } }
    pub fn subtle() -> Self { Self { enabled: true, intensity: 0.2, ..Self::new() } }
    pub fn strong() -> Self { Self { enabled: true, intensity: 1.5, sample_count: 5, ..Self::new() } }
}

impl Default for ChromaticAberrationConfig { fn default() -> Self { Self::new() } }

// ── Film Grain ────────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct FilmGrainConfig {
    pub enabled: bool,
    pub intensity: f32,
    pub size: f32,
    pub luminance_contribution: f32,
    pub color: bool,
    pub animated: bool,
}

impl FilmGrainConfig {
    pub fn new() -> Self { Self { enabled: false, intensity: 0.1, size: 1.5, luminance_contribution: 0.8, color: false, animated: true } }
    pub fn subtle() -> Self { Self { enabled: true, intensity: 0.05, ..Self::new() } }
    pub fn heavy() -> Self { Self { enabled: true, intensity: 0.4, ..Self::new() } }
}

impl Default for FilmGrainConfig { fn default() -> Self { Self::new() } }

// ── Anti-Aliasing Config ──────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct AntiAliasingConfig {
    pub mode: AntiAliasingMode,
    pub msaa_samples: u32,
    pub fxaa: bool,
    pub taa: Option<TaaConfig>,
    pub smaa_quality: u32,
}

#[derive(Clone, Debug, PartialEq)]
pub enum AntiAliasingMode { None, Msaa, Fxaa, Taa, Smaa, Dlss }

impl AntiAliasingConfig {
    pub fn none() -> Self { Self { mode: AntiAliasingMode::None, msaa_samples: 1, fxaa: false, taa: None, smaa_quality: 0 } }
    pub fn fxaa() -> Self { Self { mode: AntiAliasingMode::Fxaa, fxaa: true, ..Self::none() } }
    pub fn taa() -> Self { Self { mode: AntiAliasingMode::Taa, taa: Some(TaaConfig::new()), ..Self::none() } }
    pub fn msaa(samples: u32) -> Self { Self { mode: AntiAliasingMode::Msaa, msaa_samples: samples, ..Self::none() } }
    pub fn smaa(quality: u32) -> Self { Self { mode: AntiAliasingMode::Smaa, smaa_quality: quality, ..Self::none() } }
    pub fn is_temporal(&self) -> bool { self.mode == AntiAliasingMode::Taa || self.mode == AntiAliasingMode::Dlss }
    pub fn requires_velocity_buffer(&self) -> bool { self.is_temporal() }
}

impl Default for AntiAliasingConfig { fn default() -> Self { Self::fxaa() } }

// ── Extended post process config ──────────────────────────────────────────────

#[derive(Clone, Debug, Default)]
pub struct ExtendedPostProcessConfig {
    pub motion_blur: MotionBlurConfig,
    pub vignette: VignetteConfig,
    pub chromatic_aberration: ChromaticAberrationConfig,
    pub film_grain: FilmGrainConfig,
    pub anti_aliasing: AntiAliasingConfig,
}

impl ExtendedPostProcessConfig {
    pub fn new() -> Self { Self::default() }
    pub fn cinematic() -> Self {
        Self { motion_blur: MotionBlurConfig::cinematic(), vignette: VignetteConfig::dramatic(), chromatic_aberration: ChromaticAberrationConfig::subtle(), film_grain: FilmGrainConfig::subtle(), anti_aliasing: AntiAliasingConfig::taa() }
    }
    pub fn game() -> Self {
        Self { motion_blur: MotionBlurConfig::subtle(), vignette: VignetteConfig::subtle(), anti_aliasing: AntiAliasingConfig::fxaa(), ..Self::new() }
    }
    pub fn count_active(&self) -> usize {
        [self.motion_blur.enabled, self.vignette.enabled, self.chromatic_aberration.enabled, self.film_grain.enabled].iter().filter(|&&b| b).count()
    }
}

// ── GPU Program Lifecycle ─────────────────────────────────────────────────────

#[derive(Clone, Debug, PartialEq)]
pub enum GpuProgramState { Uncompiled, Compiling, Compiled, Failed, Stale }

#[derive(Clone, Debug)]
pub struct GpuProgramLifecycle {
    pub program_id: u32,
    pub state: GpuProgramState,
    pub compile_attempts: u32,
    pub last_success: Option<u64>,
    pub last_failure: Option<u64>,
    pub auto_retry: bool,
    pub max_retries: u32,
}

impl GpuProgramLifecycle {
    pub fn new(program_id: u32) -> Self { Self { program_id, state: GpuProgramState::Uncompiled, compile_attempts: 0, last_success: None, last_failure: None, auto_retry: true, max_retries: 3 } }
    pub fn begin_compile(&mut self) { self.state = GpuProgramState::Compiling; self.compile_attempts += 1; }
    pub fn mark_success(&mut self, ts: u64) { self.state = GpuProgramState::Compiled; self.last_success = Some(ts); }
    pub fn mark_failure(&mut self, ts: u64) { self.state = GpuProgramState::Failed; self.last_failure = Some(ts); }
    pub fn mark_stale(&mut self) { self.state = GpuProgramState::Stale; }
    pub fn can_retry(&self) -> bool { self.auto_retry && self.compile_attempts < self.max_retries }
    pub fn is_compiled(&self) -> bool { self.state == GpuProgramState::Compiled }
    pub fn is_failed(&self) -> bool { self.state == GpuProgramState::Failed }
}

// ── Final system constants ────────────────────────────────────────────────────

pub const MOTION_BLUR_MAX_SAMPLES: u32 = 32;
pub const FILM_GRAIN_MAX_SIZE: f32 = 10.0;
pub const VIGNETTE_MAX_INTENSITY: f32 = 1.0;
pub const CHROMATIC_MAX_OFFSET: f32 = 0.1;
pub const AA_MSAA_MAX_SAMPLES: u32 = 8;
pub const SHADER_GPU_PROGRAM_MAX_RETRIES: u32 = 3;
pub const RENDER_EXTENDED_PP_EFFECT_COUNT: usize = 5;

pub fn anti_aliasing_name(mode: &AntiAliasingMode) -> &'static str {
    match mode { AntiAliasingMode::None => "None", AntiAliasingMode::Msaa => "MSAA", AntiAliasingMode::Fxaa => "FXAA", AntiAliasingMode::Taa => "TAA", AntiAliasingMode::Smaa => "SMAA", AntiAliasingMode::Dlss => "DLSS" }
}
pub fn gpu_program_state_name(s: &GpuProgramState) -> &'static str {
    match s { GpuProgramState::Uncompiled => "Uncompiled", GpuProgramState::Compiling => "Compiling", GpuProgramState::Compiled => "Compiled", GpuProgramState::Failed => "Failed", GpuProgramState::Stale => "Stale" }
}
pub fn shader_editor_complete_version() -> String { format!("ShaderCompilerEditor — complete build, v{}", shader_system_version()) }


// ── Shader Input Assembler ────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct InputAssemblerConfig {
    pub topology: PrimitiveTopology,
    pub restart_enabled: bool,
    pub restart_index: u32,
    pub vertex_layout: VertexLayout,
}

#[derive(Clone, Debug, PartialEq)]
pub enum PrimitiveTopology { PointList, LineList, LineStrip, TriangleList, TriangleStrip, TriangleFan, PatchList(u32) }

impl PrimitiveTopology {
    pub fn name(&self) -> &'static str {
        match self { PrimitiveTopology::PointList => "PointList", PrimitiveTopology::LineList => "LineList", PrimitiveTopology::LineStrip => "LineStrip", PrimitiveTopology::TriangleList => "TriangleList", PrimitiveTopology::TriangleStrip => "TriangleStrip", PrimitiveTopology::TriangleFan => "TriangleFan", PrimitiveTopology::PatchList(_) => "PatchList" }
    }
    pub fn is_strip(&self) -> bool { matches!(self, PrimitiveTopology::LineStrip | PrimitiveTopology::TriangleStrip) }
    pub fn is_triangle(&self) -> bool { matches!(self, PrimitiveTopology::TriangleList | PrimitiveTopology::TriangleStrip | PrimitiveTopology::TriangleFan) }
}

impl InputAssemblerConfig {
    pub fn triangles(layout: VertexLayout) -> Self { Self { topology: PrimitiveTopology::TriangleList, restart_enabled: false, restart_index: 0xFFFFFFFF, vertex_layout: layout } }
    pub fn lines(layout: VertexLayout) -> Self { Self { topology: PrimitiveTopology::LineList, restart_enabled: false, restart_index: 0xFFFFFFFF, vertex_layout: layout } }
    pub fn points(layout: VertexLayout) -> Self { Self { topology: PrimitiveTopology::PointList, restart_enabled: false, restart_index: 0xFFFFFFFF, vertex_layout: layout } }
}

// ── Stencil Config ────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct StencilConfig {
    pub enabled: bool,
    pub ref_value: u32,
    pub read_mask: u32,
    pub write_mask: u32,
    pub fail_op: StencilOp,
    pub depth_fail_op: StencilOp,
    pub pass_op: StencilOp,
    pub compare_func: CompareFunc,
}

#[derive(Clone, Debug, PartialEq)]
pub enum StencilOp { Keep, Zero, Replace, IncrClamp, DecrClamp, Invert, IncrWrap, DecrWrap }

impl StencilConfig {
    pub fn disabled() -> Self { Self { enabled: false, ref_value: 0, read_mask: 0xFF, write_mask: 0xFF, fail_op: StencilOp::Keep, depth_fail_op: StencilOp::Keep, pass_op: StencilOp::Keep, compare_func: CompareFunc::Always } }
    pub fn write_mask(mask: u32) -> Self { Self { enabled: true, write_mask: mask, pass_op: StencilOp::Replace, ref_value: mask, ..Self::disabled() } }
    pub fn test_mask(mask: u32) -> Self { Self { enabled: true, read_mask: mask, ref_value: mask, ..Self::disabled() } }
}

impl Default for StencilConfig { fn default() -> Self { Self::disabled() } }

// ── Viewport Config ───────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ViewportConfig {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub min_depth: f32,
    pub max_depth: f32,
}

impl ViewportConfig {
    pub fn new(width: f32, height: f32) -> Self { Self { x: 0.0, y: 0.0, width, height, min_depth: 0.0, max_depth: 1.0 } }
    pub fn aspect_ratio(&self) -> f32 { if self.height == 0.0 { 1.0 } else { self.width / self.height } }
    pub fn scale(mut self, s: f32) -> Self { self.width *= s; self.height *= s; self }
    pub fn ndc_to_pixel(&self, ndc_x: f32, ndc_y: f32) -> (f32, f32) {
        ((ndc_x * 0.5 + 0.5) * self.width + self.x, (ndc_y * -0.5 + 0.5) * self.height + self.y)
    }
    pub fn pixel_to_ndc(&self, px: f32, py: f32) -> (f32, f32) {
        ((px - self.x) / self.width * 2.0 - 1.0, -((py - self.y) / self.height * 2.0 - 1.0))
    }
}

impl Default for ViewportConfig { fn default() -> Self { Self::new(1920.0, 1080.0) } }

// ── Rasterizer State ──────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct RasterizerState {
    pub cull_mode: CullMode,
    pub front_face: FrontFace,
    pub polygon_mode: PolygonMode,
    pub depth_bias: f32,
    pub depth_bias_slope_scale: f32,
    pub depth_bias_clamp: f32,
    pub depth_clamp: bool,
    pub rasterizer_discard: bool,
    pub multisample: bool,
    pub line_width: f32,
    pub conservative: bool,
}

impl Default for RasterizerState {
    fn default() -> Self { Self { cull_mode: CullMode::Back, front_face: FrontFace::CounterClockwise, polygon_mode: PolygonMode::Fill, depth_bias: 0.0, depth_bias_slope_scale: 0.0, depth_bias_clamp: 0.0, depth_clamp: false, rasterizer_discard: false, multisample: false, line_width: 1.0, conservative: false } }
}

impl RasterizerState {
    pub fn wireframe() -> Self { Self { polygon_mode: PolygonMode::Line, cull_mode: CullMode::None, ..Default::default() } }
    pub fn shadow_map() -> Self { Self { depth_bias: 1.0, depth_bias_slope_scale: 1.5, ..Default::default() } }
    pub fn two_sided() -> Self { Self { cull_mode: CullMode::None, ..Default::default() } }
    pub fn is_wireframe(&self) -> bool { self.polygon_mode == PolygonMode::Line }
    pub fn has_depth_bias(&self) -> bool { self.depth_bias.abs() > 1e-6 || self.depth_bias_slope_scale.abs() > 1e-6 }
}

// ── Complete Graphics Pipeline Descriptor ─────────────────────────────────────

#[derive(Clone, Debug)]
pub struct GraphicsPipelineDescriptor {
    pub name: String,
    pub vertex_shader_id: u32,
    pub fragment_shader_id: u32,
    pub geometry_shader_id: Option<u32>,
    pub input_assembly: InputAssemblerConfig,
    pub rasterizer: RasterizerState,
    pub depth_stencil: (bool, bool, CompareFunc, StencilConfig),
    pub blend_state: PipelineState,
    pub viewport: ViewportConfig,
    pub render_pass_id: u32,
    pub subpass: u32,
    pub layout: PipelineLayout,
}

impl GraphicsPipelineDescriptor {
    pub fn new(name: impl Into<String>, vert_id: u32, frag_id: u32) -> Self {
        Self { name: name.into(), vertex_shader_id: vert_id, fragment_shader_id: frag_id, geometry_shader_id: None, input_assembly: InputAssemblerConfig::triangles(VertexLayout::standard_mesh()), rasterizer: RasterizerState::default(), depth_stencil: (true, true, CompareFunc::Less, StencilConfig::disabled()), blend_state: PipelineState::opaque(), viewport: ViewportConfig::default(), render_pass_id: 0, subpass: 0, layout: PipelineLayout::new() }
    }
    pub fn transparent(name: impl Into<String>, vert_id: u32, frag_id: u32) -> Self {
        let mut d = Self::new(name, vert_id, frag_id); d.blend_state = PipelineState::transparent(); d.depth_stencil.1 = false; d
    }
    pub fn has_geometry_shader(&self) -> bool { self.geometry_shader_id.is_some() }
    pub fn depth_test_enabled(&self) -> bool { self.depth_stencil.0 }
    pub fn depth_write_enabled(&self) -> bool { self.depth_stencil.1 }
}

// ── Final shader constants ────────────────────────────────────────────────────

pub const STENCIL_MAX_REF_VALUE: u32 = 255;
pub const VIEWPORT_MAX_RENDER_SCALE: f32 = 2.0;
pub const RASTERIZER_MAX_LINE_WIDTH: f32 = 16.0;
pub const GRAPHICS_PIPELINE_MAX: usize = 512;
pub const INPUT_ASSEMBLER_MAX_VERTEX_STREAMS: usize = 8;

pub fn stencil_op_name(op: &StencilOp) -> &'static str {
    match op { StencilOp::Keep => "Keep", StencilOp::Zero => "Zero", StencilOp::Replace => "Replace", StencilOp::IncrClamp => "IncrClamp", StencilOp::DecrClamp => "DecrClamp", StencilOp::Invert => "Invert", StencilOp::IncrWrap => "IncrWrap", StencilOp::DecrWrap => "DecrWrap" }
}
pub fn primitive_topology_vertex_count(topo: &PrimitiveTopology, primitive_count: u32) -> u32 {
    match topo { PrimitiveTopology::PointList => primitive_count, PrimitiveTopology::LineList => primitive_count * 2, PrimitiveTopology::LineStrip => primitive_count + 1, PrimitiveTopology::TriangleList => primitive_count * 3, PrimitiveTopology::TriangleStrip | PrimitiveTopology::TriangleFan => primitive_count + 2, PrimitiveTopology::PatchList(n) => primitive_count * n }
}

pub fn shader_compiler_feature_summary() -> String {
    let features = shader_compiler_module_list();
    format!("ShaderCompilerEditor v{}: {} modules — {}", shader_system_version(), features.len(), features.join(", "))
}


// ── Render Target Management ──────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct RenderTargetSet {
    pub id: u32,
    pub name: String,
    pub width: u32,
    pub height: u32,
    pub color_targets: Vec<u32>,
    pub depth_target: Option<u32>,
    pub msaa_samples: u32,
    pub active: bool,
}

impl RenderTargetSet {
    pub fn new(id: u32, name: impl Into<String>, w: u32, h: u32) -> Self {
        Self { id, name: name.into(), width: w, height: h, color_targets: Vec::new(), depth_target: None, msaa_samples: 1, active: false }
    }
    pub fn add_color(&mut self, tex_id: u32) { self.color_targets.push(tex_id); }
    pub fn set_depth(&mut self, tex_id: u32) { self.depth_target = Some(tex_id); }
    pub fn enable(&mut self) { self.active = true; }
    pub fn disable(&mut self) { self.active = false; }
    pub fn color_count(&self) -> usize { self.color_targets.len() }
    pub fn has_depth(&self) -> bool { self.depth_target.is_some() }
    pub fn total_attachments(&self) -> usize { self.color_targets.len() + if self.has_depth() { 1 } else { 0 } }
    pub fn aspect_ratio(&self) -> f32 { if self.height == 0 { 1.0 } else { self.width as f32 / self.height as f32 } }
    pub fn is_multisampled(&self) -> bool { self.msaa_samples > 1 }
    pub fn total_bytes(&self, bpp: u32) -> u64 { self.width as u64 * self.height as u64 * bpp as u64 * (self.color_targets.len() + 1) as u64 }
}

#[derive(Clone, Debug)]
pub struct RenderTargetManager {
    pub sets: HashMap<u32, RenderTargetSet>,
    pub active_set: Option<u32>,
    pub next_id: u32,
    pub backbuffer_id: u32,
}

impl RenderTargetManager {
    pub fn new() -> Self { Self { sets: HashMap::new(), active_set: None, next_id: 1, backbuffer_id: 0 } }
    pub fn create(&mut self, name: impl Into<String>, w: u32, h: u32) -> u32 {
        let id = self.next_id; self.next_id += 1;
        self.sets.insert(id, RenderTargetSet::new(id, name, w, h));
        id
    }
    pub fn get(&self, id: u32) -> Option<&RenderTargetSet> { self.sets.get(&id) }
    pub fn bind(&mut self, id: u32) { if let Some(s) = self.sets.get_mut(&id) { s.enable(); } self.active_set = Some(id); }
    pub fn unbind(&mut self) { if let Some(id) = self.active_set { if let Some(s) = self.sets.get_mut(&id) { s.disable(); } } self.active_set = None; }
    pub fn resize_all(&mut self, w: u32, h: u32) { for s in self.sets.values_mut() { s.width = w; s.height = h; } }
    pub fn count(&self) -> usize { self.sets.len() }
    pub fn active(&self) -> Option<&RenderTargetSet> { self.active_set.and_then(|id| self.sets.get(&id)) }
}

impl Default for RenderTargetManager { fn default() -> Self { Self::new() } }

// ── Frame Graph Executor ──────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct FrameGraphExecutor {
    pub render_graph: RenderGraph,
    pub rt_manager: RenderTargetManager,
    pub frame: u64,
    pub paused: bool,
}

impl FrameGraphExecutor {
    pub fn new() -> Self { Self { render_graph: RenderGraph::new("frame"), rt_manager: RenderTargetManager::new(), frame: 0, paused: false } }
    pub fn begin_frame(&mut self) { if !self.paused { self.frame += 1; } }
    pub fn pause(&mut self) { self.paused = true; }
    pub fn resume(&mut self) { self.paused = false; }
    pub fn node_count(&self) -> usize { self.render_graph.node_count() }
    pub fn is_running(&self) -> bool { !self.paused }
    pub fn frame_number(&self) -> u64 { self.frame }
}

impl Default for FrameGraphExecutor { fn default() -> Self { Self::new() } }

// ── Shader Compiler Statistics ────────────────────────────────────────────────

#[derive(Clone, Debug, Default)]
pub struct ShaderCompilerStats {
    pub total_programs: usize,
    pub total_materials: usize,
    pub total_textures: usize,
    pub total_buffers: usize,
    pub total_passes: usize,
    pub total_post_effects: usize,
    pub cache_entries: usize,
    pub cache_hit_rate: f32,
    pub total_compile_ms: f32,
    pub failed_compiles: u32,
    pub hot_reloads: u32,
}

impl ShaderCompilerStats {
    pub fn from_workspace(ws: &ShaderWorkspace) -> Self {
        Self {
            total_programs: ws.program_count(),
            total_materials: ws.material_count(),
            total_textures: ws.texture_count(),
            total_buffers: ws.buffer_count(),
            total_passes: ws.pipeline.pass_count(),
            total_post_effects: ws.post_process.effect_count(),
            cache_entries: ws.cache.size(),
            cache_hit_rate: ws.cache.hit_rate(),
            ..Default::default()
        }
    }
    pub fn summary(&self) -> String {
        format!("Programs:{} Materials:{} Textures:{} Buffers:{} Cache:{:.0}%", self.total_programs, self.total_materials, self.total_textures, self.total_buffers, self.cache_hit_rate * 100.0)
    }
}

// ── Final module constants ────────────────────────────────────────────────────

pub const RENDER_TARGET_MAX: usize = 64;
pub const FRAME_GRAPH_MAX_NODES: usize = 128;
pub const RT_MAX_COLOR_ATTACHMENTS: usize = 8;
pub const RT_DEFAULT_MSAA: u32 = 1;
pub const SHADER_COMPILER_SESSION_MAX: usize = 4;

pub fn all_post_process_effect_names() -> &'static [&'static str] {
    &["Bloom", "Tone Mapping", "SSAO", "SSR", "TAA", "Depth of Field", "Volumetric Fog", "Lens Flare", "Motion Blur", "Vignette", "Chromatic Aberration", "Film Grain", "FXAA", "Color Grading", "SMAA"]
}

pub fn shader_compiler_comprehensive_info() -> String {
    format!(concat!(
        "ShaderCompilerEditor v{} Summary:\n",
        "  Modules: {}\n",
        "  Render API targets: {}\n",
        "  Quality presets: {}\n",
        "  Post-process effects: {}\n",
        "  Builtin GLSL snippets: {}\n",
        "  Builtin GLSL functions: {}\n"
    ),
    shader_system_version(),
    shader_module_count(),
    supported_render_apis().len(),
    RENDER_QUALITY_PRESET_COUNT,
    all_post_process_effect_names().len(),
    SHADER_BUILTIN_SNIPPETS,
    SHADER_GLSL_BUILTIN_FUNCTIONS)
}


// ── Shader Manager ────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderManager {
    pub compiler: ShaderCompilerMain,
    pub post_config: FullPostProcessConfig,
    pub extended_post: ExtendedPostProcessConfig,
    pub anti_aliasing: AntiAliasingConfig,
    pub quality_preset: String,
    pub quality_presets: Vec<RenderQualityPreset>,
    pub frame_executor: FrameGraphExecutor,
    pub rt_manager: RenderTargetManager,
    pub uniform_tracker: UniformTracker,
    pub occlusion_cull: OcclusionCullSystem,
    pub instance_batches: InstanceBatchManager,
    pub render_state: RenderStateTracker,
    pub error_reports: Vec<ShaderErrorReport>,
    pub compile_stats: CompileStats,
}

impl ShaderManager {
    pub fn new() -> Self {
        Self {
            compiler: ShaderCompilerMain::new(),
            post_config: FullPostProcessConfig::new(),
            extended_post: ExtendedPostProcessConfig::new(),
            anti_aliasing: AntiAliasingConfig::default(),
            quality_preset: "High".into(),
            quality_presets: build_quality_presets(),
            frame_executor: FrameGraphExecutor::new(),
            rt_manager: RenderTargetManager::new(),
            uniform_tracker: UniformTracker::new(),
            occlusion_cull: OcclusionCullSystem::new(),
            instance_batches: InstanceBatchManager::new(),
            render_state: RenderStateTracker::new(),
            error_reports: Vec::new(),
            compile_stats: CompileStats::new(),
        }
    }
    pub fn add_program(&mut self, prog: ShaderProgram) -> u32 { self.compiler.add_program(prog) }
    pub fn add_material(&mut self, mat: Material) -> u32 { self.compiler.add_material(mat) }
    pub fn begin_frame(&mut self) { self.compiler.begin_frame(); self.frame_executor.begin_frame(); self.render_state.begin_frame(); self.occlusion_cull.begin_frame(); self.instance_batches.clear_all(); }
    pub fn set_quality(&mut self, preset_name: &str) { if self.quality_presets.iter().any(|p| p.name == preset_name) { self.quality_preset = preset_name.to_string(); } }
    pub fn record_error(&mut self, report: ShaderErrorReport) { self.error_reports.push(report); }
    pub fn clear_errors(&mut self) { self.error_reports.clear(); }
    pub fn has_errors(&self) -> bool { !self.error_reports.is_empty() }
    pub fn error_count(&self) -> usize { self.error_reports.len() }
    pub fn program_count(&self) -> usize { self.compiler.program_count() }
    pub fn compilation_summary(&self) -> String { self.compiler.compilation_summary() }
    pub fn stats(&self) -> ShaderCompilerStats { ShaderCompilerStats::from_workspace(&self.compiler.workspace) }
}

impl Default for ShaderManager { fn default() -> Self { Self::new() } }

// ── GLSL Intrinsics Documentation ─────────────────────────────────────────────

pub struct GlslIntrinsicDoc {
    pub name: &'static str,
    pub signature: &'static str,
    pub description: &'static str,
    pub category: &'static str,
}

pub const GLSL_DOCS: &[GlslIntrinsicDoc] = &[
    GlslIntrinsicDoc { name: "radians", signature: "genType radians(genType degrees)", description: "Convert degrees to radians", category: "trigonometry" },
    GlslIntrinsicDoc { name: "degrees", signature: "genType degrees(genType radians)", description: "Convert radians to degrees", category: "trigonometry" },
    GlslIntrinsicDoc { name: "sin", signature: "genType sin(genType angle)", description: "Sine of angle in radians", category: "trigonometry" },
    GlslIntrinsicDoc { name: "cos", signature: "genType cos(genType angle)", description: "Cosine of angle in radians", category: "trigonometry" },
    GlslIntrinsicDoc { name: "tan", signature: "genType tan(genType angle)", description: "Tangent of angle in radians", category: "trigonometry" },
    GlslIntrinsicDoc { name: "asin", signature: "genType asin(genType x)", description: "Arc sine", category: "trigonometry" },
    GlslIntrinsicDoc { name: "acos", signature: "genType acos(genType x)", description: "Arc cosine", category: "trigonometry" },
    GlslIntrinsicDoc { name: "atan", signature: "genType atan(genType y_over_x)", description: "Arc tangent", category: "trigonometry" },
    GlslIntrinsicDoc { name: "sinh", signature: "genType sinh(genType x)", description: "Hyperbolic sine", category: "trigonometry" },
    GlslIntrinsicDoc { name: "cosh", signature: "genType cosh(genType x)", description: "Hyperbolic cosine", category: "trigonometry" },
    GlslIntrinsicDoc { name: "pow", signature: "genType pow(genType x, genType y)", description: "x raised to y power", category: "exponential" },
    GlslIntrinsicDoc { name: "exp", signature: "genType exp(genType x)", description: "e raised to x", category: "exponential" },
    GlslIntrinsicDoc { name: "log", signature: "genType log(genType x)", description: "Natural logarithm", category: "exponential" },
    GlslIntrinsicDoc { name: "exp2", signature: "genType exp2(genType x)", description: "2 raised to x", category: "exponential" },
    GlslIntrinsicDoc { name: "log2", signature: "genType log2(genType x)", description: "Base-2 logarithm", category: "exponential" },
    GlslIntrinsicDoc { name: "sqrt", signature: "genType sqrt(genType x)", description: "Square root", category: "exponential" },
    GlslIntrinsicDoc { name: "inversesqrt", signature: "genType inversesqrt(genType x)", description: "Inverse square root", category: "exponential" },
    GlslIntrinsicDoc { name: "abs", signature: "genType abs(genType x)", description: "Absolute value", category: "common" },
    GlslIntrinsicDoc { name: "sign", signature: "genType sign(genType x)", description: "Sign of x", category: "common" },
    GlslIntrinsicDoc { name: "floor", signature: "genType floor(genType x)", description: "Floor function", category: "common" },
    GlslIntrinsicDoc { name: "ceil", signature: "genType ceil(genType x)", description: "Ceiling function", category: "common" },
    GlslIntrinsicDoc { name: "round", signature: "genType round(genType x)", description: "Round to nearest", category: "common" },
    GlslIntrinsicDoc { name: "fract", signature: "genType fract(genType x)", description: "Fractional part", category: "common" },
    GlslIntrinsicDoc { name: "mod", signature: "genType mod(genType x, genType y)", description: "Modulo operation", category: "common" },
    GlslIntrinsicDoc { name: "min", signature: "genType min(genType x, genType y)", description: "Minimum of two values", category: "common" },
    GlslIntrinsicDoc { name: "max", signature: "genType max(genType x, genType y)", description: "Maximum of two values", category: "common" },
    GlslIntrinsicDoc { name: "clamp", signature: "genType clamp(genType x, genType minVal, genType maxVal)", description: "Clamp x between min and max", category: "common" },
    GlslIntrinsicDoc { name: "mix", signature: "genType mix(genType x, genType y, genType a)", description: "Linear interpolation", category: "common" },
    GlslIntrinsicDoc { name: "step", signature: "genType step(genType edge, genType x)", description: "Step function", category: "common" },
    GlslIntrinsicDoc { name: "smoothstep", signature: "genType smoothstep(genType edge0, genType edge1, genType x)", description: "Smooth step function", category: "common" },
];

pub fn find_glsl_doc(name: &str) -> Option<&'static GlslIntrinsicDoc> { GLSL_DOCS.iter().find(|d| d.name == name) }
pub fn glsl_doc_count() -> usize { GLSL_DOCS.len() }
pub fn glsl_docs_in_category(cat: &str) -> Vec<&'static GlslIntrinsicDoc> { GLSL_DOCS.iter().filter(|d| d.category == cat).collect() }

pub const SHADER_MANAGER_VERSION: &str = "ShaderManager v1.0";
pub const SHADER_GLSL_INTRINSIC_DOC_COUNT: usize = 30;
pub const SHADER_MAX_ERROR_REPORTS: usize = 256;
pub const FRAME_GRAPH_EXECUTOR_MAX_NODES: usize = 128;

pub fn shader_manager_info() -> String {
    format!("{} — {} programs max, {} intrinsics documented, {} quality presets", SHADER_MANAGER_VERSION, SHADER_MAX_PROGRAMS, SHADER_GLSL_INTRINSIC_DOC_COUNT, RENDER_QUALITY_PRESET_COUNT)
}


// ── Geometry Shader Support ───────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct GeometryShaderConfig {
    pub input_primitive: GeometryPrimitive,
    pub output_primitive: GeometryPrimitive,
    pub max_vertices_out: u32,
    pub invocations: u32,
}

#[derive(Clone, Debug, PartialEq)]
pub enum GeometryPrimitive { Points, Lines, LinesAdjacency, Triangles, TrianglesAdjacency, LineStrip, TriangleStrip }

impl GeometryShaderConfig {
    pub fn passthrough_triangles() -> Self { Self { input_primitive: GeometryPrimitive::Triangles, output_primitive: GeometryPrimitive::TriangleStrip, max_vertices_out: 3, invocations: 1 } }
    pub fn silhouette_detection() -> Self { Self { input_primitive: GeometryPrimitive::TrianglesAdjacency, output_primitive: GeometryPrimitive::LineStrip, max_vertices_out: 4, invocations: 1 } }
    pub fn shadow_volumes() -> Self { Self { input_primitive: GeometryPrimitive::Triangles, output_primitive: GeometryPrimitive::TriangleStrip, max_vertices_out: 18, invocations: 1 } }
    pub fn point_sprites() -> Self { Self { input_primitive: GeometryPrimitive::Points, output_primitive: GeometryPrimitive::TriangleStrip, max_vertices_out: 4, invocations: 1 } }
    pub fn cubemap_rendering() -> Self { Self { input_primitive: GeometryPrimitive::Triangles, output_primitive: GeometryPrimitive::TriangleStrip, max_vertices_out: 18, invocations: 6 } }
}

impl Default for GeometryShaderConfig { fn default() -> Self { Self::passthrough_triangles() } }

// ── Tessellation Shader Support ───────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct TessellationConfig {
    pub enabled: bool,
    pub patch_size: u32,
    pub outer_level: [f32; 4],
    pub inner_level: [f32; 2],
    pub spacing: TessSpacing,
    pub winding: TessWinding,
    pub primitive: TessPrimitive,
    pub point_mode: bool,
    pub adaptive: bool,
    pub max_tess_level: f32,
    pub screen_space_factor: f32,
}

#[derive(Clone, Debug, PartialEq)]
pub enum TessSpacing { Equal, FractionalEven, FractionalOdd }
#[derive(Clone, Debug, PartialEq)]
pub enum TessWinding { Ccw, Cw }
#[derive(Clone, Debug, PartialEq)]
pub enum TessPrimitive { Triangles, Quads, Isolines }

impl TessellationConfig {
    pub fn new() -> Self { Self { enabled: false, patch_size: 3, outer_level: [4.0; 4], inner_level: [4.0; 2], spacing: TessSpacing::Equal, winding: TessWinding::Ccw, primitive: TessPrimitive::Triangles, point_mode: false, adaptive: false, max_tess_level: 64.0, screen_space_factor: 1.0 } }
    pub fn displacement_mapping() -> Self { Self { enabled: true, adaptive: true, ..Self::new() } }
    pub fn lod_triangles(level: f32) -> Self { Self { enabled: true, outer_level: [level; 4], inner_level: [level; 2], ..Self::new() } }
    pub fn disabled() -> Self { Self { enabled: false, ..Self::new() } }
    pub fn effective_patch_vertices(&self) -> u32 {
        match self.primitive { TessPrimitive::Triangles => 3, TessPrimitive::Quads => 4, TessPrimitive::Isolines => 2 }
    }
}

impl Default for TessellationConfig { fn default() -> Self { Self::new() } }

// ── Wireframe Overlay ─────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct WireframeConfig {
    pub enabled: bool,
    pub color: [f32; 4],
    pub line_width: f32,
    pub overlay_on_solid: bool,
    pub show_normals: bool,
    pub normal_length: f32,
    pub normal_color: [f32; 4],
    pub show_tangents: bool,
    pub highlight_selected: bool,
    pub selection_color: [f32; 4],
}

impl WireframeConfig {
    pub fn new() -> Self { Self { enabled: false, color: [0.0, 1.0, 0.0, 1.0], line_width: 1.0, overlay_on_solid: true, show_normals: false, normal_length: 0.1, normal_color: [0.0, 0.0, 1.0, 1.0], show_tangents: false, highlight_selected: true, selection_color: [1.0, 0.5, 0.0, 1.0] } }
    pub fn enable(&mut self) { self.enabled = true; }
    pub fn disable(&mut self) { self.enabled = false; }
    pub fn show_normals(mut self) -> Self { self.show_normals = true; self }
}

impl Default for WireframeConfig { fn default() -> Self { Self::new() } }

// ── Shader Error Recovery ─────────────────────────────────────────────────────

#[derive(Clone, Debug)]
pub struct ShaderFallback {
    pub trigger_on_error: bool,
    pub fallback_program_id: u32,
    pub fallback_name: String,
    pub auto_compile_fallback: bool,
    pub notify_on_fallback: bool,
}

impl ShaderFallback {
    pub fn new(fallback_id: u32) -> Self { Self { trigger_on_error: true, fallback_program_id: fallback_id, fallback_name: "error_fallback".into(), auto_compile_fallback: true, notify_on_fallback: true } }
    pub fn with_name(mut self, name: impl Into<String>) -> Self { self.fallback_name = name.into(); self }
    pub fn silent(mut self) -> Self { self.notify_on_fallback = false; self }
}

impl Default for ShaderFallback { fn default() -> Self { Self::new(0) } }

// ── Final constants ───────────────────────────────────────────────────────────

pub const TESSELLATION_MAX_PATCH_SIZE: u32 = 32;
pub const TESSELLATION_MAX_LEVEL: f32 = 64.0;
pub const GEOMETRY_SHADER_MAX_VERTICES_OUT: u32 = 256;
pub const GEOMETRY_SHADER_MAX_INVOCATIONS: u32 = 32;
pub const WIREFRAME_LINE_WIDTH_MAX: f32 = 8.0;
pub const SHADER_FALLBACK_MAX_DEPTH: u32 = 3;

pub fn geometry_primitive_name(p: &GeometryPrimitive) -> &'static str {
    match p { GeometryPrimitive::Points => "points", GeometryPrimitive::Lines => "lines", GeometryPrimitive::LinesAdjacency => "lines_adjacency", GeometryPrimitive::Triangles => "triangles", GeometryPrimitive::TrianglesAdjacency => "triangles_adjacency", GeometryPrimitive::LineStrip => "line_strip", GeometryPrimitive::TriangleStrip => "triangle_strip" }
}

pub fn tess_spacing_name(s: &TessSpacing) -> &'static str {
    match s { TessSpacing::Equal => "equal_spacing", TessSpacing::FractionalEven => "fractional_even_spacing", TessSpacing::FractionalOdd => "fractional_odd_spacing" }
}

pub fn glsl_layout_tess_ctrl(patch_size: u32) -> String { format!("layout(vertices = {}) out;", patch_size) }
pub fn glsl_layout_tess_eval(primitive: &TessPrimitive, spacing: &TessSpacing, winding: &TessWinding) -> String {
    format!("layout({}, {}, {}) in;", match primitive { TessPrimitive::Triangles => "triangles", TessPrimitive::Quads => "quads", TessPrimitive::Isolines => "isolines" }, tess_spacing_name(spacing), match winding { TessWinding::Ccw => "ccw", TessWinding::Cw => "cw" })
}
pub fn glsl_layout_geometry(input: &GeometryPrimitive, output: &GeometryPrimitive, max_verts: u32) -> String {
    format!("layout({}) in;\nlayout({}, max_vertices = {}) out;", geometry_primitive_name(input), geometry_primitive_name(output), max_verts)
}

pub fn shader_complete_feature_list() -> Vec<String> {
    let mut features = shader_compiler_module_list().iter().map(|s| s.to_string()).collect::<Vec<_>>();
    features.extend(all_post_process_effect_names().iter().map(|s| s.to_string()));
    features.extend(all_glsl_keywords().iter().map(|s| s.to_string()));
    features
}
pub fn shader_feature_count() -> usize { shader_complete_feature_list().len() }


// ── Shader Compilation Summary ────────────────────────────────────────────────

#[derive(Clone, Debug, Default)]
pub struct ShaderSystemState {
    pub initialized: bool,
    pub programs_loaded: u32,
    pub materials_loaded: u32,
    pub textures_loaded: u32,
    pub compile_errors: u32,
    pub compile_warnings: u32,
    pub last_error: Option<String>,
    pub uptime_frames: u64,
    pub total_draw_calls: u64,
    pub total_triangles: u64,
}

impl ShaderSystemState {
    pub fn new() -> Self { Self { initialized: false, ..Default::default() } }
    pub fn initialize(&mut self) { self.initialized = true; }
    pub fn record_draw(&mut self, triangles: u64) { self.total_draw_calls += 1; self.total_triangles += triangles; }
    pub fn record_compile_error(&mut self, msg: impl Into<String>) { self.compile_errors += 1; self.last_error = Some(msg.into()); }
    pub fn record_compile_warning(&mut self) { self.compile_warnings += 1; }
    pub fn tick_frame(&mut self) { self.uptime_frames += 1; }
    pub fn is_healthy(&self) -> bool { self.initialized && self.compile_errors == 0 }
    pub fn avg_tris_per_call(&self) -> f64 { if self.total_draw_calls == 0 { 0.0 } else { self.total_triangles as f64 / self.total_draw_calls as f64 } }
    pub fn summary(&self) -> String {
        format!("ShaderSystem: init={}, programs={}, materials={}, textures={}, errors={}, warnings={}", self.initialized, self.programs_loaded, self.materials_loaded, self.textures_loaded, self.compile_errors, self.compile_warnings)
    }
}

// ── Built-in PBR Vertex Shader ────────────────────────────────────────────────

pub fn builtin_pbr_vertex_shader() -> &'static str {
    r#"#version 450
layout(location=0) in vec3 a_position;
layout(location=1) in vec3 a_normal;
layout(location=2) in vec2 a_uv;
layout(location=3) in vec4 a_tangent;
layout(std140, binding=0) uniform PerFrame { mat4 view; mat4 proj; mat4 view_proj; vec4 camera_pos; float time; float delta_time; float near_plane; float far_plane; };
layout(std140, binding=1) uniform PerObject { mat4 model; mat4 mvp; mat4 normal_matrix; };
layout(location=0) out vec3 v_world_pos;
layout(location=1) out vec3 v_normal;
layout(location=2) out vec2 v_uv;
layout(location=3) out vec3 v_tangent;
layout(location=4) out vec3 v_bitangent;
void main() {
    vec4 world_pos = model * vec4(a_position, 1.0);
    v_world_pos = world_pos.xyz;
    v_normal = normalize((normal_matrix * vec4(a_normal, 0.0)).xyz);
    v_tangent = normalize((normal_matrix * vec4(a_tangent.xyz, 0.0)).xyz);
    v_bitangent = cross(v_normal, v_tangent) * a_tangent.w;
    v_uv = a_uv;
    gl_Position = view_proj * world_pos;
}"#
}

pub fn builtin_pbr_fragment_shader() -> &'static str {
    r#"#version 450
layout(location=0) in vec3 v_world_pos;
layout(location=1) in vec3 v_normal;
layout(location=2) in vec2 v_uv;
layout(location=3) in vec3 v_tangent;
layout(location=4) in vec3 v_bitangent;
layout(std140, binding=2) uniform PerMaterial { vec4 albedo_color; vec4 emissive_color; float roughness; float metalness; float normal_scale; float occlusion_strength; float emissive_intensity; float opacity; };
layout(binding=0) uniform sampler2D u_albedo;
layout(binding=1) uniform sampler2D u_normal_map;
layout(binding=2) uniform sampler2D u_orm;
layout(location=0) out vec4 out_color;
const float PI = 3.14159265;
void main() {
    vec3 albedo = texture(u_albedo, v_uv).rgb * albedo_color.rgb;
    vec3 orm = texture(u_orm, v_uv).rgb;
    float ao = orm.r; float roughness_v = orm.g * roughness; float metalness_v = orm.b * metalness;
    vec3 N = normalize(v_normal);
    vec3 emit = emissive_color.rgb * emissive_intensity;
    out_color = vec4(albedo + emit, opacity);
}"#
}

pub fn builtin_unlit_vertex_shader() -> &'static str {
    r#"#version 450
layout(location=0) in vec3 a_position;
layout(location=2) in vec2 a_uv;
layout(std140, binding=1) uniform PerObject { mat4 mvp; mat4 model; mat4 normal_matrix; };
layout(location=0) out vec2 v_uv;
void main() { v_uv = a_uv; gl_Position = mvp * vec4(a_position, 1.0); }"#
}

pub fn builtin_unlit_fragment_shader() -> &'static str {
    r#"#version 450
layout(location=0) in vec2 v_uv;
layout(binding=0) uniform sampler2D u_texture;
layout(std140, binding=2) uniform PerMaterial { vec4 albedo_color; vec4 emissive_color; float roughness; float metalness; float normal_scale; float occlusion_strength; float emissive_intensity; float opacity; };
layout(location=0) out vec4 out_color;
void main() { out_color = texture(u_texture, v_uv) * albedo_color; }"#
}

pub const SHADER_SYSTEM_STATE_VERSION: u32 = 1;
pub const BUILTIN_PBR_SHADER_STAGES: usize = 2;
pub const BUILTIN_UNLIT_SHADER_STAGES: usize = 2;
pub const BUILTIN_SHADER_COUNT: usize = 4;

pub fn builtin_shader_names() -> &'static [&'static str] { &["pbr_vertex", "pbr_fragment", "unlit_vertex", "unlit_fragment"] }
pub fn get_builtin_shader(name: &str) -> Option<&'static str> {
    match name {
        "pbr_vertex" => Some(builtin_pbr_vertex_shader()),
        "pbr_fragment" => Some(builtin_pbr_fragment_shader()),
        "unlit_vertex" => Some(builtin_unlit_vertex_shader()),
        "unlit_fragment" => Some(builtin_unlit_fragment_shader()),
        _ => None,
    }
}
pub fn shader_editor_complete_build_info() -> String {
    format!("ShaderCompilerEditor Complete Build — {} builtin shaders, {} intrinsic docs, {} module total", BUILTIN_SHADER_COUNT, SHADER_GLSL_INTRINSIC_DOC_COUNT, shader_module_count())
}


// ── Shader Utility Functions ──────────────────────────────────────────────────

pub fn blend_factor_to_str(f: &BlendFactor) -> &'static str {
    match f {
        BlendFactor::Zero => "Zero",
        BlendFactor::One => "One",
        BlendFactor::SrcAlpha => "SrcAlpha",
        BlendFactor::OneMinusSrcAlpha => "OneMinusSrcAlpha",
        BlendFactor::DstAlpha => "DstAlpha",
        BlendFactor::OneMinusDstAlpha => "OneMinusDstAlpha",
        BlendFactor::SrcColor => "SrcColor",
        BlendFactor::OneMinusSrcColor => "OneMinusSrcColor",
        BlendFactor::ConstantAlpha => "ConstantAlpha",
    }
}

pub fn compare_func_to_str(f: &CompareFunc) -> &'static str {
    match f {
        CompareFunc::Never => "Never",
        CompareFunc::Less => "Less",
        CompareFunc::Equal => "Equal",
        CompareFunc::LessEqual => "LessEqual",
        CompareFunc::Greater => "Greater",
        CompareFunc::NotEqual => "NotEqual",
        CompareFunc::GreaterEqual => "GreaterEqual",
        CompareFunc::Always => "Always",
    }
}

pub fn cull_mode_to_str(m: &CullMode) -> &'static str {
    match m {
        CullMode::None => "None",
        CullMode::Front => "Front",
        CullMode::Back => "Back",
        CullMode::FrontAndBack => "FrontAndBack",
    }
}

pub fn polygon_mode_to_str(m: &PolygonMode) -> &'static str {
    match m { PolygonMode::Fill => "Fill", PolygonMode::Line => "Line", PolygonMode::Point => "Point" }
}

pub fn attachment_format_is_depth(f: &AttachmentFormat) -> bool {
    matches!(f, AttachmentFormat::Depth16 | AttachmentFormat::Depth24 | AttachmentFormat::Depth32F | AttachmentFormat::Depth24Stencil8)
}

pub fn attachment_format_channel_count(f: &AttachmentFormat) -> u32 {
    match f {
        AttachmentFormat::Rgba8 | AttachmentFormat::Rgba16F | AttachmentFormat::Rgba32F => 4,
        AttachmentFormat::Rg8 | AttachmentFormat::Rg16F => 2,
        AttachmentFormat::R8 | AttachmentFormat::R16F | AttachmentFormat::R32F => 1,
        AttachmentFormat::Depth16 | AttachmentFormat::Depth24 | AttachmentFormat::Depth32F => 1,
        AttachmentFormat::Depth24Stencil8 => 2,
    }
}

pub fn buffer_usage_to_str(u: &BufferUsage) -> &'static str {
    match u {
        BufferUsage::Vertex => "Vertex",
        BufferUsage::Index => "Index",
        BufferUsage::Uniform => "Uniform",
        BufferUsage::Storage => "Storage",
        BufferUsage::Indirect => "Indirect",
        BufferUsage::Staging => "Staging",
    }
}

pub fn sampler_type_to_str(t: &SamplerType) -> &'static str {
    match t {
        SamplerType::Linear => "Linear",
        SamplerType::Nearest => "Nearest",
        SamplerType::LinearMipmap => "LinearMipmap",
        SamplerType::Trilinear => "Trilinear",
        SamplerType::Anisotropic => "Anisotropic",
    }
}

pub fn render_pass_type_to_str(t: &RenderPassType) -> &'static str {
    match t {
        RenderPassType::Opaque => "Opaque",
        RenderPassType::Transparent => "Transparent",
        RenderPassType::Shadow => "Shadow",
        RenderPassType::PostProcess => "PostProcess",
        RenderPassType::Ui => "UI",
        RenderPassType::Compute => "Compute",
        RenderPassType::Custom => "Custom",
    }
}

pub fn post_effect_type_to_str(t: &PostEffectType) -> &'static str {
    match t {
        PostEffectType::Bloom => "Bloom",
        PostEffectType::Tonemap => "Tonemap",
        PostEffectType::Vignette => "Vignette",
        PostEffectType::ChromaticAberration => "ChromaticAberration",
        PostEffectType::DepthOfField => "DepthOfField",
        PostEffectType::MotionBlur => "MotionBlur",
        PostEffectType::Ssao => "SSAO",
        PostEffectType::Fxaa => "FXAA",
        PostEffectType::Custom => "Custom",
    }
}

pub fn tone_mapping_mode_to_str(m: &ToneMappingMode) -> &'static str {
    match m {
        ToneMappingMode::None => "None",
        ToneMappingMode::Reinhard => "Reinhard",
        ToneMappingMode::Aces => "ACES",
        ToneMappingMode::Filmic => "Filmic",
        ToneMappingMode::Uncharted2 => "Uncharted2",
        ToneMappingMode::Custom => "Custom",
    }
}

pub fn lighting_model_type_to_str(t: &LightingModelType) -> &'static str {
    match t {
        LightingModelType::Pbr => "PBR",
        LightingModelType::Phong => "Phong",
        LightingModelType::BlinnPhong => "BlinnPhong",
        LightingModelType::Lambert => "Lambert",
        LightingModelType::Toon => "Toon",
        LightingModelType::Unlit => "Unlit",
        LightingModelType::Custom(_) => "Custom",
    }
}

pub fn descriptor_type_to_str(t: &DescriptorType) -> &'static str {
    match t {
        DescriptorType::UniformBuffer => "UniformBuffer",
        DescriptorType::StorageBuffer => "StorageBuffer",
        DescriptorType::Sampler => "Sampler",
        DescriptorType::SampledImage => "SampledImage",
        DescriptorType::StorageImage => "StorageImage",
        DescriptorType::CombinedImageSampler => "CombinedImageSampler",
        DescriptorType::InputAttachment => "InputAttachment",
    }
}

pub fn render_graph_node_type_to_str(t: &RenderGraphNodeType) -> &'static str {
    match t {
        RenderGraphNodeType::Pass => "Pass",
        RenderGraphNodeType::Blit => "Blit",
        RenderGraphNodeType::Compute => "Compute",
        RenderGraphNodeType::Present => "Present",
        RenderGraphNodeType::Upload => "Upload",
        RenderGraphNodeType::Barrier => "Barrier",
        RenderGraphNodeType::Custom(_) => "Custom",
    }
}

pub fn bloom_mode_to_str(m: &BloomMode) -> &'static str {
    match m {
        BloomMode::Classic => "Classic",
        BloomMode::Kawase => "Kawase",
        BloomMode::Dual => "Dual",
        BloomMode::Convolution => "Convolution",
    }
}

pub fn ssao_quality_to_str(q: &SsaoQuality) -> &'static str {
    match q {
        SsaoQuality::Low => "Low",
        SsaoQuality::Medium => "Medium",
        SsaoQuality::High => "High",
        SsaoQuality::Ultra => "Ultra",
    }
}

pub fn anti_aliasing_mode_to_str(m: &AntiAliasingMode) -> &'static str {
    match m {
        AntiAliasingMode::None => "None",
        AntiAliasingMode::Msaa => "MSAA",
        AntiAliasingMode::Fxaa => "FXAA",
        AntiAliasingMode::Taa => "TAA",
        AntiAliasingMode::Smaa => "SMAA",
        AntiAliasingMode::Dlss => "DLSS",
    }
}

pub fn optimization_level_to_str(o: &OptimizationLevel) -> &'static str {
    match o {
        OptimizationLevel::None => "None",
        OptimizationLevel::Low => "Low",
        OptimizationLevel::Medium => "Medium",
        OptimizationLevel::High => "High",
        OptimizationLevel::Aggressive => "Aggressive",
    }
}

pub fn code_gen_target_to_str(t: &CodeGenTarget) -> &'static str {
    match t {
        CodeGenTarget::Glsl450 => "GLSL 4.50",
        CodeGenTarget::Glsl300Es => "GLSL 3.00 ES",
        CodeGenTarget::Wgsl => "WGSL",
        CodeGenTarget::Hlsl50 => "HLSL 5.0",
        CodeGenTarget::Msl20 => "Metal SL 2.0",
    }
}

pub fn shader_export_format_to_str(f: &ShaderExportFormat) -> &'static str {
    match f {
        ShaderExportFormat::Glsl => "GLSL",
        ShaderExportFormat::SpirV => "SPIR-V",
        ShaderExportFormat::Wgsl => "WGSL",
        ShaderExportFormat::Json => "JSON",
        ShaderExportFormat::Binary => "Binary",
    }
}

pub fn stencil_op_to_str(op: &StencilOp) -> &'static str {
    match op {
        StencilOp::Keep => "Keep", StencilOp::Zero => "Zero", StencilOp::Replace => "Replace",
        StencilOp::IncrClamp => "IncrClamp", StencilOp::DecrClamp => "DecrClamp",
        StencilOp::Invert => "Invert", StencilOp::IncrWrap => "IncrWrap", StencilOp::DecrWrap => "DecrWrap",
    }
}

pub fn tess_primitive_to_str(p: &TessPrimitive) -> &'static str {
    match p { TessPrimitive::Triangles => "triangles", TessPrimitive::Quads => "quads", TessPrimitive::Isolines => "isolines" }
}

pub fn tess_winding_to_str(w: &TessWinding) -> &'static str {
    match w { TessWinding::Ccw => "ccw", TessWinding::Cw => "cw" }
}

// ── Shader System Credits & Versioning ───────────────────────────────────────

pub const SHADER_COMPILER_FULL_VERSION: &str = "ShaderCompilerEditor v2.0.0-proof-engine";
pub const SHADER_COMPILER_BUILD_DATE: &str = "2026-03-29";
pub const SHADER_COMPILER_AUTHOR: &str = "proof-engine rendering team";
pub const SHADER_MAX_MATERIALS_PER_PASS: usize = 256;
pub const SHADER_MAX_LIGHTS: usize = 512;
pub const SHADER_MAX_SHADOW_CASCADES: usize = 4;
pub const SHADER_MAX_REFLECTION_PROBES: usize = 64;
pub const SHADER_COMPUTE_MAX_WORKGROUP_SIZE: u32 = 1024;
pub const SHADER_MAX_PUSH_CONSTANT_BYTES: u32 = 128;
pub const SHADER_MAX_DESCRIPTOR_SETS: u32 = 4;
pub const SHADER_MAX_BINDINGS_PER_SET: u32 = 16;

pub fn shader_compiler_credits() -> &'static str {
    "ShaderCompilerEditor — Built for proof-engine. Supports GLSL, HLSL, WGSL, SPIR-V, and Metal SL."
}

pub fn shader_pipeline_summary(manager: &ShaderManager) -> String {
    format!(
        "Programs: {} | Errors: {} | Quality: {} | Frames: {}",
        manager.program_count(),
        manager.error_count(),
        manager.quality_preset,
        manager.frame_executor.frame_number(),
    )
}