rdpe 0.1.0

Reaction Diffusion Particle Engine - GPU particle simulations made easy
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
//! Visual configuration for particle rendering.
//!
//! This module provides rendering options that control how particles appear,
//! separate from the behavioral rules that control how they move.
//!
//! # Usage
//!
//! ```ignore
//! Simulation::<MyParticle>::new()
//!     .with_visuals(|v| {
//!         v.blend_mode(BlendMode::Additive);
//!         v.shape(ParticleShape::Circle);
//!         v.palette(Palette::Viridis, ColorMapping::Speed);
//!     })
//!     .with_rule(Rule::Gravity(9.8))
//!     .run();
//! ```

use glam::Vec3;

/// Pre-defined color palettes for particle rendering.
///
/// These palettes are sampled based on a [`ColorMapping`] to automatically
/// color particles without needing to set colors manually.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Palette {
    /// No palette - use particle's own color (default).
    #[default]
    None,

    /// Viridis - perceptually uniform, colorblind-friendly (purple to yellow).
    Viridis,

    /// Magma - perceptually uniform (black to yellow through red).
    Magma,

    /// Plasma - perceptually uniform (purple to yellow through pink).
    Plasma,

    /// Inferno - perceptually uniform (black to yellow through red/orange).
    Inferno,

    /// Rainbow - classic rainbow gradient (red through violet).
    Rainbow,

    /// Sunset - warm oranges and pinks.
    Sunset,

    /// Ocean - cool blues and teals.
    Ocean,

    /// Fire - black through red, orange, yellow, white.
    Fire,

    /// Ice - white through light blue to deep blue.
    Ice,

    /// Neon - vibrant cyberpunk colors (pink, cyan, purple).
    Neon,

    /// Forest - natural greens and browns.
    Forest,

    /// Grayscale - black to white.
    Grayscale,

    /// Custom palette with user-defined color stops.
    Custom([Vec3; 5]),
}

impl Palette {
    /// Get the color stops for this palette (5 colors).
    pub fn colors(&self) -> [Vec3; 5] {
        match self {
            Palette::None => [
                Vec3::new(1.0, 1.0, 1.0),
                Vec3::new(1.0, 1.0, 1.0),
                Vec3::new(1.0, 1.0, 1.0),
                Vec3::new(1.0, 1.0, 1.0),
                Vec3::new(1.0, 1.0, 1.0),
            ],
            Palette::Viridis => [
                Vec3::new(0.267, 0.004, 0.329), // Dark purple
                Vec3::new(0.282, 0.140, 0.458), // Purple
                Vec3::new(0.127, 0.566, 0.551), // Teal
                Vec3::new(0.369, 0.789, 0.383), // Green
                Vec3::new(0.993, 0.906, 0.144), // Yellow
            ],
            Palette::Magma => [
                Vec3::new(0.001, 0.0, 0.014),   // Black
                Vec3::new(0.329, 0.071, 0.435), // Purple
                Vec3::new(0.716, 0.215, 0.475), // Pink
                Vec3::new(0.994, 0.541, 0.380), // Orange
                Vec3::new(0.987, 0.991, 0.749), // Light yellow
            ],
            Palette::Plasma => [
                Vec3::new(0.050, 0.030, 0.528), // Dark blue
                Vec3::new(0.494, 0.012, 0.658), // Purple
                Vec3::new(0.798, 0.280, 0.470), // Pink
                Vec3::new(0.973, 0.580, 0.254), // Orange
                Vec3::new(0.940, 0.975, 0.131), // Yellow
            ],
            Palette::Inferno => [
                Vec3::new(0.001, 0.0, 0.014),   // Black
                Vec3::new(0.341, 0.063, 0.429), // Purple
                Vec3::new(0.735, 0.216, 0.330), // Red
                Vec3::new(0.988, 0.645, 0.198), // Orange
                Vec3::new(0.988, 1.0, 0.644),   // Light yellow
            ],
            Palette::Rainbow => [
                Vec3::new(1.0, 0.0, 0.0),   // Red
                Vec3::new(1.0, 1.0, 0.0),   // Yellow
                Vec3::new(0.0, 1.0, 0.0),   // Green
                Vec3::new(0.0, 1.0, 1.0),   // Cyan
                Vec3::new(0.5, 0.0, 1.0),   // Purple
            ],
            Palette::Sunset => [
                Vec3::new(0.1, 0.0, 0.2),   // Dark purple
                Vec3::new(0.5, 0.0, 0.5),   // Purple
                Vec3::new(1.0, 0.2, 0.4),   // Pink
                Vec3::new(1.0, 0.5, 0.2),   // Orange
                Vec3::new(1.0, 0.9, 0.4),   // Yellow
            ],
            Palette::Ocean => [
                Vec3::new(0.0, 0.05, 0.15), // Deep blue
                Vec3::new(0.0, 0.2, 0.4),   // Dark blue
                Vec3::new(0.0, 0.4, 0.6),   // Blue
                Vec3::new(0.2, 0.6, 0.8),   // Light blue
                Vec3::new(0.6, 0.9, 1.0),   // Cyan
            ],
            Palette::Fire => [
                Vec3::new(0.1, 0.0, 0.0),   // Dark red
                Vec3::new(0.5, 0.0, 0.0),   // Red
                Vec3::new(1.0, 0.3, 0.0),   // Orange
                Vec3::new(1.0, 0.7, 0.0),   // Yellow-orange
                Vec3::new(1.0, 1.0, 0.8),   // White-yellow
            ],
            Palette::Ice => [
                Vec3::new(1.0, 1.0, 1.0),   // White
                Vec3::new(0.8, 0.9, 1.0),   // Light blue
                Vec3::new(0.4, 0.7, 1.0),   // Blue
                Vec3::new(0.1, 0.4, 0.8),   // Medium blue
                Vec3::new(0.0, 0.1, 0.4),   // Dark blue
            ],
            Palette::Neon => [
                Vec3::new(1.0, 0.0, 0.5),   // Pink
                Vec3::new(0.5, 0.0, 1.0),   // Purple
                Vec3::new(0.0, 0.5, 1.0),   // Blue
                Vec3::new(0.0, 1.0, 1.0),   // Cyan
                Vec3::new(0.5, 1.0, 0.5),   // Green
            ],
            Palette::Forest => [
                Vec3::new(0.1, 0.05, 0.0),  // Dark brown
                Vec3::new(0.3, 0.15, 0.05), // Brown
                Vec3::new(0.2, 0.4, 0.1),   // Dark green
                Vec3::new(0.3, 0.6, 0.2),   // Green
                Vec3::new(0.5, 0.8, 0.3),   // Light green
            ],
            Palette::Grayscale => [
                Vec3::new(0.0, 0.0, 0.0),   // Black
                Vec3::new(0.25, 0.25, 0.25),
                Vec3::new(0.5, 0.5, 0.5),
                Vec3::new(0.75, 0.75, 0.75),
                Vec3::new(1.0, 1.0, 1.0),   // White
            ],
            Palette::Custom(colors) => *colors,
        }
    }
}

/// How to map particle properties to palette colors.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum ColorMapping {
    /// Use the particle's own color field (default).
    #[default]
    None,

    /// Map particle index to color (creates bands/stripes).
    Index,

    /// Map particle speed to color (slow = start, fast = end).
    Speed {
        /// Minimum speed (maps to palette start).
        min: f32,
        /// Maximum speed (maps to palette end).
        max: f32,
    },

    /// Map particle age to color (young = start, old = end).
    Age {
        /// Maximum age for full palette range.
        max_age: f32,
    },

    /// Map Y position to color (bottom = start, top = end).
    PositionY {
        /// Minimum Y (maps to palette start).
        min: f32,
        /// Maximum Y (maps to palette end).
        max: f32,
    },

    /// Map distance from origin to color.
    Distance {
        /// Maximum distance for full palette range.
        max_dist: f32,
    },

    /// Random color per particle (uses particle index as seed).
    Random,
}

/// Blend mode for particle rendering.
///
/// Controls how particle colors combine with the background and each other.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BlendMode {
    /// Standard alpha blending (default).
    ///
    /// Particles blend based on their alpha value. Good for solid,
    /// opaque-looking particles.
    #[default]
    Alpha,

    /// Additive blending.
    ///
    /// Particle colors are added together, creating a glowing effect.
    /// Overlapping particles become brighter. Perfect for fire, magic,
    /// energy effects, and anything that should "glow".
    Additive,

    /// Multiplicative blending.
    ///
    /// Colors are multiplied, darkening the result. Useful for shadows,
    /// smoke, or atmospheric effects.
    Multiply,

    /// Screen blending.
    ///
    /// Inverts, multiplies, then inverts again: `1 - (1-src)*(1-dst)`.
    /// Brightens the image without burning out to white as quickly as additive.
    /// Great for light effects, glows, and lens flares.
    Screen,

    /// Overlay blending.
    ///
    /// Combines multiply and screen: multiplies dark areas, screens light areas.
    /// Increases contrast while preserving highlights and shadows.
    /// Useful for dramatic lighting effects.
    Overlay,

    /// Soft light blending.
    ///
    /// Gentler version of overlay. Darkens or lightens depending on source color.
    /// Creates subtle, natural-looking lighting adjustments.
    SoftLight,

    /// Subtractive blending.
    ///
    /// Subtracts source from destination: `dst - src`.
    /// Creates cutting/masking effects, useful for negative space
    /// and creating holes in existing colors.
    Subtractive,
}

/// Particle shape for rendering.
///
/// Controls the visual shape of each particle. All shapes use the UV coordinate
/// system where (-1, -1) is bottom-left and (1, 1) is top-right of the particle quad.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ParticleShape {
    /// Soft circle with smooth falloff (default).
    #[default]
    Circle,

    /// Hard-edged circle with no falloff.
    CircleHard,

    /// Square/rectangle shape.
    Square,

    /// Ring/donut shape.
    Ring,

    /// 5-pointed star.
    Star,

    /// Equilateral triangle pointing up.
    Triangle,

    /// Regular hexagon.
    Hexagon,

    /// Diamond/rhombus shape.
    Diamond,

    /// Single pixel point (fastest, no shape calculation).
    Point,
}

impl ParticleShape {
    /// Generate the WGSL fragment shader body for this shape.
    ///
    /// The shader receives `in.uv` as vec2 in range [-1, 1] and `in.color` as vec3.
    /// It should return a vec4 color with alpha.
    pub fn to_wgsl_fragment(&self) -> &'static str {
        match self {
            ParticleShape::Circle => r#"    let dist = length(in.uv);
    if dist > 1.0 {
        discard;
    }
    let alpha = 1.0 - smoothstep(0.5, 1.0, dist);
    return vec4<f32>(in.color, alpha);"#,

            ParticleShape::CircleHard => r#"    let dist = length(in.uv);
    if dist > 1.0 {
        discard;
    }
    return vec4<f32>(in.color, 1.0);"#,

            ParticleShape::Square => r#"    return vec4<f32>(in.color, 1.0);"#,

            ParticleShape::Ring => r#"    let dist = length(in.uv);
    if dist > 1.0 || dist < 0.6 {
        discard;
    }
    let alpha = 1.0 - smoothstep(0.85, 1.0, dist);
    return vec4<f32>(in.color, alpha);"#,

            ParticleShape::Star => r#"    // 5-pointed star using polar coordinates
    let angle = atan2(in.uv.y, in.uv.x);
    let dist = length(in.uv);

    // Star shape: varies radius based on angle (5 points)
    let points = 5.0;
    let star_angle = angle + 3.14159 / 2.0; // Rotate so point faces up
    let star_factor = cos(star_angle * points) * 0.4 + 0.6;

    if dist > star_factor {
        discard;
    }
    return vec4<f32>(in.color, 1.0);"#,

            ParticleShape::Triangle => r#"    // Equilateral triangle pointing up
    let p = in.uv;

    // Triangle: use simple half-plane tests
    // Top vertex at (0, 0.8), bottom edge at y = -0.6
    // Left edge: from (-0.8, -0.6) to (0, 0.8)
    // Right edge: from (0.8, -0.6) to (0, 0.8)

    // Bottom edge
    if p.y < -0.6 {
        discard;
    }

    // Left edge: points right of line from (-0.8, -0.6) to (0, 0.8)
    // Line equation: 1.4x - 0.8y + 0.64 > 0 for inside
    let left = 1.4 * p.x - 0.8 * p.y + 0.64;
    if left < 0.0 {
        discard;
    }

    // Right edge: points left of line from (0.8, -0.6) to (0, 0.8)
    // Line equation: -1.4x - 0.8y + 0.64 > 0 for inside
    let right = -1.4 * p.x - 0.8 * p.y + 0.64;
    if right < 0.0 {
        discard;
    }

    return vec4<f32>(in.color, 1.0);"#,

            ParticleShape::Hexagon => r#"    // Regular hexagon using max of 3 axes
    let p = abs(in.uv);

    // Hexagon distance: check against 3 edge normals
    // Pointy-top hexagon
    let hex_dist = max(p.x * 0.866025 + p.y * 0.5, p.y);

    if hex_dist > 0.9 {
        discard;
    }
    return vec4<f32>(in.color, 1.0);"#,

            ParticleShape::Diamond => r#"    // Diamond/rhombus: Manhattan distance
    let dist = abs(in.uv.x) + abs(in.uv.y);
    if dist > 1.0 {
        discard;
    }
    return vec4<f32>(in.color, 1.0);"#,

            ParticleShape::Point => r#"    // Single pixel - no shape calculation needed
    return vec4<f32>(in.color, 1.0);"#,
        }
    }
}

/// Configuration for particle visuals.
///
/// Built using the closure passed to [`crate::Simulation::with_visuals`].
#[derive(Debug, Clone)]
pub struct VisualConfig {
    /// Blend mode for particle rendering.
    pub blend_mode: BlendMode,
    /// Particle shape.
    pub shape: ParticleShape,
    /// Trail length (0 = no trails).
    pub trail_length: u32,
    /// Whether to draw connections between nearby particles.
    pub connections_enabled: bool,
    /// Radius for particle connections.
    pub connections_radius: f32,
    /// Color for particle connections (RGB, 0.0-1.0).
    pub connections_color: Vec3,
    /// Whether to stretch particles in velocity direction.
    pub velocity_stretch: bool,
    /// Maximum stretch factor for velocity stretching.
    pub velocity_stretch_factor: f32,
    /// Color palette for automatic coloring.
    pub palette: Palette,
    /// How to map particle properties to palette colors.
    pub color_mapping: ColorMapping,
    /// Background clear color (RGB, 0.0-1.0).
    pub background_color: Vec3,
    /// Custom post-processing shader code (fragment shader body).
    pub post_process_shader: Option<String>,
    /// Spatial grid visualization opacity (0.0 = off, 1.0 = full).
    pub spatial_grid_opacity: f32,
    /// Wireframe mesh for 3D particle shapes (None = use billboard shapes).
    pub wireframe_mesh: Option<WireframeMesh>,
    /// Line thickness for wireframe rendering (in clip space, ~0.001-0.01).
    pub wireframe_thickness: f32,
}

impl Default for VisualConfig {
    fn default() -> Self {
        Self {
            blend_mode: BlendMode::Alpha,
            shape: ParticleShape::Circle,
            trail_length: 0,
            connections_enabled: false,
            connections_radius: 0.1,
            connections_color: Vec3::new(0.5, 0.7, 1.0),
            velocity_stretch: false,
            velocity_stretch_factor: 2.0,
            palette: Palette::None,
            color_mapping: ColorMapping::None,
            background_color: Vec3::new(0.02, 0.02, 0.05), // Dark blue-black
            post_process_shader: None,
            spatial_grid_opacity: 0.0, // Off by default
            wireframe_mesh: None,
            wireframe_thickness: 0.003, // Default line thickness
        }
    }
}

impl VisualConfig {
    /// Create a new visual config with defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the blend mode.
    ///
    /// # Example
    ///
    /// ```ignore
    /// .with_visuals(|v| {
    ///     v.blend_mode(BlendMode::Additive); // Glowy particles
    /// })
    /// ```
    pub fn blend_mode(&mut self, mode: BlendMode) -> &mut Self {
        self.blend_mode = mode;
        self
    }

    /// Set the particle shape.
    ///
    /// # Example
    ///
    /// ```ignore
    /// .with_visuals(|v| {
    ///     v.shape(ParticleShape::Star);
    /// })
    /// ```
    pub fn shape(&mut self, shape: ParticleShape) -> &mut Self {
        self.shape = shape;
        self
    }

    /// Enable particle trails.
    ///
    /// Trails render a fading history of particle positions.
    ///
    /// # Arguments
    ///
    /// * `length` - Number of previous positions to render (0 = disabled)
    ///
    /// # Example
    ///
    /// ```ignore
    /// .with_visuals(|v| {
    ///     v.trails(10); // 10-frame trails
    /// })
    /// ```
    pub fn trails(&mut self, length: u32) -> &mut Self {
        self.trail_length = length;
        self
    }

    /// Enable connections between nearby particles.
    ///
    /// Draws lines between particles within the specified radius.
    /// Creates web-like or network visualizations.
    ///
    /// # Arguments
    ///
    /// * `radius` - Maximum distance for connections
    ///
    /// # Example
    ///
    /// ```ignore
    /// .with_visuals(|v| {
    ///     v.connections(0.15); // Connect particles within 0.15 units
    /// })
    /// ```
    pub fn connections(&mut self, radius: f32) -> &mut Self {
        self.connections_enabled = true;
        self.connections_radius = radius;
        self
    }

    /// Set the color for particle connections.
    ///
    /// # Arguments
    ///
    /// * `color` - RGB color (0.0-1.0)
    ///
    /// # Example
    ///
    /// ```ignore
    /// .with_visuals(|v| {
    ///     v.connections(0.15)
    ///      .connections_color(Vec3::new(1.0, 0.5, 0.0)); // Orange connections
    /// })
    /// ```
    pub fn connections_color(&mut self, color: Vec3) -> &mut Self {
        self.connections_color = color;
        self
    }

    /// Enable velocity-based stretching.
    ///
    /// Particles stretch in their direction of motion, creating
    /// a speed-blur effect.
    ///
    /// # Arguments
    ///
    /// * `max_factor` - Maximum stretch multiplier (e.g., 3.0 = 3x longer)
    ///
    /// # Example
    ///
    /// ```ignore
    /// .with_visuals(|v| {
    ///     v.velocity_stretch(3.0); // Stretch up to 3x in motion direction
    /// })
    /// ```
    pub fn velocity_stretch(&mut self, max_factor: f32) -> &mut Self {
        self.velocity_stretch = true;
        self.velocity_stretch_factor = max_factor;
        self
    }

    /// Set a color palette with automatic mapping.
    ///
    /// Overrides particle colors with palette colors based on the mapping.
    ///
    /// # Arguments
    ///
    /// * `palette` - The color palette to use
    /// * `mapping` - How to map particle properties to colors
    ///
    /// # Example
    ///
    /// ```ignore
    /// .with_visuals(|v| {
    ///     // Color by speed using the fire palette
    ///     v.palette(Palette::Fire, ColorMapping::Speed { min: 0.0, max: 2.0 });
    /// })
    /// ```
    pub fn palette(&mut self, palette: Palette, mapping: ColorMapping) -> &mut Self {
        self.palette = palette;
        self.color_mapping = mapping;
        self
    }

    /// Set the background clear color.
    ///
    /// # Arguments
    ///
    /// * `color` - RGB color values (0.0-1.0 range)
    ///
    /// # Example
    ///
    /// ```ignore
    /// .with_visuals(|v| {
    ///     v.background(Vec3::new(0.0, 0.0, 0.0)); // Pure black
    ///     v.background(Vec3::new(0.1, 0.0, 0.15)); // Dark purple
    /// })
    /// ```
    pub fn background(&mut self, color: Vec3) -> &mut Self {
        self.background_color = color;
        self
    }

    /// Show the spatial hash grid as a wireframe overlay.
    ///
    /// Useful for debugging spatial configuration and understanding
    /// how the neighbor query system works.
    ///
    /// # Arguments
    ///
    /// * `opacity` - Grid line opacity (0.0 = off, 1.0 = fully visible)
    ///
    /// # Example
    ///
    /// ```ignore
    /// .with_visuals(|v| {
    ///     v.spatial_grid(0.3); // Subtle grid overlay
    /// })
    /// ```
    pub fn spatial_grid(&mut self, opacity: f32) -> &mut Self {
        self.spatial_grid_opacity = opacity.clamp(0.0, 1.0);
        self
    }

    /// Set a custom post-processing shader.
    ///
    /// The shader code runs as a fullscreen pass after particles are rendered.
    /// Your code has access to:
    ///
    /// - `in.uv` - Screen UV coordinates (0.0 to 1.0)
    /// - `scene` - Texture sampler for the rendered particle scene
    /// - `uniforms.time` - Current simulation time
    /// - `uniforms.resolution` - Screen resolution (vec2)
    ///
    /// Use `textureSample(scene, scene_sampler, uv)` to sample the scene.
    /// Must return `vec4<f32>` (RGBA color output).
    ///
    /// # Example
    ///
    /// ```ignore
    /// .with_visuals(|v| {
    ///     // Vignette effect
    ///     v.post_process(r#"
    ///         let color = textureSample(scene, scene_sampler, in.uv);
    ///         let dist = length(in.uv - vec2(0.5));
    ///         let vignette = 1.0 - smoothstep(0.3, 0.7, dist);
    ///         return vec4(color.rgb * vignette, 1.0);
    ///     "#);
    /// })
    /// ```
    ///
    /// # Effects you can create
    ///
    /// - **Vignette**: Darken edges based on distance from center
    /// - **Color grading**: Adjust colors, contrast, saturation
    /// - **Chromatic aberration**: Offset RGB channels
    /// - **CRT/scanlines**: Add retro display effects
    /// - **Blur**: Sample nearby pixels (limited without multiple passes)
    pub fn post_process(&mut self, wgsl_code: &str) -> &mut Self {
        self.post_process_shader = Some(wgsl_code.to_string());
        self
    }

    /// Set a wireframe mesh for 3D particle shapes.
    ///
    /// Instead of rendering particles as billboards (flat shapes facing the camera),
    /// this renders each particle as a 3D wireframe mesh. The mesh is scaled by
    /// the particle's scale and colored by its color.
    ///
    /// # Example
    ///
    /// ```ignore
    /// .with_visuals(|v| {
    ///     v.wireframe(WireframeMesh::cube(), 0.002); // Cube with 0.002 line thickness
    /// })
    /// ```
    pub fn wireframe(&mut self, mesh: WireframeMesh, line_thickness: f32) -> &mut Self {
        self.wireframe_mesh = Some(mesh);
        self.wireframe_thickness = line_thickness;
        self
    }

    /// Compare this config with another to determine what kind of rebuild is needed.
    ///
    /// Returns a `ConfigDiff` describing which changes can be hot-swapped and
    /// which require pipeline rebuilds.
    pub fn diff(&self, other: &VisualConfig) -> ConfigDiff {
        let mut hot_swappable = Vec::new();

        // Check hot-swappable changes
        if self.background_color != other.background_color {
            hot_swappable.push(HotSwapChange::BackgroundColor(other.background_color));
        }
        if self.spatial_grid_opacity != other.spatial_grid_opacity {
            hot_swappable.push(HotSwapChange::GridOpacity(other.spatial_grid_opacity));
        }

        // Check if render pipeline rebuild is needed
        let needs_render_rebuild = self.blend_mode != other.blend_mode
            || self.shape != other.shape
            || self.palette != other.palette
            || self.color_mapping != other.color_mapping
            || self.trail_length != other.trail_length
            || self.connections_enabled != other.connections_enabled
            || self.connections_radius != other.connections_radius
            || self.velocity_stretch != other.velocity_stretch
            || self.velocity_stretch_factor != other.velocity_stretch_factor
            || self.wireframe_mesh != other.wireframe_mesh
            || self.wireframe_thickness != other.wireframe_thickness
            || self.post_process_shader != other.post_process_shader;

        ConfigDiff {
            needs_render_rebuild,
            hot_swappable,
        }
    }
}

/// Result of comparing two `VisualConfig`s.
///
/// Describes what kind of updates are needed when changing visual settings.
#[derive(Debug, Clone)]
pub struct ConfigDiff {
    /// Whether the render pipeline needs to be rebuilt.
    ///
    /// This is required for changes to blend mode, shape, palette, trails, etc.
    pub needs_render_rebuild: bool,

    /// Changes that can be applied without rebuilding pipelines.
    pub hot_swappable: Vec<HotSwapChange>,
}

impl ConfigDiff {
    /// Returns true if no changes are needed.
    pub fn is_empty(&self) -> bool {
        !self.needs_render_rebuild && self.hot_swappable.is_empty()
    }

    /// Returns true if any changes require a rebuild.
    pub fn needs_rebuild(&self) -> bool {
        self.needs_render_rebuild
    }
}

/// A visual change that can be applied at runtime without rebuilding pipelines.
#[derive(Debug, Clone)]
pub enum HotSwapChange {
    /// Change the background clear color.
    BackgroundColor(Vec3),
    /// Change the spatial grid debug opacity.
    GridOpacity(f32),
}

/// A wireframe mesh for 3D particle rendering.
///
/// Instead of rendering particles as flat billboards, wireframe meshes render
/// each particle as a 3D shape made of line segments. This is purely visual -
/// it doesn't affect the physics simulation.
///
/// # Built-in Shapes
///
/// Use the constructor methods for common shapes:
///
/// ```ignore
/// WireframeMesh::tetrahedron() // 4 triangular faces
/// WireframeMesh::cube()        // Classic cube
/// WireframeMesh::octahedron()  // 8 triangular faces
/// WireframeMesh::diamond()     // Two pyramids joined at base
/// WireframeMesh::axes()        // XYZ axis indicator
/// ```
///
/// # Custom Shapes
///
/// Create custom wireframes from line segment pairs:
///
/// ```ignore
/// WireframeMesh::custom(vec![
///     (Vec3::ZERO, Vec3::X),           // Line from origin to +X
///     (Vec3::ZERO, Vec3::Y),           // Line from origin to +Y
///     (Vec3::X, Vec3::new(1.0, 1.0, 0.0)), // Diagonal
/// ])
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct WireframeMesh {
    /// Line segments as pairs of endpoints (start, end).
    pub lines: Vec<(Vec3, Vec3)>,
}

impl WireframeMesh {
    /// Create a custom wireframe from line segments.
    pub fn custom(lines: Vec<(Vec3, Vec3)>) -> Self {
        Self { lines }
    }

    /// Tetrahedron (4 triangular faces, 6 edges).
    pub fn tetrahedron() -> Self {
        let s = 0.5;
        // Vertices of a regular tetrahedron
        let v0 = Vec3::new(s, s, s);
        let v1 = Vec3::new(s, -s, -s);
        let v2 = Vec3::new(-s, s, -s);
        let v3 = Vec3::new(-s, -s, s);

        Self {
            lines: vec![
                (v0, v1),
                (v0, v2),
                (v0, v3),
                (v1, v2),
                (v1, v3),
                (v2, v3),
            ],
        }
    }

    /// Cube (6 faces, 12 edges).
    pub fn cube() -> Self {
        let s = 0.5;
        // 8 vertices of a cube
        let v000 = Vec3::new(-s, -s, -s);
        let v001 = Vec3::new(-s, -s, s);
        let v010 = Vec3::new(-s, s, -s);
        let v011 = Vec3::new(-s, s, s);
        let v100 = Vec3::new(s, -s, -s);
        let v101 = Vec3::new(s, -s, s);
        let v110 = Vec3::new(s, s, -s);
        let v111 = Vec3::new(s, s, s);

        Self {
            lines: vec![
                // Bottom face
                (v000, v100),
                (v100, v101),
                (v101, v001),
                (v001, v000),
                // Top face
                (v010, v110),
                (v110, v111),
                (v111, v011),
                (v011, v010),
                // Vertical edges
                (v000, v010),
                (v100, v110),
                (v101, v111),
                (v001, v011),
            ],
        }
    }

    /// Octahedron (8 triangular faces, 12 edges).
    pub fn octahedron() -> Self {
        let s = 0.5;
        // 6 vertices at axis extremes
        let px = Vec3::new(s, 0.0, 0.0);
        let nx = Vec3::new(-s, 0.0, 0.0);
        let py = Vec3::new(0.0, s, 0.0);
        let ny = Vec3::new(0.0, -s, 0.0);
        let pz = Vec3::new(0.0, 0.0, s);
        let nz = Vec3::new(0.0, 0.0, -s);

        Self {
            lines: vec![
                // Top pyramid
                (py, px),
                (py, nx),
                (py, pz),
                (py, nz),
                // Bottom pyramid
                (ny, px),
                (ny, nx),
                (ny, pz),
                (ny, nz),
                // Equator
                (px, pz),
                (pz, nx),
                (nx, nz),
                (nz, px),
            ],
        }
    }

    /// Diamond shape (two pyramids joined at base, 8 edges).
    pub fn diamond() -> Self {
        let s = 0.5;
        let h = 0.7; // Height of each pyramid half

        // 6 vertices: top, bottom, and 4 at equator
        let top = Vec3::new(0.0, h, 0.0);
        let bot = Vec3::new(0.0, -h, 0.0);
        let e0 = Vec3::new(s, 0.0, 0.0);
        let e1 = Vec3::new(0.0, 0.0, s);
        let e2 = Vec3::new(-s, 0.0, 0.0);
        let e3 = Vec3::new(0.0, 0.0, -s);

        Self {
            lines: vec![
                // Top to equator
                (top, e0),
                (top, e1),
                (top, e2),
                (top, e3),
                // Bottom to equator
                (bot, e0),
                (bot, e1),
                (bot, e2),
                (bot, e3),
            ],
        }
    }

    /// Icosahedron (20 triangular faces, 30 edges).
    pub fn icosahedron() -> Self {
        // Golden ratio
        let phi = (1.0 + 5.0_f32.sqrt()) / 2.0;
        let s = 0.3; // Scale down to fit

        // 12 vertices
        let vertices = [
            Vec3::new(-1.0, phi, 0.0) * s,
            Vec3::new(1.0, phi, 0.0) * s,
            Vec3::new(-1.0, -phi, 0.0) * s,
            Vec3::new(1.0, -phi, 0.0) * s,
            Vec3::new(0.0, -1.0, phi) * s,
            Vec3::new(0.0, 1.0, phi) * s,
            Vec3::new(0.0, -1.0, -phi) * s,
            Vec3::new(0.0, 1.0, -phi) * s,
            Vec3::new(phi, 0.0, -1.0) * s,
            Vec3::new(phi, 0.0, 1.0) * s,
            Vec3::new(-phi, 0.0, -1.0) * s,
            Vec3::new(-phi, 0.0, 1.0) * s,
        ];

        // 30 edges (each unique edge of the icosahedron)
        let edges = [
            (0, 1), (0, 5), (0, 7), (0, 10), (0, 11),
            (1, 5), (1, 7), (1, 8), (1, 9),
            (2, 3), (2, 4), (2, 6), (2, 10), (2, 11),
            (3, 4), (3, 6), (3, 8), (3, 9),
            (4, 5), (4, 9), (4, 11),
            (5, 9), (5, 11),
            (6, 7), (6, 8), (6, 10),
            (7, 8), (7, 10),
            (8, 9),
            (10, 11),
        ];

        Self {
            lines: edges.iter().map(|(i, j)| (vertices[*i], vertices[*j])).collect(),
        }
    }

    /// XYZ axes indicator.
    pub fn axes() -> Self {
        let s = 0.5;
        Self {
            lines: vec![
                (Vec3::ZERO, Vec3::new(s, 0.0, 0.0)),  // X axis
                (Vec3::ZERO, Vec3::new(0.0, s, 0.0)),  // Y axis
                (Vec3::ZERO, Vec3::new(0.0, 0.0, s)),  // Z axis
            ],
        }
    }

    /// Star shape (spiky, 6 points).
    pub fn star() -> Self {
        let inner = 0.2;
        let outer = 0.5;
        let points = 6;

        let mut lines = Vec::new();
        for i in 0..points {
            let angle = (i as f32 / points as f32) * std::f32::consts::TAU;
            let outer_point = Vec3::new(angle.cos() * outer, angle.sin() * outer, 0.0);

            // Connect to center
            lines.push((Vec3::ZERO, outer_point));

            // Connect to adjacent inner points
            let angle_prev = ((i as f32 - 0.5) / points as f32) * std::f32::consts::TAU;
            let angle_next = ((i as f32 + 0.5) / points as f32) * std::f32::consts::TAU;
            let inner_prev = Vec3::new(angle_prev.cos() * inner, angle_prev.sin() * inner, 0.0);
            let inner_next = Vec3::new(angle_next.cos() * inner, angle_next.sin() * inner, 0.0);

            lines.push((outer_point, inner_prev));
            lines.push((outer_point, inner_next));
        }

        Self { lines }
    }

    /// Spiral shape.
    pub fn spiral(turns: f32, segments: u32) -> Self {
        let mut lines = Vec::new();
        let height = 0.5;
        let radius = 0.3;

        for i in 0..segments {
            let t0 = i as f32 / segments as f32;
            let t1 = (i + 1) as f32 / segments as f32;

            let angle0 = t0 * turns * std::f32::consts::TAU;
            let angle1 = t1 * turns * std::f32::consts::TAU;

            let p0 = Vec3::new(
                angle0.cos() * radius,
                t0 * height - height / 2.0,
                angle0.sin() * radius,
            );
            let p1 = Vec3::new(
                angle1.cos() * radius,
                t1 * height - height / 2.0,
                angle1.sin() * radius,
            );

            lines.push((p0, p1));
        }

        Self { lines }
    }

    /// Get the total number of line segments.
    pub fn line_count(&self) -> u32 {
        self.lines.len() as u32
    }

    /// Get vertices as flat f32 array for GPU buffer.
    /// Each line is 6 floats: [x0, y0, z0, x1, y1, z1]
    pub fn to_vertices(&self) -> Vec<f32> {
        self.lines
            .iter()
            .flat_map(|(a, b)| [a.x, a.y, a.z, b.x, b.y, b.z])
            .collect()
    }
}

/// Vertex shader effects for particle rendering.
///
/// Pre-built, composable effects that modify particle vertex transformations.
/// Effects stack together and generate optimized WGSL code. Use these instead
/// of raw [`crate::Simulation::with_vertex_shader`] for common effects.
///
/// # Example
///
/// ```ignore
/// Simulation::<Ball>::new()
///     .with_vertex_effect(VertexEffect::Rotate { speed: 2.0 })
///     .with_vertex_effect(VertexEffect::Wobble {
///         frequency: 3.0,
///         amplitude: 0.05,
///     })
///     .with_vertex_effect(VertexEffect::Pulse {
///         frequency: 4.0,
///         amplitude: 0.3,
///     })
///     .run();
/// ```
///
/// Effects are applied in order and compose naturally.
#[derive(Debug, Clone)]
pub enum VertexEffect {
    /// Rotate particles around their facing axis.
    ///
    /// Each particle spins at the specified speed, with a per-particle
    /// phase offset based on instance index for variety.
    Rotate {
        /// Rotation speed in radians per second.
        speed: f32,
    },

    /// Wobble particles with sinusoidal position offset.
    ///
    /// Creates a gentle floating/swaying motion.
    Wobble {
        /// Oscillation frequency (higher = faster wobble).
        frequency: f32,
        /// Maximum offset distance.
        amplitude: f32,
    },

    /// Pulse particle size over time.
    ///
    /// Particles grow and shrink rhythmically.
    Pulse {
        /// Pulse frequency (higher = faster pulsing).
        frequency: f32,
        /// Pulse amplitude (0.3 = +/- 30% size variation).
        amplitude: f32,
    },

    /// Wave effect coordinated across particles.
    ///
    /// Creates a wave pattern that travels through the particle field.
    Wave {
        /// Wave direction (normalized).
        direction: Vec3,
        /// Wave frequency (spatial).
        frequency: f32,
        /// Wave speed (temporal).
        speed: f32,
        /// Wave amplitude (offset distance).
        amplitude: f32,
    },

    /// Random per-frame jitter/shake.
    ///
    /// Adds noise-like motion to particles.
    Jitter {
        /// Maximum jitter offset.
        amplitude: f32,
    },

    /// Stretch particles in their velocity direction.
    ///
    /// Requires velocity data passed to vertex shader.
    /// Note: This is a visual hint only - actual velocity stretching
    /// requires velocity in the vertex attributes.
    StretchToVelocity {
        /// Maximum stretch multiplier.
        max_stretch: f32,
    },

    /// Scale particles based on distance from a point.
    ///
    /// Particles closer to the point are larger.
    ScaleByDistance {
        /// Center point.
        center: Vec3,
        /// Scale at center (closest).
        min_scale: f32,
        /// Scale at max_distance (farthest).
        max_scale: f32,
        /// Distance at which max_scale is reached.
        max_distance: f32,
    },

    /// Fade particles based on distance from camera/origin.
    ///
    /// Modifies alpha based on distance for depth-based fading.
    FadeByDistance {
        /// Distance at which particles are fully visible.
        near: f32,
        /// Distance at which particles are fully transparent.
        far: f32,
    },

    /// Cylindrical billboarding - rotate only around one axis.
    ///
    /// Useful for grass, trees, flames - things that should stay upright
    /// but still face the camera horizontally.
    BillboardCylindrical {
        /// The axis to stay fixed (typically Y for upright sprites).
        axis: Vec3,
    },

    /// Fixed orientation - disable billboarding entirely.
    ///
    /// Particles maintain a fixed orientation in world space.
    /// Useful for debris, leaves, or when combined with Rotate for tumbling.
    BillboardFixed {
        /// Forward direction of the quad in world space.
        forward: Vec3,
        /// Up direction of the quad in world space.
        up: Vec3,
    },

    /// Orient particles to face a specific point.
    ///
    /// All particles rotate to look at the target point.
    FacePoint {
        /// The point all particles should face toward.
        target: Vec3,
    },

    /// Orbit particles around a center point.
    ///
    /// Creates circular motion around a specified axis.
    Orbit {
        /// Center point of the orbit.
        center: Vec3,
        /// Orbit speed in radians per second.
        speed: f32,
        /// Orbit radius.
        radius: f32,
        /// Axis of rotation (normalized).
        axis: Vec3,
    },

    /// Spiral particles outward or inward.
    ///
    /// Creates expanding or contracting spiral motion.
    Spiral {
        /// Center point of the spiral.
        center: Vec3,
        /// Rotation speed in radians per second.
        speed: f32,
        /// Expansion rate (positive = outward, negative = inward).
        expansion: f32,
        /// Vertical speed (for 3D spirals).
        vertical_speed: f32,
    },

    /// Sway particles like grass or trees.
    ///
    /// Creates a natural swaying motion anchored at the base.
    Sway {
        /// Sway frequency.
        frequency: f32,
        /// Maximum sway amplitude.
        amplitude: f32,
        /// Sway axis (typically horizontal).
        axis: Vec3,
    },

    /// Scale particles based on their speed.
    ///
    /// Faster particles appear larger or smaller.
    ScaleBySpeed {
        /// Scale at zero speed.
        min_scale: f32,
        /// Scale at max speed.
        max_scale: f32,
        /// Speed at which max_scale is reached.
        max_speed: f32,
    },

    /// Squash/flatten particles along an axis.
    ///
    /// Creates a flattened appearance, good for impact effects.
    Squash {
        /// Axis to squash along.
        axis: Vec3,
        /// Squash amount (0 = flat, 1 = normal).
        amount: f32,
    },

    /// Tumble particles with random 3D rotation.
    ///
    /// Creates chaotic spinning in all directions.
    Tumble {
        /// Rotation speed multiplier.
        speed: f32,
    },

    /// Attract particles toward a point.
    ///
    /// Pulls particles closer to the target.
    Attract {
        /// Attraction target point.
        target: Vec3,
        /// Attraction strength.
        strength: f32,
        /// Maximum displacement.
        max_displacement: f32,
    },

    /// Repel particles away from a point.
    ///
    /// Pushes particles away from the source.
    Repel {
        /// Repulsion source point.
        source: Vec3,
        /// Repulsion strength.
        strength: f32,
        /// Effect radius (no effect beyond this).
        radius: f32,
    },

    /// Turbulence/noise-based displacement.
    ///
    /// Creates organic, chaotic motion using noise.
    Turbulence {
        /// Noise frequency (higher = more detail).
        frequency: f32,
        /// Displacement amplitude.
        amplitude: f32,
        /// Animation speed.
        speed: f32,
    },

    /// Scale particles over their lifetime.
    ///
    /// Particles grow or shrink as they age (approximated).
    ScaleByAge {
        /// Scale at birth.
        start_scale: f32,
        /// Scale at end of life.
        end_scale: f32,
        /// Lifetime duration in seconds.
        lifetime: f32,
    },

    /// Fade particles over their lifetime.
    ///
    /// Particles become transparent as they age.
    FadeByAge {
        /// Alpha at birth.
        start_alpha: f32,
        /// Alpha at end of life.
        end_alpha: f32,
        /// Lifetime duration in seconds.
        lifetime: f32,
    },

    /// Vortex/tornado effect - orbit with vertical pull.
    ///
    /// Creates a whirlpool or tornado-like motion.
    Vortex {
        /// Center point of the vortex.
        center: Vec3,
        /// Rotation speed in radians per second.
        speed: f32,
        /// Vertical pull strength (positive = up, negative = down).
        pull: f32,
        /// Vortex radius influence.
        radius: f32,
    },

    /// Bounce particles with gravity-like motion.
    ///
    /// Creates a bouncing ball effect.
    Bounce {
        /// Bounce height.
        height: f32,
        /// Bounce frequency (bounces per second).
        frequency: f32,
        /// Energy loss per bounce (0 = no loss, 1 = full loss).
        damping: f32,
    },

    /// Figure-8 / Lissajous curve motion.
    ///
    /// Creates infinity loops and complex orbital patterns.
    Figure8 {
        /// Horizontal amplitude.
        width: f32,
        /// Vertical amplitude.
        height: f32,
        /// Animation speed.
        speed: f32,
        /// Frequency ratio (2 = figure-8, other values = Lissajous).
        ratio: f32,
    },

    /// Helix/corkscrew motion along an axis.
    ///
    /// Creates DNA-like spiraling motion.
    Helix {
        /// Axis of helix progression.
        axis: Vec3,
        /// Helix radius.
        radius: f32,
        /// Rotation speed.
        speed: f32,
        /// Forward movement speed along axis.
        progression: f32,
    },

    /// Flutter - rapid small oscillations.
    ///
    /// Creates leaf or butterfly-like trembling motion.
    Flutter {
        /// Flutter intensity.
        intensity: f32,
        /// Flutter speed (higher = more rapid).
        speed: f32,
    },

    /// Brownian motion - random walk.
    ///
    /// Creates organic wandering motion that evolves over time.
    Brownian {
        /// Movement intensity.
        intensity: f32,
        /// How fast the random direction changes.
        speed: f32,
    },
}

impl VertexEffect {
    /// Generate WGSL code that modifies transformation variables.
    ///
    /// Available variables to read/modify:
    /// - `pos_offset: vec3<f32>` - position offset (starts at 0)
    /// - `rotated_quad: vec2<f32>` - quad coordinates (starts at quad_pos)
    /// - `size_mult: f32` - size multiplier (starts at 1.0)
    /// - `color_mod: vec3<f32>` - color modifier (starts at particle_color)
    ///
    /// Also available (read-only):
    /// - `particle_pos`, `particle_size`, `scale`
    /// - `uniforms.time`, `instance_index`, `vertex_index`
    pub fn to_wgsl(&self) -> String {
        match self {
            VertexEffect::Rotate { speed } => format!(
                r#"
    // Rotate effect
    {{
        let rot_speed = {speed}f;
        let rot_angle = uniforms.time * rot_speed + f32(instance_index) * 0.1;
        let cos_a = cos(rot_angle);
        let sin_a = sin(rot_angle);
        let rx = rotated_quad.x;
        let ry = rotated_quad.y;
        rotated_quad = vec2<f32>(
            rx * cos_a - ry * sin_a,
            rx * sin_a + ry * cos_a
        );
    }}"#
            ),

            VertexEffect::Wobble { frequency, amplitude } => format!(
                r#"
    // Wobble effect
    {{
        let wobble_freq = {frequency}f;
        let wobble_amp = {amplitude}f;
        let phase = f32(instance_index) * 0.5;
        pos_offset += vec3<f32>(
            sin(uniforms.time * wobble_freq + phase) * wobble_amp,
            cos(uniforms.time * wobble_freq * 1.3 + phase * 0.7) * wobble_amp,
            sin(uniforms.time * wobble_freq * 0.7 + phase * 0.3) * wobble_amp
        );
    }}"#
            ),

            VertexEffect::Pulse { frequency, amplitude } => format!(
                r#"
    // Pulse effect
    {{
        let pulse_freq = {frequency}f;
        let pulse_amp = {amplitude}f;
        let phase = f32(instance_index) * 0.2;
        size_mult *= 1.0 + sin(uniforms.time * pulse_freq + phase) * pulse_amp;
    }}"#
            ),

            VertexEffect::Wave { direction, frequency, speed, amplitude } => format!(
                r#"
    // Wave effect
    {{
        let wave_dir = vec3<f32>({}f, {}f, {}f);
        let wave_freq = {frequency}f;
        let wave_speed = {speed}f;
        let wave_amp = {amplitude}f;
        let wave_phase = dot(particle_pos, wave_dir) * wave_freq - uniforms.time * wave_speed;
        pos_offset += wave_dir * sin(wave_phase) * wave_amp;
    }}"#,
                direction.x, direction.y, direction.z
            ),

            VertexEffect::Jitter { amplitude } => format!(
                r#"
    // Jitter effect
    {{
        let jitter_amp = {amplitude}f;
        let seed = u32(uniforms.time * 60.0) + instance_index * 12345u;
        let jx = fract(sin(f32(seed) * 12.9898) * 43758.5453) * 2.0 - 1.0;
        let jy = fract(sin(f32(seed + 1u) * 12.9898) * 43758.5453) * 2.0 - 1.0;
        let jz = fract(sin(f32(seed + 2u) * 12.9898) * 43758.5453) * 2.0 - 1.0;
        pos_offset += vec3<f32>(jx, jy, jz) * jitter_amp;
    }}"#
            ),

            VertexEffect::StretchToVelocity { max_stretch } => format!(
                r#"
    // Stretch to velocity effect (approximated from position delta)
    {{
        let stretch_max = {max_stretch}f;
        // Note: This is a visual approximation. For true velocity stretching,
        // use with_vertex_shader() with velocity passed as attribute.
        let stretch_dir = normalize(particle_pos + vec3<f32>(0.001, 0.001, 0.001));
        let stretch_factor = 1.0 + length(particle_pos) * (stretch_max - 1.0);
        // Stretch quad in the direction of motion
        let stretch_dot = dot(normalize(rotated_quad), stretch_dir.xy);
        size_mult *= mix(1.0, stretch_factor, abs(stretch_dot));
    }}"#
            ),

            VertexEffect::ScaleByDistance { center, min_scale, max_scale, max_distance } => format!(
                r#"
    // Scale by distance effect
    {{
        let scale_center = vec3<f32>({}f, {}f, {}f);
        let scale_min = {min_scale}f;
        let scale_max = {max_scale}f;
        let scale_max_dist = {max_distance}f;
        let dist = length(particle_pos - scale_center);
        let t = clamp(dist / scale_max_dist, 0.0, 1.0);
        size_mult *= mix(scale_min, scale_max, t);
    }}"#,
                center.x, center.y, center.z
            ),

            VertexEffect::FadeByDistance { near, far } => format!(
                r#"
    // Fade by distance effect
    {{
        let fade_near = {near}f;
        let fade_far = {far}f;
        let dist = length(particle_pos);
        let fade = 1.0 - clamp((dist - fade_near) / (fade_far - fade_near), 0.0, 1.0);
        color_mod *= fade;
    }}"#
            ),

            VertexEffect::BillboardCylindrical { axis } => format!(
                r#"
    // Cylindrical billboard - fixed axis, face camera horizontally
    {{
        let fixed_axis = normalize(vec3<f32>({}f, {}f, {}f));
        // Camera is at origin looking at particles, so camera_dir approximates view
        let to_camera = normalize(-particle_pos);
        // Project to_camera onto plane perpendicular to fixed_axis
        let camera_flat = normalize(to_camera - fixed_axis * dot(to_camera, fixed_axis));
        // Right vector is perpendicular to both
        let right = cross(fixed_axis, camera_flat);
        // Build world-space offset from quad coordinates
        billboard_right = right;
        billboard_up = fixed_axis;
        use_world_billboard = true;
    }}"#,
                axis.x, axis.y, axis.z
            ),

            VertexEffect::BillboardFixed { forward, up } => format!(
                r#"
    // Fixed billboard - no camera facing
    {{
        let fwd = normalize(vec3<f32>({}f, {}f, {}f));
        let up_dir = normalize(vec3<f32>({}f, {}f, {}f));
        let right = cross(up_dir, fwd);
        billboard_right = right;
        billboard_up = up_dir;
        use_world_billboard = true;
    }}"#,
                forward.x, forward.y, forward.z,
                up.x, up.y, up.z
            ),

            VertexEffect::FacePoint { target } => format!(
                r#"
    // Face point - orient toward target
    {{
        let target_pos = vec3<f32>({}f, {}f, {}f);
        let to_target = normalize(target_pos - particle_pos);
        // Use world up as reference
        let world_up = vec3<f32>(0.0, 1.0, 0.0);
        var right = cross(world_up, to_target);
        if length(right) < 0.001 {{
            right = vec3<f32>(1.0, 0.0, 0.0);
        }} else {{
            right = normalize(right);
        }}
        let up_dir = cross(to_target, right);
        billboard_right = right;
        billboard_up = up_dir;
        use_world_billboard = true;
    }}"#,
                target.x, target.y, target.z
            ),

            VertexEffect::Orbit { center, speed, radius, axis } => format!(
                r#"
    // Orbit effect - circular motion around center
    {{
        let orbit_center = vec3<f32>({}f, {}f, {}f);
        let orbit_speed = {speed}f;
        let orbit_radius = {radius}f;
        let orbit_axis = normalize(vec3<f32>({}f, {}f, {}f));

        // Phase offset per particle for variety
        let phase = f32(instance_index) * 0.618033988749; // Golden ratio
        let angle = uniforms.time * orbit_speed + phase * 6.283185;

        // Build rotation around axis
        let cos_a = cos(angle);
        let sin_a = sin(angle);

        // Get perpendicular vectors to orbit axis
        var perp1 = cross(orbit_axis, vec3<f32>(0.0, 1.0, 0.0));
        if length(perp1) < 0.001 {{
            perp1 = cross(orbit_axis, vec3<f32>(1.0, 0.0, 0.0));
        }}
        perp1 = normalize(perp1);
        let perp2 = cross(orbit_axis, perp1);

        // Circular offset
        let orbit_offset = (perp1 * cos_a + perp2 * sin_a) * orbit_radius;
        pos_offset += orbit_offset;
    }}"#,
                center.x, center.y, center.z,
                axis.x, axis.y, axis.z
            ),

            VertexEffect::Spiral { center, speed, expansion, vertical_speed } => format!(
                r#"
    // Spiral effect - expanding/contracting spiral motion
    {{
        let spiral_center = vec3<f32>({}f, {}f, {}f);
        let spiral_speed = {speed}f;
        let spiral_expansion = {expansion}f;
        let spiral_vertical = {vertical_speed}f;

        let phase = f32(instance_index) * 0.618033988749;
        let t = uniforms.time + phase;
        let angle = t * spiral_speed;
        let radius_t = spiral_expansion * t;

        pos_offset += vec3<f32>(
            cos(angle) * radius_t,
            t * spiral_vertical,
            sin(angle) * radius_t
        );
    }}"#,
                center.x, center.y, center.z
            ),

            VertexEffect::Sway { frequency, amplitude, axis } => format!(
                r#"
    // Sway effect - grass/tree-like motion
    {{
        let sway_freq = {frequency}f;
        let sway_amp = {amplitude}f;
        let sway_axis = normalize(vec3<f32>({}f, {}f, {}f));

        // Use particle height (Y) as anchor point - higher = more sway
        let height_factor = max(0.0, particle_pos.y + 0.5);
        let phase = f32(instance_index) * 0.37 + particle_pos.x * 2.0;

        // Primary sway
        let sway1 = sin(uniforms.time * sway_freq + phase) * sway_amp * height_factor;
        // Secondary slower sway for more organic feel
        let sway2 = sin(uniforms.time * sway_freq * 0.4 + phase * 1.3) * sway_amp * 0.3 * height_factor;

        pos_offset += sway_axis * (sway1 + sway2);
    }}"#,
                axis.x, axis.y, axis.z
            ),

            VertexEffect::ScaleBySpeed { min_scale, max_scale, max_speed } => format!(
                r#"
    // Scale by speed effect (approximated from position variance)
    {{
        let speed_min_scale = {min_scale}f;
        let speed_max_scale = {max_scale}f;
        let speed_max = {max_speed}f;

        // Approximate speed from position-based hash (changes with movement)
        let pos_hash = fract(sin(dot(particle_pos, vec3<f32>(12.9898, 78.233, 45.164))) * 43758.5453);
        let approx_speed = pos_hash * speed_max;
        let t = clamp(approx_speed / speed_max, 0.0, 1.0);
        size_mult *= mix(speed_min_scale, speed_max_scale, t);
    }}"#
            ),

            VertexEffect::Squash { axis, amount } => format!(
                r#"
    // Squash effect - flatten along axis
    {{
        let squash_axis = normalize(vec3<f32>({}f, {}f, {}f));
        let squash_amount = {amount}f;

        // Project quad onto squash plane
        let axis_component = dot(vec3<f32>(rotated_quad, 0.0), squash_axis);
        let squash_factor = mix(squash_amount, 1.0, 1.0 - abs(axis_component));

        // Apply squash to the appropriate quad dimension
        if abs(squash_axis.x) > 0.5 {{
            rotated_quad.x *= squash_amount;
        }}
        if abs(squash_axis.y) > 0.5 {{
            rotated_quad.y *= squash_amount;
        }}
    }}"#,
                axis.x, axis.y, axis.z
            ),

            VertexEffect::Tumble { speed } => format!(
                r#"
    // Tumble effect - chaotic 3D rotation
    {{
        let tumble_speed = {speed}f;
        let idx = f32(instance_index);

        // Different rotation speeds per axis per particle
        let rx = uniforms.time * tumble_speed * (0.5 + fract(idx * 0.1234));
        let ry = uniforms.time * tumble_speed * (0.7 + fract(idx * 0.5678));

        // Apply X rotation
        let cos_rx = cos(rx);
        let sin_rx = sin(rx);
        var q = rotated_quad;
        q.y = rotated_quad.y * cos_rx;

        // Apply Y rotation
        let cos_ry = cos(ry);
        let sin_ry = sin(ry);
        rotated_quad = vec2<f32>(
            q.x * cos_ry - q.y * sin_ry,
            q.x * sin_ry + q.y * cos_ry
        );
    }}"#
            ),

            VertexEffect::Attract { target, strength, max_displacement } => format!(
                r#"
    // Attract effect - pull toward target
    {{
        let attract_target = vec3<f32>({}f, {}f, {}f);
        let attract_strength = {strength}f;
        let attract_max = {max_displacement}f;

        let to_target = attract_target - particle_pos;
        let dist = length(to_target);
        if dist > 0.001 {{
            let dir = to_target / dist;
            // Inverse square falloff
            let force = attract_strength / (1.0 + dist * dist);
            let displacement = min(force, attract_max);
            pos_offset += dir * displacement;
        }}
    }}"#,
                target.x, target.y, target.z
            ),

            VertexEffect::Repel { source, strength, radius } => format!(
                r#"
    // Repel effect - push away from source
    {{
        let repel_source = vec3<f32>({}f, {}f, {}f);
        let repel_strength = {strength}f;
        let repel_radius = {radius}f;

        let from_source = particle_pos - repel_source;
        let dist = length(from_source);
        if dist < repel_radius && dist > 0.001 {{
            let dir = from_source / dist;
            // Linear falloff within radius
            let t = 1.0 - (dist / repel_radius);
            let force = repel_strength * t * t;
            pos_offset += dir * force;
        }}
    }}"#,
                source.x, source.y, source.z
            ),

            VertexEffect::Turbulence { frequency, amplitude, speed } => format!(
                r#"
    // Turbulence effect - noise-based displacement
    {{
        let turb_freq = {frequency}f;
        let turb_amp = {amplitude}f;
        let turb_speed = {speed}f;

        // Simple 3D noise approximation using sin combinations
        let p = particle_pos * turb_freq + uniforms.time * turb_speed;
        let n1 = sin(p.x * 1.0 + p.y * 0.5 + p.z * 0.3);
        let n2 = sin(p.y * 1.1 + p.z * 0.6 + p.x * 0.4 + 1.5);
        let n3 = sin(p.z * 0.9 + p.x * 0.7 + p.y * 0.5 + 3.0);

        // Layer multiple octaves
        let o1 = vec3<f32>(n1, n2, n3);
        let p2 = p * 2.0 + 5.0;
        let o2 = vec3<f32>(
            sin(p2.x + p2.y * 0.5),
            sin(p2.y + p2.z * 0.5),
            sin(p2.z + p2.x * 0.5)
        ) * 0.5;

        pos_offset += (o1 + o2) * turb_amp;
    }}"#
            ),

            VertexEffect::ScaleByAge { start_scale, end_scale, lifetime } => format!(
                r#"
    // Scale by age effect (approximated using time + particle index)
    {{
        let age_start_scale = {start_scale}f;
        let age_end_scale = {end_scale}f;
        let age_lifetime = {lifetime}f;

        // Approximate age using time modulo lifetime, offset by particle index
        let phase = fract(f32(instance_index) * 0.1);
        let age = fract((uniforms.time + phase * age_lifetime) / age_lifetime);
        size_mult *= mix(age_start_scale, age_end_scale, age);
    }}"#
            ),

            VertexEffect::FadeByAge { start_alpha, end_alpha, lifetime } => format!(
                r#"
    // Fade by age effect
    {{
        let fade_start = {start_alpha}f;
        let fade_end = {end_alpha}f;
        let fade_lifetime = {lifetime}f;

        // Approximate age using time modulo lifetime
        let phase = fract(f32(instance_index) * 0.1);
        let age = fract((uniforms.time + phase * fade_lifetime) / fade_lifetime);
        color_mod *= mix(fade_start, fade_end, age);
    }}"#
            ),

            VertexEffect::Vortex { center, speed, pull, radius } => format!(
                r#"
    // Vortex effect - tornado/whirlpool motion
    {{
        let vortex_center = vec3<f32>({}f, {}f, {}f);
        let vortex_speed = {speed}f;
        let vortex_pull = {pull}f;
        let vortex_radius = {radius}f;

        let to_center = particle_pos - vortex_center;
        let dist_xz = length(vec2<f32>(to_center.x, to_center.z));

        if dist_xz > 0.001 {{
            // Rotation around Y axis
            let angle = uniforms.time * vortex_speed * (1.0 + 0.5 / (dist_xz + 0.1));
            let phase = f32(instance_index) * 0.618033988749;

            let cos_a = cos(angle + phase);
            let sin_a = sin(angle + phase);

            // Tangential offset (perpendicular to radius)
            let tangent = vec3<f32>(-to_center.z, 0.0, to_center.x) / dist_xz;
            let orbit_offset = tangent * sin_a * min(dist_xz, vortex_radius) * 0.3;

            // Vertical pull toward center (stronger near center)
            let pull_factor = vortex_pull * (1.0 - clamp(dist_xz / vortex_radius, 0.0, 1.0));

            pos_offset += orbit_offset + vec3<f32>(0.0, pull_factor * sin(uniforms.time * 2.0 + phase), 0.0);
        }}
    }}"#,
                center.x, center.y, center.z
            ),

            VertexEffect::Bounce { height, frequency, damping } => format!(
                r#"
    // Bounce effect - gravity-like bouncing
    {{
        let bounce_height = {height}f;
        let bounce_freq = {frequency}f;
        let bounce_damp = {damping}f;

        let phase = f32(instance_index) * 0.37;
        let t = fract(uniforms.time * bounce_freq + phase);

        // Parabolic bounce with damping
        let bounce_cycle = floor(uniforms.time * bounce_freq + phase);
        let damp_factor = pow(1.0 - bounce_damp, bounce_cycle % 4.0);

        // Parabola: starts at 0, peaks at 0.5, returns to 0
        let h = 4.0 * t * (1.0 - t);
        pos_offset.y += h * bounce_height * damp_factor;
    }}"#
            ),

            VertexEffect::Figure8 { width, height, speed, ratio } => format!(
                r#"
    // Figure-8 / Lissajous curve motion
    {{
        let fig_width = {width}f;
        let fig_height = {height}f;
        let fig_speed = {speed}f;
        let fig_ratio = {ratio}f;

        let phase = f32(instance_index) * 0.618033988749;
        let t = uniforms.time * fig_speed + phase;

        // Lissajous curve: x = sin(t), y = sin(ratio * t)
        // ratio = 2 gives figure-8, other values give other patterns
        pos_offset.x += sin(t) * fig_width;
        pos_offset.y += sin(t * fig_ratio) * fig_height;
        pos_offset.z += sin(t * 0.5) * fig_width * 0.3;
    }}"#
            ),

            VertexEffect::Helix { axis, radius, speed, progression } => format!(
                r#"
    // Helix effect - corkscrew/DNA motion
    {{
        let helix_axis = normalize(vec3<f32>({}f, {}f, {}f));
        let helix_radius = {radius}f;
        let helix_speed = {speed}f;
        let helix_prog = {progression}f;

        let phase = f32(instance_index) * 0.618033988749;
        let t = uniforms.time * helix_speed + phase;

        // Get perpendicular vectors to axis
        var perp1 = cross(helix_axis, vec3<f32>(0.0, 1.0, 0.0));
        if length(perp1) < 0.001 {{
            perp1 = cross(helix_axis, vec3<f32>(1.0, 0.0, 0.0));
        }}
        perp1 = normalize(perp1);
        let perp2 = cross(helix_axis, perp1);

        // Circular motion perpendicular to axis
        let circle_offset = (perp1 * cos(t) + perp2 * sin(t)) * helix_radius;

        // Forward progression along axis
        let prog_offset = helix_axis * fract(t * helix_prog * 0.1) * 2.0;

        pos_offset += circle_offset + prog_offset;
    }}"#,
                axis.x, axis.y, axis.z
            ),

            VertexEffect::Flutter { intensity, speed } => format!(
                r#"
    // Flutter effect - rapid small oscillations
    {{
        let flutter_int = {intensity}f;
        let flutter_speed = {speed}f;

        let idx = f32(instance_index);
        let t = uniforms.time * flutter_speed;

        // Multiple high-frequency oscillations with different phases
        let f1 = sin(t * 15.0 + idx * 1.23) * 0.4;
        let f2 = sin(t * 23.0 + idx * 2.34) * 0.3;
        let f3 = sin(t * 31.0 + idx * 3.45) * 0.2;
        let f4 = cos(t * 19.0 + idx * 4.56) * 0.35;
        let f5 = cos(t * 27.0 + idx * 5.67) * 0.25;

        pos_offset += vec3<f32>(
            (f1 + f2) * flutter_int,
            (f3 + f4) * flutter_int,
            (f2 + f5) * flutter_int * 0.5
        );
    }}"#
            ),

            VertexEffect::Brownian { intensity, speed } => format!(
                r#"
    // Brownian motion - random walk
    {{
        let brown_int = {intensity}f;
        let brown_speed = {speed}f;

        let idx = f32(instance_index);
        let t = uniforms.time * brown_speed;

        // Layered noise-like motion that evolves over time
        // Using multiple sine waves with irrational frequency ratios
        let n1 = sin(t * 1.0 + idx * 12.9898) * sin(t * 0.7 + idx * 4.1414);
        let n2 = sin(t * 1.3 + idx * 78.233) * sin(t * 0.9 + idx * 2.7182);
        let n3 = sin(t * 0.8 + idx * 43.758) * sin(t * 1.1 + idx * 3.1415);

        // Accumulate "steps" for random walk effect
        let walk_x = n1 + sin(t * 0.3 + idx) * 0.5;
        let walk_y = n2 + sin(t * 0.4 + idx * 1.1) * 0.5;
        let walk_z = n3 + sin(t * 0.35 + idx * 0.9) * 0.5;

        pos_offset += vec3<f32>(walk_x, walk_y, walk_z) * brown_int;
    }}"#
            ),
        }
    }
}

/// What data source to visualize with vector glyphs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GlyphMode {
    /// Glyphs disabled (default).
    #[default]
    None,
    /// Show vector field values at grid sample points.
    VectorField {
        /// Which field index to visualize.
        field_index: usize,
    },
    /// Show particle velocities as arrows.
    ParticleVelocity,
}

/// How to color the glyphs.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum GlyphColorMode {
    /// Single uniform color.
    #[default]
    Uniform,
    /// Color based on vector magnitude.
    ByMagnitude,
    /// Color based on vector direction (XYZ → RGB).
    ByDirection,
}

/// Configuration for vector field glyphs.
#[derive(Debug, Clone, PartialEq)]
pub struct GlyphConfig {
    /// What to visualize.
    pub mode: GlyphMode,
    /// Grid resolution for field sampling (glyphs per axis).
    pub grid_resolution: u32,
    /// Scale factor for glyph length.
    pub scale: f32,
    /// How to color the glyphs.
    pub color_mode: GlyphColorMode,
    /// Base color (used when color_mode is Uniform).
    pub color: Vec3,
    /// Line thickness for glyphs.
    pub thickness: f32,
}

impl Default for GlyphConfig {
    fn default() -> Self {
        Self {
            mode: GlyphMode::None,
            grid_resolution: 8,
            scale: 0.1,
            color_mode: GlyphColorMode::Uniform,
            color: Vec3::new(0.0, 1.0, 0.5),
            thickness: 0.002,
        }
    }
}

/// Combine multiple vertex effects into a single WGSL vertex shader body.
pub fn combine_vertex_effects(effects: &[VertexEffect], color_expr: &str) -> String {
    if effects.is_empty() {
        // Default vertex body when no effects
        return format!(
            r#"    let world_pos = vec4<f32>(particle_pos, 1.0);
    var clip_pos = uniforms.view_proj * world_pos;

    clip_pos.x += quad_pos.x * particle_size * clip_pos.w;
    clip_pos.y += quad_pos.y * particle_size * clip_pos.w;

    out.clip_position = clip_pos;
    out.color = {color_expr};
    out.uv = quad_pos;

    return out;"#
        );
    }

    // Check if any billboard effects are used
    let has_billboard = effects.iter().any(|e| matches!(e,
        VertexEffect::BillboardCylindrical { .. } |
        VertexEffect::BillboardFixed { .. } |
        VertexEffect::FacePoint { .. }
    ));

    // Generate effect code
    let effects_code: String = effects.iter().map(|e| e.to_wgsl()).collect();

    // Billboard variables initialization (only if needed)
    let billboard_vars = if has_billboard {
        r#"
    var use_world_billboard = false;
    var billboard_right = vec3<f32>(1.0, 0.0, 0.0);
    var billboard_up = vec3<f32>(0.0, 1.0, 0.0);"#
    } else {
        ""
    };

    // Final transformation - use world billboard if enabled
    let final_transform = if has_billboard {
        r#"    // Final transformation
    let final_pos = particle_pos + pos_offset;
    let final_size = particle_size * size_mult;

    let world_pos = vec4<f32>(final_pos, 1.0);

    if use_world_billboard {
        // World-space billboarding
        let world_offset = billboard_right * rotated_quad.x * final_size
                         + billboard_up * rotated_quad.y * final_size;
        let offset_world_pos = vec4<f32>(final_pos + world_offset, 1.0);
        out.clip_position = uniforms.view_proj * offset_world_pos;
    } else {
        // Screen-space billboarding (default)
        var clip_pos = uniforms.view_proj * world_pos;
        clip_pos.x += rotated_quad.x * final_size * clip_pos.w;
        clip_pos.y += rotated_quad.y * final_size * clip_pos.w;
        out.clip_position = clip_pos;
    }

    out.color = color_mod;
    out.uv = rotated_quad;

    return out;"#
    } else {
        r#"    // Final transformation
    let final_pos = particle_pos + pos_offset;
    let final_size = particle_size * size_mult;

    let world_pos = vec4<f32>(final_pos, 1.0);
    var clip_pos = uniforms.view_proj * world_pos;

    clip_pos.x += rotated_quad.x * final_size * clip_pos.w;
    clip_pos.y += rotated_quad.y * final_size * clip_pos.w;

    out.clip_position = clip_pos;
    out.color = color_mod;
    out.uv = rotated_quad;

    return out;"#
    };

    format!(
        r#"    // Initialize effect variables
    var pos_offset = vec3<f32>(0.0);
    var rotated_quad = quad_pos;
    var size_mult = 1.0;
    var color_mod = {color_expr};{billboard_vars}

    // Apply vertex effects
{effects_code}

{final_transform}"#
    )
}