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
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
//! Particle behavior rules.
//!
//! Rules define how particles behave each frame. They are applied in order
//! and translated into WGSL compute shader code at simulation startup.
//!
//! # Rule Categories
//!
//! - **Basic Physics**: Gravity, Drag, Acceleration, SpeedLimit, Wander
//! - **Boundaries**: BounceWalls, WrapWalls
//! - **Point Forces**: AttractTo, RepelFrom, PointGravity, Spring
//! - **Field Effects**: Vortex, Turbulence, Orbit, Curl
//! - **Wave/Modulation**: Oscillate, PositionNoise
//! - **Flocking** (neighbor): Collide, Separate, Cohere, Align, Avoid
//! - **Fluid** (neighbor): NBodyGravity, Viscosity, Pressure, SurfaceTension
//! - **Electromagnetic** (neighbor): Magnetism
//! - **Type-Based** (neighbor): Typed, Convert, Chase, Evade
//! - **Lifecycle**: Age, Lifetime, FadeOut, ShrinkOut, ColorOverLife
//! - **Visual**: ColorBySpeed, ColorByAge, ScaleBySpeed
//! - **Custom**: Custom (raw WGSL), NeighborCustom (WGSL in neighbor loop)
//!
//! # Neighbor Rules
//!
//! Rules marked "(neighbor)" query nearby particles and require spatial hashing.
//! Configure with:
//!
//! ```ignore
//! .with_spatial_config(cell_size, grid_resolution)
//! ```
//!
//! The `cell_size` should be at least as large as your largest interaction
//! radius. The `grid_resolution` controls memory usage (typical: 32 or 64).
use glam::Vec3;
/// Distance falloff functions for force-based rules.
///
/// Controls how a force's strength changes with distance from the source.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Falloff {
/// Constant force regardless of distance.
#[default]
Constant,
/// Linear falloff: force decreases linearly to zero at max range.
Linear,
/// Inverse falloff: force = 1/distance (with softening).
Inverse,
/// Inverse-square falloff: force = 1/distance² (realistic gravity/EM).
InverseSquare,
/// Smooth falloff using smoothstep for gradual transitions.
Smooth,
}
impl Falloff {
/// Generate WGSL code for this falloff function.
/// Returns an expression that computes the falloff factor given `dist` and `radius`.
pub fn to_wgsl_expr(&self) -> &'static str {
match self {
Falloff::Constant => "1.0",
Falloff::Linear => "(1.0 - dist / radius)",
Falloff::Inverse => "(1.0 / (dist + 0.01))",
Falloff::InverseSquare => "(1.0 / (dist * dist + 0.0001))",
Falloff::Smooth => "(1.0 - smoothstep(0.0, radius, dist))",
}
}
}
/// A transition between agent states.
///
/// Transitions are checked in order of priority (highest first).
/// The first transition whose condition evaluates to true is taken.
#[derive(Clone, Debug)]
pub struct Transition {
/// Target state ID to transition to.
pub to: u32,
/// WGSL boolean expression that triggers this transition.
/// Has access to `p` (particle), `uniforms.time`, `uniforms.delta_time`, etc.
pub condition: String,
/// Priority (higher = checked first). Default: 0.
pub priority: i32,
}
impl Transition {
/// Create a new transition with default priority.
pub fn new(to: u32, condition: impl Into<String>) -> Self {
Self {
to,
condition: condition.into(),
priority: 0,
}
}
/// Create a transition with explicit priority.
pub fn with_priority(to: u32, condition: impl Into<String>, priority: i32) -> Self {
Self {
to,
condition: condition.into(),
priority,
}
}
}
/// A state in an agent state machine.
///
/// Each state can have:
/// - Entry action: runs once when entering this state
/// - Update action: runs every frame while in this state
/// - Exit action: runs once when leaving this state
/// - Transitions: conditions that trigger moving to other states
#[derive(Clone, Debug)]
pub struct AgentState {
/// Unique state identifier (matches the particle's state field value).
pub id: u32,
/// Optional name for debugging/documentation.
pub name: Option<String>,
/// WGSL code to execute when entering this state.
pub on_enter: Option<String>,
/// WGSL code to execute every frame while in this state.
pub on_update: Option<String>,
/// WGSL code to execute when leaving this state.
pub on_exit: Option<String>,
/// Transitions to other states.
pub transitions: Vec<Transition>,
}
impl AgentState {
/// Create a new state with the given ID.
pub fn new(id: u32) -> Self {
Self {
id,
name: None,
on_enter: None,
on_update: None,
on_exit: None,
transitions: Vec::new(),
}
}
/// Set a name for this state (for documentation).
pub fn named(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
/// Set the entry action (runs once when entering).
pub fn on_enter(mut self, code: impl Into<String>) -> Self {
self.on_enter = Some(code.into());
self
}
/// Set the update action (runs every frame while in this state).
pub fn on_update(mut self, code: impl Into<String>) -> Self {
self.on_update = Some(code.into());
self
}
/// Set the exit action (runs once when leaving).
pub fn on_exit(mut self, code: impl Into<String>) -> Self {
self.on_exit = Some(code.into());
self
}
/// Add a transition to another state.
pub fn transition(mut self, to: u32, condition: impl Into<String>) -> Self {
self.transitions.push(Transition::new(to, condition));
self
}
/// Add a transition with explicit priority.
pub fn transition_priority(
mut self,
to: u32,
condition: impl Into<String>,
priority: i32,
) -> Self {
self.transitions
.push(Transition::with_priority(to, condition, priority));
self
}
}
/// Rules that define particle behavior.
///
/// Rules are applied every frame in the order they are added. Each rule
/// modifies particle velocity (and sometimes position or type). After all
/// rules execute, velocity is integrated: `position += velocity * delta_time`.
///
/// # Example
///
/// ```ignore
/// Simulation::<MyParticle>::new()
/// .with_rule(Rule::Gravity(9.8))
/// .with_rule(Rule::Separate { radius: 0.1, strength: 2.0 })
/// .with_rule(Rule::SpeedLimit { min: 0.0, max: 5.0 })
/// .with_rule(Rule::Drag(1.0))
/// .with_rule(Rule::BounceWalls { restitution: 1.0 })
/// .run();
/// ```
#[derive(Clone, Debug)]
pub enum Rule {
/// Constant downward acceleration (negative Y).
///
/// # Parameters
///
/// - `strength` - Acceleration in units per second squared (typical: 9.8)
///
/// # Example
///
/// ```ignore
/// Rule::Gravity(9.8) // Earth-like gravity
/// Rule::Gravity(1.6) // Moon-like gravity
/// ```
Gravity(f32),
/// Reflect particles off bounding box walls.
///
/// When a particle crosses a boundary, its position is clamped and
/// its velocity component is reversed. Creates a contained simulation.
///
/// The bounds are set with `.with_bounds(size)` which creates a cube
/// from `-size` to `+size` on all axes.
///
/// # Arguments
///
/// * `restitution` - Bounce coefficient (0.0 = full stop, 1.0 = perfect bounce).
/// Values > 1.0 add energy on each bounce.
///
/// # Example
///
/// ```ignore
/// .with_bounds(1.0) // Cube from -1 to +1
/// .with_rule(Rule::BounceWalls { restitution: 0.8 }) // Loses 20% speed on bounce
/// ```
BounceWalls {
/// Coefficient of restitution (0.0-1.0 typical, >1.0 adds energy)
restitution: f32,
},
/// Wrap particles around bounding box walls (toroidal topology).
///
/// Particles exiting one side reappear on the opposite side with
/// velocity preserved. Creates an infinite-feeling space with no edges.
///
/// # Example
///
/// ```ignore
/// .with_bounds(1.0)
/// .with_rule(Rule::WrapWalls) // Endless space
/// ```
WrapWalls,
/// Velocity damping (air resistance / friction).
///
/// Reduces velocity over time. Higher values = more friction.
/// A value of 1.0 would stop particles in ~1 second.
///
/// # Parameters
///
/// - `strength` - Damping coefficient (typical: 0.5 to 3.0)
///
/// # Example
///
/// ```ignore
/// Rule::Drag(1.0) // Moderate air resistance
/// Rule::Drag(0.1) // Very little friction (space-like)
/// Rule::Drag(5.0) // Heavy friction (underwater feel)
/// ```
Drag(f32),
/// Constant acceleration in any direction.
///
/// Unlike Gravity which only affects Y, this applies force in any direction.
/// Useful for wind, currents, or directional fields.
///
/// # Parameters
///
/// - `direction` - Acceleration vector (units per second squared)
///
/// # Example
///
/// ```ignore
/// Rule::Acceleration(Vec3::new(1.0, 0.0, 0.0)) // Rightward wind
/// Rule::Acceleration(Vec3::new(0.0, -9.8, 0.0)) // Same as Gravity(9.8)
/// ```
Acceleration(Vec3),
/// Attract particles toward a fixed point.
///
/// All particles steer toward the target point. Force is constant
/// regardless of distance (not inverse-square).
///
/// # Fields
///
/// - `point` - Target position to attract toward
/// - `strength` - Force magnitude (higher = faster attraction)
///
/// # Example
///
/// ```ignore
/// Rule::AttractTo {
/// point: Vec3::ZERO, // Attract to center
/// strength: 2.0,
/// }
/// ```
AttractTo {
/// Target position.
point: Vec3,
/// Attraction strength.
strength: f32,
},
/// Repel particles from a fixed point within a radius.
///
/// Particles within `radius` of the point are pushed away.
/// Force is stronger closer to the point, zero at the edge.
///
/// # Fields
///
/// - `point` - Center of repulsion
/// - `strength` - Maximum force at center
/// - `radius` - Effect radius (force falls off to zero at edge)
///
/// # Example
///
/// ```ignore
/// Rule::RepelFrom {
/// point: Vec3::ZERO,
/// strength: 5.0,
/// radius: 0.5, // Only affects particles within 0.5 units
/// }
/// ```
RepelFrom {
/// Center of repulsion.
point: Vec3,
/// Repulsion strength.
strength: f32,
/// Effect radius.
radius: f32,
},
/// Steering behavior: seek a target point.
///
/// Applies a steering force toward a target, adjusting velocity smoothly
/// rather than setting it directly. Core autonomous agent behavior.
///
/// # Fields
///
/// - `target` - Position to seek toward
/// - `max_speed` - Maximum velocity magnitude
/// - `max_force` - Maximum steering force (lower = smoother turns)
///
/// # Example
///
/// ```ignore
/// Rule::Seek {
/// target: Vec3::new(0.5, 0.0, 0.0),
/// max_speed: 2.0,
/// max_force: 0.5,
/// }
/// ```
///
/// # Note
///
/// For dynamic targets (like mouse position), use `Rule::Custom` with
/// uniforms or combine with fields.
Seek {
/// Target position to seek.
target: Vec3,
/// Maximum speed.
max_speed: f32,
/// Maximum steering force.
max_force: f32,
},
/// Steering behavior: flee from a point.
///
/// Opposite of Seek - applies steering force away from a point.
/// The panic_radius controls when fleeing kicks in.
///
/// # Fields
///
/// - `target` - Position to flee from
/// - `max_speed` - Maximum velocity magnitude
/// - `max_force` - Maximum steering force
/// - `panic_radius` - Distance at which fleeing activates (0 = always flee)
///
/// # Example
///
/// ```ignore
/// Rule::Flee {
/// target: Vec3::ZERO,
/// max_speed: 3.0,
/// max_force: 1.0,
/// panic_radius: 0.5, // Only flee when close
/// }
/// ```
Flee {
/// Position to flee from.
target: Vec3,
/// Maximum speed.
max_speed: f32,
/// Maximum steering force.
max_force: f32,
/// Radius within which to flee (0 = always flee).
panic_radius: f32,
},
/// Steering behavior: arrive at a target with deceleration.
///
/// Like Seek but slows down as it approaches the target, coming to a
/// smooth stop. Essential for realistic goal-seeking behavior.
///
/// # Fields
///
/// - `target` - Position to arrive at
/// - `max_speed` - Maximum velocity magnitude
/// - `max_force` - Maximum steering force
/// - `slowing_radius` - Distance at which deceleration begins
///
/// # Example
///
/// ```ignore
/// Rule::Arrive {
/// target: Vec3::ZERO,
/// max_speed: 2.0,
/// max_force: 0.5,
/// slowing_radius: 0.3, // Start slowing at 0.3 units away
/// }
/// ```
Arrive {
/// Target position to arrive at.
target: Vec3,
/// Maximum speed.
max_speed: f32,
/// Maximum steering force.
max_force: f32,
/// Distance at which to start slowing down.
slowing_radius: f32,
},
/// Rotational force around an axis (vortex/whirlpool effect).
///
/// Creates tangential motion around a line through `center` along `axis`.
/// Particles spiral around the axis, useful for tornados, whirlpools,
/// and swirl effects.
///
/// # Fields
///
/// - `center` - Point on the rotation axis
/// - `axis` - Direction of rotation axis (will be normalized)
/// - `strength` - Rotational force (positive = counter-clockwise when looking down axis)
///
/// # Example
///
/// ```ignore
/// // Vertical tornado around origin
/// Rule::Vortex {
/// center: Vec3::ZERO,
/// axis: Vec3::Y, // Rotate around Y axis
/// strength: 2.0,
/// }
///
/// // Horizontal whirlpool
/// Rule::Vortex {
/// center: Vec3::new(0.0, -0.5, 0.0),
/// axis: Vec3::Y,
/// strength: 3.0,
/// }
/// ```
Vortex {
/// Point on rotation axis.
center: Vec3,
/// Direction of rotation axis.
axis: Vec3,
/// Rotational strength.
strength: f32,
},
/// Noise-based chaotic force field.
///
/// Applies forces based on 3D noise sampled at each particle's position.
/// Creates organic, turbulent motion. The noise field evolves over time.
///
/// # Fields
///
/// - `scale` - Noise frequency (smaller = larger swirls, larger = finer detail)
/// - `strength` - Force magnitude
///
/// # Example
///
/// ```ignore
/// Rule::Turbulence {
/// scale: 2.0, // Medium-sized turbulent structures
/// strength: 1.5, // Moderate force
/// }
/// ```
///
/// # Note
///
/// Uses built-in simplex noise. For more control, use `Rule::Custom`
/// with `noise3()` or `fbm3()` functions directly.
Turbulence {
/// Noise frequency (spatial scale).
scale: f32,
/// Force magnitude.
strength: f32,
},
/// Circular orbit around a center point.
///
/// Applies forces to make particles orbit around a point. Combines
/// centripetal attraction with tangential velocity to maintain orbit.
///
/// # Fields
///
/// - `center` - Point to orbit around
/// - `strength` - Orbital force (higher = tighter orbits)
///
/// # Example
///
/// ```ignore
/// Rule::Orbit {
/// center: Vec3::ZERO,
/// strength: 2.0,
/// }
/// ```
///
/// # Note
///
/// For stable orbits, balance with `Rule::Drag`. Without drag,
/// particles may spiral inward or outward.
Orbit {
/// Center of orbit.
center: Vec3,
/// Orbital strength.
strength: f32,
},
/// Curl noise for fluid-like, divergence-free flow.
///
/// Creates smooth, swirling motion that never converges to a point
/// (divergence-free). Particles flow like smoke or fluid. Based on
/// the curl of a 3D noise field.
///
/// # Fields
///
/// - `scale` - Noise frequency (smaller = larger flow structures)
/// - `strength` - Flow speed
///
/// # Example
///
/// ```ignore
/// Rule::Curl {
/// scale: 1.5, // Large flowing structures
/// strength: 2.0, // Moderate flow speed
/// }
/// ```
///
/// # Note
///
/// More computationally expensive than `Turbulence` (samples noise 6x).
/// Use for fluid/smoke effects where particles shouldn't bunch up.
Curl {
/// Noise frequency.
scale: f32,
/// Flow strength.
strength: f32,
},
/// Inverse-square gravity toward a fixed point.
///
/// Like `NBodyGravity` but attracts to a single static point rather
/// than between particles. Classic for black holes, attractors, and
/// orbital mechanics around a central body.
///
/// # Fields
///
/// - `point` - Center of attraction
/// - `strength` - Gravitational constant
/// - `softening` - Minimum distance to prevent singularities
///
/// # Example
///
/// ```ignore
/// Rule::PointGravity {
/// point: Vec3::ZERO,
/// strength: 2.0,
/// softening: 0.05,
/// }
/// ```
PointGravity {
/// Center of attraction.
point: Vec3,
/// Gravitational strength.
strength: f32,
/// Softening to prevent singularities.
softening: f32,
},
/// Spring force tethering particles to a point.
///
/// Applies Hooke's law: force proportional to displacement from rest
/// position. Good for bouncy effects, soft bodies, and cloth-like
/// behavior.
///
/// # Fields
///
/// - `anchor` - Rest position (or use `Vec3::ZERO` for origin)
/// - `stiffness` - Spring constant (higher = stiffer, snappier)
/// - `damping` - Velocity damping (prevents endless oscillation)
///
/// # Example
///
/// ```ignore
/// Rule::Spring {
/// anchor: Vec3::ZERO,
/// stiffness: 5.0,
/// damping: 0.5,
/// }
/// ```
Spring {
/// Rest position.
anchor: Vec3,
/// Spring stiffness.
stiffness: f32,
/// Damping factor.
damping: f32,
},
/// Radial force (explode/implode) with configurable falloff.
///
/// Positive strength pushes particles outward (explode).
/// Negative strength pulls particles inward (implode).
/// The `falloff` parameter controls how the force changes with distance.
///
/// # Fields
///
/// - `point` - Center of the radial force
/// - `strength` - Force magnitude (positive = outward, negative = inward)
/// - `radius` - Maximum effect radius (0.0 = unlimited)
/// - `falloff` - How force decreases with distance
///
/// # Example
///
/// ```ignore
/// // Explosion from center
/// Rule::Radial {
/// point: Vec3::ZERO,
/// strength: 5.0,
/// radius: 2.0,
/// falloff: Falloff::InverseSquare,
/// }
///
/// // Black hole with smooth falloff
/// Rule::Radial {
/// point: Vec3::ZERO,
/// strength: -3.0, // Negative = inward
/// radius: 1.5,
/// falloff: Falloff::Smooth,
/// }
/// ```
Radial {
/// Center of radial force.
point: Vec3,
/// Force strength (positive = out, negative = in).
strength: f32,
/// Maximum effect radius (0.0 = unlimited).
radius: f32,
/// Distance falloff function.
falloff: Falloff,
},
/// Expanding shockwave that pushes particles as it passes.
///
/// Creates a ring/sphere that expands outward from the origin point.
/// Particles get pushed when the wavefront passes through them.
/// The wave repeats based on the `repeat` parameter.
///
/// # Fields
///
/// - `origin` - Center point of the shockwave
/// - `speed` - How fast the wave expands (units per second)
/// - `width` - Thickness of the wavefront
/// - `strength` - Push force when wave passes
/// - `repeat` - Time between wave repetitions (0.0 = single wave)
///
/// # Example
///
/// ```ignore
/// // Single expanding shockwave
/// Rule::Shockwave {
/// origin: Vec3::ZERO,
/// speed: 2.0,
/// width: 0.3,
/// strength: 5.0,
/// repeat: 0.0, // One-time
/// }
///
/// // Repeating pulses
/// Rule::Shockwave {
/// origin: Vec3::ZERO,
/// speed: 1.5,
/// width: 0.2,
/// strength: 3.0,
/// repeat: 2.0, // Every 2 seconds
/// }
/// ```
Shockwave {
/// Center of shockwave.
origin: Vec3,
/// Expansion speed (units per second).
speed: f32,
/// Wavefront thickness.
width: f32,
/// Push strength.
strength: f32,
/// Repetition period (0.0 = no repeat).
repeat: f32,
},
/// Breathing/pulsing radial force that oscillates between expand and contract.
///
/// Combines explosion and implosion in a smooth oscillation.
/// Creates organic "breathing" motion where particles expand and contract.
///
/// # Fields
///
/// - `point` - Center of the pulse
/// - `strength` - Maximum force magnitude
/// - `frequency` - Oscillation speed (Hz)
/// - `radius` - Effect radius (0.0 = unlimited)
///
/// # Example
///
/// ```ignore
/// Rule::Pulse {
/// point: Vec3::ZERO,
/// strength: 2.0,
/// frequency: 0.5, // One breath every 2 seconds
/// radius: 1.5,
/// }
/// ```
Pulse {
/// Center of pulse.
point: Vec3,
/// Maximum force strength.
strength: f32,
/// Oscillation frequency (Hz).
frequency: f32,
/// Effect radius (0.0 = unlimited).
radius: f32,
},
/// Sine-wave oscillation applied to velocity.
///
/// Creates pulsing, breathing, or wave-like motion. Each particle
/// oscillates based on time and optionally creates radial waves
/// emanating outward from the oscillation axis.
///
/// # Fields
///
/// - `axis` - Direction of oscillation (will be normalized)
/// - `amplitude` - Oscillation strength
/// - `frequency` - Oscillations per second
/// - `spatial_scale` - If > 0, creates radial waves based on distance from axis
///
/// # Example
///
/// ```ignore
/// // Simple up-down pulse (all particles in sync)
/// Rule::Oscillate {
/// axis: Vec3::Y,
/// amplitude: 0.5,
/// frequency: 2.0,
/// spatial_scale: 0.0,
/// }
///
/// // Radial ripples (like dropping a stone in water)
/// Rule::Oscillate {
/// axis: Vec3::Y,
/// amplitude: 0.3,
/// frequency: 1.0,
/// spatial_scale: 5.0, // Higher = tighter ripples
/// }
/// ```
Oscillate {
/// Direction of oscillation.
axis: Vec3,
/// Oscillation amplitude.
amplitude: f32,
/// Frequency in Hz.
frequency: f32,
/// Spatial wave scale (0 = uniform, >0 = traveling wave).
spatial_scale: f32,
},
/// Position jitter from noise field.
///
/// Adds organic, pseudo-random displacement to particle positions.
/// Different from `Turbulence` which affects velocity - this directly
/// offsets position for a jittery, vibrating effect.
///
/// # Fields
///
/// - `scale` - Noise frequency (smaller = larger jitter patterns)
/// - `strength` - Maximum displacement
/// - `speed` - How fast the noise field evolves
///
/// # Example
///
/// ```ignore
/// Rule::PositionNoise {
/// scale: 5.0,
/// strength: 0.02,
/// speed: 2.0,
/// }
/// ```
PositionNoise {
/// Noise frequency.
scale: f32,
/// Displacement strength.
strength: f32,
/// Time evolution speed.
speed: f32,
},
/// Elastic collision response between particles.
///
/// **Requires spatial hashing.** Particles within `radius` of each other
/// exchange velocity along the collision normal, simulating elastic bounces.
/// Also separates overlapping particles to prevent interpenetration.
///
/// # Fields
///
/// - `radius` - Collision distance (sum of particle radii)
/// - `restitution` - Coefficient of restitution:
/// - `0.0` = perfectly inelastic (particles stick together)
/// - `1.0` = perfectly elastic (full energy preserved)
/// - `0.5` = typical bouncy collision
///
/// # Example
///
/// ```ignore
/// .with_spatial_config(0.1, 32)
/// .with_rule(Rule::Collide {
/// radius: 0.05, // Collision distance
/// restitution: 0.8, // Bouncy collision
/// })
/// ```
Collide {
/// Collision distance (triggers when particles are closer than this).
radius: f32,
/// Coefficient of restitution (0.0 = inelastic, 1.0 = elastic).
restitution: f32,
},
/// N-body gravitational attraction between particles.
///
/// **Requires spatial hashing.** Every particle attracts nearby particles
/// with inverse-square force (like gravity). Classic for galaxy simulations,
/// particle clustering, and organic clumping behavior.
///
/// # Fields
///
/// - `strength` - Gravitational constant (higher = stronger pull)
/// - `softening` - Minimum distance to prevent division by zero and
/// extreme forces at close range. Typical: 0.01-0.05
/// - `radius` - Maximum interaction range (for performance)
///
/// # Example
///
/// ```ignore
/// .with_spatial_config(0.3, 32)
/// .with_rule(Rule::NBodyGravity {
/// strength: 0.5,
/// softening: 0.02, // Prevents singularities
/// radius: 0.5, // Only attract within range
/// })
/// ```
///
/// # Physics Note
///
/// True n-body is O(n²), but spatial hashing limits to nearby particles.
/// For galaxy-scale simulations, combine with `Rule::Drag` to prevent
/// runaway velocities.
NBodyGravity {
/// Gravitational strength.
strength: f32,
/// Softening parameter (prevents singularities).
softening: f32,
/// Maximum interaction radius.
radius: f32,
},
/// Lennard-Jones potential for molecular dynamics.
///
/// **Requires spatial hashing.** Creates realistic molecular interactions:
/// strong repulsion at close range (Pauli exclusion) and weak attraction
/// at medium range (Van der Waals). Perfect for crystal formation,
/// liquid simulations, and soft matter physics.
///
/// # Fields
///
/// - `epsilon` - Well depth (strength of attraction at equilibrium)
/// - `sigma` - Zero-crossing distance (particle diameter)
/// - `cutoff` - Maximum interaction range (typically 2.5 * sigma)
///
/// # Example
///
/// ```ignore
/// .with_spatial_config(0.3, 32)
/// .with_rule(Rule::LennardJones {
/// epsilon: 1.0, // Attraction strength
/// sigma: 0.1, // Particle "size"
/// cutoff: 0.25, // 2.5 * sigma
/// })
/// ```
///
/// # Physics Note
///
/// The potential is V(r) = 4ε[(σ/r)¹² - (σ/r)⁶]. Particles settle at
/// r ≈ 1.12σ (the equilibrium distance). Combine with temperature-based
/// velocity initialization for molecular dynamics simulations.
LennardJones {
/// Well depth (attraction strength at equilibrium).
epsilon: f32,
/// Zero-crossing distance (effective particle diameter).
sigma: f32,
/// Cutoff radius for interaction (typically 2.5 * sigma).
cutoff: f32,
},
/// Diffusion-Limited Aggregation (DLA) for fractal growth.
///
/// **Requires spatial hashing.** Particles perform random walks until
/// they contact a "seed" particle (type 0 by default), at which point
/// they stick and become part of the growing structure. Creates beautiful
/// fractal patterns like snowflakes, coral, lightning, and mineral deposits.
///
/// # Fields
///
/// - `seed_type` - Particle type that acts as the seed/structure
/// - `mobile_type` - Particle type that diffuses and sticks
/// - `stick_radius` - Distance at which particles stick
/// - `diffusion_strength` - Random walk intensity
///
/// # Example
///
/// ```ignore
/// .with_spatial_config(0.1, 32)
/// .with_rule(Rule::DLA {
/// seed_type: 0,
/// mobile_type: 1,
/// stick_radius: 0.05,
/// diffusion_strength: 0.5,
/// })
/// ```
///
/// # Physics Note
///
/// Real DLA requires very slow aggregation for proper fractal dimension.
/// For visual effect, higher diffusion works fine. Initialize with one
/// seed particle (type 0) at center and many mobile particles (type 1).
DLA {
/// Particle type that forms the structure (immobile once stuck).
seed_type: u32,
/// Particle type that diffuses until it sticks.
mobile_type: u32,
/// Contact radius for sticking.
stick_radius: f32,
/// Brownian motion intensity.
diffusion_strength: f32,
},
/// Velocity smoothing with nearby particles (fluid viscosity).
///
/// **Requires spatial hashing.** Particles blend their velocity with
/// neighbors, creating smooth, fluid-like motion. Higher strength means
/// more uniform flow; lower means more chaotic.
///
/// # Fields
///
/// - `radius` - Interaction range
/// - `strength` - Blending rate (0.0-1.0 typical, higher = more viscous)
///
/// # Example
///
/// ```ignore
/// .with_spatial_config(0.15, 32)
/// .with_rule(Rule::Viscosity {
/// radius: 0.1,
/// strength: 0.5, // Medium viscosity
/// })
/// ```
///
/// # Physics Note
///
/// Similar to `Align` but uses distance-weighted averaging for smoother
/// gradients. Good for smoke, water, and gooey substances.
Viscosity {
/// Interaction radius.
radius: f32,
/// Viscosity strength (higher = thicker fluid).
strength: f32,
},
/// Density-based repulsion (SPH-style pressure).
///
/// **Requires spatial hashing.** Particles in crowded areas get pushed
/// outward. Creates incompressible fluid behavior where particles spread
/// to fill space evenly.
///
/// # Fields
///
/// - `radius` - Kernel radius for density estimation
/// - `strength` - Pressure force magnitude
/// - `target_density` - Desired neighbor count (particles push when above this)
///
/// # Example
///
/// ```ignore
/// .with_spatial_config(0.15, 32)
/// .with_rule(Rule::Pressure {
/// radius: 0.1,
/// strength: 2.0,
/// target_density: 8.0, // Comfortable with ~8 neighbors
/// })
/// ```
///
/// # Physics Note
///
/// This is a simplified SPH pressure. For realistic fluids, combine with
/// `Viscosity` and `Gravity`.
Pressure {
/// Kernel radius for density calculation.
radius: f32,
/// Pressure force strength.
strength: f32,
/// Target neighbor density (pushes when exceeded).
target_density: f32,
},
/// Charge-based attraction and repulsion (magnetism/electrostatics).
///
/// **Requires spatial hashing.** Particles attract or repel based on
/// their `particle_type` field acting as charge polarity. Same types
/// repel, different types attract (or vice versa).
///
/// # Fields
///
/// - `radius` - Interaction range
/// - `strength` - Force magnitude
/// - `same_repel` - If true, same types repel; if false, same types attract
///
/// # Example
///
/// ```ignore
/// // Classic magnetism: opposites attract
/// .with_spatial_config(0.2, 32)
/// .with_rule(Rule::Magnetism {
/// radius: 0.3,
/// strength: 1.5,
/// same_repel: true, // Same charge repels
/// })
/// ```
///
/// # Usage
///
/// Set `particle_type` to 0 or 1 for two polarities. Particles with
/// type 0 and type 1 will attract (if `same_repel: true`), while
/// particles with matching types will repel.
Magnetism {
/// Interaction radius.
radius: f32,
/// Force strength.
strength: f32,
/// If true, same types repel and opposites attract.
same_repel: bool,
},
/// Surface tension keeping fluid blobs together.
///
/// **Requires spatial hashing.** Particles with fewer neighbors (at the
/// edge of a group) get pulled toward the center of mass of their
/// neighbors. Creates cohesive fluid blobs that resist dispersing.
///
/// # Fields
///
/// - `radius` - Neighbor detection radius
/// - `strength` - Pull strength toward center
/// - `threshold` - Neighbor count below which tension applies
///
/// # Example
///
/// ```ignore
/// .with_spatial_config(0.15, 32)
/// .with_rule(Rule::SurfaceTension {
/// radius: 0.1,
/// strength: 2.0,
/// threshold: 8.0, // Apply tension when < 8 neighbors
/// })
/// ```
SurfaceTension {
/// Neighbor detection radius.
radius: f32,
/// Tension strength.
strength: f32,
/// Apply when neighbor count is below this.
threshold: f32,
},
/// Smooth steering-based avoidance.
///
/// **Requires spatial hashing.** Unlike `Separate` which pushes directly
/// away, this steers particles to flow around obstacles smoothly. Better
/// for flocking and crowd simulation.
///
/// # Fields
///
/// - `radius` - Detection distance
/// - `strength` - Avoidance steering force
///
/// # Example
///
/// ```ignore
/// .with_spatial_config(0.15, 32)
/// .with_rule(Rule::Avoid {
/// radius: 0.1,
/// strength: 3.0,
/// })
/// ```
Avoid {
/// Detection radius.
radius: f32,
/// Steering strength.
strength: f32,
},
/// Separation: steer away from nearby neighbors.
///
/// **Requires spatial hashing.** Part of classic boids algorithm.
/// Particles avoid crowding by steering away from neighbors.
///
/// # Fields
///
/// - `radius` - Detection distance
/// - `strength` - Separation force
///
/// # Example
///
/// ```ignore
/// .with_spatial_config(0.15, 32)
/// .with_rule(Rule::Separate {
/// radius: 0.05, // Personal space
/// strength: 2.0,
/// })
/// ```
Separate {
/// Detection radius.
radius: f32,
/// Separation strength.
strength: f32,
},
/// Cohesion: steer toward center of nearby neighbors.
///
/// **Requires spatial hashing.** Part of classic boids algorithm.
/// Particles steer toward the average position of their neighbors.
///
/// # Fields
///
/// - `radius` - Detection distance
/// - `strength` - Cohesion force
///
/// # Example
///
/// ```ignore
/// .with_spatial_config(0.15, 32)
/// .with_rule(Rule::Cohere {
/// radius: 0.15, // Flock awareness range
/// strength: 1.0,
/// })
/// ```
Cohere {
/// Detection radius.
radius: f32,
/// Cohesion strength.
strength: f32,
},
/// Alignment: match velocity with nearby neighbors.
///
/// **Requires spatial hashing.** Part of classic boids algorithm.
/// Particles steer to match the average velocity of neighbors.
///
/// # Fields
///
/// - `radius` - Detection distance
/// - `strength` - Alignment force
///
/// # Example
///
/// ```ignore
/// .with_spatial_config(0.15, 32)
/// .with_rule(Rule::Align {
/// radius: 0.1,
/// strength: 1.5,
/// })
/// ```
Align {
/// Detection radius.
radius: f32,
/// Alignment strength.
strength: f32,
},
/// Random wandering force for organic movement.
///
/// Applies a pseudo-random force that changes over time.
/// Each particle gets its own random direction based on index and time.
///
/// # Fields
///
/// - `strength` - Force magnitude
/// - `frequency` - How fast direction changes (higher = more jittery)
///
/// # Example
///
/// ```ignore
/// Rule::Wander {
/// strength: 0.5,
/// frequency: 100.0, // Smooth wandering
/// }
///
/// Rule::Wander {
/// strength: 0.3,
/// frequency: 500.0, // Jittery movement
/// }
/// ```
Wander {
/// Force magnitude.
strength: f32,
/// Direction change rate (higher = jittery).
frequency: f32,
},
/// Clamp velocity magnitude to min/max bounds.
///
/// Prevents particles from stopping completely or moving too fast.
/// Applied after other forces, before drag.
///
/// # Fields
///
/// - `min` - Minimum speed (use 0.0 for no minimum)
/// - `max` - Maximum speed
///
/// # Example
///
/// ```ignore
/// Rule::SpeedLimit {
/// min: 0.5, // Always moving
/// max: 3.0, // But not too fast
/// }
///
/// Rule::SpeedLimit {
/// min: 0.0, // Can stop
/// max: 10.0, // Hard speed cap
/// }
/// ```
SpeedLimit {
/// Minimum speed (0.0 for no minimum).
min: f32,
/// Maximum speed.
max: f32,
},
/// Raw WGSL code for custom behavior.
///
/// For advanced users who need behavior not covered by built-in rules.
/// The code runs in the compute shader with access to:
///
/// - `p` - Current particle (read/write)
/// - `index` - Particle index (`u32`)
/// - `uniforms.time` - Elapsed time (`f32`)
/// - `uniforms.delta_time` - Frame delta time (`f32`)
///
/// # Example
///
/// ```ignore
/// Rule::Custom(r#"
/// // Oscillate Y velocity based on time
/// p.velocity.y += sin(uniforms.time * 2.0) * 0.1;
///
/// // Color based on speed
/// let speed = length(p.velocity);
/// p.color = vec3<f32>(speed, 0.5, 1.0 - speed);
/// "#.to_string())
/// ```
///
/// # Note
///
/// Custom rules don't have access to neighbor data. For neighbor-aware
/// custom behavior, use [`Rule::NeighborCustom`].
Custom(String),
/// Raw WGSL code that runs inside the neighbor iteration loop.
///
/// **Requires spatial hashing.** For advanced users who need custom
/// particle-particle interactions not covered by built-in rules.
///
/// # Available Variables
///
/// Inside your code, these variables are available:
///
/// - `p` - Current particle (read/write)
/// - `other` - Neighbor particle (read-only)
/// - `neighbor_dist` - Distance to neighbor (`f32`)
/// - `neighbor_dir` - Unit vector from neighbor to self (`vec3<f32>`)
/// - `neighbor_pos` - Neighbor position (`vec3<f32>`)
/// - `neighbor_vel` - Neighbor velocity (`vec3<f32>`)
/// - `index` - Current particle index (`u32`)
/// - `other_idx` - Neighbor particle index (`u32`)
/// - `uniforms.time` - Elapsed time (`f32`)
/// - `uniforms.delta_time` - Frame delta time (`f32`)
///
/// # Example: Magnetic attraction
///
/// ```ignore
/// .with_spatial_config(0.3, 32)
/// .with_rule(Rule::NeighborCustom(r#"
/// if neighbor_dist < 0.2 && neighbor_dist > 0.01 {
/// // Inverse-square attraction
/// let force = 0.5 / (neighbor_dist * neighbor_dist);
/// p.velocity -= neighbor_dir * force * uniforms.delta_time;
/// }
/// "#.into()))
/// ```
///
/// # Example: Color blending with neighbors
///
/// ```ignore
/// .with_rule(Rule::NeighborCustom(r#"
/// if neighbor_dist < 0.1 {
/// // Blend colors with nearby particles
/// let blend = 0.1 * (1.0 - neighbor_dist / 0.1);
/// p.color = mix(p.color, other.color, blend * uniforms.delta_time);
/// }
/// "#.into()))
/// ```
///
/// # Example: Type-based interactions
///
/// ```ignore
/// .with_rule(Rule::NeighborCustom(r#"
/// // Red particles attract blue, blue repels red
/// if p.particle_type == 0u && other.particle_type == 1u {
/// if neighbor_dist < 0.3 {
/// p.velocity -= neighbor_dir * 2.0 * uniforms.delta_time;
/// }
/// }
/// if p.particle_type == 1u && other.particle_type == 0u {
/// if neighbor_dist < 0.2 {
/// p.velocity += neighbor_dir * 3.0 * uniforms.delta_time;
/// }
/// }
/// "#.into()))
/// ```
///
/// # Performance Note
///
/// This code runs once for every nearby particle pair. Keep it efficient!
/// Complex calculations here multiply by neighbor count.
NeighborCustom(String),
/// Custom collision response with user-defined WGSL code.
///
/// **Requires spatial hashing.** When particles are within `radius` of each
/// other, executes your custom WGSL code. This is the power-user version
/// of [`Rule::Collide`] for implementing custom collision physics.
///
/// # Fields
///
/// - `radius` - Collision distance (code only runs when closer than this)
/// - `response` - WGSL code to execute on collision
///
/// # Available Variables
///
/// Inside your code, these variables are available:
///
/// - `p` - Current particle (read/write)
/// - `other` - Colliding particle (read-only)
/// - `neighbor_dist` - Distance to neighbor (`f32`)
/// - `neighbor_dir` - Unit vector from neighbor toward self (`vec3<f32>`)
/// - `neighbor_pos` - Neighbor position (`vec3<f32>`)
/// - `neighbor_vel` - Neighbor velocity (`vec3<f32>`)
/// - `overlap` - Penetration depth: `radius - neighbor_dist` (`f32`)
/// - `rel_vel` - Relative velocity along collision normal (`f32`, positive = approaching)
/// - `uniforms.delta_time` - Frame delta time (`f32`)
///
/// # Example: Sticky collision
///
/// ```ignore
/// .with_spatial_config(0.1, 32)
/// .with_rule(Rule::OnCollision {
/// radius: 0.05,
/// response: r#"
/// // Average velocities on collision (perfectly inelastic)
/// let avg_vel = (p.velocity + neighbor_vel) * 0.5;
/// p.velocity = avg_vel;
/// // Separate overlapping particles
/// p.position += neighbor_dir * overlap * 0.5;
/// "#.into(),
/// })
/// ```
///
/// # Example: Explosive collision
///
/// ```ignore
/// .with_rule(Rule::OnCollision {
/// radius: 0.05,
/// response: r#"
/// // Explode apart on collision
/// p.velocity += neighbor_dir * 5.0;
/// p.color = vec3<f32>(1.0, 0.5, 0.0); // Flash orange
/// "#.into(),
/// })
/// ```
///
/// # Example: Type-dependent collision
///
/// ```ignore
/// .with_rule(Rule::OnCollision {
/// radius: 0.04,
/// response: r#"
/// if p.particle_type != other.particle_type {
/// // Different types bounce hard
/// p.velocity += neighbor_dir * rel_vel * 2.0;
/// } else {
/// // Same types stick together
/// p.velocity = mix(p.velocity, neighbor_vel, 0.1);
/// }
/// "#.into(),
/// })
/// ```
OnCollision {
/// Collision distance threshold.
radius: f32,
/// WGSL code to execute when particles collide.
response: String,
},
/// Oscillator synchronization via field coupling (Kuramoto model).
///
/// Each particle has an internal phase that advances over time. When the
/// phase exceeds 2π, the particle "fires" (emits to field, runs callback,
/// resets phase). Particles detect nearby firing through the field and
/// adjust their phase to synchronize.
///
/// This implements the Kuramoto model for coupled oscillators, which
/// describes synchronization in fireflies, neurons, pacemaker cells,
/// applause, and many other natural phenomena.
///
/// # Fields
///
/// - `phase_field` - Name of the particle field storing phase (must be `f32`)
/// - `frequency` - Base oscillation frequency in Hz (cycles per second)
/// - `field` - Field index to emit to and read from
/// - `emit_amount` - How much to deposit to field when firing
/// - `coupling` - How strongly to adjust phase when detecting neighbors (0.0-1.0)
/// - `detection_threshold` - Minimum field value to trigger coupling
/// - `on_fire` - Optional WGSL code to run when the oscillator fires
///
/// # Available Variables in `on_fire`
///
/// - `p` - Current particle (read/write)
/// - `uniforms.time`, `uniforms.delta_time` - Time values
///
/// # Example: Firefly synchronization
///
/// ```ignore
/// #[derive(Particle)]
/// struct Firefly {
/// position: Vec3,
/// velocity: Vec3,
/// phase: f32, // Oscillator phase
/// brightness: f32, // For visual flash
/// }
///
/// .with_field("light", FieldConfig::new(48).with_decay(0.85))
/// .with_rule(Rule::Sync {
/// phase_field: "phase".into(),
/// frequency: 1.0,
/// field: 0,
/// emit_amount: 0.5,
/// coupling: 0.3,
/// detection_threshold: 0.1,
/// on_fire: Some(r#"
/// p.brightness = 1.0;
/// p.color = vec3<f32>(1.0, 1.0, 0.5);
/// "#.into()),
/// })
/// ```
///
/// # Example: Neuron firing
///
/// ```ignore
/// .with_rule(Rule::Sync {
/// phase_field: "membrane_potential".into(),
/// frequency: 2.0, // 2 Hz base firing rate
/// field: 0,
/// emit_amount: 0.8,
/// coupling: 0.5,
/// detection_threshold: 0.2,
/// on_fire: Some(r#"
/// // Action potential!
/// p.color = vec3<f32>(1.0, 0.3, 0.1);
/// // Could trigger downstream effects here
/// "#.into()),
/// })
/// ```
///
/// # The Math
///
/// Phase advances: `dφ/dt = ω + K * sin(φ/2) * field_value`
///
/// Where `ω` is frequency and `K` is coupling. The `sin(φ/2)` term means
/// particles respond most strongly when halfway through their cycle.
Sync {
/// Name of the particle field storing phase (f32, 0 to 2π).
phase_field: String,
/// Base oscillation frequency in Hz.
frequency: f32,
/// Field index to use for communication.
field: u32,
/// Amount to deposit to field when firing.
emit_amount: f32,
/// Coupling strength for phase adjustment (0.0-1.0 typical).
coupling: f32,
/// Minimum field value to trigger phase adjustment.
detection_threshold: f32,
/// Optional WGSL code to execute when the oscillator fires.
on_fire: Option<String>,
},
/// Spring forces between bonded particles.
///
/// Applies spring physics to particles connected by stored bond indices.
/// Each particle stores indices of bonded neighbors in `u32` fields, and
/// this rule applies spring forces (Hooke's law + damping) to maintain
/// rest lengths.
///
/// This enables cloth, ropes, soft bodies, and molecular simulations
/// without requiring special bond infrastructure.
///
/// # Fields
///
/// - `bonds` - Names of particle fields storing bond indices (e.g., `["bond_left", "bond_right"]`)
/// - `stiffness` - Spring constant (higher = stiffer, typical: 50-1000)
/// - `damping` - Velocity damping along spring (prevents oscillation, typical: 5-20)
/// - `rest_length` - Natural spring length (when stretch = 0)
/// - `max_stretch` - Optional maximum stretch ratio before extra-stiff correction (e.g., 1.3 = 130%)
///
/// # Example: Cloth
///
/// ```ignore
/// #[derive(Particle)]
/// struct ClothPoint {
/// position: Vec3,
/// velocity: Vec3,
/// bond_left: u32, // Index of left neighbor (u32::MAX = none)
/// bond_right: u32,
/// bond_up: u32,
/// bond_down: u32,
/// }
///
/// // In spawner, set up bond indices based on grid position
///
/// .with_rule(Rule::BondSprings {
/// bonds: vec!["bond_left", "bond_right", "bond_up", "bond_down"],
/// stiffness: 800.0,
/// damping: 15.0,
/// rest_length: 0.05,
/// max_stretch: Some(1.3),
/// })
/// ```
///
/// # Bond Index Convention
///
/// Use `u32::MAX` (4294967295) as a sentinel for "no bond". The rule
/// automatically skips these.
///
/// # Physics Note
///
/// The force applied is:
/// - Spring: `F = stiffness * (distance - rest_length)`
/// - Damping: `F += damping * relative_velocity_along_spring`
/// - Over-stretch: When `distance/rest_length > max_stretch`, additional
/// corrective force kicks in to prevent runaway stretching.
BondSprings {
/// Particle field names containing bond indices.
bonds: Vec<&'static str>,
/// Spring stiffness (Hooke's constant).
stiffness: f32,
/// Damping coefficient.
damping: f32,
/// Rest length (natural spring length).
rest_length: f32,
/// Maximum stretch ratio before extra stiffening (e.g., 1.3 = 130%).
max_stretch: Option<f32>,
},
/// Spring chain using sequential particle indices.
///
/// Automatically bonds particle `i` to particles `i-1` and `i+1`.
/// No bond fields needed - just spawn particles in order!
///
/// Perfect for ropes, chains, tentacles, snakes, and hair.
///
/// # Fields
///
/// - `stiffness` - Spring constant (higher = stiffer)
/// - `damping` - Velocity damping along spring
/// - `rest_length` - Natural length between particles
/// - `max_stretch` - Optional maximum stretch ratio
///
/// # Example: Rope
///
/// ```ignore
/// Simulation::<RopePoint>::new()
/// .with_particle_count(50) // 50-segment rope
/// .with_spawner(|i, _| RopePoint {
/// position: Vec3::new(0.0, 0.5 - i as f32 * 0.02, 0.0),
/// velocity: Vec3::ZERO,
/// pinned: if i == 0 { 1.0 } else { 0.0 },
/// })
/// .with_rule(Rule::ChainSprings {
/// stiffness: 500.0,
/// damping: 10.0,
/// rest_length: 0.02,
/// max_stretch: Some(1.2),
/// })
/// .with_rule(Rule::Gravity(5.0))
/// .run();
/// ```
ChainSprings {
/// Spring stiffness.
stiffness: f32,
/// Damping coefficient.
damping: f32,
/// Rest length between particles.
rest_length: f32,
/// Maximum stretch ratio.
max_stretch: Option<f32>,
},
/// Radial spring structure with center hub.
///
/// Particle 0 is the center hub. All other particles connect to the center
/// AND to their sequential neighbors, forming a wheel/web structure.
///
/// Great for spider webs, wheels, radial explosions, and soft body blobs.
///
/// # Fields
///
/// - `hub_stiffness` - Spring strength to center hub
/// - `ring_stiffness` - Spring strength between ring neighbors
/// - `damping` - Velocity damping
/// - `hub_length` - Rest length to center
/// - `ring_length` - Rest length between ring neighbors
///
/// # Example: Spider Web
///
/// ```ignore
/// .with_rule(Rule::RadialSprings {
/// hub_stiffness: 200.0,
/// ring_stiffness: 100.0,
/// damping: 5.0,
/// hub_length: 0.3,
/// ring_length: 0.1,
/// })
/// ```
RadialSprings {
/// Spring stiffness to center hub.
hub_stiffness: f32,
/// Spring stiffness between ring neighbors.
ring_stiffness: f32,
/// Damping coefficient.
damping: f32,
/// Rest length to center hub.
hub_length: f32,
/// Rest length between ring neighbors.
ring_length: f32,
},
/// Springs applied to all neighbors in the adjacency buffer.
///
/// Creates dynamic soft-body behavior where nearby particles form temporary
/// spring connections based on the pre-computed adjacency buffer.
///
/// Requires adjacency to be enabled in the simulation config.
///
/// # Fields
///
/// - `stiffness` - Spring constant (Hooke's law)
/// - `damping` - Velocity damping along spring direction
/// - `rest_length` - Natural spring length
/// - `max_stretch` - Optional maximum stretch ratio before extra stiffening
///
/// # Example
///
/// ```ignore
/// .with_rule(Rule::AdjacencySprings {
/// stiffness: 200.0,
/// damping: 10.0,
/// rest_length: 0.1,
/// max_stretch: Some(1.5),
/// })
/// ```
AdjacencySprings {
/// Spring stiffness (Hooke's constant).
stiffness: f32,
/// Damping coefficient.
damping: f32,
/// Rest length (natural spring length).
rest_length: f32,
/// Maximum stretch ratio before extra stiffening.
max_stretch: Option<f32>,
},
/// Buoyancy force based on height.
///
/// Particles below `surface_y` experience upward force proportional to
/// depth. Creates floating/sinking behavior for water simulations.
///
/// # Fields
///
/// - `surface_y` - Y coordinate of the water surface
/// - `density` - Buoyancy strength (1.0 = neutral, >1 = floats, <1 = sinks)
///
/// # Example
///
/// ```ignore
/// .with_rule(Rule::Gravity(9.8))
/// .with_rule(Rule::Buoyancy {
/// surface_y: 0.0,
/// density: 1.2, // Slightly buoyant - floats up
/// })
/// ```
Buoyancy {
/// Y coordinate of the surface.
surface_y: f32,
/// Buoyancy factor (>1 floats, <1 sinks).
density: f32,
},
/// Ground friction that slows particles near a surface.
///
/// Particles below `ground_y` experience velocity damping, simulating
/// friction with the ground. Useful for particles that roll/slide.
///
/// # Fields
///
/// - `ground_y` - Y coordinate of the ground plane
/// - `strength` - Friction coefficient (0-1, higher = more friction)
/// - `threshold` - Distance above ground where friction starts
///
/// # Example
///
/// ```ignore
/// .with_rule(Rule::Gravity(9.8))
/// .with_rule(Rule::Friction {
/// ground_y: -1.0,
/// strength: 0.8,
/// threshold: 0.1,
/// })
/// ```
Friction {
/// Y coordinate of the ground.
ground_y: f32,
/// Friction strength (0-1).
strength: f32,
/// Distance above ground where friction applies.
threshold: f32,
},
/// Directional wind force with optional turbulence.
///
/// Applies a constant directional force plus optional noise-based
/// turbulence for realistic wind effects.
///
/// # Fields
///
/// - `direction` - Wind direction (will be normalized)
/// - `strength` - Base wind force
/// - `turbulence` - Random variation (0 = steady, 1 = very gusty)
///
/// # Example
///
/// ```ignore
/// // Gentle breeze from the left
/// Rule::Wind {
/// direction: Vec3::new(1.0, 0.0, 0.0),
/// strength: 2.0,
/// turbulence: 0.3,
/// }
///
/// // Strong gusty wind
/// Rule::Wind {
/// direction: Vec3::new(1.0, 0.2, 0.5),
/// strength: 5.0,
/// turbulence: 0.8,
/// }
/// ```
Wind {
/// Wind direction (normalized internally).
direction: Vec3,
/// Wind strength.
strength: f32,
/// Turbulence factor (0-1).
turbulence: f32,
},
/// Follow a 3D field as a flow/current.
///
/// Particles are pushed in the direction of the field gradient,
/// creating river-like currents or atmospheric flows.
///
/// **Requires a field** defined with `.with_field()`.
///
/// # Fields
///
/// - `field` - Name of the field to follow
/// - `strength` - Flow strength
///
/// # Example
///
/// ```ignore
/// // Define a swirling flow field
/// .with_field("flow", 32, |x, y, z| {
/// (x * x + z * z).sqrt() // Distance from Y axis
/// })
/// .with_rule(Rule::Current {
/// field: "flow",
/// strength: 2.0,
/// })
/// ```
///
/// # Note
///
/// The current follows the field's gradient (direction of increasing values).
/// For circular flows, use a field based on angle; for streams, use
/// directional gradients.
Current {
/// Name of the field to follow.
field: &'static str,
/// Current strength.
strength: f32,
},
/// Respawn particles that fall below a threshold.
///
/// When a particle's Y position drops below `threshold_y`, it gets
/// teleported back to `spawn_y` with reset velocity. Perfect for
/// fountains, rain, and endless falling effects.
///
/// # Fields
///
/// - `threshold_y` - Y position that triggers respawn
/// - `spawn_y` - Y position to respawn at
/// - `reset_velocity` - Whether to zero velocity on respawn
///
/// # Example: Rain
///
/// ```ignore
/// .with_rule(Rule::Gravity(5.0))
/// .with_rule(Rule::RespawnBelow {
/// threshold_y: -1.0,
/// spawn_y: 1.0,
/// reset_velocity: true,
/// })
/// ```
///
/// # Example: Fountain (keep momentum)
///
/// ```ignore
/// .with_rule(Rule::RespawnBelow {
/// threshold_y: -0.5,
/// spawn_y: 0.0,
/// reset_velocity: false, // Keep horizontal velocity
/// })
/// ```
RespawnBelow {
/// Y position that triggers respawn.
threshold_y: f32,
/// Y position to respawn at.
spawn_y: f32,
/// Whether to reset velocity on respawn.
reset_velocity: bool,
},
/// Type-filtered wrapper for neighbor rules.
///
/// Wraps a neighbor-based rule to only apply when particle types match.
/// The inner rule only executes for matching type combinations.
///
/// # Fields
///
/// - `self_type` - Type of particle this rule applies to
/// - `other_type` - Type of neighbors to consider (`None` = all types)
/// - `rule` - The wrapped neighbor rule
///
/// # Example
///
/// ```ignore
/// // Prey only flocks with other prey
/// Rule::Typed {
/// self_type: Species::Prey.into(),
/// other_type: Some(Species::Prey.into()),
/// rule: Box::new(Rule::Cohere { radius: 0.15, strength: 1.0 }),
/// }
///
/// // Predators collide with everyone
/// Rule::Typed {
/// self_type: Species::Predator.into(),
/// other_type: None, // All types
/// rule: Box::new(Rule::Collide { radius: 0.05, restitution: 0.8 }),
/// }
/// ```
Typed {
/// Type of particle this rule applies to.
self_type: u32,
/// Type of neighbors to interact with (`None` = any).
other_type: Option<u32>,
/// The wrapped rule (must be a neighbor rule).
rule: Box<Rule>,
},
/// Change particle type on proximity to trigger type.
///
/// **Requires spatial hashing.** When a particle of `from_type` is
/// within `radius` of a particle of `trigger_type`, it may convert
/// to `to_type` based on `probability`.
///
/// # Fields
///
/// - `from_type` - Type that can be converted
/// - `trigger_type` - Type that triggers conversion
/// - `to_type` - Result type after conversion
/// - `radius` - Contact distance
/// - `probability` - Chance per neighbor per frame (0.0 to 1.0)
///
/// # Example: Infection
///
/// ```ignore
/// // Healthy → Infected on contact
/// Rule::Convert {
/// from_type: Health::Healthy.into(),
/// trigger_type: Health::Infected.into(),
/// to_type: Health::Infected.into(),
/// radius: 0.08,
/// probability: 0.15, // 15% chance per contact
/// }
///
/// // Self-triggered recovery (use same type with tiny radius)
/// Rule::Convert {
/// from_type: Health::Infected.into(),
/// trigger_type: Health::Infected.into(),
/// to_type: Health::Recovered.into(),
/// radius: 0.01,
/// probability: 0.002,
/// }
/// ```
Convert {
/// Type that can be converted.
from_type: u32,
/// Type that triggers conversion.
trigger_type: u32,
/// Result type.
to_type: u32,
/// Contact distance.
radius: f32,
/// Conversion probability (0.0-1.0).
probability: f32,
},
/// Steer toward nearest particle of target type.
///
/// **Requires spatial hashing.** Finds the closest particle of
/// `target_type` within `radius` and steers toward it.
/// Unlike [`Rule::Cohere`], this targets the *nearest* rather than averaging.
///
/// # Fields
///
/// - `self_type` - Type of chaser
/// - `target_type` - Type to chase
/// - `radius` - Vision range
/// - `strength` - Pursuit force
///
/// # Example
///
/// ```ignore
/// Rule::Chase {
/// self_type: Species::Predator.into(),
/// target_type: Species::Prey.into(),
/// radius: 0.4, // Can see prey within 0.4 units
/// strength: 4.0, // Strong pursuit
/// }
/// ```
Chase {
/// Type of particle that chases.
self_type: u32,
/// Type of particle to chase.
target_type: u32,
/// Vision radius.
radius: f32,
/// Pursuit strength.
strength: f32,
},
/// Steer away from nearest particle of threat type.
///
/// **Requires spatial hashing.** Finds the closest particle of
/// `threat_type` within `radius` and steers away from it.
/// Unlike [`Rule::Separate`], this flees from the *nearest* threat only.
///
/// # Fields
///
/// - `self_type` - Type that evades
/// - `threat_type` - Type to flee from
/// - `radius` - Awareness range
/// - `strength` - Evasion force
///
/// # Example
///
/// ```ignore
/// Rule::Evade {
/// self_type: Species::Prey.into(),
/// threat_type: Species::Predator.into(),
/// radius: 0.25, // Detect predators at 0.25 units
/// strength: 6.0, // Flee faster than predator chases
/// }
/// ```
Evade {
/// Type of particle that evades.
self_type: u32,
/// Type of particle to flee from.
threat_type: u32,
/// Awareness radius.
radius: f32,
/// Evasion strength.
strength: f32,
},
/// Increment particle age each frame.
///
/// Adds `delta_time` to the particle's `age` field every frame.
/// Use with [`Rule::Lifetime`] to kill particles after a duration,
/// or access `p.age` in custom rules for age-based effects.
///
/// # Example
///
/// ```ignore
/// .with_rule(Rule::Age)
/// .with_rule(Rule::Lifetime(2.0)) // Die after 2 seconds
/// ```
///
/// # Custom age-based effects
///
/// ```ignore
/// .with_rule(Rule::Age)
/// .with_rule(Rule::Custom(r#"
/// // Fade out as particle ages
/// let fade = 1.0 - (p.age / 2.0);
/// p.color = p.color * fade;
/// "#.to_string()))
/// ```
Age,
/// Kill particles after a duration.
///
/// When a particle's `age` exceeds the specified duration, its `alive`
/// field is set to 0. Dead particles are not simulated or rendered.
///
/// # Parameters
///
/// - `seconds` - Maximum particle lifetime
///
/// # Example
///
/// ```ignore
/// .with_rule(Rule::Age) // Must age particles first
/// .with_rule(Rule::Lifetime(3.0)) // Die after 3 seconds
/// ```
///
/// # Note
///
/// This rule requires [`Rule::Age`] to be active, otherwise particles
/// never age and will never die.
Lifetime(f32),
/// Fade out particle color over its lifetime.
///
/// Multiplies particle color by `(1.0 - age / duration)`, creating a
/// smooth fade to black as the particle ages.
///
/// # Parameters
///
/// - `duration` - Time in seconds over which to fade (should match Lifetime)
///
/// # Example
///
/// ```ignore
/// .with_rule(Rule::Age)
/// .with_rule(Rule::FadeOut(2.0)) // Fade over 2 seconds
/// .with_rule(Rule::Lifetime(2.0)) // Die at 2 seconds
/// ```
///
/// # Note
///
/// Requires [`Rule::Age`] to be active. Works by dimming RGB values,
/// not alpha (particles render as additive blended points).
FadeOut(f32),
/// Shrink particle scale over its lifetime.
///
/// Sets particle scale to `1.0 - (age / duration)`, shrinking from
/// full size to zero as the particle ages.
///
/// # Parameters
///
/// - `duration` - Time in seconds over which to shrink (should match Lifetime)
///
/// # Example
///
/// ```ignore
/// .with_rule(Rule::Age)
/// .with_rule(Rule::ShrinkOut(2.0)) // Shrink over 2 seconds
/// .with_rule(Rule::Lifetime(2.0)) // Die at 2 seconds
/// ```
///
/// # Note
///
/// Requires [`Rule::Age`] to be active.
ShrinkOut(f32),
/// Lerp particle color from start to end over its lifetime.
///
/// Smoothly transitions particle color based on age. At age 0, color
/// is `start`. At `duration`, color is `end`.
///
/// # Fields
///
/// - `start` - Color at birth (RGB, 0.0-1.0)
/// - `end` - Color at death (RGB, 0.0-1.0)
/// - `duration` - Transition time in seconds (should match Lifetime)
///
/// # Example
///
/// ```ignore
/// .with_rule(Rule::Age)
/// .with_rule(Rule::ColorOverLife {
/// start: Vec3::new(1.0, 1.0, 0.0), // Yellow
/// end: Vec3::new(1.0, 0.0, 0.0), // Red
/// duration: 2.0,
/// })
/// .with_rule(Rule::Lifetime(2.0))
/// ```
///
/// # Note
///
/// Requires [`Rule::Age`] to be active. Overwrites color each frame,
/// so place after any other color modifications.
ColorOverLife {
/// Color at age 0.
start: Vec3,
/// Color at max age.
end: Vec3,
/// Transition duration in seconds.
duration: f32,
},
/// Color particles based on their speed.
///
/// Maps velocity magnitude to a color gradient. Slow particles get
/// `slow_color`, fast particles get `fast_color`. Very common effect
/// for visualizing flow and energy.
///
/// # Fields
///
/// - `slow_color` - Color at zero velocity
/// - `fast_color` - Color at max_speed
/// - `max_speed` - Speed at which color is fully `fast_color`
///
/// # Example
///
/// ```ignore
/// Rule::ColorBySpeed {
/// slow_color: Vec3::new(0.2, 0.3, 0.8), // Blue when slow
/// fast_color: Vec3::new(1.0, 0.9, 0.5), // Yellow when fast
/// max_speed: 2.0,
/// }
/// ```
ColorBySpeed {
/// Color at zero speed.
slow_color: Vec3,
/// Color at max speed.
fast_color: Vec3,
/// Speed for full fast_color.
max_speed: f32,
},
/// Color particles based on their age.
///
/// Maps age to a color gradient. Similar to `ColorOverLife` but uses
/// a max_age parameter instead of duration, and won't reset.
///
/// # Fields
///
/// - `young_color` - Color at age 0
/// - `old_color` - Color at max_age
/// - `max_age` - Age at which color is fully `old_color`
///
/// # Example
///
/// ```ignore
/// .with_rule(Rule::Age)
/// .with_rule(Rule::ColorByAge {
/// young_color: Vec3::new(1.0, 1.0, 1.0), // White when young
/// old_color: Vec3::new(1.0, 0.3, 0.1), // Red when old
/// max_age: 3.0,
/// })
/// ```
ColorByAge {
/// Color at age 0.
young_color: Vec3,
/// Color at max age.
old_color: Vec3,
/// Age for full old_color.
max_age: f32,
},
/// Scale particles based on their speed.
///
/// Fast-moving particles become larger (or smaller). Creates visual
/// emphasis on motion and energy.
///
/// # Fields
///
/// - `min_scale` - Scale at zero velocity
/// - `max_scale` - Scale at max_speed
/// - `max_speed` - Speed at which scale is `max_scale`
///
/// # Example
///
/// ```ignore
/// // Fast particles get bigger
/// Rule::ScaleBySpeed {
/// min_scale: 0.5,
/// max_scale: 2.0,
/// max_speed: 3.0,
/// }
///
/// // Fast particles get smaller (motion blur feel)
/// Rule::ScaleBySpeed {
/// min_scale: 1.0,
/// max_scale: 0.3,
/// max_speed: 2.0,
/// }
/// ```
ScaleBySpeed {
/// Scale at zero speed.
min_scale: f32,
/// Scale at max speed.
max_scale: f32,
/// Speed for full max_scale.
max_speed: f32,
},
/// Probabilistic execution of custom WGSL code.
///
/// Runs the provided action with a given probability each frame.
/// Useful for random events like spontaneous death, mutation, color changes,
/// or any stochastic behavior.
///
/// # Fields
///
/// - `probability` - Chance per frame (0.0 to 1.0). Note: higher framerates
/// mean more rolls, so 0.01 at 60fps ≈ 0.6 triggers/second.
/// - `action` - WGSL code to execute when the roll succeeds.
///
/// # Available Variables
///
/// Same as [`Rule::Custom`]:
/// - `p` - Current particle (read/write)
/// - `index` - Particle index (`u32`)
/// - `uniforms.time`, `uniforms.delta_time` - Time values
/// - Field functions if fields are configured
///
/// # Example: Random death
///
/// ```ignore
/// Rule::Maybe {
/// probability: 0.001, // 0.1% chance per frame
/// action: r#"
/// p.alive = false;
/// "#.into(),
/// }
/// ```
///
/// # Example: Random color flash
///
/// ```ignore
/// Rule::Maybe {
/// probability: 0.02,
/// action: r#"
/// p.color = vec3<f32>(1.0, 0.0, 0.0); // Flash red
/// "#.into(),
/// }
/// ```
///
/// # Example: Spontaneous direction change
///
/// ```ignore
/// Rule::Maybe {
/// probability: 0.005,
/// action: r#"
/// // Random new direction (using position as seed)
/// let seed = p.position * 12.9898 + uniforms.time;
/// let rx = fract(sin(dot(seed.xy, vec2(12.9898, 78.233))) * 43758.5453);
/// let ry = fract(sin(dot(seed.yz, vec2(12.9898, 78.233))) * 43758.5453);
/// let rz = fract(sin(dot(seed.xz, vec2(12.9898, 78.233))) * 43758.5453);
/// p.velocity = normalize(vec3(rx, ry, rz) - 0.5) * length(p.velocity);
/// "#.into(),
/// }
/// ```
Maybe {
/// Probability of executing action (0.0 to 1.0).
probability: f32,
/// WGSL code to execute when probability check passes.
action: String,
},
/// Conditional action execution.
///
/// Evaluates a WGSL boolean condition and executes action if true.
/// The fundamental "when X, do Y" pattern for reactive particle behavior.
///
/// # Fields
///
/// - `condition` - WGSL boolean expression (must evaluate to `bool`)
/// - `action` - WGSL code to execute when condition is true
///
/// # Available Variables
///
/// Same as [`Rule::Custom`]:
/// - `p` - Current particle (read/write)
/// - `index` - Particle index (`u32`)
/// - `uniforms.time`, `uniforms.delta_time` - Time values
/// - Field functions if fields are configured
///
/// # Example: Low energy warning
///
/// ```ignore
/// Rule::Trigger {
/// condition: "p.energy < 0.2".into(),
/// action: r#"
/// p.color = vec3<f32>(1.0, 0.0, 0.0); // Flash red
/// "#.into(),
/// }
/// ```
///
/// # Example: Boundary reaction
///
/// ```ignore
/// Rule::Trigger {
/// condition: "p.position.y < -0.8".into(),
/// action: r#"
/// p.velocity.y = abs(p.velocity.y) * 1.5; // Bounce up hard
/// p.color = vec3<f32>(1.0, 1.0, 1.0);
/// "#.into(),
/// }
/// ```
///
/// # Example: Field-reactive behavior
///
/// ```ignore
/// Rule::Trigger {
/// condition: "field_read(0u, p.position) > 0.5".into(),
/// action: r#"
/// p.velocity *= 2.0; // Speed up in high-field regions
/// "#.into(),
/// }
/// ```
///
/// # Example: Compound conditions
///
/// ```ignore
/// Rule::Trigger {
/// condition: "p.age > 2.0 && p.energy < 0.3".into(),
/// action: r#"
/// p.state = 2u; // Transition to dying state
/// "#.into(),
/// }
/// ```
Trigger {
/// WGSL boolean expression (e.g., "p.energy < 0.1").
condition: String,
/// WGSL code to execute when condition is true.
action: String,
},
/// Periodic time-based action execution.
///
/// Executes action at regular intervals. Each particle fires independently
/// based on global time, with optional per-particle phase offset for
/// staggered timing.
///
/// # Fields
///
/// - `interval` - Time between executions in seconds
/// - `phase_field` - Optional particle field name for phase offset (creates staggered pulses)
/// - `action` - WGSL code to execute on each pulse
///
/// # Available Variables
///
/// Same as [`Rule::Custom`]:
/// - `p` - Current particle (read/write)
/// - `index` - Particle index (`u32`)
/// - `uniforms.time`, `uniforms.delta_time` - Time values
///
/// # Example: Heartbeat emission
///
/// ```ignore
/// Rule::Periodic {
/// interval: 0.5, // Every 0.5 seconds
/// phase_field: None,
/// action: r#"
/// field_write(0u, p.position, 1.0);
/// p.color = vec3<f32>(1.0, 0.5, 0.5);
/// "#.into(),
/// }
/// ```
///
/// # Example: Staggered pulses using phase field
///
/// ```ignore
/// // Particles pulse at same interval but offset by their phase
/// Rule::Periodic {
/// interval: 1.0,
/// phase_field: Some("phase".into()), // Uses p.phase for offset
/// action: r#"
/// p.brightness = 1.0;
/// "#.into(),
/// }
/// ```
///
/// # Example: Periodic spawning trigger
///
/// ```ignore
/// Rule::Periodic {
/// interval: 2.0,
/// phase_field: None,
/// action: r#"
/// p.should_spawn = 1u; // Flag for spawn system
/// "#.into(),
/// }
/// ```
Periodic {
/// Time between pulses in seconds.
interval: f32,
/// Optional particle field for phase offset (staggered timing).
phase_field: Option<String>,
/// WGSL code to execute on each pulse.
action: String,
},
/// Move toward higher or lower field values (chemotaxis/gradient following).
///
/// Samples the field gradient at each particle's position and applies
/// force in that direction. Classic for slime mold, bacteria following
/// nutrients, heat-seeking, or any gradient-based navigation.
///
/// # Fields
///
/// - `field` - Field index to sample
/// - `strength` - Force magnitude
/// - `ascending` - If true, move toward higher values; if false, toward lower
///
/// # How It Works
///
/// Samples field at particle position ± small offset to estimate gradient,
/// then applies force along that gradient direction.
///
/// # Example: Slime mold following pheromones
///
/// ```ignore
/// // Particles emit pheromones and follow the gradient
/// .with_field("pheromone", FieldConfig::new(64).with_decay(0.98))
/// .with_rule(Rule::Custom(r#"
/// field_write(0u, p.position, 0.1); // Emit pheromone
/// "#.into()))
/// .with_rule(Rule::Gradient {
/// field: 0,
/// strength: 2.0,
/// ascending: true, // Move toward higher pheromone
/// })
/// ```
///
/// # Example: Heat-seeking particles
///
/// ```ignore
/// Rule::Gradient {
/// field: 0, // Heat field
/// strength: 5.0,
/// ascending: true, // Move toward heat
/// }
/// ```
///
/// # Example: Flee from danger
///
/// ```ignore
/// Rule::Gradient {
/// field: 1, // Danger field
/// strength: 3.0,
/// ascending: false, // Move away from danger (descending)
/// }
/// ```
Gradient {
/// Field index to sample for gradient.
field: u32,
/// Force strength.
strength: f32,
/// If true, move toward higher values; if false, toward lower.
ascending: bool,
},
/// Smoothly interpolate a particle field toward a target value.
///
/// Exponential decay toward the target: `field = lerp(field, target, rate * dt)`.
/// Useful for equilibration, smooth transitions, relaxation dynamics.
///
/// # Fields
///
/// - `field` - Particle field name to interpolate (must be `f32`)
/// - `target` - Target value to approach
/// - `rate` - Interpolation speed (higher = faster approach)
///
/// # Example: Temperature equilibration
///
/// ```ignore
/// // Temperature relaxes toward ambient (0.5) over time
/// Rule::Lerp {
/// field: "temperature".into(),
/// target: 0.5,
/// rate: 2.0,
/// }
/// ```
///
/// # Example: Energy decay
///
/// ```ignore
/// Rule::Lerp {
/// field: "energy".into(),
/// target: 0.0,
/// rate: 0.5, // Slow decay
/// }
/// ```
///
/// # Example: Brightness fade
///
/// ```ignore
/// Rule::Lerp {
/// field: "brightness".into(),
/// target: 0.1, // Dim but not off
/// rate: 3.0,
/// }
/// ```
Lerp {
/// Particle field name to interpolate (f32).
field: String,
/// Target value to approach.
target: f32,
/// Interpolation rate (speed of approach).
rate: f32,
},
/// Classic boid flocking behavior (separation + cohesion + alignment).
///
/// **Requires spatial hashing.** Combines the three fundamental boid rules
/// into one convenient rule. For fine-grained control, use the individual
/// [`Rule::Separate`], [`Rule::Cohere`], and [`Rule::Align`] rules.
///
/// # Fields
///
/// - `radius` - Detection distance for all three behaviors
/// - `separation` - Strength of avoidance (prevent crowding)
/// - `cohesion` - Strength of attraction to flock center
/// - `alignment` - Strength of velocity matching
///
/// # Example: Basic boid flock
///
/// ```ignore
/// .with_spatial_config(0.2, 32)
/// .with_rule(Rule::Flock {
/// radius: 0.15,
/// separation: 2.0,
/// cohesion: 1.0,
/// alignment: 1.5,
/// })
/// .with_rule(Rule::SpeedLimit { min: 0.5, max: 2.0 })
/// ```
///
/// # Tuning Tips
///
/// - Higher separation → more spread out, less clumping
/// - Higher cohesion → tighter groups, may become too dense
/// - Higher alignment → smoother motion, more synchronized turns
/// - Balance is key: start with separation=2, cohesion=1, alignment=1.5
Flock {
/// Detection radius for all behaviors.
radius: f32,
/// Separation strength (avoid crowding).
separation: f32,
/// Cohesion strength (move toward center).
cohesion: f32,
/// Alignment strength (match velocity).
alignment: f32,
},
/// Conditional particle death.
///
/// Evaluates a WGSL condition and "kills" the particle if true by setting
/// a specified boolean field to false. Useful for lifecycle management,
/// particles leaving bounds, energy depletion, etc.
///
/// # Fields
///
/// - `condition` - WGSL boolean expression for when to die
/// - `field` - Particle field name to set false (typically "alive")
///
/// # Example: Die when out of energy
///
/// ```ignore
/// #[derive(Particle)]
/// struct Cell {
/// // ...
/// alive: bool,
/// energy: f32,
/// }
///
/// Rule::Die {
/// condition: "p.energy <= 0.0".into(),
/// field: "alive".into(),
/// }
/// ```
///
/// # Example: Die when old
///
/// ```ignore
/// Rule::Die {
/// condition: "p.age > 10.0".into(),
/// field: "alive".into(),
/// }
/// ```
///
/// # Example: Die when leaving bounds
///
/// ```ignore
/// Rule::Die {
/// condition: "length(p.position) > 2.0".into(),
/// field: "alive".into(),
/// }
/// ```
///
/// # Note
///
/// The particle isn't removed from simulation (that would require CPU
/// intervention). Instead, "dead" particles can be:
/// - Rendered invisible (check alive in color logic)
/// - Recycled (respawn at new position when alive == false)
/// - Ignored in interactions (check alive in neighbor rules)
Die {
/// WGSL boolean condition for death.
condition: String,
/// Particle field to set false (e.g., "alive").
field: String,
},
/// Finite state machine with conditional transitions.
///
/// Particles have a state (stored in a `u32` field) and transition between
/// states based on WGSL conditions. Useful for lifecycle stages, behavior
/// modes, or any discrete state-based logic.
///
/// # Fields
///
/// - `field` - Particle field storing state (must be `u32`)
/// - `transitions` - List of (from_state, to_state, condition) tuples
///
/// # Example: Simple lifecycle
///
/// ```ignore
/// #[derive(Particle)]
/// struct Cell {
/// // ...
/// state: u32, // 0=young, 1=mature, 2=old, 3=dead
/// age: f32,
/// }
///
/// Rule::State {
/// field: "state".into(),
/// transitions: vec![
/// (0, 1, "p.age > 2.0".into()), // young → mature
/// (1, 2, "p.age > 5.0".into()), // mature → old
/// (2, 3, "p.age > 8.0".into()), // old → dead
/// ],
/// }
/// ```
///
/// # Example: Behavior modes
///
/// ```ignore
/// // States: 0=idle, 1=hunting, 2=fleeing
/// Rule::State {
/// field: "behavior".into(),
/// transitions: vec![
/// (0, 1, "p.hunger > 0.7".into()), // idle → hunting
/// (0, 2, "p.threat_level > 0.5".into()), // idle → fleeing
/// (1, 0, "p.hunger < 0.3".into()), // hunting → idle
/// (2, 0, "p.threat_level < 0.2".into()), // fleeing → idle
/// ],
/// }
/// ```
///
/// # Note
///
/// - Transitions are evaluated in order; first matching transition wins
/// - Use separate [`Rule::Trigger`] rules to execute actions on state entry
/// - Combine with [`Rule::Custom`] to implement state-dependent behavior
State {
/// Particle field storing state (u32).
field: String,
/// Transitions: (from_state, to_state, condition).
transitions: Vec<(u32, u32, String)>,
},
/// Full-featured agent state machine.
///
/// A more powerful alternative to [`Rule::State`] that supports:
/// - Entry actions (run once when entering a state)
/// - Update actions (run every frame while in a state)
/// - Exit actions (run once when leaving a state)
/// - Priority-based transitions
/// - Optional state duration tracking
///
/// # Particle Requirements
///
/// Your particle must have:
/// - A `u32` field to store the current state (specified by `state_field`)
/// - A `u32` field to store the previous state for edge detection (`prev_state_field`)
/// - Optionally, a `f32` field to track time in current state (`state_timer_field`)
///
/// # Example: Predator behavior
///
/// ```ignore
/// #[derive(Particle, Clone)]
/// struct Predator {
/// position: Vec3,
/// velocity: Vec3,
/// state: u32, // 0=roaming, 1=chasing, 2=eating, 3=resting
/// prev_state: u32,
/// state_timer: f32,
/// energy: f32,
/// target_dist: f32,
/// }
///
/// Rule::Agent {
/// state_field: "state".into(),
/// prev_state_field: "prev_state".into(),
/// state_timer_field: Some("state_timer".into()),
/// states: vec![
/// AgentState::new(0)
/// .named("roaming")
/// .on_update("p.velocity += rand_sphere(index) * 0.1;")
/// .transition(1, "p.target_dist < 0.5") // See prey → chase
/// .transition(3, "p.energy < 0.2"), // Tired → rest
///
/// AgentState::new(1)
/// .named("chasing")
/// .on_enter("p.color = vec3<f32>(1.0, 0.0, 0.0);") // Turn red
/// .on_update("p.energy -= 0.01 * uniforms.delta_time;")
/// .transition(2, "p.target_dist < 0.05") // Caught → eat
/// .transition(0, "p.target_dist > 1.0"), // Lost prey → roam
///
/// AgentState::new(2)
/// .named("eating")
/// .on_enter("p.velocity = vec3<f32>(0.0);")
/// .on_update("p.energy += 0.1 * uniforms.delta_time;")
/// .transition(0, "p.state_timer > 2.0"), // Done eating → roam
///
/// AgentState::new(3)
/// .named("resting")
/// .on_enter("p.color = vec3<f32>(0.5, 0.5, 0.5);")
/// .on_update("p.energy += 0.05 * uniforms.delta_time;")
/// .transition(0, "p.energy > 0.8"), // Rested → roam
/// ],
/// }
/// ```
///
/// # How It Works
///
/// Each frame, for each particle:
/// 1. If state changed since last frame, run the exit action of the old state
/// and the entry action of the new state
/// 2. Run the update action for the current state
/// 3. Increment the state timer (if configured)
/// 4. Check transitions in priority order; first matching transition wins
/// 5. If a transition fires, update the state field (entry/exit run next frame)
///
/// # Note
///
/// - State timer resets to 0 when the state changes
/// - Transitions are sorted by priority (highest first) at compile time
/// - Use `prev_state_field` to detect state changes and run entry/exit actions
Agent {
/// Particle field storing current state (u32).
state_field: String,
/// Particle field storing previous frame's state (u32).
/// Used to detect state changes and trigger entry/exit actions.
prev_state_field: String,
/// Optional field to track time in current state (f32).
/// Resets to 0 on state change.
state_timer_field: Option<String>,
/// The state definitions.
states: Vec<AgentState>,
},
/// Grow or shrink particle scale over time.
///
/// Changes `p.scale` at a constant rate, clamped to min/max bounds.
/// Positive rate = grow, negative rate = shrink.
///
/// # Fields
///
/// - `rate` - Scale change per second (can be negative)
/// - `min` - Minimum scale (won't shrink below this)
/// - `max` - Maximum scale (won't grow above this)
///
/// # Example: Growing particles
///
/// ```ignore
/// Rule::Grow { rate: 0.5, min: 0.1, max: 2.0 }
/// ```
///
/// # Example: Shrinking particles
///
/// ```ignore
/// Rule::Grow { rate: -0.3, min: 0.0, max: 1.0 }
/// ```
///
/// # Example: Grow then die when too big
///
/// ```ignore
/// Rule::Grow { rate: 0.2, min: 0.1, max: 3.0 },
/// Rule::Die { condition: "p.scale >= 3.0".into(), field: "alive".into() },
/// ```
Grow {
/// Scale change per second (positive = grow, negative = shrink).
rate: f32,
/// Minimum scale bound.
min: f32,
/// Maximum scale bound.
max: f32,
},
/// Multiplicative decay of a field toward zero.
///
/// Each frame: `field *= rate`. Different from [`Rule::Lerp`] which does
/// additive interpolation. Decay is good for exponential falloff (energy,
/// heat, intensity).
///
/// # Fields
///
/// - `field` - Particle field to decay (f32)
/// - `rate` - Multiplier per second (0.0-1.0 for decay, >1.0 for growth)
///
/// # Example: Energy decay
///
/// ```ignore
/// // Energy halves roughly every second
/// Rule::Decay { field: "energy".into(), rate: 0.5 }
/// ```
///
/// # Example: Slow fade
///
/// ```ignore
/// Rule::Decay { field: "brightness".into(), rate: 0.9 }
/// ```
///
/// # Math Note
///
/// The actual per-frame multiplier is `rate^delta_time` to be framerate
/// independent. A rate of 0.5 means "multiply by 0.5 per second".
Decay {
/// Field to decay (f32).
field: String,
/// Decay rate per second (0.5 = halve per second).
rate: f32,
},
/// Buoyancy force based on per-particle density.
///
/// Applies vertical force based on particle density vs medium density.
/// Light particles (density < medium) float up, heavy particles sink.
/// Classic for fluid simulations with varying densities.
///
/// Unlike `Rule::Buoyancy` which uses a fixed buoyancy factor, this reads
/// density from a particle field, enabling per-particle buoyancy effects.
///
/// # Fields
///
/// - `density_field` - Particle field storing density (f32)
/// - `medium_density` - Density of the surrounding medium
/// - `strength` - Force multiplier
///
/// # Example: Oil and water
///
/// ```ignore
/// // Oil (density 0.8) floats, rocks (density 2.5) sink
/// Rule::DensityBuoyancy {
/// density_field: "density".into(),
/// medium_density: 1.0, // Water
/// strength: 5.0,
/// }
/// ```
///
/// # Physics Note
///
/// Force = (medium_density - particle_density) * strength * up
/// Positive when lighter than medium (floats), negative when heavier (sinks).
DensityBuoyancy {
/// Particle field storing density (f32).
density_field: String,
/// Density of surrounding medium.
medium_density: f32,
/// Force strength multiplier.
strength: f32,
},
/// Property diffusion through neighbor averaging.
///
/// **Requires spatial hashing.** A particle's property value moves toward
/// the average of its neighbors. Classic for heat diffusion, chemical
/// concentration spreading, or any equilibrating property.
///
/// # Fields
///
/// - `field` - Particle field to diffuse (f32)
/// - `rate` - Diffusion speed (0.0-1.0, higher = faster equilibration)
/// - `radius` - Neighbor detection distance
///
/// # Example: Heat diffusion
///
/// ```ignore
/// Rule::Diffuse {
/// field: "temperature".into(),
/// rate: 0.3,
/// radius: 0.15,
/// }
/// ```
///
/// # Example: Chemical spreading
///
/// ```ignore
/// Rule::Diffuse {
/// field: "concentration".into(),
/// rate: 0.1,
/// radius: 0.1,
/// }
/// ```
Diffuse {
/// Particle field to diffuse (f32).
field: String,
/// Diffusion rate (0.0-1.0).
rate: f32,
/// Neighbor detection radius.
radius: f32,
},
/// Refractory period / cooldown mechanic for particle fields.
///
/// Models a "charge" that depletes when a trigger field is active and
/// regenerates when inactive. Perfect for:
/// - Bioluminescence (luciferin depletion/regeneration)
/// - Neuron firing (refractory period)
/// - Ability cooldowns
/// - Energy systems
///
/// When `trigger` field is above `active_threshold`:
/// - Charge depletes at `depletion_rate * trigger_value`
///
/// When `trigger` field is below `active_threshold`:
/// - Charge regenerates at `regen_rate`
///
/// # Fields
///
/// - `trigger` - Field that triggers depletion (e.g., "glow")
/// - `charge` - Field storing the charge level (e.g., "energy")
/// - `active_threshold` - Trigger value above which charge depletes
/// - `depletion_rate` - How fast charge depletes when active
/// - `regen_rate` - How fast charge regenerates when inactive
///
/// # Example: Bioluminescence
///
/// ```ignore
/// Rule::Refractory {
/// trigger: "glow".into(),
/// charge: "luciferin".into(),
/// active_threshold: 0.05,
/// depletion_rate: 0.03,
/// regen_rate: 0.008,
/// }
/// ```
///
/// # Example: Neuron firing
///
/// ```ignore
/// Rule::Refractory {
/// trigger: "firing".into(),
/// charge: "membrane_potential".into(),
/// active_threshold: 0.1,
/// depletion_rate: 0.5, // Fast depletion during firing
/// regen_rate: 0.02, // Slow recovery
/// }
/// ```
Refractory {
/// Field that triggers depletion when high.
trigger: String,
/// Field storing the charge (0.0 to 1.0).
charge: String,
/// Threshold above which trigger causes depletion.
active_threshold: f32,
/// Depletion rate (multiplied by trigger value).
depletion_rate: f32,
/// Regeneration rate when trigger is low.
regen_rate: f32,
},
/// Run custom WGSL code when a particle dies.
///
/// Triggered on the frame when `p.alive` transitions from 1 to 0.
/// Useful for death effects, recording final state, or triggering
/// other systems.
///
/// # Available Variables
///
/// - `p` - The particle at the moment of death (read/write)
/// - `index` - Particle index (`u32`)
/// - `uniforms.time`, `uniforms.delta_time` - Time values
///
/// # Example: Flash color on death
///
/// ```ignore
/// .with_rule(Rule::Lifetime(3.0))
/// .with_rule(Rule::OnDeath {
/// action: r#"
/// p.color = vec3<f32>(1.0, 1.0, 1.0); // Flash white
/// "#.into(),
/// })
/// ```
///
/// # Example: Deposit to field on death
///
/// ```ignore
/// .with_rule(Rule::OnDeath {
/// action: r#"
/// // Leave a "corpse" marker in the field
/// field_write(0u, p.position, 1.0);
/// "#.into(),
/// })
/// ```
///
/// # Note
///
/// The action runs after all other rules have executed, just before
/// the particle is written back to the buffer. The particle is still
/// "alive" in the sense that you can modify its fields, but `p.alive`
/// will be 0.
OnDeath {
/// WGSL code to execute when particle dies.
action: String,
},
/// Run custom WGSL code when a condition is true.
///
/// A declarative wrapper around conditional logic. More readable than
/// `Rule::Custom` with an if statement when the pattern is simple.
///
/// # Fields
///
/// - `condition` - WGSL boolean expression (e.g., `"p.energy < 0.1"`)
/// - `action` - WGSL code to run when condition is true
///
/// # Example: Low health warning
///
/// ```ignore
/// Rule::OnCondition {
/// condition: "p.health < 0.2".into(),
/// action: "p.color = vec3<f32>(1.0, 0.0, 0.0);".into(),
/// }
/// ```
///
/// # Example: Speed boost when charged
///
/// ```ignore
/// Rule::OnCondition {
/// condition: "p.charge > 0.8".into(),
/// action: r#"
/// p.velocity *= 1.5;
/// p.color = vec3<f32>(1.0, 1.0, 0.0);
/// "#.into(),
/// }
/// ```
OnCondition {
/// WGSL boolean expression.
condition: String,
/// WGSL code to execute when condition is true.
action: String,
},
/// Run custom WGSL code at regular time intervals.
///
/// Triggers once per interval when the simulation time crosses an
/// interval boundary. Useful for periodic effects like pulses,
/// spawning, or state changes.
///
/// # Fields
///
/// - `interval` - Time between triggers in seconds
/// - `action` - WGSL code to run at each interval
///
/// # Example: Periodic pulse
///
/// ```ignore
/// Rule::OnInterval {
/// interval: 0.5,
/// action: "p.glow = 1.0;".into(),
/// }
/// ```
///
/// # Example: Random color change every second
///
/// ```ignore
/// Rule::OnInterval {
/// interval: 1.0,
/// action: r#"
/// p.color = vec3<f32>(
/// rand_f32(index, 0u),
/// rand_f32(index, 1u),
/// rand_f32(index, 2u)
/// );
/// "#.into(),
/// }
/// ```
///
/// # Note
///
/// The trigger detection uses `floor(time / interval)` comparison,
/// so it fires once per particle when crossing each interval boundary.
OnInterval {
/// Time between triggers in seconds.
interval: f32,
/// WGSL code to execute at each interval.
action: String,
},
/// Run custom WGSL code when a particle spawns.
///
/// Triggered on the frame when `p.alive` transitions from 0 to 1
/// (i.e., when an emitter spawns the particle). Useful for
/// initialization effects, random starting values, or spawn bursts.
///
/// # Available Variables
///
/// - `p` - The newly spawned particle (read/write)
/// - `index` - Particle index (`u32`)
/// - `uniforms.time`, `uniforms.delta_time` - Time values
///
/// # Example: Random color on spawn
///
/// ```ignore
/// .with_rule(Rule::OnSpawn {
/// action: r#"
/// p.color = vec3<f32>(
/// rand_f32(index, 0u),
/// rand_f32(index, 1u),
/// rand_f32(index, 2u)
/// );
/// "#.into(),
/// })
/// ```
///
/// # Example: Spawn burst effect
///
/// ```ignore
/// .with_rule(Rule::OnSpawn {
/// action: r#"
/// p.glow = 1.0;
/// p.scale = 2.0;
/// "#.into(),
/// })
/// ```
///
/// # Note
///
/// This triggers for emitter-spawned particles, not for particles
/// created at simulation start (those are initialized via the spawner).
OnSpawn {
/// WGSL code to execute when particle spawns.
action: String,
},
/// Copy one particle field to another.
///
/// Simple field assignment. Useful for tracking previous values,
/// creating derived fields, or synchronizing state.
///
/// # Fields
///
/// - `from` - Source field name
/// - `to` - Destination field name
///
/// # Example: Track previous position
///
/// ```ignore
/// Rule::CopyField {
/// from: "position".into(),
/// to: "prev_position".into(),
/// }
/// ```
///
/// # Example: Sync color to velocity-based color
///
/// ```ignore
/// Rule::CopyField {
/// from: "computed_color".into(),
/// to: "color".into(),
/// }
/// ```
CopyField {
/// Source field name.
from: String,
/// Destination field name.
to: String,
},
/// Accumulate a value from neighbors into a target field.
///
/// Gathers values from nearby particles and combines them using the
/// specified operation. Useful for sensing neighbor properties like
/// density, average temperature, maximum threat, etc.
///
/// # Fields
///
/// - `source` - Field to read from neighbors (f32)
/// - `target` - Field to write the result to (f32)
/// - `radius` - Neighbor detection radius
/// - `operation` - How to combine values: "sum", "average", "max", "min"
/// - `falloff` - Optional distance falloff for weighting
///
/// # Example: Sense neighbor density
///
/// ```ignore
/// Rule::Accumulate {
/// source: "mass".into(),
/// target: "sensed_density".into(),
/// radius: 0.2,
/// operation: "sum".into(),
/// falloff: Some(Falloff::Linear),
/// }
/// ```
///
/// # Example: Find hottest neighbor
///
/// ```ignore
/// Rule::Accumulate {
/// source: "temperature".into(),
/// target: "max_nearby_temp".into(),
/// radius: 0.15,
/// operation: "max".into(),
/// falloff: None,
/// }
/// ```
///
/// # Example: Average neighbor energy
///
/// ```ignore
/// Rule::Accumulate {
/// source: "energy".into(),
/// target: "local_energy".into(),
/// radius: 0.1,
/// operation: "average".into(),
/// falloff: Some(Falloff::InverseSquare),
/// }
/// ```
Accumulate {
/// Field to read from neighbors (f32).
source: String,
/// Field to write result to (f32).
target: String,
/// Neighbor detection radius.
radius: f32,
/// How to combine values: "sum", "average", "max", "min".
operation: String,
/// Optional distance-based weighting.
falloff: Option<Falloff>,
},
/// Deposit a particle value into a 3D field at the particle's position.
///
/// Particles leave a trail or accumulate influence in a spatial field.
/// Useful for pheromone trails, heat maps, density fields, etc.
///
/// # Fields
///
/// - `field_index` - Index of the 3D field to write to (0, 1, 2...)
/// - `source` - Particle field to read value from (f32)
/// - `amount` - Multiplier for the deposited value
///
/// # Example: Pheromone trail
///
/// ```ignore
/// // Ants deposit pheromones as they walk
/// Rule::Deposit {
/// field_index: 0,
/// source: "pheromone_strength".into(),
/// amount: 0.1,
/// }
/// ```
///
/// # Example: Heat emission
///
/// ```ignore
/// // Hot particles warm the field around them
/// Rule::Deposit {
/// field_index: 0, // heat field
/// source: "temperature".into(),
/// amount: 0.05,
/// }
/// ```
Deposit {
/// Index of the 3D field (registered via with_field).
field_index: u32,
/// Particle field to read value from.
source: String,
/// Amount multiplier (scales the deposited value).
amount: f32,
},
/// Read a value from a 3D field at the particle's position.
///
/// Particles sample the field and store the result in a particle property.
/// Use with field_gradient for chemotaxis-style behavior.
///
/// # Fields
///
/// - `field_index` - Index of the 3D field to read from
/// - `target` - Particle field to store the value in (f32)
///
/// # Example: Sense pheromones
///
/// ```ignore
/// // Read pheromone concentration into particle
/// Rule::Sense {
/// field_index: 0,
/// target: "sensed_pheromone".into(),
/// }
/// ```
Sense {
/// Index of the 3D field to read from.
field_index: u32,
/// Particle field to store the sensed value.
target: String,
},
/// Read and consume value from a 3D field (depletes the field).
///
/// Particles extract resources from the field, reducing its value.
/// The consumed amount is stored in a particle field.
///
/// # Fields
///
/// - `field_index` - Index of the 3D field to consume from
/// - `target` - Particle field to store consumed amount
/// - `rate` - Maximum consumption rate per frame
///
/// # Example: Eating food
///
/// ```ignore
/// // Consume food from field, gain energy
/// Rule::Consume {
/// field_index: 0, // food field
/// target: "energy".into(),
/// rate: 0.1,
/// }
/// ```
Consume {
/// Index of the 3D field to consume from.
field_index: u32,
/// Particle field to store consumed amount.
target: String,
/// Maximum consumption rate per frame.
rate: f32,
},
/// Broadcast a signal value to nearby particles.
///
/// The particle writes its value to all neighbors within radius.
/// Neighbors accumulate signals (additive). Useful for communication,
/// alarm signals, or influence spreading.
///
/// Note: Due to GPU parallelism, signals are accumulated additively.
/// For "strongest signal wins", use Rule::Accumulate with operation: "max".
///
/// # Fields
///
/// - `source` - Particle field containing the signal to broadcast
/// - `target` - Particle field on neighbors to receive the signal
/// - `radius` - Broadcast radius
/// - `strength` - Signal strength multiplier
/// - `falloff` - Optional distance-based attenuation
///
/// # Example: Alarm signal
///
/// ```ignore
/// // Frightened particles broadcast alarm to neighbors
/// Rule::Signal {
/// source: "alarm".into(),
/// target: "received_alarm".into(),
/// radius: 0.5,
/// strength: 1.0,
/// falloff: Some(Falloff::InverseSquare),
/// }
/// ```
Signal {
/// Particle field containing the signal value.
source: String,
/// Particle field on neighbors to write to.
target: String,
/// Broadcast radius.
radius: f32,
/// Signal strength multiplier.
strength: f32,
/// Optional distance-based falloff.
falloff: Option<Falloff>,
},
/// Absorb nearby particles of a matching type.
///
/// When particles are within range, the absorber kills them and
/// accumulates their properties (mass, energy, etc.).
///
/// # Fields
///
/// - `target_type` - Type of particles to absorb (None = any type)
/// - `radius` - Absorption radius
/// - `source_field` - Field to absorb from dying particles
/// - `target_field` - Field to accumulate absorbed values into
///
/// # Example: Predator eating prey
///
/// ```ignore
/// Rule::Absorb {
/// target_type: Some(Species::Prey.into()),
/// radius: 0.1,
/// source_field: "energy".into(),
/// target_field: "energy".into(),
/// }
/// ```
///
/// # Example: Black hole absorbing mass
///
/// ```ignore
/// Rule::Typed {
/// self_type: ParticleType::BlackHole.into(),
/// rule: Box::new(Rule::Absorb {
/// target_type: None, // absorb anything
/// radius: 0.05,
/// source_field: "mass".into(),
/// target_field: "mass".into(),
/// }),
/// }
/// ```
Absorb {
/// Type of particles to absorb (None = any type).
target_type: Option<u32>,
/// Absorption radius.
radius: f32,
/// Field to read from absorbed particles.
source_field: String,
/// Field to accumulate absorbed values into.
target_field: String,
},
/// Switch between two rules based on a condition.
///
/// Evaluates a WGSL condition and applies either the `then` rule
/// or the `else` rule. Useful for state-dependent behavior.
///
/// # Fields
///
/// - `condition` - WGSL boolean expression
/// - `then_rule` - Rule to apply when condition is true
/// - `else_rule` - Optional rule to apply when condition is false
///
/// # Example: Flee when low health
///
/// ```ignore
/// Rule::Switch {
/// condition: "p.health < 0.3".into(),
/// then_rule: Box::new(Rule::Evade { ... }),
/// else_rule: Some(Box::new(Rule::Chase { ... })),
/// }
/// ```
///
/// # Example: Different behavior by type
///
/// ```ignore
/// Rule::Switch {
/// condition: "p.particle_type == 0u".into(),
/// then_rule: Box::new(Rule::Gravity(9.8)),
/// else_rule: Some(Box::new(Rule::Gravity(-5.0))),
/// }
/// ```
Switch {
/// WGSL boolean condition (has access to `p`, `uniforms`).
condition: String,
/// Rule to apply when condition is true.
then_rule: Box<Rule>,
/// Optional rule to apply when condition is false.
else_rule: Option<Box<Rule>>,
},
/// Divide a particle when a condition is met.
///
/// When the condition evaluates to true, the particle spawns offspring
/// and optionally consumes resources (e.g., energy, mass). Uses the
/// sub-emitter system for spawning.
///
/// # Fields
///
/// - `condition` - WGSL boolean expression (has access to `p`, `uniforms`)
/// - `offspring_count` - Number of offspring to spawn (1-10)
/// - `offspring_type` - Particle type for offspring (same as parent if None)
/// - `resource_field` - Optional field to consume when splitting
/// - `resource_cost` - Amount of resource consumed per split
/// - `spread` - Velocity spread angle in radians (default: PI/4)
/// - `speed` - Speed range for offspring velocity
///
/// # Example: Cell Division
///
/// ```ignore
/// Rule::Split {
/// condition: "p.energy > 1.5".into(),
/// offspring_count: 2,
/// offspring_type: None, // Same type as parent
/// resource_field: Some("energy".into()),
/// resource_cost: 0.8,
/// spread: std::f32::consts::PI / 4.0,
/// speed: 0.1..0.3,
/// }
/// ```
///
/// # Example: Fragmentation
///
/// ```ignore
/// Rule::Split {
/// condition: "p.health < 0.1".into(),
/// offspring_count: 5,
/// offspring_type: Some(FragmentType.into()),
/// resource_field: None,
/// resource_cost: 0.0,
/// spread: std::f32::consts::TAU, // Full sphere
/// speed: 0.5..1.5,
/// }
/// ```
Split {
/// WGSL boolean condition that triggers splitting.
condition: String,
/// Number of offspring particles to spawn.
offspring_count: u32,
/// Particle type for offspring (None = same as parent).
offspring_type: Option<u32>,
/// Optional particle field to consume when splitting.
resource_field: Option<String>,
/// Amount of resource consumed per split.
resource_cost: f32,
/// Spread angle for offspring velocity (radians).
spread: f32,
/// Speed range for offspring (min, max).
speed_min: f32,
speed_max: f32,
},
/// Scale accelerations by inverse mass (F=ma → a=F/m).
///
/// Makes heavy particles sluggish and light particles responsive.
/// Apply this rule AFTER force-applying rules to scale their effect
/// by particle mass.
///
/// # Fields
///
/// - `field` - Particle field storing mass (f32, should be > 0)
///
/// # Example
///
/// ```ignore
/// // Apply forces first
/// Rule::Gravity(9.8),
/// Rule::Attract { point: Vec3::ZERO, strength: 2.0 },
/// // Then scale by mass
/// Rule::Mass { field: "mass".into() },
/// ```
///
/// # Implementation Note
///
/// This divides velocity changes by mass. For proper physics, place it
/// after all force rules but before position integration (which RDPE
/// does automatically).
Mass {
/// Particle field storing mass (f32).
field: String,
},
/// Animate a property from start to end over a duration.
///
/// Smoothly interpolates a field based on elapsed time from a timer field.
/// Great for spawn animations, death fades, or any time-based transitions.
///
/// # Fields
///
/// - `field` - Property to animate (f32)
/// - `from` - Starting value
/// - `to` - Ending value
/// - `duration` - Animation duration in seconds
/// - `timer_field` - Particle field tracking elapsed time (use with Rule::Age)
///
/// # Example: Spawn scale-in
///
/// ```ignore
/// Rule::Age { field: "age".into() },
/// Rule::Tween {
/// field: "scale".into(),
/// from: 0.0,
/// to: 1.0,
/// duration: 0.5,
/// timer_field: "age".into(),
/// }
/// ```
///
/// # Example: Fade out before death
///
/// ```ignore
/// // Assumes death_timer starts counting when dying
/// Rule::Tween {
/// field: "alpha".into(),
/// from: 1.0,
/// to: 0.0,
/// duration: 1.0,
/// timer_field: "death_timer".into(),
/// }
/// ```
///
/// # Note
///
/// Animation clamps at `to` value when timer exceeds duration.
Tween {
/// Property to animate (f32).
field: String,
/// Starting value.
from: f32,
/// Ending value.
to: f32,
/// Animation duration in seconds.
duration: f32,
/// Timer field tracking elapsed time.
timer_field: String,
},
/// Binary step function (Schmitt trigger without hysteresis).
///
/// Outputs one value when input is above threshold, another when below.
/// Classic for state transitions, on/off switches, or discretizing
/// continuous values.
///
/// # Fields
///
/// - `input_field` - Field to test against threshold
/// - `output_field` - Field to write result to
/// - `threshold` - The threshold value
/// - `above` - Value to output when input >= threshold
/// - `below` - Value to output when input < threshold
///
/// # Example: Binary alive/dead state
///
/// ```ignore
/// Rule::Threshold {
/// input_field: "health".into(),
/// output_field: "alive".into(),
/// threshold: 0.0,
/// above: 1.0,
/// below: 0.0,
/// }
/// ```
///
/// # Example: Hot/cold indicator
///
/// ```ignore
/// Rule::Threshold {
/// input_field: "temperature".into(),
/// output_field: "is_hot".into(),
/// threshold: 100.0,
/// above: 1.0,
/// below: 0.0,
/// }
/// ```
Threshold {
/// Field to test.
input_field: String,
/// Field to write result to.
output_field: String,
/// Threshold value.
threshold: f32,
/// Output when input >= threshold.
above: f32,
/// Output when input < threshold.
below: f32,
},
/// Conditional action gate.
///
/// Executes WGSL code only when a condition is true. Like `Rule::Trigger`
/// but without the "only once" semantic - runs every frame the condition
/// is met.
///
/// # Fields
///
/// - `condition` - WGSL boolean expression
/// - `action` - WGSL code to execute when condition is true
///
/// # Example: Boost speed when energy is high
///
/// ```ignore
/// Rule::Gate {
/// condition: "p.energy > 0.8".into(),
/// action: "p.velocity *= 1.5;".into(),
/// }
/// ```
///
/// # Example: Glow when nearby other particles
///
/// ```ignore
/// Rule::Gate {
/// condition: "p.neighbor_count > 5.0".into(),
/// action: "p.brightness = 1.0;".into(),
/// }
/// ```
///
/// # Note
///
/// For one-shot triggers (fire once then stop), use [`Rule::Trigger`].
Gate {
/// WGSL boolean condition.
condition: String,
/// WGSL code to run when true.
action: String,
},
/// Add procedural noise to a field.
///
/// Applies smooth Perlin-style noise to a particle field based on
/// position and/or time. Great for organic movement, flickering,
/// or natural variation.
///
/// # Fields
///
/// - `field` - Field to add noise to
/// - `amplitude` - Noise strength (how much it varies)
/// - `frequency` - Spatial frequency (higher = more detail)
/// - `time_scale` - How fast noise evolves (0 = static)
///
/// # Example: Flickering brightness
///
/// ```ignore
/// Rule::Noise {
/// field: "brightness".into(),
/// amplitude: 0.3,
/// frequency: 2.0,
/// time_scale: 5.0,
/// }
/// ```
///
/// # Example: Organic position jitter
///
/// ```ignore
/// Rule::Noise {
/// field: "position.x".into(),
/// amplitude: 0.05,
/// frequency: 1.0,
/// time_scale: 2.0,
/// }
/// ```
///
/// # Note
///
/// Uses the simulation's built-in `noise3` function. Noise is additive
/// (adds to existing field value, doesn't replace it).
Noise {
/// Field to add noise to.
field: String,
/// Noise amplitude.
amplitude: f32,
/// Spatial frequency.
frequency: f32,
/// Time evolution speed (0 = static noise).
time_scale: f32,
},
/// Remap a field from one range to another.
///
/// Linear interpolation: maps `[in_min, in_max]` to `[out_min, out_max]`.
/// Values outside input range are extrapolated (use with Clamp if needed).
///
/// # Fields
///
/// - `field` - Field to remap (modified in place)
/// - `in_min`, `in_max` - Input range
/// - `out_min`, `out_max` - Output range
///
/// # Example: Age to opacity (young=visible, old=faded)
///
/// ```ignore
/// Rule::Remap {
/// field: "opacity".into(),
/// in_min: 0.0, in_max: 10.0, // age range
/// out_min: 1.0, out_max: 0.0, // fade out
/// }
/// ```
///
/// # Example: Normalize velocity magnitude
///
/// ```ignore
/// Rule::Remap {
/// field: "speed_normalized".into(),
/// in_min: 0.0, in_max: 5.0,
/// out_min: 0.0, out_max: 1.0,
/// }
/// ```
Remap {
/// Field to remap.
field: String,
/// Input range minimum.
in_min: f32,
/// Input range maximum.
in_max: f32,
/// Output range minimum.
out_min: f32,
/// Output range maximum.
out_max: f32,
},
/// Clamp a field to a range.
///
/// Simple bounds constraint. Values below min become min,
/// values above max become max.
///
/// # Example: Limit energy
///
/// ```ignore
/// Rule::Clamp {
/// field: "energy".into(),
/// min: 0.0,
/// max: 100.0,
/// }
/// ```
Clamp {
/// Field to clamp.
field: String,
/// Minimum value.
min: f32,
/// Maximum value.
max: f32,
},
/// Exponential smoothing toward a target value.
///
/// Low-pass filter that smoothly moves a field toward a target.
/// Higher rate = faster convergence. Classic for easing, damping,
/// or filtering noisy values.
///
/// # Fields
///
/// - `field` - Field to smooth
/// - `target` - Target value to approach
/// - `rate` - Smoothing rate (0-1, higher = faster)
///
/// # Example: Smooth brightness toward 0
///
/// ```ignore
/// Rule::Smooth {
/// field: "brightness".into(),
/// target: 0.0,
/// rate: 0.1,
/// }
/// ```
///
/// # Note
///
/// Formula: `field = mix(field, target, rate * delta_time)`
Smooth {
/// Field to smooth.
field: String,
/// Target value.
target: f32,
/// Smoothing rate per second.
rate: f32,
},
/// Quantize a field to discrete steps.
///
/// Snaps continuous values to a grid. Useful for pixelated effects,
/// discrete states, or grid-based movement.
///
/// # Example: Snap position to grid
///
/// ```ignore
/// Rule::Quantize {
/// field: "position.x".into(),
/// step: 0.1,
/// }
/// ```
///
/// # Example: Discrete energy levels
///
/// ```ignore
/// Rule::Quantize {
/// field: "energy".into(),
/// step: 10.0, // 0, 10, 20, 30...
/// }
/// ```
Quantize {
/// Field to quantize.
field: String,
/// Step size (values snap to multiples of this).
step: f32,
},
/// Wrap a field value within a range (modulo).
///
/// Values that exceed max wrap back to min, and vice versa.
/// Essential for cyclic quantities like angles, phases, or
/// toroidal coordinates.
///
/// # Example: Wrap phase to 0-2π
///
/// ```ignore
/// Rule::Modulo {
/// field: "phase".into(),
/// min: 0.0,
/// max: 6.28318,
/// }
/// ```
///
/// # Example: Wrap hue for color cycling
///
/// ```ignore
/// Rule::Modulo {
/// field: "hue".into(),
/// min: 0.0,
/// max: 1.0,
/// }
/// ```
Modulo {
/// Field to wrap.
field: String,
/// Range minimum.
min: f32,
/// Range maximum.
max: f32,
},
/// Copy one field to another.
///
/// Optionally scale and offset the value during copy.
/// Useful for derived values, backups, or transformations.
///
/// # Fields
///
/// - `from` - Source field
/// - `to` - Destination field
/// - `scale` - Multiply by this (default 1.0)
/// - `offset` - Add this after scaling (default 0.0)
///
/// # Example: Copy age to display value
///
/// ```ignore
/// Rule::Copy {
/// from: "age".into(),
/// to: "display_age".into(),
/// scale: 1.0,
/// offset: 0.0,
/// }
/// ```
///
/// # Example: Invert and shift
///
/// ```ignore
/// Rule::Copy {
/// from: "health".into(),
/// to: "damage".into(),
/// scale: -1.0,
/// offset: 100.0, // damage = 100 - health
/// }
/// ```
Copy {
/// Source field.
from: String,
/// Destination field.
to: String,
/// Scale factor.
scale: f32,
/// Offset added after scaling.
offset: f32,
},
// =========================================================================
// Logic Gates (analog/signal style)
// =========================================================================
/// Logical AND (analog: minimum of two fields).
///
/// Output is the minimum of two input fields. In boolean terms,
/// both must be "high" for output to be high.
///
/// # Example
///
/// ```ignore
/// Rule::And {
/// a: "has_energy".into(),
/// b: "is_ready".into(),
/// output: "can_fire".into(),
/// }
/// ```
And {
/// First input field.
a: String,
/// Second input field.
b: String,
/// Output field.
output: String,
},
/// Logical OR (analog: maximum of two fields).
///
/// Output is the maximum of two input fields. In boolean terms,
/// either being "high" makes output high.
///
/// # Example
///
/// ```ignore
/// Rule::Or {
/// a: "danger_left".into(),
/// b: "danger_right".into(),
/// output: "any_danger".into(),
/// }
/// ```
Or {
/// First input field.
a: String,
/// Second input field.
b: String,
/// Output field.
output: String,
},
/// Logical NOT (inversion).
///
/// Inverts a field value. Default is `1.0 - x` but can specify
/// custom range for inversion.
///
/// # Example: Simple invert (0↔1)
///
/// ```ignore
/// Rule::Not {
/// input: "alive".into(),
/// output: "dead".into(),
/// max: 1.0,
/// }
/// ```
///
/// # Example: Invert in custom range
///
/// ```ignore
/// Rule::Not {
/// input: "brightness".into(),
/// output: "darkness".into(),
/// max: 100.0, // darkness = 100 - brightness
/// }
/// ```
Not {
/// Input field.
input: String,
/// Output field.
output: String,
/// Maximum value (output = max - input).
max: f32,
},
/// Logical XOR (analog: absolute difference).
///
/// Output is `abs(a - b)`. High when inputs differ, low when same.
/// Useful for detecting disagreement or change.
///
/// # Example
///
/// ```ignore
/// Rule::Xor {
/// a: "signal_a".into(),
/// b: "signal_b".into(),
/// output: "mismatch".into(),
/// }
/// ```
Xor {
/// First input field.
a: String,
/// Second input field.
b: String,
/// Output field.
output: String,
},
// =========================================================================
// Stateful Logic
// =========================================================================
/// Hysteresis (Schmitt trigger) - two-threshold switching.
///
/// Prevents oscillation at boundaries by using separate thresholds
/// for turning on vs off. Output goes high when input exceeds
/// `high_threshold`, stays high until input drops below `low_threshold`.
///
/// # Fields
///
/// - `input` - Field to monitor
/// - `output` - Field to set (acts as state memory too)
/// - `low_threshold` - Turn off below this
/// - `high_threshold` - Turn on above this
/// - `on_value` - Value when "on" (default 1.0)
/// - `off_value` - Value when "off" (default 0.0)
///
/// # Example: Temperature control
///
/// ```ignore
/// // Heater turns on at 18°, stays on until 22°
/// Rule::Hysteresis {
/// input: "temperature".into(),
/// output: "heater_on".into(),
/// low_threshold: 18.0,
/// high_threshold: 22.0,
/// on_value: 1.0,
/// off_value: 0.0,
/// }
/// ```
Hysteresis {
/// Input field to monitor.
input: String,
/// Output field (also stores state).
output: String,
/// Turn off when input drops below this.
low_threshold: f32,
/// Turn on when input rises above this.
high_threshold: f32,
/// Output value when "on".
on_value: f32,
/// Output value when "off".
off_value: f32,
},
/// Set-Reset Latch (SR flip-flop).
///
/// Persistent memory that sets on one condition, resets on another.
/// Once set, stays set until explicitly reset.
///
/// # Example: Alarm that latches on
///
/// ```ignore
/// Rule::Latch {
/// output: "alarm".into(),
/// set_condition: "p.danger > 0.9".into(),
/// reset_condition: "p.acknowledged > 0.5".into(),
/// set_value: 1.0,
/// reset_value: 0.0,
/// }
/// ```
Latch {
/// Output field (stores latched state).
output: String,
/// WGSL condition to set the latch.
set_condition: String,
/// WGSL condition to reset the latch.
reset_condition: String,
/// Value when set.
set_value: f32,
/// Value when reset.
reset_value: f32,
},
/// Edge detector - fire on transition.
///
/// Outputs a pulse (one frame) when input crosses a threshold.
/// Requires a "previous value" field to track state.
///
/// # Fields
///
/// - `input` - Field to monitor
/// - `prev_field` - Field storing previous frame's value
/// - `output` - Field to pulse on edge
/// - `threshold` - Crossing point
/// - `rising` - Detect low→high transitions
/// - `falling` - Detect high→low transitions
///
/// # Example: Detect when energy crosses 50%
///
/// ```ignore
/// Rule::Edge {
/// input: "energy".into(),
/// prev_field: "energy_prev".into(),
/// output: "energy_crossed".into(),
/// threshold: 0.5,
/// rising: true,
/// falling: true,
/// }
/// ```
Edge {
/// Input field to monitor.
input: String,
/// Field storing previous value (you must initialize this).
prev_field: String,
/// Output pulse field.
output: String,
/// Threshold to detect crossing.
threshold: f32,
/// Detect rising edge (low to high).
rising: bool,
/// Detect falling edge (high to low).
falling: bool,
},
// =========================================================================
// Selectors
// =========================================================================
/// Conditional select (ternary operator).
///
/// `output = condition ? then_value : else_value`
///
/// # Example: Choose speed based on state
///
/// ```ignore
/// Rule::Select {
/// condition: "p.is_fleeing > 0.5".into(),
/// then_field: "fast_speed".into(),
/// else_field: "normal_speed".into(),
/// output: "current_speed".into(),
/// }
/// ```
Select {
/// WGSL boolean condition.
condition: String,
/// Field to use when true.
then_field: String,
/// Field to use when false.
else_field: String,
/// Output field.
output: String,
},
/// Blend two fields by a weight field.
///
/// `output = mix(a, b, weight)` where weight 0→a, weight 1→b.
///
/// # Example: Blend colors by temperature
///
/// ```ignore
/// Rule::Blend {
/// a: "cold_color".into(),
/// b: "hot_color".into(),
/// weight: "temperature_normalized".into(),
/// output: "display_color".into(),
/// }
/// ```
Blend {
/// First input field (weight=0).
a: String,
/// Second input field (weight=1).
b: String,
/// Weight field (0-1).
weight: String,
/// Output field.
output: String,
},
/// Custom WGSL code with dynamic, editable parameters.
///
/// Unlike [`Rule::Custom`], this variant allows you to define parameters
/// that can be edited at runtime through the rule inspector. Parameters
/// are exposed as uniform values.
///
/// # Creating Custom Dynamic Rules
///
/// Use the builder pattern for ergonomic parameter declaration:
///
/// ```ignore
/// .with_rule(Rule::custom_dynamic(r#"
/// p.velocity.y += uniforms.bounce_strength * sin(uniforms.time * uniforms.frequency);
/// p.color = mix(p.color, uniforms.target_color, 0.1);
/// "#)
/// .with_param("bounce_strength", 2.0)
/// .with_param("frequency", 3.0)
/// .with_param("target_color", Vec3::new(1.0, 0.5, 0.0))
/// )
/// ```
///
/// # Available Variables
///
/// Same as [`Rule::Custom`]:
/// - `p` - Current particle (read/write)
/// - `index` - Particle index (`u32`)
/// - `uniforms.time`, `uniforms.delta_time` - Time values
/// - `uniforms.your_param_name` - Your custom parameters
///
/// # Parameter Types
///
/// Supported parameter types:
/// - `f32` - Single float (drag value)
/// - `u32`, `i32` - Integers
/// - `Vec2`, `Vec3`, `Vec4` - Vectors (shown as x/y/z/w components)
CustomDynamic {
/// The WGSL code to execute.
code: String,
/// Named parameters that can be edited at runtime.
/// Each parameter becomes `uniforms.rule_N_paramname` in the shader.
params: Vec<(String, crate::uniforms::UniformValue)>,
},
/// Custom neighbor WGSL code with dynamic, editable parameters.
///
/// Like [`Rule::CustomDynamic`] but runs inside the neighbor iteration loop.
/// **Requires spatial hashing.**
///
/// # Creating Neighbor Custom Dynamic Rules
///
/// ```ignore
/// .with_spatial_config(0.2, 32)
/// .with_rule(Rule::neighbor_custom_dynamic(r#"
/// if neighbor_dist < uniforms.interact_radius {
/// let force = uniforms.interact_strength / (neighbor_dist + 0.01);
/// p.velocity += neighbor_dir * force * uniforms.delta_time;
/// }
/// "#)
/// .with_param("interact_radius", 0.15)
/// .with_param("interact_strength", 2.0)
/// )
/// ```
///
/// # Available Variables
///
/// Same as [`Rule::NeighborCustom`]:
/// - `p` - Current particle (read/write)
/// - `other` - Neighbor particle (read-only)
/// - `neighbor_dist` - Distance to neighbor (`f32`)
/// - `neighbor_dir` - Unit vector from neighbor to self (`vec3<f32>`)
/// - `neighbor_pos` - Neighbor position (`vec3<f32>`)
/// - `neighbor_vel` - Neighbor velocity (`vec3<f32>`)
/// - `index`, `other_idx` - Particle indices
/// - `uniforms.your_param_name` - Your custom parameters
NeighborCustomDynamic {
/// The WGSL code to execute inside the neighbor loop.
code: String,
/// Named parameters that can be edited at runtime.
params: Vec<(String, crate::uniforms::UniformValue)>,
},
/// Custom collision response with dynamic, editable parameters.
///
/// Like [`Rule::OnCollision`] but with editable parameters.
/// **Requires spatial hashing.**
///
/// # Example
///
/// ```ignore
/// .with_rule(Rule::collision_dynamic(r#"
/// p.velocity += neighbor_dir * uniforms.bounce_force;
/// p.color = uniforms.collision_color;
/// "#)
/// .with_param("bounce_force", 5.0)
/// .with_param("collision_color", Vec3::new(1.0, 0.0, 0.0))
/// .with_radius(0.05)
/// )
/// ```
OnCollisionDynamic {
/// Collision detection radius.
radius: f32,
/// The WGSL code to execute on collision.
response: String,
/// Named parameters that can be edited at runtime.
params: Vec<(String, crate::uniforms::UniformValue)>,
},
}
/// Builder for creating custom rules with dynamic parameters.
///
/// Use [`Rule::custom_dynamic`] or [`Rule::neighbor_custom_dynamic`] to create.
#[derive(Clone, Debug)]
pub struct CustomRuleBuilder {
code: String,
params: Vec<(String, crate::uniforms::UniformValue)>,
kind: CustomRuleKind,
radius: Option<f32>,
}
#[derive(Clone, Debug)]
enum CustomRuleKind {
Custom,
Neighbor,
Collision,
}
impl CustomRuleBuilder {
fn new(code: impl Into<String>, kind: CustomRuleKind) -> Self {
Self {
code: code.into(),
params: vec![],
kind,
radius: None,
}
}
/// Add a parameter that can be edited at runtime.
///
/// The parameter will be accessible in WGSL as `uniforms.rule_N_name`
/// where N is the rule index.
///
/// # Supported Types
///
/// - `f32` - Single float
/// - `u32`, `i32` - Integers
/// - `Vec2`, `Vec3`, `Vec4` - Vectors
///
/// # Example
///
/// ```ignore
/// Rule::custom_dynamic("p.velocity.y += uniforms.strength;")
/// .with_param("strength", 2.0)
/// ```
pub fn with_param<V: Into<crate::uniforms::UniformValue>>(mut self, name: &str, value: V) -> Self {
self.params.push((name.to_string(), value.into()));
self
}
/// Set the collision radius (only for collision rules).
pub fn with_radius(mut self, radius: f32) -> Self {
self.radius = Some(radius);
self
}
/// Build the rule. Usually not needed as the builder converts automatically.
pub fn build(self) -> Rule {
match self.kind {
CustomRuleKind::Custom => Rule::CustomDynamic {
code: self.code,
params: self.params,
},
CustomRuleKind::Neighbor => Rule::NeighborCustomDynamic {
code: self.code,
params: self.params,
},
CustomRuleKind::Collision => Rule::OnCollisionDynamic {
radius: self.radius.unwrap_or(0.05),
response: self.code,
params: self.params,
},
}
}
}
impl From<CustomRuleBuilder> for Rule {
fn from(builder: CustomRuleBuilder) -> Self {
builder.build()
}
}
impl Rule {
/// Create a custom rule with dynamic, editable parameters.
///
/// # Example
///
/// ```ignore
/// .with_rule(Rule::custom_dynamic(r#"
/// p.velocity.y += uniforms.bounce * sin(uniforms.time);
/// "#)
/// .with_param("bounce", 2.0)
/// )
/// ```
pub fn custom_dynamic(code: impl Into<String>) -> CustomRuleBuilder {
CustomRuleBuilder::new(code, CustomRuleKind::Custom)
}
/// Create a neighbor custom rule with dynamic, editable parameters.
///
/// **Requires spatial hashing.**
///
/// # Example
///
/// ```ignore
/// .with_rule(Rule::neighbor_custom_dynamic(r#"
/// if neighbor_dist < uniforms.radius {
/// p.velocity += neighbor_dir * uniforms.force;
/// }
/// "#)
/// .with_param("radius", 0.2)
/// .with_param("force", 1.5)
/// )
/// ```
pub fn neighbor_custom_dynamic(code: impl Into<String>) -> CustomRuleBuilder {
CustomRuleBuilder::new(code, CustomRuleKind::Neighbor)
}
/// Create a collision rule with dynamic, editable parameters.
///
/// **Requires spatial hashing.**
///
/// # Example
///
/// ```ignore
/// .with_rule(Rule::collision_dynamic(r#"
/// p.velocity += neighbor_dir * uniforms.bounce;
/// "#)
/// .with_param("bounce", 3.0)
/// .with_radius(0.05)
/// )
/// ```
pub fn collision_dynamic(code: impl Into<String>) -> CustomRuleBuilder {
CustomRuleBuilder::new(code, CustomRuleKind::Collision)
}
}
// Macro to generate accumulator checker methods for the Rule enum.
// Each generated method returns true if the rule uses a specific accumulator type.
macro_rules! define_accumulator_checker {
($fn_name:ident, $($variant:ident),+) => {
macro_rules! $fn_name {
($self:ident) => {
pub(crate) fn $fn_name(&$self) -> bool {
match $self {
$(Rule::$variant { .. })|+ => true,
Rule::Typed { rule, .. } => rule.$fn_name(),
_ => false,
}
}
};
}
};
}
define_accumulator_checker!(needs_cohesion_accumulator, Cohere, Flock);
define_accumulator_checker!(needs_alignment_accumulator, Align, Flock);
define_accumulator_checker!(needs_chase_accumulator, Chase);
define_accumulator_checker!(needs_evade_accumulator, Evade);
define_accumulator_checker!(needs_viscosity_accumulator, Viscosity);
define_accumulator_checker!(needs_pressure_accumulator, Pressure);
define_accumulator_checker!(needs_surface_tension_accumulator, SurfaceTension);
define_accumulator_checker!(needs_avoid_accumulator, Avoid);
define_accumulator_checker!(needs_diffuse_accumulator, Diffuse);
define_accumulator_checker!(needs_accumulate_accumulator, Accumulate);
define_accumulator_checker!(needs_signal_accumulator, Signal);
define_accumulator_checker!(needs_absorb_accumulator, Absorb);
impl Rule {
/// Returns `true` if this is an OnDeath rule.
pub fn is_on_death(&self) -> bool {
matches!(self, Rule::OnDeath { .. })
}
/// Generate WGSL code for OnDeath handling.
///
/// Returns the code to run when `was_alive == 1u && p.alive == 0u`.
pub fn to_on_death_wgsl(&self) -> String {
match self {
Rule::OnDeath { action } => format!(
" // OnDeath action\n{}",
action
),
_ => String::new(),
}
}
/// Returns `true` if this is an OnSpawn rule.
pub fn is_on_spawn(&self) -> bool {
matches!(self, Rule::OnSpawn { .. })
}
/// Generate WGSL code for OnSpawn handling.
///
/// Returns the code to run when `was_alive == 0u && p.alive == 1u`.
pub fn to_on_spawn_wgsl(&self) -> String {
match self {
Rule::OnSpawn { action } => format!(
" // OnSpawn action\n{}",
action
),
_ => String::new(),
}
}
/// Returns `true` if this rule requires spatial hashing.
///
/// Neighbor-based rules (Collide, Separate, Cohere, Align, Convert,
/// Chase, Evade, NeighborCustom) need spatial hashing enabled via
/// `with_spatial_config()`.
pub fn requires_neighbors(&self) -> bool {
match self {
Rule::Collide { .. }
| Rule::OnCollision { .. }
| Rule::NBodyGravity { .. }
| Rule::LennardJones { .. }
| Rule::DLA { .. }
| Rule::Viscosity { .. }
| Rule::Pressure { .. }
| Rule::Magnetism { .. }
| Rule::SurfaceTension { .. }
| Rule::Avoid { .. }
| Rule::Separate { .. }
| Rule::Cohere { .. }
| Rule::Align { .. }
| Rule::Flock { .. }
| Rule::Convert { .. }
| Rule::Chase { .. }
| Rule::Evade { .. }
| Rule::Diffuse { .. }
| Rule::Accumulate { .. }
| Rule::Signal { .. }
| Rule::Absorb { .. }
| Rule::NeighborCustom(_) => true,
Rule::Typed { rule, .. } => rule.requires_neighbors(),
Rule::Switch { then_rule, else_rule, .. } => {
then_rule.requires_neighbors()
|| else_rule.as_ref().map(|r| r.requires_neighbors()).unwrap_or(false)
}
_ => false,
}
}
needs_cohesion_accumulator!(self);
needs_alignment_accumulator!(self);
needs_chase_accumulator!(self);
needs_evade_accumulator!(self);
needs_viscosity_accumulator!(self);
needs_pressure_accumulator!(self);
needs_surface_tension_accumulator!(self);
needs_avoid_accumulator!(self);
needs_diffuse_accumulator!(self);
needs_accumulate_accumulator!(self);
needs_signal_accumulator!(self);
needs_absorb_accumulator!(self);
/// Generate WGSL code for non-neighbor rules.
pub fn to_wgsl(&self, bounds: f32) -> String {
match self {
Rule::Gravity(g) => format!(
" // Gravity\n p.velocity.y -= {} * uniforms.delta_time;",
g
),
Rule::BounceWalls { restitution } => format!(
r#" // Bounce off walls (restitution: {restitution})
if p.position.x < -{bounds} {{
p.position.x = -{bounds};
p.velocity.x = abs(p.velocity.x) * {restitution};
}} else if p.position.x > {bounds} {{
p.position.x = {bounds};
p.velocity.x = -abs(p.velocity.x) * {restitution};
}}
if p.position.y < -{bounds} {{
p.position.y = -{bounds};
p.velocity.y = abs(p.velocity.y) * {restitution};
}} else if p.position.y > {bounds} {{
p.position.y = {bounds};
p.velocity.y = -abs(p.velocity.y) * {restitution};
}}
if p.position.z < -{bounds} {{
p.position.z = -{bounds};
p.velocity.z = abs(p.velocity.z) * {restitution};
}} else if p.position.z > {bounds} {{
p.position.z = {bounds};
p.velocity.z = -abs(p.velocity.z) * {restitution};
}}"#,
bounds = bounds,
restitution = restitution
),
Rule::WrapWalls => {
let size = bounds * 2.0;
format!(
r#" // Wrap around walls (toroidal)
if p.position.x < -{bounds} {{
p.position.x += {size};
}} else if p.position.x > {bounds} {{
p.position.x -= {size};
}}
if p.position.y < -{bounds} {{
p.position.y += {size};
}} else if p.position.y > {bounds} {{
p.position.y -= {size};
}}
if p.position.z < -{bounds} {{
p.position.z += {size};
}} else if p.position.z > {bounds} {{
p.position.z -= {size};
}}"#,
bounds = bounds,
size = size
)
}
Rule::Drag(d) => format!(
" // Drag\n p.velocity *= 1.0 - ({} * uniforms.delta_time);",
d
),
Rule::Acceleration(acc) => format!(
" // Acceleration\n p.velocity += vec3<f32>({}, {}, {}) * uniforms.delta_time;",
acc.x, acc.y, acc.z
),
Rule::AttractTo { point, strength } => format!(
r#" // Attract to point
{{
let attract_dir = vec3<f32>({}, {}, {}) - p.position;
let dist = length(attract_dir);
if dist > 0.001 {{
p.velocity += normalize(attract_dir) * {} * uniforms.delta_time;
}}
}}"#,
point.x, point.y, point.z, strength
),
Rule::RepelFrom { point, strength, radius } => format!(
r#" // Repel from point
{{
let repel_dir = p.position - vec3<f32>({}, {}, {});
let dist = length(repel_dir);
if dist < {} && dist > 0.001 {{
let force = ({} - dist) / {} * {};
p.velocity += normalize(repel_dir) * force * uniforms.delta_time;
}}
}}"#,
point.x, point.y, point.z, radius, radius, radius, strength
),
Rule::Seek { target, max_speed, max_force } => format!(
r#" // Seek: steering toward target
{{
let seek_target = vec3<f32>({tx:.6}, {ty:.6}, {tz:.6});
let desired = seek_target - p.position;
let dist = length(desired);
if dist > 0.001 {{
// Desired velocity at max speed toward target
let desired_vel = normalize(desired) * {max_speed:.6};
// Steering = desired - current velocity
var steering = desired_vel - p.velocity;
let steer_mag = length(steering);
if steer_mag > {max_force:.6} {{
steering = normalize(steering) * {max_force:.6};
}}
p.velocity += steering * uniforms.delta_time;
}}
}}"#,
tx = target.x, ty = target.y, tz = target.z,
max_speed = max_speed, max_force = max_force
),
Rule::Flee { target, max_speed, max_force, panic_radius } => format!(
r#" // Flee: steering away from target
{{
let flee_target = vec3<f32>({tx:.6}, {ty:.6}, {tz:.6});
let away = p.position - flee_target;
let dist = length(away);
let should_flee = {panic_radius:.6} <= 0.0 || dist < {panic_radius:.6};
if should_flee && dist > 0.001 {{
// Desired velocity at max speed away from target
let desired_vel = normalize(away) * {max_speed:.6};
// Steering = desired - current velocity
var steering = desired_vel - p.velocity;
let steer_mag = length(steering);
if steer_mag > {max_force:.6} {{
steering = normalize(steering) * {max_force:.6};
}}
p.velocity += steering * uniforms.delta_time;
}}
}}"#,
tx = target.x, ty = target.y, tz = target.z,
max_speed = max_speed, max_force = max_force, panic_radius = panic_radius
),
Rule::Arrive { target, max_speed, max_force, slowing_radius } => format!(
r#" // Arrive: seek with deceleration
{{
let arrive_target = vec3<f32>({tx:.6}, {ty:.6}, {tz:.6});
let desired = arrive_target - p.position;
let dist = length(desired);
if dist > 0.001 {{
// Scale desired speed based on distance
var target_speed = {max_speed:.6};
if dist < {slowing_radius:.6} {{
target_speed = {max_speed:.6} * (dist / {slowing_radius:.6});
}}
let desired_vel = normalize(desired) * target_speed;
var steering = desired_vel - p.velocity;
let steer_mag = length(steering);
if steer_mag > {max_force:.6} {{
steering = normalize(steering) * {max_force:.6};
}}
p.velocity += steering * uniforms.delta_time;
}}
}}"#,
tx = target.x, ty = target.y, tz = target.z,
max_speed = max_speed, max_force = max_force, slowing_radius = slowing_radius
),
Rule::Vortex { center, axis, strength } => {
// Normalize axis at compile time for the shader
let axis_len = (axis.x * axis.x + axis.y * axis.y + axis.z * axis.z).sqrt();
let (ax, ay, az) = if axis_len > 0.0001 {
(axis.x / axis_len, axis.y / axis_len, axis.z / axis_len)
} else {
(0.0, 1.0, 0.0) // Default to Y axis
};
format!(
r#" // Vortex
{{
let vortex_center = vec3<f32>({cx}, {cy}, {cz});
let vortex_axis = vec3<f32>({ax}, {ay}, {az});
let to_particle = p.position - vortex_center;
// Project onto plane perpendicular to axis
let along_axis = dot(to_particle, vortex_axis) * vortex_axis;
let radial = to_particle - along_axis;
let dist = length(radial);
if dist > 0.001 {{
// Tangent is perpendicular to both axis and radial
let tangent = cross(vortex_axis, radial) / dist;
p.velocity += tangent * {strength} * uniforms.delta_time;
}}
}}"#,
cx = center.x, cy = center.y, cz = center.z,
ax = ax, ay = ay, az = az,
strength = strength
)
}
Rule::Turbulence { scale, strength } => format!(
r#" // Turbulence (noise-based force)
{{
let turb_pos = p.position * {scale} + uniforms.time * 0.5;
let turb_force = vec3<f32>(
noise3(turb_pos + vec3<f32>(0.0, 0.0, 0.0)),
noise3(turb_pos + vec3<f32>(100.0, 0.0, 0.0)),
noise3(turb_pos + vec3<f32>(0.0, 100.0, 0.0))
);
p.velocity += turb_force * {strength} * uniforms.delta_time;
}}"#,
scale = scale, strength = strength
),
Rule::Orbit { center, strength } => format!(
r#" // Orbit
{{
let orbit_center = vec3<f32>({cx}, {cy}, {cz});
let to_center = orbit_center - p.position;
let dist = length(to_center);
if dist > 0.001 {{
// Centripetal force toward center
let centripetal = normalize(to_center) * {strength};
// Tangential direction (perpendicular in XZ plane)
let tangent = vec3<f32>(-to_center.z, 0.0, to_center.x) / dist;
// Adjust tangent velocity to maintain orbit
let orbital_speed = sqrt({strength} * dist);
let current_tangent_speed = dot(p.velocity, tangent);
p.velocity += centripetal * uniforms.delta_time;
p.velocity += tangent * (orbital_speed - current_tangent_speed) * 0.1 * uniforms.delta_time;
}}
}}"#,
cx = center.x, cy = center.y, cz = center.z,
strength = strength
),
Rule::Curl { scale, strength } => format!(
r#" // Curl noise (divergence-free flow)
{{
let curl_pos = p.position * {scale};
let eps = 0.01;
// Compute curl via finite differences of noise field
let dx = vec3<f32>(eps, 0.0, 0.0);
let dy = vec3<f32>(0.0, eps, 0.0);
let dz = vec3<f32>(0.0, 0.0, eps);
// Sample noise at offset positions
let n_py = noise3(curl_pos + dy + vec3<f32>(0.0, 0.0, 100.0));
let n_my = noise3(curl_pos - dy + vec3<f32>(0.0, 0.0, 100.0));
let n_pz = noise3(curl_pos + dz + vec3<f32>(0.0, 100.0, 0.0));
let n_mz = noise3(curl_pos - dz + vec3<f32>(0.0, 100.0, 0.0));
let n_px = noise3(curl_pos + dx + vec3<f32>(100.0, 0.0, 0.0));
let n_mx = noise3(curl_pos - dx + vec3<f32>(100.0, 0.0, 0.0));
// Curl = (dFz/dy - dFy/dz, dFx/dz - dFz/dx, dFy/dx - dFx/dy)
let curl = vec3<f32>(
(n_py - n_my) - (n_pz - n_mz),
(n_pz - n_mz) - (n_px - n_mx),
(n_px - n_mx) - (n_py - n_my)
) / (2.0 * eps);
p.velocity += curl * {strength} * uniforms.delta_time;
}}"#,
scale = scale, strength = strength
),
Rule::Wander { strength, frequency } => format!(
r#" // Wander (random movement)
{{
let wander_seed = index * 1103515245u + u32(uniforms.time * {frequency});
let hx = (wander_seed ^ (wander_seed >> 15u)) * 0x45d9f3bu;
let hy = ((wander_seed + 1u) ^ ((wander_seed + 1u) >> 15u)) * 0x45d9f3bu;
let hz = ((wander_seed + 2u) ^ ((wander_seed + 2u) >> 15u)) * 0x45d9f3bu;
let wander_force = vec3<f32>(
f32(hx & 0xFFFFu) / 32768.0 - 1.0,
f32(hy & 0xFFFFu) / 32768.0 - 1.0,
f32(hz & 0xFFFFu) / 32768.0 - 1.0
);
p.velocity += wander_force * {strength} * uniforms.delta_time;
}}"#
),
Rule::SpeedLimit { min, max } => format!(
r#" // Speed limit
{{
let speed = length(p.velocity);
if speed > 0.0001 {{
let clamped_speed = clamp(speed, {min:.6}, {max:.6});
p.velocity = normalize(p.velocity) * clamped_speed;
}}
}}"#
),
Rule::Custom(code) => format!(" // Custom rule\n{}", code),
// CustomDynamic uses static values when not using rule inspector
Rule::CustomDynamic { code, .. } => format!(" // Custom rule (dynamic)\n{}", code),
Rule::OnCondition { condition, action } => format!(
r#" // OnCondition
if {condition} {{
{action}
}}"#
),
Rule::OnInterval { interval, action } => format!(
r#" // OnInterval ({interval}s)
{{
let prev_intervals = floor((uniforms.time - uniforms.delta_time) / {interval});
let curr_intervals = floor(uniforms.time / {interval});
if curr_intervals > prev_intervals {{
{action}
}}
}}"#
),
Rule::Sync {
phase_field,
frequency,
field,
emit_amount,
coupling,
detection_threshold,
on_fire,
} => {
let on_fire_code = on_fire.as_ref().map(|c| c.as_str()).unwrap_or("");
format!(
r#" // Oscillator synchronization (Kuramoto model)
{{
let tau = 6.28318;
// Advance phase by frequency
p.{phase_field} += {frequency} * uniforms.delta_time * tau;
// Read field to detect nearby firing
let detected = field_read({field}u, p.position);
// If we detect activity, nudge our phase (coupling)
if detected > {detection_threshold} {{
// sin(phase/2) peaks at phase=π, meaning particles respond most
// strongly when halfway through their cycle
let phase_response = sin(p.{phase_field} * 0.5);
p.{phase_field} += {coupling} * phase_response * detected * uniforms.delta_time * tau;
}}
// Check if it's time to fire
if p.{phase_field} >= tau {{
// Reset phase (keep remainder for stability)
p.{phase_field} = p.{phase_field} - tau;
// Emit to field
field_write({field}u, p.position, {emit_amount});
// Run custom on_fire callback
{on_fire_code}
}}
}}"#
)
}
Rule::BondSprings { bonds, stiffness, damping, rest_length, max_stretch } => {
let no_bond = u32::MAX;
let max_stretch_code = if let Some(max_s) = max_stretch {
format!(
r#"
let stretch_ratio = dist / {rest_length};
if stretch_ratio > {max_s} {{
stretch = stretch + (stretch_ratio - {max_s}) * {rest_length} * 10.0;
}}"#,
rest_length = rest_length,
max_s = max_s
)
} else {
String::new()
};
let mut bond_code = String::new();
for bond_field in bonds {
bond_code.push_str(&format!(
r#"
// Bond: {bond_field}
if p.{bond_field} != {no_bond}u {{
let other = particles[p.{bond_field}];
let delta = other.position - p.position;
let dist = length(delta);
if dist > 0.0001 {{
let dir = delta / dist;
var stretch = dist - {rest_length};{max_stretch_code}
bond_force += dir * stretch * {stiffness};
let rel_vel = dot(other.velocity - p.velocity, dir);
bond_force += dir * rel_vel * {damping};
}}
}}
"#,
bond_field = bond_field,
no_bond = no_bond,
rest_length = rest_length,
stiffness = stiffness,
damping = damping,
max_stretch_code = max_stretch_code,
));
}
format!(
r#" // Bond springs
{{
var bond_force = vec3<f32>(0.0);
let dt = uniforms.delta_time;
{bond_code}
p.velocity += bond_force * dt;
}}"#,
bond_code = bond_code
)
}
Rule::ChainSprings { stiffness, damping, rest_length, max_stretch } => {
let max_stretch_code = if let Some(max_s) = max_stretch {
format!(
r#"
let stretch_ratio = dist / {rest_length};
if stretch_ratio > {max_s} {{
stretch = stretch + (stretch_ratio - {max_s}) * {rest_length} * 10.0;
}}"#
)
} else {
String::new()
};
format!(
r#" // Chain springs (index-based)
{{
var chain_force = vec3<f32>(0.0);
let dt = uniforms.delta_time;
let num_particles = arrayLength(&particles);
// Bond to previous particle (index - 1)
if index > 0u {{
let other = particles[index - 1u];
let delta = other.position - p.position;
let dist = length(delta);
if dist > 0.0001 {{
let dir = delta / dist;
var stretch = dist - {rest_length};{max_stretch_code}
chain_force += dir * stretch * {stiffness};
let rel_vel = dot(other.velocity - p.velocity, dir);
chain_force += dir * rel_vel * {damping};
}}
}}
// Bond to next particle (index + 1)
if index < num_particles - 1u {{
let other = particles[index + 1u];
let delta = other.position - p.position;
let dist = length(delta);
if dist > 0.0001 {{
let dir = delta / dist;
var stretch = dist - {rest_length};{max_stretch_code}
chain_force += dir * stretch * {stiffness};
let rel_vel = dot(other.velocity - p.velocity, dir);
chain_force += dir * rel_vel * {damping};
}}
}}
p.velocity += chain_force * dt;
}}"#,
rest_length = rest_length,
stiffness = stiffness,
damping = damping,
max_stretch_code = max_stretch_code,
)
}
Rule::RadialSprings { hub_stiffness, ring_stiffness, damping, hub_length, ring_length } => {
format!(
r#" // Radial springs (hub + ring)
{{
var radial_force = vec3<f32>(0.0);
let dt = uniforms.delta_time;
let num_particles = arrayLength(&particles);
if index > 0u {{
// Connect to center hub (particle 0)
let hub = particles[0u];
let delta = hub.position - p.position;
let dist = length(delta);
if dist > 0.0001 {{
let dir = delta / dist;
let stretch = dist - {hub_length};
radial_force += dir * stretch * {hub_stiffness};
let rel_vel = dot(hub.velocity - p.velocity, dir);
radial_force += dir * rel_vel * {damping};
}}
// Connect to ring neighbors (wrapping)
let ring_size = num_particles - 1u;
let ring_idx = index - 1u; // 0-based ring index
// Previous in ring
let prev_ring = (ring_idx + ring_size - 1u) % ring_size;
let prev_idx = prev_ring + 1u;
{{
let other = particles[prev_idx];
let delta = other.position - p.position;
let dist = length(delta);
if dist > 0.0001 {{
let dir = delta / dist;
let stretch = dist - {ring_length};
radial_force += dir * stretch * {ring_stiffness};
let rel_vel = dot(other.velocity - p.velocity, dir);
radial_force += dir * rel_vel * {damping};
}}
}}
// Next in ring
let next_ring = (ring_idx + 1u) % ring_size;
let next_idx = next_ring + 1u;
{{
let other = particles[next_idx];
let delta = other.position - p.position;
let dist = length(delta);
if dist > 0.0001 {{
let dir = delta / dist;
let stretch = dist - {ring_length};
radial_force += dir * stretch * {ring_stiffness};
let rel_vel = dot(other.velocity - p.velocity, dir);
radial_force += dir * rel_vel * {damping};
}}
}}
}}
p.velocity += radial_force * dt;
}}"#,
hub_stiffness = hub_stiffness,
ring_stiffness = ring_stiffness,
damping = damping,
hub_length = hub_length,
ring_length = ring_length,
)
}
Rule::AdjacencySprings { stiffness, damping, rest_length, max_stretch } => {
let max_stretch_code = if let Some(max_s) = max_stretch {
format!(
r#"
let stretch_ratio = dist / {rest_length};
if stretch_ratio > {max_s} {{
stretch = stretch + (stretch_ratio - {max_s}) * {rest_length} * 10.0;
}}"#
)
} else {
String::new()
};
format!(
r#" // Adjacency springs (dynamic soft-body)
{{
var adj_spring_force = vec3<f32>(0.0);
let dt = uniforms.delta_time;
let adj_count = adjacency_count(index);
for (var i = 0u; i < adj_count; i++) {{
let other_idx = adjacency_neighbor(index, i);
let other = particles[other_idx];
let delta = other.position - p.position;
let dist = length(delta);
if dist > 0.0001 {{
let dir = delta / dist;
var stretch = dist - {rest_length};{max_stretch_code}
adj_spring_force += dir * stretch * {stiffness};
let rel_vel = dot(other.velocity - p.velocity, dir);
adj_spring_force += dir * rel_vel * {damping};
}}
}}
p.velocity += adj_spring_force * dt;
}}"#,
rest_length = rest_length,
stiffness = stiffness,
damping = damping,
max_stretch_code = max_stretch_code,
)
}
Rule::Buoyancy { surface_y, density } => {
format!(
r#" // Buoyancy
{{
let depth = {surface_y} - p.position.y;
if depth > 0.0 {{
// Upward force proportional to depth and density
let buoyancy_force = depth * {density} * 10.0;
p.velocity.y += buoyancy_force * uniforms.delta_time;
// Water resistance (drag when submerged)
p.velocity *= 1.0 - (0.5 * uniforms.delta_time);
}}
}}"#,
surface_y = surface_y,
density = density,
)
}
Rule::Friction { ground_y, strength, threshold } => {
format!(
r#" // Ground friction
{{
let height_above_ground = p.position.y - {ground_y};
if height_above_ground < {threshold} {{
// Friction increases as we get closer to ground
let friction_factor = 1.0 - (height_above_ground / {threshold});
let friction = {strength} * friction_factor;
// Apply friction to horizontal velocity
p.velocity.x *= 1.0 - (friction * uniforms.delta_time);
p.velocity.z *= 1.0 - (friction * uniforms.delta_time);
// Prevent sinking below ground
if p.position.y < {ground_y} {{
p.position.y = {ground_y};
p.velocity.y = max(p.velocity.y, 0.0);
}}
}}
}}"#,
ground_y = ground_y,
strength = strength,
threshold = threshold,
)
}
Rule::Wind { direction, strength, turbulence } => {
// Normalize direction
let len = (direction.x * direction.x + direction.y * direction.y + direction.z * direction.z).sqrt();
let (dx, dy, dz) = if len > 0.0001 {
(direction.x / len, direction.y / len, direction.z / len)
} else {
(1.0, 0.0, 0.0)
};
// Generate different code paths based on whether turbulence is enabled
if *turbulence > 0.0 {
format!(
r#" // Wind with turbulence
{{
let wind_dir = vec3<f32>({dx:.6}, {dy:.6}, {dz:.6});
var wind_strength = {strength:.6};
let turb_pos = p.position * 3.0 + uniforms.time * 2.0;
let turb = noise3(turb_pos) * {turbulence:.6};
wind_strength = wind_strength * (1.0 + turb);
// Also vary direction slightly
let turb_dir = vec3<f32>(
noise3(turb_pos + vec3<f32>(100.0, 0.0, 0.0)),
noise3(turb_pos + vec3<f32>(0.0, 100.0, 0.0)),
noise3(turb_pos + vec3<f32>(0.0, 0.0, 100.0))
) * {turbulence:.6} * 0.5;
p.velocity += (wind_dir + turb_dir) * wind_strength * uniforms.delta_time;
}}"#,
dx = dx,
dy = dy,
dz = dz,
strength = strength,
turbulence = turbulence,
)
} else {
format!(
r#" // Wind (steady)
{{
let wind_dir = vec3<f32>({dx:.6}, {dy:.6}, {dz:.6});
p.velocity += wind_dir * {strength:.6} * uniforms.delta_time;
}}"#,
dx = dx,
dy = dy,
dz = dz,
strength = strength,
)
}
}
Rule::Current { field, strength } => {
format!(
r#" // Current (follow field gradient)
{{
let gradient = field_{field}_gradient(p.position);
p.velocity += gradient * {strength} * uniforms.delta_time;
}}"#,
field = field,
strength = strength,
)
}
Rule::RespawnBelow { threshold_y, spawn_y, reset_velocity } => {
let velocity_reset = if *reset_velocity {
"p.velocity = vec3<f32>(0.0);"
} else {
"p.velocity.y = 0.0;" // Just stop falling
};
format!(
r#" // Respawn below threshold
if p.position.y < {threshold_y} {{
// Randomize X and Z position on respawn
let seed = index + u32(uniforms.time * 1000.0);
let hash1 = (seed * 1103515245u + 12345u);
let hash2 = (hash1 * 1103515245u + 12345u);
let rx = f32(hash1 % 10000u) / 10000.0 * 2.0 - 1.0;
let rz = f32(hash2 % 10000u) / 10000.0 * 2.0 - 1.0;
p.position.x = rx * 0.8; // Spread across bounds
p.position.y = {spawn_y};
p.position.z = rz * 0.8;
{velocity_reset}
}}"#,
threshold_y = threshold_y,
spawn_y = spawn_y,
velocity_reset = velocity_reset,
)
}
Rule::Age => " // Age\n p.age += uniforms.delta_time;".to_string(),
Rule::Lifetime(seconds) => format!(
r#" // Lifetime
if p.age > {seconds} {{
p.alive = 0u;
}}"#
),
Rule::FadeOut(duration) => format!(
r#" // Fade out
{{
let fade = clamp(1.0 - p.age / {duration}, 0.0, 1.0);
p.color *= fade;
}}"#
),
Rule::ShrinkOut(duration) => format!(
r#" // Shrink out
p.scale = clamp(1.0 - p.age / {duration}, 0.0, 1.0);"#
),
Rule::Refractory {
trigger,
charge,
active_threshold,
depletion_rate,
regen_rate,
} => format!(
r#" // Refractory: charge depletion/regeneration
if p.{trigger} > {active_threshold} {{
// Trigger is active - deplete charge
p.{charge} = max(p.{charge} - p.{trigger} * {depletion_rate}, 0.0);
}} else {{
// Trigger inactive - regenerate charge
p.{charge} = min(p.{charge} + {regen_rate}, 1.0);
}}"#
),
Rule::ColorOverLife { start, end, duration } => format!(
r#" // Color over life
{{
let t = clamp(p.age / {duration}, 0.0, 1.0);
p.color = mix(vec3<f32>({}, {}, {}), vec3<f32>({}, {}, {}), t);
}}"#,
start.x, start.y, start.z, end.x, end.y, end.z
),
Rule::PointGravity { point, strength, softening } => format!(
r#" // Point gravity (inverse-square)
{{
let to_point = vec3<f32>({}, {}, {}) - p.position;
let dist_sq = dot(to_point, to_point) + {softening} * {softening};
let dist = sqrt(dist_sq);
if dist > 0.001 {{
let force = {strength} / dist_sq;
p.velocity += (to_point / dist) * force * uniforms.delta_time;
}}
}}"#,
point.x, point.y, point.z
),
Rule::Spring { anchor, stiffness, damping } => format!(
r#" // Spring (Hooke's law)
{{
let anchor_pos = vec3<f32>({}, {}, {});
let displacement = anchor_pos - p.position;
let spring_force = displacement * {stiffness};
let damping_force = -p.velocity * {damping};
p.velocity += (spring_force + damping_force) * uniforms.delta_time;
}}"#,
anchor.x, anchor.y, anchor.z
),
Rule::Radial { point, strength, radius, falloff } => {
let softening = 0.01_f32;
let radius_check = if *radius > 0.0 {
format!("dist < {radius} && ")
} else {
String::new()
};
let falloff_expr = match falloff {
Falloff::Constant => "1.0".to_string(),
Falloff::Linear => format!("(1.0 - dist / {radius})"),
Falloff::Inverse => format!("(1.0 / (dist + {softening}))"),
Falloff::InverseSquare => format!("(1.0 / (dist * dist + {softening} * {softening}))"),
Falloff::Smooth => format!("(1.0 - smoothstep(0.0, {radius}, dist))"),
};
format!(
r#" // Radial force (strength={strength}, falloff={falloff:?})
{{
let radial_center = vec3<f32>({px}, {py}, {pz});
let to_particle = p.position - radial_center;
let dist = length(to_particle);
if {radius_check}dist > 0.001 {{
let falloff = {falloff_expr};
let dir = to_particle / dist;
p.velocity += dir * {strength} * falloff * uniforms.delta_time;
}}
}}"#,
px = point.x, py = point.y, pz = point.z,
strength = strength,
falloff = falloff,
radius_check = radius_check,
falloff_expr = falloff_expr
)
}
Rule::Shockwave { origin, speed, width, strength, repeat } => {
let time_expr = if *repeat > 0.0 {
format!("(uniforms.time % {repeat})")
} else {
"uniforms.time".to_string()
};
format!(
r#" // Shockwave (speed={speed}, repeat={repeat})
{{
let wave_center = vec3<f32>({ox}, {oy}, {oz});
let to_particle = p.position - wave_center;
let dist = length(to_particle);
let wave_time = {time_expr};
let wave_radius = wave_time * {speed};
let wave_dist = abs(dist - wave_radius);
if wave_dist < {width} && dist > 0.001 {{
// Smooth falloff within wavefront
let wave_strength = (1.0 - wave_dist / {width}) * {strength};
let dir = to_particle / dist;
p.velocity += dir * wave_strength * uniforms.delta_time;
}}
}}"#,
ox = origin.x, oy = origin.y, oz = origin.z,
speed = speed, width = width, strength = strength, repeat = repeat,
time_expr = time_expr
)
}
Rule::Pulse { point, strength, frequency, radius } => {
let radius_check = if *radius > 0.0 {
format!("dist < {} && ", radius)
} else {
String::new()
};
format!(
r#" // Pulse (breathing force, freq={frequency}Hz)
{{
let pulse_center = vec3<f32>({px}, {py}, {pz});
let to_particle = p.position - pulse_center;
let dist = length(to_particle);
if {radius_check}dist > 0.001 {{
// Sine oscillation: positive = expand, negative = contract
let pulse_factor = sin(uniforms.time * {frequency} * 6.283185);
let dir = to_particle / dist;
p.velocity += dir * {strength} * pulse_factor * uniforms.delta_time;
}}
}}"#,
px = point.x, py = point.y, pz = point.z,
strength = strength, frequency = frequency,
radius_check = radius_check
)
}
Rule::Oscillate { axis, amplitude, frequency, spatial_scale } => {
let axis_len = (axis.x * axis.x + axis.y * axis.y + axis.z * axis.z).sqrt();
let (ax, ay, az) = if axis_len > 0.0001 {
(axis.x / axis_len, axis.y / axis_len, axis.z / axis_len)
} else {
(0.0, 1.0, 0.0)
};
if *spatial_scale > 0.0 {
format!(
r#" // Oscillate (traveling wave)
{{
let osc_axis = vec3<f32>({ax}, {ay}, {az});
// Compute distance from oscillation axis for radial waves
let along_axis = osc_axis * dot(p.position, osc_axis);
let perpendicular = p.position - along_axis;
let radial_dist = length(perpendicular);
let phase = uniforms.time * {frequency} * 6.283185 - radial_dist * {spatial_scale};
let wave = sin(phase) * {amplitude};
p.velocity += osc_axis * wave * uniforms.delta_time;
}}"#
)
} else {
format!(
r#" // Oscillate (uniform)
{{
let osc_axis = vec3<f32>({ax}, {ay}, {az});
let phase = uniforms.time * {frequency} * 6.283185;
let wave = sin(phase) * {amplitude};
p.velocity += osc_axis * wave * uniforms.delta_time;
}}"#
)
}
}
Rule::PositionNoise { scale, strength, speed } => format!(
r#" // Position noise (jitter)
{{
let noise_pos = p.position * {scale} + uniforms.time * {speed};
let jitter = vec3<f32>(
noise3(noise_pos),
noise3(noise_pos + vec3<f32>(31.7, 0.0, 0.0)),
noise3(noise_pos + vec3<f32>(0.0, 47.3, 0.0))
);
p.position += jitter * {strength};
}}"#
),
Rule::ColorBySpeed { slow_color, fast_color, max_speed } => format!(
r#" // Color by speed
{{
let speed = length(p.velocity);
let t = clamp(speed / {max_speed}, 0.0, 1.0);
p.color = mix(vec3<f32>({}, {}, {}), vec3<f32>({}, {}, {}), t);
}}"#,
slow_color.x, slow_color.y, slow_color.z,
fast_color.x, fast_color.y, fast_color.z
),
Rule::ColorByAge { young_color, old_color, max_age } => format!(
r#" // Color by age
{{
let t = clamp(p.age / {max_age}, 0.0, 1.0);
p.color = mix(vec3<f32>({}, {}, {}), vec3<f32>({}, {}, {}), t);
}}"#,
young_color.x, young_color.y, young_color.z,
old_color.x, old_color.y, old_color.z
),
Rule::ScaleBySpeed { min_scale, max_scale, max_speed } => format!(
r#" // Scale by speed
{{
let speed = length(p.velocity);
let t = clamp(speed / {max_speed:.6}, 0.0, 1.0);
p.scale = mix({min_scale:.6}, {max_scale:.6}, t);
}}"#
),
Rule::Maybe { probability, action } => format!(
r#" // Maybe (probabilistic)
{{
// Hash-based random using particle index and time
let hash_seed = f32(index) * 12.9898 + uniforms.time * 78.233;
let rand = fract(sin(hash_seed) * 43758.5453);
if rand < {probability} {{
{action}
}}
}}"#
),
Rule::Trigger { condition, action } => format!(
r#" // Trigger (conditional)
if {condition} {{
{action}
}}"#
),
Rule::Periodic { interval, phase_field, action } => {
let phase_offset = match phase_field {
Some(field) => format!("p.{field}"),
None => "0.0".to_string(),
};
format!(
r#" // Periodic (time-based)
{{
let phase_offset = {phase_offset};
let adjusted_time = uniforms.time + phase_offset * {interval};
let prev_time = adjusted_time - uniforms.delta_time;
let current_cycle = floor(adjusted_time / {interval});
let prev_cycle = floor(prev_time / {interval});
if current_cycle != prev_cycle {{
{action}
}}
}}"#
)
}
Rule::Gradient { field, strength, ascending } => {
let sign = if *ascending { 1.0 } else { -1.0 };
format!(
r#" // Gradient (chemotaxis)
{{
let eps = 0.02; // Sample offset
let here = field_read({field}u, p.position);
let dx = field_read({field}u, p.position + vec3<f32>(eps, 0.0, 0.0)) - field_read({field}u, p.position - vec3<f32>(eps, 0.0, 0.0));
let dy = field_read({field}u, p.position + vec3<f32>(0.0, eps, 0.0)) - field_read({field}u, p.position - vec3<f32>(0.0, eps, 0.0));
let dz = field_read({field}u, p.position + vec3<f32>(0.0, 0.0, eps)) - field_read({field}u, p.position - vec3<f32>(0.0, 0.0, eps));
let grad = vec3<f32>(dx, dy, dz) / (2.0 * eps);
let grad_len = length(grad);
if grad_len > 0.0001 {{
p.velocity += normalize(grad) * {strength} * {sign:.1} * uniforms.delta_time;
}}
}}"#
)
}
Rule::Lerp { field, target, rate } => format!(
r#" // Lerp (smooth interpolation)
p.{field} = mix(p.{field}, {target}, clamp({rate} * uniforms.delta_time, 0.0, 1.0));"#
),
Rule::Die { condition, field } => format!(
r#" // Die (conditional death)
if {condition} {{
p.{field} = 0u;
}}"#
),
Rule::State { field, transitions } => {
let mut code = String::from(" // State machine transitions\n");
for (from, to, condition) in transitions {
code.push_str(&format!(
" if p.{field} == {from}u && {condition} {{ p.{field} = {to}u; }}\n"
));
}
code
}
Rule::Agent {
state_field,
prev_state_field,
state_timer_field,
states,
} => {
let mut code = String::from(" // Agent state machine\n {\n");
// Check if state changed (for entry/exit actions)
code.push_str(&format!(
" let state_changed = p.{state_field} != p.{prev_state_field};\n"
));
// Handle state timer reset on state change
if let Some(timer_field) = state_timer_field {
code.push_str(&format!(
" if state_changed {{ p.{timer_field} = 0.0; }}\n"
));
}
// Generate exit actions (run when leaving a state)
let has_exit_actions = states.iter().any(|s| s.on_exit.is_some());
if has_exit_actions {
code.push_str("\n // Exit actions (previous state)\n");
code.push_str(" if state_changed {\n");
for state in states.iter() {
if let Some(exit_code) = &state.on_exit {
let state_id = state.id;
let name_comment = state
.name
.as_ref()
.map(|n| format!(" // {}", n))
.unwrap_or_default();
code.push_str(&format!(
" if p.{prev_state_field} == {state_id}u {{{name_comment}\n"
));
for line in exit_code.lines() {
code.push_str(&format!(" {}\n", line.trim()));
}
code.push_str(" }\n");
}
}
code.push_str(" }\n");
}
// Generate entry actions (run when entering a state)
let has_entry_actions = states.iter().any(|s| s.on_enter.is_some());
if has_entry_actions {
code.push_str("\n // Entry actions (current state)\n");
code.push_str(" if state_changed {\n");
for state in states.iter() {
if let Some(enter_code) = &state.on_enter {
let state_id = state.id;
let name_comment = state
.name
.as_ref()
.map(|n| format!(" // {}", n))
.unwrap_or_default();
code.push_str(&format!(
" if p.{state_field} == {state_id}u {{{name_comment}\n"
));
for line in enter_code.lines() {
code.push_str(&format!(" {}\n", line.trim()));
}
code.push_str(" }\n");
}
}
code.push_str(" }\n");
}
// Update prev_state AFTER entry/exit actions (so transitions can trigger them next frame)
code.push_str(&format!(
"\n // Mark state change as processed\n p.{prev_state_field} = p.{state_field};\n"
));
// Generate update actions (run every frame for current state)
let has_update_actions = states.iter().any(|s| s.on_update.is_some());
if has_update_actions {
code.push_str("\n // Update actions (current state)\n");
for state in states.iter() {
if let Some(update_code) = &state.on_update {
let state_id = state.id;
let name_comment = state
.name
.as_ref()
.map(|n| format!(" // {}", n))
.unwrap_or_default();
code.push_str(&format!(
" if p.{state_field} == {state_id}u {{{name_comment}\n"
));
for line in update_code.lines() {
code.push_str(&format!(" {}\n", line.trim()));
}
code.push_str(" }\n");
}
}
}
// Increment state timer
if let Some(timer_field) = state_timer_field {
code.push_str(&format!(
"\n // Increment state timer\n p.{timer_field} += uniforms.delta_time;\n"
));
}
// Generate transitions (sorted by priority, highest first)
code.push_str("\n // State transitions\n");
for state in states.iter() {
if state.transitions.is_empty() {
continue;
}
let state_id = state.id;
let name_comment = state
.name
.as_ref()
.map(|n| format!(" // from {}", n))
.unwrap_or_default();
// Sort transitions by priority (highest first)
let mut sorted_transitions = state.transitions.clone();
sorted_transitions.sort_by(|a, b| b.priority.cmp(&a.priority));
code.push_str(&format!(
" if p.{state_field} == {state_id}u {{{name_comment}\n"
));
for (i, transition) in sorted_transitions.iter().enumerate() {
let condition = &transition.condition;
let to_state = transition.to;
if i == 0 {
code.push_str(&format!(
" if {condition} {{\n p.{state_field} = {to_state}u;\n }}"
));
} else {
code.push_str(&format!(
" else if {condition} {{\n p.{state_field} = {to_state}u;\n }}"
));
}
}
// Close the if-else chain with newline
if !sorted_transitions.is_empty() {
code.push('\n');
}
code.push_str(" }\n");
}
code.push_str(" }\n");
code
}
Rule::Grow { rate, min, max } => format!(
r#" // Grow (scale over time)
p.scale = clamp(p.scale + {rate:.6} * uniforms.delta_time, {min:.6}, {max:.6});"#
),
Rule::Decay { field, rate } => format!(
r#" // Decay (multiplicative)
p.{field} *= pow({rate:.6}, uniforms.delta_time);"#
),
Rule::DensityBuoyancy { density_field, medium_density, strength } => format!(
r#" // Density-based buoyancy
{{
let buoyancy_force = ({medium_density} - p.{density_field}) * {strength};
p.velocity.y += buoyancy_force * uniforms.delta_time;
}}"#
),
Rule::Mass { field } => format!(
r#" // Mass scaling (F=ma → a=F/m)
{{
let inv_mass = 1.0 / max(p.{field}, 0.001);
// Scale this frame's velocity change by inverse mass
// Note: this assumes velocity changes since last frame are forces
p.velocity *= inv_mass;
}}"#
),
Rule::Tween { field, from, to, duration, timer_field } => format!(
r#" // Tween animation
{{
let t = clamp(p.{timer_field} / {duration}, 0.0, 1.0);
p.{field} = mix({from}, {to}, t);
}}"#
),
Rule::Threshold { input_field, output_field, threshold, above, below } => format!(
r#" // Threshold (step function)
if p.{input_field} >= {threshold} {{
p.{output_field} = {above};
}} else {{
p.{output_field} = {below};
}}"#
),
Rule::Gate { condition, action } => format!(
r#" // Gate (conditional action)
if {condition} {{
{action}
}}"#
),
Rule::Noise { field, amplitude, frequency, time_scale } => format!(
r#" // Procedural noise
{{
let noise_pos = p.position * {frequency} + vec3<f32>(uniforms.time * {time_scale});
p.{field} += noise3(noise_pos) * {amplitude};
}}"#
),
Rule::Remap { field, in_min, in_max, out_min, out_max } => format!(
r#" // Remap range
{{
let t = (p.{field} - {in_min:.6}) / ({in_max:.6} - {in_min:.6});
p.{field} = {out_min:.6} + t * ({out_max:.6} - {out_min:.6});
}}"#
),
Rule::Clamp { field, min, max } => format!(
" // Clamp\n p.{field} = clamp(p.{field}, {min:.6}, {max:.6});"
),
Rule::Smooth { field, target, rate } => format!(
" // Smooth toward target\n p.{field} = mix(p.{field}, {target:.6}, {rate:.6} * uniforms.delta_time);"
),
Rule::Quantize { field, step } => format!(
" // Quantize to steps\n p.{field} = floor(p.{field} / {step:.6}) * {step:.6};"
),
Rule::Modulo { field, min, max } => format!(
r#" // Modulo wrap
{{
let range = {max:.6} - {min:.6};
p.{field} = {min:.6} + (((p.{field} - {min:.6}) % range) + range) % range;
}}"#
),
Rule::Copy { from, to, scale, offset } => format!(
" // Copy field\n p.{to} = p.{from} * {scale:.6} + {offset:.6};"
),
// Logic gates
Rule::And { a, b, output } => format!(
" // AND (min)\n p.{output} = min(p.{a}, p.{b});"
),
Rule::Or { a, b, output } => format!(
" // OR (max)\n p.{output} = max(p.{a}, p.{b});"
),
Rule::Not { input, output, max } => format!(
" // NOT (invert)\n p.{output} = {max:.6} - p.{input};"
),
Rule::Xor { a, b, output } => format!(
" // XOR (abs difference)\n p.{output} = abs(p.{a} - p.{b});"
),
Rule::Hysteresis { input, output, low_threshold, high_threshold, on_value, off_value } => format!(
r#" // Hysteresis (Schmitt trigger)
if p.{input} > {high_threshold:.6} {{
p.{output} = {on_value:.6};
}} else if p.{input} < {low_threshold:.6} {{
p.{output} = {off_value:.6};
}}"#
),
Rule::Latch { output, set_condition, reset_condition, set_value, reset_value } => format!(
r#" // Latch (SR flip-flop)
if {reset_condition} {{
p.{output} = {reset_value:.6};
}} else if {set_condition} {{
p.{output} = {set_value:.6};
}}"#
),
Rule::Edge { input, prev_field, output, threshold, rising, falling } => {
let rising_check = if *rising {
format!("(p.{prev_field} < {threshold:.6} && p.{input} >= {threshold:.6})")
} else {
"false".to_string()
};
let falling_check = if *falling {
format!("(p.{prev_field} >= {threshold:.6} && p.{input} < {threshold:.6})")
} else {
"false".to_string()
};
format!(
r#" // Edge detector
if {rising_check} || {falling_check} {{
p.{output} = 1.0;
}} else {{
p.{output} = 0.0;
}}
p.{prev_field} = p.{input};"#
)
}
Rule::Select { condition, then_field, else_field, output } => format!(
r#" // Select (ternary)
if {condition} {{
p.{output} = p.{then_field};
}} else {{
p.{output} = p.{else_field};
}}"#
),
Rule::Blend { a, b, weight, output } => format!(
" // Blend by weight\n p.{output} = mix(p.{a}, p.{b}, p.{weight});"
),
Rule::CopyField { from, to } => format!(
" // Copy field\n p.{to} = p.{from};"
),
// Neighbor rules generate code through to_neighbor_wgsl
Rule::Collide { .. }
| Rule::OnCollision { .. }
| Rule::NBodyGravity { .. }
| Rule::LennardJones { .. }
| Rule::DLA { .. }
| Rule::Viscosity { .. }
| Rule::Pressure { .. }
| Rule::Magnetism { .. }
| Rule::SurfaceTension { .. }
| Rule::Avoid { .. }
| Rule::Separate { .. }
| Rule::Cohere { .. }
| Rule::Align { .. }
| Rule::Flock { .. }
| Rule::Typed { .. }
| Rule::Convert { .. }
| Rule::Chase { .. }
| Rule::Evade { .. }
| Rule::Diffuse { .. }
| Rule::Accumulate { .. }
| Rule::Signal { .. }
| Rule::Absorb { .. }
| Rule::NeighborCustom(_)
| Rule::NeighborCustomDynamic { .. }
| Rule::OnCollisionDynamic { .. }
| Rule::OnDeath { .. }
| Rule::OnSpawn { .. } => String::new(), // OnDeath/OnSpawn/neighbor rules handled separately
Rule::Deposit { field_index, source, amount } => format!(
r#" // Deposit: write particle value to field
field_write({field_index}u, p.position, p.{source} * {amount});"#
),
Rule::Sense { field_index, target } => format!(
r#" // Sense: read field value into particle
p.{target} = field_read({field_index}u, p.position);"#
),
Rule::Consume { field_index, target, rate } => format!(
r#" // Consume: read field value and deplete
let consumed_val = min(field_read({field_index}u, p.position), {rate});
p.{target} += consumed_val;
field_write({field_index}u, p.position, -consumed_val);"#
),
Rule::Switch { condition, then_rule, else_rule } => {
let then_code = then_rule.to_wgsl(bounds);
let else_code = else_rule.as_ref().map(|r| r.to_wgsl(bounds)).unwrap_or_default();
if else_code.is_empty() {
format!(
r#" // Switch: conditional rule
if {condition} {{
{then_code}
}}"#
)
} else {
format!(
r#" // Switch: conditional rule
if {condition} {{
{then_code}
}} else {{
{else_code}
}}"#
)
}
},
Rule::Split {
condition,
offspring_count,
offspring_type,
resource_field,
resource_cost,
spread,
speed_min,
speed_max,
} => {
let resource_check = if let Some(field) = resource_field {
format!(" && p.{field} >= {resource_cost}")
} else {
String::new()
};
let resource_deduct = if let Some(field) = resource_field {
format!("\n p.{field} -= {resource_cost};")
} else {
String::new()
};
let child_type = offspring_type
.map(|t| format!("{t}u"))
.unwrap_or_else(|| "p.particle_type".to_string());
format!(
r#" // Split: spawn offspring when condition met
if ({condition}){resource_check} {{
// Record split event for sub-emitter processing
let split_idx = atomicAdd(&death_count, 1u);
if split_idx < arrayLength(&death_buffer) {{
death_buffer[split_idx].position = p.position;
death_buffer[split_idx].velocity = p.velocity;
death_buffer[split_idx].color = p.color;
death_buffer[split_idx].parent_type = {child_type};
// Store spawn parameters in padding fields
// offspring_count={offspring_count}, spread={spread}, speed_min={speed_min}, speed_max={speed_max}
}}{resource_deduct}
}}"#
)
},
}
}
/// Generate WGSL code for neighbor-based rules (inside neighbor loop).
pub fn to_neighbor_wgsl(&self) -> String {
match self {
Rule::Collide { radius, restitution } => format!(
r#" // Elastic collision
if neighbor_dist < {radius} && neighbor_dist > 0.0001 {{
// Relative velocity along collision normal (positive = approaching)
let rel_vel = dot(neighbor_vel - p.velocity, neighbor_dir);
// Only respond if particles are approaching
if rel_vel > 0.0 {{
// Impulse for elastic collision (assumes equal masses)
// For two equal masses: each gets half the momentum exchange
let impulse = (1.0 + {restitution}) * rel_vel * 0.5;
p.velocity += neighbor_dir * impulse;
}}
// Position correction to resolve overlap
let overlap = {radius} - neighbor_dist;
p.velocity += neighbor_dir * overlap * 2.0;
}}"#
),
Rule::OnCollision { radius, response } => format!(
r#" // Custom collision response
if neighbor_dist < {radius} && neighbor_dist > 0.0001 {{
// Precompute useful collision variables
let overlap = {radius} - neighbor_dist;
let rel_vel = dot(neighbor_vel - p.velocity, neighbor_dir);
// User-defined collision response
{response}
}}"#
),
Rule::NBodyGravity { strength, softening, radius } => format!(
r#" // N-body gravity
if neighbor_dist < {radius} {{
let dist_sq = neighbor_dist * neighbor_dist + {softening} * {softening};
let force = {strength} / dist_sq;
// Attract toward neighbor (opposite of neighbor_dir)
p.velocity -= neighbor_dir * force * uniforms.delta_time;
}}"#
),
Rule::LennardJones { epsilon, sigma, cutoff } => format!(
r#" // Lennard-Jones potential
if neighbor_dist < {cutoff} && neighbor_dist > 0.0001 {{
// LJ potential: V(r) = 4ε[(σ/r)^12 - (σ/r)^6]
// Force: F(r) = 24ε/r * [2(σ/r)^12 - (σ/r)^6]
let sr = {sigma} / neighbor_dist;
let sr6 = sr * sr * sr * sr * sr * sr;
let sr12 = sr6 * sr6;
// Force magnitude (positive = repulsive, negative = attractive)
let force_mag = 24.0 * {epsilon} / neighbor_dist * (2.0 * sr12 - sr6);
// Apply force along neighbor direction (positive pushes away)
p.velocity += neighbor_dir * force_mag * uniforms.delta_time;
}}"#
),
Rule::DLA { seed_type, mobile_type, stick_radius, diffusion_strength } => format!(
r#" // Diffusion-Limited Aggregation
// Mobile particles stick to seed particles on contact
if p.particle_type == {mobile_type}u && other.particle_type == {seed_type}u {{
if neighbor_dist < {stick_radius} {{
// Stick: become part of the structure
p.particle_type = {seed_type}u;
p.velocity = vec3<f32>(0.0, 0.0, 0.0);
}}
}}
// Apply diffusion (random walk) to mobile particles
if p.particle_type == {mobile_type}u {{
let diff_seed = index * 1103515245u + u32(uniforms.time * 1000.0);
let hx = (diff_seed ^ (diff_seed >> 15u)) * 0x45d9f3bu;
let hy = ((diff_seed + 1u) ^ ((diff_seed + 1u) >> 15u)) * 0x45d9f3bu;
let hz = ((diff_seed + 2u) ^ ((diff_seed + 2u) >> 15u)) * 0x45d9f3bu;
let diff_force = vec3<f32>(
f32(hx & 0xFFFFu) / 32768.0 - 1.0,
f32(hy & 0xFFFFu) / 32768.0 - 1.0,
f32(hz & 0xFFFFu) / 32768.0 - 1.0
);
p.velocity += diff_force * {diffusion_strength} * uniforms.delta_time;
}}"#
),
Rule::Viscosity { radius, strength: _ } => format!(
r#" // Viscosity (accumulate for averaging)
if neighbor_dist < {radius} {{
let weight = 1.0 - neighbor_dist / {radius};
viscosity_sum += neighbor_vel * weight;
viscosity_weight += weight;
}}"#
),
Rule::Pressure { radius, strength, target_density: _ } => format!(
r#" // Pressure (accumulate density and force)
if neighbor_dist < {radius} && neighbor_dist > 0.001 {{
let weight = 1.0 - neighbor_dist / {radius};
pressure_density += weight;
// Accumulate weighted push direction
pressure_force += neighbor_dir * weight * {strength};
}}"#
),
Rule::Magnetism { radius, strength, same_repel } => {
let same_sign = if *same_repel { "1.0" } else { "-1.0" };
format!(
r#" // Magnetism
if neighbor_dist < {radius} && neighbor_dist > 0.001 {{
let same_type = select(-1.0, 1.0, p.particle_type == other.particle_type);
let force_dir = same_type * {same_sign}; // +1 = repel, -1 = attract
let falloff = 1.0 - neighbor_dist / {radius};
p.velocity += neighbor_dir * force_dir * falloff * {strength} * uniforms.delta_time;
}}"#
)
}
Rule::SurfaceTension { radius, .. } => format!(
r#" // Surface tension (accumulate neighbor info)
if neighbor_dist < {radius} {{
surface_neighbor_count += 1.0;
surface_center_sum += neighbor_pos;
}}"#
),
Rule::Avoid { radius, .. } => format!(
r#" // Avoid (accumulate weighted avoidance)
if neighbor_dist < {radius} && neighbor_dist > 0.001 {{
let weight = 1.0 - neighbor_dist / {radius};
avoid_sum += neighbor_dir * weight;
avoid_count += 1.0;
}}"#
),
Rule::Separate { radius, strength } => format!(
r#" // Separation
if neighbor_dist < {radius} && neighbor_dist > 0.0001 {{
let force = ({radius} - neighbor_dist) / {radius};
p.velocity += neighbor_dir * force * {strength} * uniforms.delta_time;
}}"#
),
Rule::Cohere { radius, strength: _ } => format!(
r#" // Cohesion (accumulate for averaging)
if neighbor_dist < {radius} {{
cohesion_sum += neighbor_pos;
cohesion_count += 1.0;
}}"#
),
Rule::Align { radius, strength: _ } => format!(
r#" // Alignment (accumulate for averaging)
if neighbor_dist < {radius} {{
alignment_sum += neighbor_vel;
alignment_count += 1.0;
}}"#
),
Rule::Flock { radius, separation, .. } => format!(
r#" // Flock: separation + cohesion + alignment accumulation
if neighbor_dist < {radius} {{
// Separation (immediate)
if neighbor_dist > 0.0001 {{
let sep_force = ({radius} - neighbor_dist) / {radius};
p.velocity += neighbor_dir * sep_force * {separation} * uniforms.delta_time;
}}
// Cohesion accumulation
cohesion_sum += neighbor_pos;
cohesion_count += 1.0;
// Alignment accumulation
alignment_sum += neighbor_vel;
alignment_count += 1.0;
}}"#
),
Rule::Typed { self_type, other_type, rule } => {
let inner = rule.to_neighbor_wgsl();
if inner.is_empty() {
return String::new();
}
let other_check = match other_type {
Some(t) => format!(" && other.particle_type == {}u", t),
None => String::new(),
};
format!(
r#" // Typed rule (self={}, other={:?})
if p.particle_type == {}u{} {{
{}
}}"#,
self_type, other_type, self_type, other_check, inner
)
}
Rule::Convert { from_type, trigger_type, to_type, radius, probability } => {
format!(
r#" // Convert type {} -> {} (triggered by {})
if p.particle_type == {from_type}u && other.particle_type == {trigger_type}u && neighbor_dist < {radius} {{
// Hash-based random using particle indices and time
let hash_input = index ^ (other_idx * 1103515245u) ^ u32(uniforms.time * 1000.0);
let hash = (hash_input ^ (hash_input >> 16u)) * 0x45d9f3bu;
let rand = f32(hash & 0xFFFFu) / 65535.0;
if rand < {probability} {{
p.particle_type = {to_type}u;
}}
}}"#,
from_type, to_type, trigger_type
)
}
Rule::Chase { self_type, target_type, radius, .. } => format!(
r#" // Chase: track nearest target
if p.particle_type == {self_type}u && other.particle_type == {target_type}u && neighbor_dist < {radius} {{
if neighbor_dist < chase_nearest_dist {{
chase_nearest_dist = neighbor_dist;
chase_nearest_pos = neighbor_pos;
}}
}}"#
),
Rule::Evade { self_type, threat_type, radius, .. } => format!(
r#" // Evade: track nearest threat
if p.particle_type == {self_type}u && other.particle_type == {threat_type}u && neighbor_dist < {radius} {{
if neighbor_dist < evade_nearest_dist {{
evade_nearest_dist = neighbor_dist;
evade_nearest_pos = neighbor_pos;
}}
}}"#
),
Rule::NeighborCustom(code) => format!(
" // Custom neighbor rule\n{}",
code
),
// Dynamic neighbor rules - static fallback (uses hardcoded param values)
Rule::NeighborCustomDynamic { code, .. } => format!(
" // Custom neighbor rule (dynamic)\n{}",
code
),
Rule::OnCollisionDynamic { radius, response, .. } => format!(
r#" // Custom collision response (dynamic)
if neighbor_dist < {radius} && neighbor_dist > 0.0001 {{
let overlap = {radius} - neighbor_dist;
let rel_vel = dot(neighbor_vel - p.velocity, neighbor_dir);
{response}
}}"#
),
Rule::Diffuse { field, radius, .. } => format!(
r#" // Diffuse: accumulate neighbor values
if neighbor_dist < {radius} {{
diffuse_sum += other.{field};
diffuse_count += 1.0;
}}"#
),
Rule::Accumulate { source, radius, falloff, operation, .. } => {
let weight_expr = if let Some(f) = falloff {
// Falloff expressions expect `dist` and `radius` in scope
format!(
"let dist = neighbor_dist;\n let radius = {radius};\n let acc_weight = {};",
f.to_wgsl_expr()
)
} else {
"let acc_weight = 1.0;".to_string()
};
let update_expr = match operation.as_str() {
"max" => format!("accumulate_value = max(accumulate_value, other.{source} * acc_weight);"),
"min" => format!("accumulate_value = min(accumulate_value, other.{source} * acc_weight);"),
_ => format!("accumulate_sum += other.{source} * acc_weight;\n accumulate_weight += acc_weight;"),
};
format!(
r#" // Accumulate: gather from neighbors
if neighbor_dist < {radius} {{
{weight_expr}
{update_expr}
}}"#
)
},
Rule::Signal { source, target: _, radius, strength, falloff } => {
let falloff_expr = if let Some(f) = falloff {
format!(
"let dist = neighbor_dist;\n let radius = {radius};\n let signal_strength = {} * {strength};",
f.to_wgsl_expr()
)
} else {
format!("let signal_strength = {strength};")
};
format!(
r#" // Signal: receive broadcast from neighbors
if neighbor_dist < {radius} {{
{falloff_expr}
signal_sum += other.{source} * signal_strength;
signal_count += 1.0;
}}"#
)
},
Rule::Absorb { target_type, radius, source_field, target_field: _ } => {
let type_check = if let Some(t) = target_type {
format!("other.particle_type == {t}u && ")
} else {
String::new()
};
format!(
r#" // Absorb: consume nearby particles
if {type_check}neighbor_dist < {radius} && other.alive == 1u {{
absorb_sum += other.{source_field};
// Mark neighbor for absorption (will be killed)
if !absorb_found {{
absorb_found = true;
absorb_target_idx = other_idx;
}}
}}"#
)
},
_ => String::new(),
}
}
/// Generate post-neighbor-loop WGSL (for averaging rules).
pub fn to_post_neighbor_wgsl(&self) -> String {
match self {
Rule::Cohere { strength, .. } => format!(
r#" // Apply cohesion
if cohesion_count > 0.0 {{
let center = cohesion_sum / cohesion_count;
let to_center = center - p.position;
p.velocity += normalize(to_center) * {strength} * uniforms.delta_time;
}}"#
),
Rule::Align { strength, .. } => format!(
r#" // Apply alignment
if alignment_count > 0.0 {{
let avg_vel = alignment_sum / alignment_count;
p.velocity += (avg_vel - p.velocity) * {strength} * uniforms.delta_time;
}}"#
),
Rule::Flock { cohesion, alignment, .. } => format!(
r#" // Apply flock cohesion and alignment
if cohesion_count > 0.0 {{
// Cohesion: steer toward center
let center = cohesion_sum / cohesion_count;
let to_center = center - p.position;
let center_dist = length(to_center);
if center_dist > 0.001 {{
p.velocity += normalize(to_center) * {cohesion} * uniforms.delta_time;
}}
}}
if alignment_count > 0.0 {{
// Alignment: match average velocity
let avg_vel = alignment_sum / alignment_count;
p.velocity += (avg_vel - p.velocity) * {alignment} * uniforms.delta_time;
}}"#
),
Rule::Typed { self_type, rule, .. } => {
let inner = rule.to_post_neighbor_wgsl();
if inner.is_empty() {
return String::new();
}
format!(
r#" // Typed post-neighbor (self={})
if p.particle_type == {}u {{
{}
}}"#,
self_type, self_type, inner
)
}
Rule::Chase { self_type, strength, .. } => format!(
r#" // Apply chase steering
if p.particle_type == {self_type}u && chase_nearest_dist < 1000.0 {{
let to_target = chase_nearest_pos - p.position;
let dist = length(to_target);
if dist > 0.001 {{
p.velocity += normalize(to_target) * {strength} * uniforms.delta_time;
}}
}}"#
),
Rule::Evade { self_type, strength, .. } => format!(
r#" // Apply evade steering
if p.particle_type == {self_type}u && evade_nearest_dist < 1000.0 {{
let away_from_threat = p.position - evade_nearest_pos;
let dist = length(away_from_threat);
if dist > 0.001 {{
p.velocity += normalize(away_from_threat) * {strength} * uniforms.delta_time;
}}
}}"#
),
Rule::Viscosity { strength, .. } => format!(
r#" // Apply viscosity
if viscosity_weight > 0.0 {{
let avg_vel = viscosity_sum / viscosity_weight;
p.velocity = mix(p.velocity, avg_vel, {strength} * uniforms.delta_time);
}}"#
),
Rule::Pressure { target_density, .. } => format!(
r#" // Apply pressure
if pressure_density > {target_density} {{
let excess = pressure_density - {target_density};
p.velocity += pressure_force * excess * uniforms.delta_time;
}}"#
),
Rule::SurfaceTension { strength, threshold, .. } => format!(
r#" // Apply surface tension
if surface_neighbor_count > 0.0 && surface_neighbor_count < {threshold} {{
let center = surface_center_sum / surface_neighbor_count;
let to_center = center - p.position;
let dist = length(to_center);
if dist > 0.001 {{
// Pull toward center of neighbors (surface tension effect)
let tension = ({threshold} - surface_neighbor_count) / {threshold};
p.velocity += normalize(to_center) * tension * {strength} * uniforms.delta_time;
}}
}}"#
),
Rule::Avoid { strength, .. } => format!(
r#" // Apply avoidance steering
if avoid_count > 0.0 {{
let avg_avoid = avoid_sum / avoid_count;
let avoid_len = length(avg_avoid);
if avoid_len > 0.001 {{
// Steer away smoothly
p.velocity += normalize(avg_avoid) * {strength} * uniforms.delta_time;
}}
}}"#
),
Rule::Diffuse { field, rate, .. } => format!(
r#" // Apply diffusion (blend toward neighbor average)
if diffuse_count > 0.0 {{
let avg_value = diffuse_sum / diffuse_count;
p.{field} = mix(p.{field}, avg_value, {rate} * uniforms.delta_time);
}}"#
),
Rule::Accumulate { target, operation, .. } => {
let assign_expr = match operation.as_str() {
"max" => format!("p.{target} = accumulate_value;"),
"min" => format!("p.{target} = accumulate_value;"),
"average" => format!(
"if accumulate_weight > 0.0 {{\n p.{target} = accumulate_sum / accumulate_weight;\n }}"
),
// "sum" and default
_ => format!("p.{target} = accumulate_sum;"),
};
format!(
r#" // Apply accumulated value
{assign_expr}"#
)
},
Rule::Signal { target, .. } => format!(
r#" // Apply received signal
if signal_count > 0.0 {{
p.{target} += signal_sum / signal_count;
}}"#
),
Rule::Absorb { target_field, .. } => format!(
r#" // Apply absorption result
if absorb_found {{
p.{target_field} += absorb_sum;
// Kill the absorbed particle (must be done via storage access)
// Note: Actual kill happens via particles_out[absorb_target_idx].alive = 0u;
}}"#
),
_ => String::new(),
}
}
/// Get a human-readable display name for this rule.
pub fn display_name(&self) -> &'static str {
match self {
Rule::Gravity(_) => "Gravity",
Rule::BounceWalls { .. } => "Bounce Walls",
Rule::WrapWalls => "Wrap Walls",
Rule::Drag(_) => "Drag",
Rule::Acceleration(_) => "Acceleration",
Rule::AttractTo { .. } => "Attract To",
Rule::RepelFrom { .. } => "Repel From",
Rule::Seek { .. } => "Seek",
Rule::Flee { .. } => "Flee",
Rule::Arrive { .. } => "Arrive",
Rule::Vortex { .. } => "Vortex",
Rule::Turbulence { .. } => "Turbulence",
Rule::Orbit { .. } => "Orbit",
Rule::Curl { .. } => "Curl",
Rule::PointGravity { .. } => "Point Gravity",
Rule::Spring { .. } => "Spring",
Rule::Radial { .. } => "Radial",
Rule::Shockwave { .. } => "Shockwave",
Rule::Pulse { .. } => "Pulse",
Rule::Oscillate { .. } => "Oscillate",
Rule::PositionNoise { .. } => "Position Noise",
Rule::SpeedLimit { .. } => "Speed Limit",
Rule::Wander { .. } => "Wander",
Rule::Collide { .. } => "Collide",
Rule::Separate { .. } => "Separate",
Rule::Cohere { .. } => "Cohere",
Rule::Align { .. } => "Align",
Rule::Avoid { .. } => "Avoid",
Rule::NBodyGravity { .. } => "N-Body Gravity",
Rule::LennardJones { .. } => "Lennard-Jones",
Rule::DLA { .. } => "DLA",
Rule::Viscosity { .. } => "Viscosity",
Rule::Pressure { .. } => "Pressure",
Rule::Magnetism { .. } => "Magnetism",
Rule::SurfaceTension { .. } => "Surface Tension",
Rule::Typed { .. } => "Typed",
Rule::Convert { .. } => "Convert",
Rule::Chase { .. } => "Chase",
Rule::Evade { .. } => "Evade",
Rule::Age => "Age",
Rule::Lifetime(_) => "Lifetime",
Rule::FadeOut { .. } => "Fade Out",
Rule::ShrinkOut { .. } => "Shrink Out",
Rule::ColorOverLife { .. } => "Color Over Life",
Rule::ColorBySpeed { .. } => "Color By Speed",
Rule::ColorByAge { .. } => "Color By Age",
Rule::ScaleBySpeed { .. } => "Scale By Speed",
Rule::Custom(_) => "Custom",
Rule::NeighborCustom(_) => "Neighbor Custom",
Rule::CustomDynamic { .. } => "Custom (Dynamic)",
Rule::NeighborCustomDynamic { .. } => "Neighbor Custom (Dynamic)",
Rule::OnDeath { .. } => "On Death",
Rule::OnSpawn { .. } => "On Spawn",
Rule::OnCollision { .. } => "On Collision",
Rule::OnCollisionDynamic { .. } => "On Collision (Dynamic)",
Rule::State { .. } => "State",
Rule::Agent { .. } => "Agent",
Rule::Signal { .. } => "Signal",
Rule::Absorb { .. } => "Absorb",
// Catch-all for any other variants
_ => "Rule",
}
}
/// Extract editable parameters from this rule with a unique prefix.
///
/// Returns Vec of (parameter_name, value) pairs for runtime editing.
/// The prefix ensures unique names when multiple rules of the same type exist.
pub fn params(&self, index: usize) -> Vec<(String, crate::uniforms::UniformValue)> {
use crate::uniforms::UniformValue;
let prefix = format!("rule_{}", index);
match self {
Rule::Gravity(strength) => vec![
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::Drag(coefficient) => vec![
(format!("{}_coefficient", prefix), UniformValue::F32(*coefficient)),
],
Rule::Acceleration(acc) => vec![
(format!("{}_acceleration", prefix), UniformValue::Vec3(*acc)),
],
Rule::AttractTo { point, strength } => vec![
(format!("{}_point", prefix), UniformValue::Vec3(*point)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::RepelFrom { point, strength, radius } => vec![
(format!("{}_point", prefix), UniformValue::Vec3(*point)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
],
Rule::Seek { target, max_speed, max_force } => vec![
(format!("{}_target", prefix), UniformValue::Vec3(*target)),
(format!("{}_max_speed", prefix), UniformValue::F32(*max_speed)),
(format!("{}_max_force", prefix), UniformValue::F32(*max_force)),
],
Rule::Flee { target, max_speed, max_force, panic_radius } => vec![
(format!("{}_target", prefix), UniformValue::Vec3(*target)),
(format!("{}_max_speed", prefix), UniformValue::F32(*max_speed)),
(format!("{}_max_force", prefix), UniformValue::F32(*max_force)),
(format!("{}_panic_radius", prefix), UniformValue::F32(*panic_radius)),
],
Rule::Arrive { target, max_speed, max_force, slowing_radius } => vec![
(format!("{}_target", prefix), UniformValue::Vec3(*target)),
(format!("{}_max_speed", prefix), UniformValue::F32(*max_speed)),
(format!("{}_max_force", prefix), UniformValue::F32(*max_force)),
(format!("{}_slowing_radius", prefix), UniformValue::F32(*slowing_radius)),
],
Rule::Vortex { center, axis, strength } => vec![
(format!("{}_center", prefix), UniformValue::Vec3(*center)),
(format!("{}_axis", prefix), UniformValue::Vec3(*axis)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::Turbulence { scale, strength } => vec![
(format!("{}_scale", prefix), UniformValue::F32(*scale)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::Orbit { center, strength } => vec![
(format!("{}_center", prefix), UniformValue::Vec3(*center)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::Curl { scale, strength } => vec![
(format!("{}_scale", prefix), UniformValue::F32(*scale)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::PointGravity { point, strength, softening } => vec![
(format!("{}_point", prefix), UniformValue::Vec3(*point)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
(format!("{}_softening", prefix), UniformValue::F32(*softening)),
],
Rule::Spring { anchor, stiffness, damping } => vec![
(format!("{}_anchor", prefix), UniformValue::Vec3(*anchor)),
(format!("{}_stiffness", prefix), UniformValue::F32(*stiffness)),
(format!("{}_damping", prefix), UniformValue::F32(*damping)),
],
Rule::Pulse { point, strength, frequency, radius } => vec![
(format!("{}_point", prefix), UniformValue::Vec3(*point)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
(format!("{}_frequency", prefix), UniformValue::F32(*frequency)),
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
],
Rule::Oscillate { axis, amplitude, frequency, spatial_scale } => vec![
(format!("{}_axis", prefix), UniformValue::Vec3(*axis)),
(format!("{}_amplitude", prefix), UniformValue::F32(*amplitude)),
(format!("{}_frequency", prefix), UniformValue::F32(*frequency)),
(format!("{}_spatial_scale", prefix), UniformValue::F32(*spatial_scale)),
],
Rule::SpeedLimit { min, max } => vec![
(format!("{}_min", prefix), UniformValue::F32(*min)),
(format!("{}_max", prefix), UniformValue::F32(*max)),
],
Rule::Wander { strength, frequency } => vec![
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
(format!("{}_frequency", prefix), UniformValue::F32(*frequency)),
],
Rule::Separate { radius, strength } => vec![
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::Cohere { radius, strength } => vec![
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::Align { radius, strength } => vec![
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::Collide { radius, restitution } => vec![
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
(format!("{}_restitution", prefix), UniformValue::F32(*restitution)),
],
Rule::Chase { self_type, target_type, radius, strength } => vec![
(format!("{}_self_type", prefix), UniformValue::U32(*self_type)),
(format!("{}_target_type", prefix), UniformValue::U32(*target_type)),
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::Evade { self_type, threat_type, radius, strength } => vec![
(format!("{}_self_type", prefix), UniformValue::U32(*self_type)),
(format!("{}_threat_type", prefix), UniformValue::U32(*threat_type)),
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::Lifetime(duration) => vec![
(format!("{}_duration", prefix), UniformValue::F32(*duration)),
],
Rule::Radial { point, strength, radius, .. } => vec![
(format!("{}_point", prefix), UniformValue::Vec3(*point)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
],
Rule::Shockwave { origin, speed, width, strength, repeat } => vec![
(format!("{}_origin", prefix), UniformValue::Vec3(*origin)),
(format!("{}_speed", prefix), UniformValue::F32(*speed)),
(format!("{}_width", prefix), UniformValue::F32(*width)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
(format!("{}_repeat", prefix), UniformValue::F32(*repeat)),
],
Rule::PositionNoise { scale, strength, speed } => vec![
(format!("{}_scale", prefix), UniformValue::F32(*scale)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
(format!("{}_speed", prefix), UniformValue::F32(*speed)),
],
Rule::NBodyGravity { strength, softening, radius } => vec![
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
(format!("{}_softening", prefix), UniformValue::F32(*softening)),
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
],
Rule::LennardJones { epsilon, sigma, cutoff } => vec![
(format!("{}_epsilon", prefix), UniformValue::F32(*epsilon)),
(format!("{}_sigma", prefix), UniformValue::F32(*sigma)),
(format!("{}_cutoff", prefix), UniformValue::F32(*cutoff)),
],
Rule::DLA { seed_type, mobile_type, stick_radius, diffusion_strength } => vec![
(format!("{}_seed_type", prefix), UniformValue::U32(*seed_type)),
(format!("{}_mobile_type", prefix), UniformValue::U32(*mobile_type)),
(format!("{}_stick_radius", prefix), UniformValue::F32(*stick_radius)),
(format!("{}_diffusion_strength", prefix), UniformValue::F32(*diffusion_strength)),
],
Rule::Viscosity { radius, strength } => vec![
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::Pressure { radius, strength, target_density } => vec![
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
(format!("{}_target_density", prefix), UniformValue::F32(*target_density)),
],
Rule::Magnetism { radius, strength, .. } => vec![
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::SurfaceTension { radius, strength, threshold } => vec![
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
(format!("{}_threshold", prefix), UniformValue::F32(*threshold)),
],
Rule::Avoid { radius, strength } => vec![
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::Buoyancy { surface_y, density } => vec![
(format!("{}_surface_y", prefix), UniformValue::F32(*surface_y)),
(format!("{}_density", prefix), UniformValue::F32(*density)),
],
Rule::Friction { ground_y, strength, threshold } => vec![
(format!("{}_ground_y", prefix), UniformValue::F32(*ground_y)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
(format!("{}_threshold", prefix), UniformValue::F32(*threshold)),
],
Rule::Wind { direction, strength, turbulence } => vec![
(format!("{}_direction", prefix), UniformValue::Vec3(*direction)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
(format!("{}_turbulence", prefix), UniformValue::F32(*turbulence)),
],
Rule::RespawnBelow { threshold_y, spawn_y, .. } => vec![
(format!("{}_threshold_y", prefix), UniformValue::F32(*threshold_y)),
(format!("{}_spawn_y", prefix), UniformValue::F32(*spawn_y)),
],
Rule::Convert { from_type, trigger_type, to_type, radius, probability } => vec![
(format!("{}_from_type", prefix), UniformValue::U32(*from_type)),
(format!("{}_trigger_type", prefix), UniformValue::U32(*trigger_type)),
(format!("{}_to_type", prefix), UniformValue::U32(*to_type)),
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
(format!("{}_probability", prefix), UniformValue::F32(*probability)),
],
Rule::FadeOut(duration) => vec![
(format!("{}_duration", prefix), UniformValue::F32(*duration)),
],
Rule::ShrinkOut(duration) => vec![
(format!("{}_duration", prefix), UniformValue::F32(*duration)),
],
Rule::ColorOverLife { start, end, duration } => vec![
(format!("{}_start", prefix), UniformValue::Vec3(*start)),
(format!("{}_end", prefix), UniformValue::Vec3(*end)),
(format!("{}_duration", prefix), UniformValue::F32(*duration)),
],
Rule::ColorBySpeed { slow_color, fast_color, max_speed } => vec![
(format!("{}_slow_color", prefix), UniformValue::Vec3(*slow_color)),
(format!("{}_fast_color", prefix), UniformValue::Vec3(*fast_color)),
(format!("{}_max_speed", prefix), UniformValue::F32(*max_speed)),
],
Rule::ColorByAge { young_color, old_color, max_age } => vec![
(format!("{}_young_color", prefix), UniformValue::Vec3(*young_color)),
(format!("{}_old_color", prefix), UniformValue::Vec3(*old_color)),
(format!("{}_max_age", prefix), UniformValue::F32(*max_age)),
],
Rule::ScaleBySpeed { min_scale, max_scale, max_speed } => vec![
(format!("{}_min_scale", prefix), UniformValue::F32(*min_scale)),
(format!("{}_max_scale", prefix), UniformValue::F32(*max_scale)),
(format!("{}_max_speed", prefix), UniformValue::F32(*max_speed)),
],
Rule::Flock { radius, separation, cohesion, alignment } => vec![
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
(format!("{}_separation", prefix), UniformValue::F32(*separation)),
(format!("{}_cohesion", prefix), UniformValue::F32(*cohesion)),
(format!("{}_alignment", prefix), UniformValue::F32(*alignment)),
],
Rule::Grow { rate, min, max } => vec![
(format!("{}_rate", prefix), UniformValue::F32(*rate)),
(format!("{}_min", prefix), UniformValue::F32(*min)),
(format!("{}_max", prefix), UniformValue::F32(*max)),
],
Rule::Gradient { field, strength, .. } => vec![
(format!("{}_field", prefix), UniformValue::U32(*field)),
(format!("{}_strength", prefix), UniformValue::F32(*strength)),
],
Rule::ChainSprings { stiffness, damping, rest_length, .. } => vec![
(format!("{}_stiffness", prefix), UniformValue::F32(*stiffness)),
(format!("{}_damping", prefix), UniformValue::F32(*damping)),
(format!("{}_rest_length", prefix), UniformValue::F32(*rest_length)),
],
Rule::RadialSprings { hub_stiffness, ring_stiffness, damping, hub_length, ring_length } => vec![
(format!("{}_hub_stiffness", prefix), UniformValue::F32(*hub_stiffness)),
(format!("{}_ring_stiffness", prefix), UniformValue::F32(*ring_stiffness)),
(format!("{}_damping", prefix), UniformValue::F32(*damping)),
(format!("{}_hub_length", prefix), UniformValue::F32(*hub_length)),
(format!("{}_ring_length", prefix), UniformValue::F32(*ring_length)),
],
Rule::AdjacencySprings { stiffness, damping, rest_length, .. } => vec![
(format!("{}_stiffness", prefix), UniformValue::F32(*stiffness)),
(format!("{}_damping", prefix), UniformValue::F32(*damping)),
(format!("{}_rest_length", prefix), UniformValue::F32(*rest_length)),
],
// Dynamic custom rules - extract user-defined params
Rule::CustomDynamic { params, .. } |
Rule::NeighborCustomDynamic { params, .. } => {
params.iter().map(|(name, value)| {
(format!("{}_{}", prefix, name), *value)
}).collect()
},
Rule::OnCollisionDynamic { radius, params, .. } => {
let mut result: Vec<(String, UniformValue)> = vec![
(format!("{}_radius", prefix), UniformValue::F32(*radius)),
];
result.extend(params.iter().map(|(name, value)| {
(format!("{}_{}", prefix, name), *value)
}));
result
},
// Rules with no numeric params or complex types (strings, closures, etc.)
// Use catch-all to handle any remaining rules not explicitly matched
_ => vec![],
}
}
/// Generate WGSL code that reads parameters from the uniforms struct.
///
/// When rule inspector is enabled, rule parameters are stored as custom uniforms
/// and can be modified at runtime through the inspector UI.
/// For rules without dynamic support, falls back to static to_wgsl().
pub fn to_wgsl_dynamic(&self, index: usize, bounds: f32) -> String {
let prefix = format!("rule_{}", index);
match self {
Rule::Gravity(_) => format!(
" // Gravity (dynamic)\n p.velocity.y -= uniforms.{prefix}_strength * uniforms.delta_time;"
),
Rule::Drag(_) => format!(
" // Drag (dynamic)\n p.velocity *= 1.0 - (uniforms.{prefix}_coefficient * uniforms.delta_time);"
),
Rule::Acceleration(_) => format!(
" // Acceleration (dynamic)\n p.velocity += uniforms.{prefix}_acceleration * uniforms.delta_time;"
),
Rule::AttractTo { .. } => format!(
r#" // Attract to point (dynamic)
{{
let attract_dir = uniforms.{prefix}_point - p.position;
let dist = length(attract_dir);
if dist > 0.001 {{
p.velocity += normalize(attract_dir) * uniforms.{prefix}_strength * uniforms.delta_time;
}}
}}"#
),
Rule::RepelFrom { .. } => format!(
r#" // Repel from point (dynamic)
{{
let repel_dir = p.position - uniforms.{prefix}_point;
let dist = length(repel_dir);
if dist < uniforms.{prefix}_radius && dist > 0.001 {{
let force = (uniforms.{prefix}_radius - dist) / uniforms.{prefix}_radius * uniforms.{prefix}_strength;
p.velocity += normalize(repel_dir) * force * uniforms.delta_time;
}}
}}"#
),
Rule::Vortex { .. } => format!(
r#" // Vortex (dynamic)
{{
let to_particle = p.position - uniforms.{prefix}_center;
let axis_norm = normalize(uniforms.{prefix}_axis);
let proj = dot(to_particle, axis_norm) * axis_norm;
let radial = to_particle - proj;
let dist = length(radial);
if dist > 0.001 {{
let tangent = cross(axis_norm, normalize(radial));
p.velocity += tangent * uniforms.{prefix}_strength * uniforms.delta_time;
}}
}}"#
),
Rule::Turbulence { .. } => format!(
r#" // Turbulence (dynamic)
{{
let noise_pos = p.position * uniforms.{prefix}_scale + vec3<f32>(uniforms.time * 0.5);
let force = vec3<f32>(
noise3(noise_pos),
noise3(noise_pos + vec3<f32>(100.0, 0.0, 0.0)),
noise3(noise_pos + vec3<f32>(0.0, 100.0, 0.0))
);
p.velocity += force * uniforms.{prefix}_strength * uniforms.delta_time;
}}"#
),
Rule::Orbit { .. } => format!(
r#" // Orbit (dynamic)
{{
let to_center = uniforms.{prefix}_center - p.position;
let dist = length(to_center);
if dist > 0.001 {{
let tangent = normalize(cross(vec3<f32>(0.0, 1.0, 0.0), to_center));
p.velocity += tangent * uniforms.{prefix}_strength * uniforms.delta_time;
p.velocity += normalize(to_center) * uniforms.{prefix}_strength * 0.1 * uniforms.delta_time;
}}
}}"#
),
Rule::PointGravity { .. } => format!(
r#" // Point gravity (dynamic)
{{
let to_point = uniforms.{prefix}_point - p.position;
let dist_sq = dot(to_point, to_point) + uniforms.{prefix}_softening * uniforms.{prefix}_softening;
let force = uniforms.{prefix}_strength / dist_sq;
p.velocity += normalize(to_point) * force * uniforms.delta_time;
}}"#
),
Rule::Spring { .. } => format!(
r#" // Spring (dynamic)
{{
let displacement = uniforms.{prefix}_anchor - p.position;
let spring_force = displacement * uniforms.{prefix}_stiffness;
let damping_force = -p.velocity * uniforms.{prefix}_damping;
p.velocity += (spring_force + damping_force) * uniforms.delta_time;
}}"#
),
Rule::Pulse { .. } => format!(
r#" // Pulse (dynamic)
{{
let to_particle = p.position - uniforms.{prefix}_point;
let dist = length(to_particle);
if uniforms.{prefix}_radius <= 0.0 || dist < uniforms.{prefix}_radius {{
let pulse = sin(uniforms.time * uniforms.{prefix}_frequency * 6.28318) * uniforms.{prefix}_strength;
if dist > 0.001 {{
p.velocity += normalize(to_particle) * pulse * uniforms.delta_time;
}}
}}
}}"#
),
Rule::SpeedLimit { .. } => format!(
r#" // Speed limit (dynamic)
{{
let speed = length(p.velocity);
if speed > uniforms.{prefix}_max {{
p.velocity = normalize(p.velocity) * uniforms.{prefix}_max;
}} else if speed < uniforms.{prefix}_min && speed > 0.001 {{
p.velocity = normalize(p.velocity) * uniforms.{prefix}_min;
}}
}}"#
),
Rule::Lifetime(_) => format!(
r#" // Lifetime (dynamic)
if p.age >= uniforms.{prefix}_duration {{
p.alive = 0u;
}}"#
),
Rule::Curl { .. } => format!(
r#" // Curl noise (dynamic)
{{
let curl_pos = p.position * uniforms.{prefix}_scale + vec3<f32>(uniforms.time * 0.3);
let eps = 0.01;
let dx = noise3(curl_pos + vec3<f32>(eps, 0.0, 0.0)) - noise3(curl_pos - vec3<f32>(eps, 0.0, 0.0));
let dy = noise3(curl_pos + vec3<f32>(0.0, eps, 0.0)) - noise3(curl_pos - vec3<f32>(0.0, eps, 0.0));
let dz = noise3(curl_pos + vec3<f32>(0.0, 0.0, eps)) - noise3(curl_pos - vec3<f32>(0.0, 0.0, eps));
let curl = vec3<f32>(dy - dz, dz - dx, dx - dy) / (2.0 * eps);
p.velocity += curl * uniforms.{prefix}_strength * uniforms.delta_time;
}}"#
),
Rule::Oscillate { .. } => format!(
r#" // Oscillate (dynamic)
{{
let phase = uniforms.time * uniforms.{prefix}_frequency * 6.28318;
var wave = sin(phase);
if uniforms.{prefix}_spatial_scale > 0.0 {{
let dist = length(p.position.xz);
wave = sin(phase - dist * uniforms.{prefix}_spatial_scale);
}}
p.velocity += normalize(uniforms.{prefix}_axis) * wave * uniforms.{prefix}_amplitude * uniforms.delta_time;
}}"#
),
Rule::Wander { .. } => format!(
r#" // Wander (dynamic)
{{
let seed = f32(index) * 0.1 + uniforms.time * uniforms.{prefix}_frequency;
let wander_dir = vec3<f32>(
sin(seed * 1.1),
sin(seed * 0.7 + 2.0),
sin(seed * 0.9 + 4.0)
);
p.velocity += wander_dir * uniforms.{prefix}_strength * uniforms.delta_time;
}}"#
),
Rule::Seek { .. } => format!(
r#" // Seek (dynamic)
{{
let desired = normalize(uniforms.{prefix}_target - p.position) * uniforms.{prefix}_max_speed;
var steer = desired - p.velocity;
let steer_mag = length(steer);
if steer_mag > uniforms.{prefix}_max_force {{
steer = normalize(steer) * uniforms.{prefix}_max_force;
}}
p.velocity += steer * uniforms.delta_time;
}}"#
),
Rule::Flee { .. } => format!(
r#" // Flee (dynamic)
{{
let to_target = uniforms.{prefix}_target - p.position;
let dist = length(to_target);
if uniforms.{prefix}_panic_radius <= 0.0 || dist < uniforms.{prefix}_panic_radius {{
let desired = normalize(-to_target) * uniforms.{prefix}_max_speed;
var steer = desired - p.velocity;
let steer_mag = length(steer);
if steer_mag > uniforms.{prefix}_max_force {{
steer = normalize(steer) * uniforms.{prefix}_max_force;
}}
p.velocity += steer * uniforms.delta_time;
}}
}}"#
),
Rule::Arrive { .. } => format!(
r#" // Arrive (dynamic)
{{
let to_target = uniforms.{prefix}_target - p.position;
let dist = length(to_target);
var desired_speed = uniforms.{prefix}_max_speed;
if dist < uniforms.{prefix}_slowing_radius {{
desired_speed = uniforms.{prefix}_max_speed * (dist / uniforms.{prefix}_slowing_radius);
}}
let desired = normalize(to_target) * desired_speed;
var steer = desired - p.velocity;
let steer_mag = length(steer);
if steer_mag > uniforms.{prefix}_max_force {{
steer = normalize(steer) * uniforms.{prefix}_max_force;
}}
p.velocity += steer * uniforms.delta_time;
}}"#
),
Rule::Wind { .. } => format!(
r#" // Wind (dynamic)
{{
let wind_dir = normalize(uniforms.{prefix}_direction);
var force = wind_dir * uniforms.{prefix}_strength;
if uniforms.{prefix}_turbulence > 0.0 {{
let noise_pos = p.position * 2.0 + vec3<f32>(uniforms.time);
force += vec3<f32>(
noise3(noise_pos),
noise3(noise_pos + vec3<f32>(100.0, 0.0, 0.0)),
noise3(noise_pos + vec3<f32>(0.0, 100.0, 0.0))
) * uniforms.{prefix}_turbulence * uniforms.{prefix}_strength;
}}
p.velocity += force * uniforms.delta_time;
}}"#
),
Rule::Buoyancy { .. } => format!(
r#" // Buoyancy (dynamic)
{{
if p.position.y < uniforms.{prefix}_surface_y {{
let depth = uniforms.{prefix}_surface_y - p.position.y;
p.velocity.y += depth * uniforms.{prefix}_density * uniforms.delta_time;
}}
}}"#
),
Rule::Friction { .. } => format!(
r#" // Friction (dynamic)
{{
if p.position.y < uniforms.{prefix}_ground_y + uniforms.{prefix}_threshold {{
let friction = uniforms.{prefix}_strength * uniforms.delta_time;
p.velocity.x *= 1.0 - friction;
p.velocity.z *= 1.0 - friction;
}}
}}"#
),
Rule::RespawnBelow { reset_velocity, .. } => {
let reset_code = if *reset_velocity {
"p.velocity = vec3<f32>(0.0);"
} else {
""
};
format!(
r#" // Respawn below (dynamic)
if p.position.y < uniforms.{prefix}_threshold_y {{
p.position.y = uniforms.{prefix}_spawn_y;
{reset_code}
}}"#
)
},
Rule::FadeOut(_) => format!(
r#" // Fade out (dynamic)
{{
let fade = max(0.0, 1.0 - p.age / uniforms.{prefix}_duration);
p.color *= fade;
}}"#
),
Rule::ShrinkOut(_) => format!(
r#" // Shrink out (dynamic)
{{
p.scale = max(0.0, 1.0 - p.age / uniforms.{prefix}_duration);
}}"#
),
Rule::ColorOverLife { .. } => format!(
r#" // Color over life (dynamic)
{{
let t = clamp(p.age / uniforms.{prefix}_duration, 0.0, 1.0);
p.color = mix(uniforms.{prefix}_start, uniforms.{prefix}_end, t);
}}"#
),
Rule::ColorBySpeed { .. } => format!(
r#" // Color by speed (dynamic)
{{
let speed = length(p.velocity);
let t = clamp(speed / uniforms.{prefix}_max_speed, 0.0, 1.0);
p.color = mix(uniforms.{prefix}_slow_color, uniforms.{prefix}_fast_color, t);
}}"#
),
Rule::ColorByAge { .. } => format!(
r#" // Color by age (dynamic)
{{
let t = clamp(p.age / uniforms.{prefix}_max_age, 0.0, 1.0);
p.color = mix(uniforms.{prefix}_young_color, uniforms.{prefix}_old_color, t);
}}"#
),
Rule::ScaleBySpeed { .. } => format!(
r#" // Scale by speed (dynamic)
{{
let speed = length(p.velocity);
let t = clamp(speed / uniforms.{prefix}_max_speed, 0.0, 1.0);
p.scale = mix(uniforms.{prefix}_min_scale, uniforms.{prefix}_max_scale, t);
}}"#
),
Rule::Grow { .. } => format!(
r#" // Grow (dynamic)
{{
p.scale = clamp(p.scale + uniforms.{prefix}_rate * uniforms.delta_time, uniforms.{prefix}_min, uniforms.{prefix}_max);
}}"#
),
Rule::PositionNoise { .. } => format!(
r#" // Position noise (dynamic)
{{
let noise_pos = p.position * uniforms.{prefix}_scale + vec3<f32>(uniforms.time * uniforms.{prefix}_speed);
let jitter = vec3<f32>(
noise3(noise_pos) - 0.5,
noise3(noise_pos + vec3<f32>(100.0, 0.0, 0.0)) - 0.5,
noise3(noise_pos + vec3<f32>(0.0, 100.0, 0.0)) - 0.5
) * 2.0;
p.position += jitter * uniforms.{prefix}_strength;
}}"#
),
Rule::Shockwave { .. } => format!(
r#" // Shockwave (dynamic)
{{
var t = uniforms.time;
if uniforms.{prefix}_repeat > 0.0 {{
t = fract(t / uniforms.{prefix}_repeat) * uniforms.{prefix}_repeat;
}}
let wave_radius = t * uniforms.{prefix}_speed;
let to_particle = p.position - uniforms.{prefix}_origin;
let dist = length(to_particle);
let wave_dist = abs(dist - wave_radius);
if wave_dist < uniforms.{prefix}_width {{
let force = (1.0 - wave_dist / uniforms.{prefix}_width) * uniforms.{prefix}_strength;
if dist > 0.001 {{
p.velocity += normalize(to_particle) * force * uniforms.delta_time;
}}
}}
}}"#
),
Rule::Radial { falloff, .. } => {
let falloff_code = match falloff {
Falloff::Constant => "let falloff = 1.0;",
Falloff::Linear => "let falloff = 1.0 - dist / uniforms.{prefix}_radius;",
Falloff::Inverse => "let falloff = 1.0 / (dist + 0.01);",
Falloff::InverseSquare => "let falloff = 1.0 / (dist * dist + 0.01);",
Falloff::Smooth => "let t = dist / uniforms.{prefix}_radius; let falloff = 1.0 - t * t * (3.0 - 2.0 * t);",
};
format!(
r#" // Radial (dynamic)
{{
let to_particle = p.position - uniforms.{prefix}_point;
let dist = length(to_particle);
if uniforms.{prefix}_radius <= 0.0 || dist < uniforms.{prefix}_radius {{
{falloff_code}
if dist > 0.001 {{
p.velocity += normalize(to_particle) * uniforms.{prefix}_strength * falloff * uniforms.delta_time;
}}
}}
}}"#
)
},
// Dynamic custom rules - transform param references to use rule prefix
Rule::CustomDynamic { code, params } => {
let mut transformed_code = code.clone();
// Replace uniforms.param_name with uniforms.rule_N_param_name
for (param_name, _) in params {
transformed_code = transformed_code.replace(
&format!("uniforms.{}", param_name),
&format!("uniforms.{}_{}", prefix, param_name)
);
}
format!(" // Custom (dynamic)\n{}", transformed_code)
},
// NeighborCustomDynamic is handled by neighbor_rule_wgsl_dynamic
// but we need a placeholder here
Rule::NeighborCustomDynamic { .. } => String::new(),
// OnCollisionDynamic is handled by neighbor_rule_wgsl_dynamic
Rule::OnCollisionDynamic { .. } => String::new(),
// Fall back to static for complex rules or rules without dynamic support
_ => self.to_wgsl(bounds),
}
}
/// Generate dynamic WGSL code for neighbor rules.
///
/// Similar to `neighbor_rule_wgsl` but reads parameters from uniforms
/// for runtime editing through the rule inspector.
pub fn neighbor_rule_wgsl_dynamic(&self, index: usize) -> String {
let prefix = format!("rule_{}", index);
match self {
Rule::NeighborCustomDynamic { code, params } => {
let mut transformed_code = code.clone();
// Replace uniforms.param_name with uniforms.rule_N_param_name
for (param_name, _) in params {
transformed_code = transformed_code.replace(
&format!("uniforms.{}", param_name),
&format!("uniforms.{}_{}", prefix, param_name)
);
}
transformed_code
},
Rule::OnCollisionDynamic { response, params, .. } => {
let mut transformed_code = response.clone();
// Replace uniforms.param_name with uniforms.rule_N_param_name
for (param_name, _) in params {
transformed_code = transformed_code.replace(
&format!("uniforms.{}", param_name),
&format!("uniforms.{}_{}", prefix, param_name)
);
}
format!(
r#"if neighbor_dist < uniforms.{prefix}_radius {{
let overlap = uniforms.{prefix}_radius - neighbor_dist;
let rel_vel = dot(p.velocity - neighbor_vel, neighbor_dir);
{transformed_code}
}}"#
)
},
// For other neighbor rules, use dynamic versions if available
Rule::Separate { .. } => format!(
r#"if neighbor_dist < uniforms.{prefix}_radius && neighbor_dist > 0.001 {{
let repel_force = (uniforms.{prefix}_radius - neighbor_dist) / uniforms.{prefix}_radius;
p.velocity += neighbor_dir * repel_force * uniforms.{prefix}_strength * uniforms.delta_time;
}}"#
),
Rule::Cohere { .. } => format!(
r#"if neighbor_dist < uniforms.{prefix}_radius {{
cohere_sum += neighbor_pos;
cohere_count += 1.0;
}}"#
),
Rule::Align { .. } => format!(
r#"if neighbor_dist < uniforms.{prefix}_radius {{
align_sum += neighbor_vel;
align_count += 1.0;
}}"#
),
Rule::Collide { .. } => format!(
r#"if neighbor_dist < uniforms.{prefix}_radius && neighbor_dist > 0.001 {{
let overlap = uniforms.{prefix}_radius - neighbor_dist;
let rel_vel = dot(p.velocity - neighbor_vel, neighbor_dir);
if rel_vel < 0.0 {{
p.velocity -= neighbor_dir * rel_vel * (1.0 + uniforms.{prefix}_restitution) * 0.5;
}}
p.position += neighbor_dir * overlap * 0.5;
}}"#
),
Rule::Avoid { .. } => format!(
r#"if neighbor_dist < uniforms.{prefix}_radius && neighbor_dist > 0.001 {{
let urgency = 1.0 - neighbor_dist / uniforms.{prefix}_radius;
let tangent = normalize(cross(vec3<f32>(0.0, 1.0, 0.0), neighbor_dir));
p.velocity += tangent * urgency * uniforms.{prefix}_strength * uniforms.delta_time;
}}"#
),
Rule::Viscosity { .. } => format!(
r#"if neighbor_dist < uniforms.{prefix}_radius {{
let weight = 1.0 - neighbor_dist / uniforms.{prefix}_radius;
p.velocity = mix(p.velocity, neighbor_vel, weight * uniforms.{prefix}_strength * uniforms.delta_time);
}}"#
),
Rule::Pressure { .. } => format!(
r#"if neighbor_dist < uniforms.{prefix}_radius {{
pressure_density += 1.0;
}}"#
),
Rule::Chase { .. } => format!(
r#"if p.particle_type == uniforms.{prefix}_self_type && other.particle_type == uniforms.{prefix}_target_type {{
if neighbor_dist < uniforms.{prefix}_radius && (chase_dist < 0.0 || neighbor_dist < chase_dist) {{
chase_dist = neighbor_dist;
chase_dir = -neighbor_dir;
}}
}}"#
),
Rule::Evade { .. } => format!(
r#"if p.particle_type == uniforms.{prefix}_self_type && other.particle_type == uniforms.{prefix}_threat_type {{
if neighbor_dist < uniforms.{prefix}_radius && (evade_dist < 0.0 || neighbor_dist < evade_dist) {{
evade_dist = neighbor_dist;
evade_dir = neighbor_dir;
}}
}}"#
),
_ => self.to_neighbor_wgsl(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Wraps rule WGSL code in a minimal valid compute shader for validation.
fn wrap_in_shader(rule_code: &str) -> String {
format!(
r#"
struct Particle {{
position: vec3<f32>,
velocity: vec3<f32>,
color: vec3<f32>,
particle_type: u32,
alive: u32,
age: f32,
lifetime: f32,
size: f32,
_pad: f32,
}};
struct Uniforms {{
delta_time: f32,
time: f32,
bounds: f32,
}};
@group(0) @binding(0) var<storage, read_write> particles: array<Particle>;
@group(0) @binding(1) var<uniform> uniforms: Uniforms;
// Minimal noise function for rules that use it
fn noise3(p: vec3<f32>) -> f32 {{
return fract(sin(dot(p, vec3<f32>(12.9898, 78.233, 45.164))) * 43758.5453);
}}
@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {{
let index = global_id.x;
var p = particles[index];
{rule_code}
particles[index] = p;
}}
"#,
rule_code = rule_code
)
}
/// Validates WGSL code using naga.
fn validate_wgsl(code: &str) -> Result<(), String> {
let module = naga::front::wgsl::parse_str(code)
.map_err(|e| format!("WGSL parse error: {:?}", e))?;
let mut validator = naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
);
validator
.validate(&module)
.map_err(|e| format!("WGSL validation error: {:?}", e))?;
Ok(())
}
// ========== Basic Physics Rules ==========
#[test]
fn test_gravity_wgsl() {
let rule = Rule::Gravity(9.8);
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Gravity"));
assert!(wgsl.contains("velocity.y"));
assert!(wgsl.contains("9.8"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("Gravity WGSL should be valid");
}
#[test]
fn test_drag_wgsl() {
let rule = Rule::Drag(1.5);
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Drag"));
assert!(wgsl.contains("1.5"));
assert!(wgsl.contains("velocity *="));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("Drag WGSL should be valid");
}
#[test]
fn test_acceleration_wgsl() {
let rule = Rule::Acceleration(Vec3::new(1.0, 2.0, 3.0));
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Acceleration"));
assert!(wgsl.contains("1"));
assert!(wgsl.contains("2"));
assert!(wgsl.contains("3"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("Acceleration WGSL should be valid");
}
#[test]
fn test_speed_limit_wgsl() {
let rule = Rule::SpeedLimit { min: 0.5, max: 5.0 };
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Speed limit"));
assert!(wgsl.contains("0.5"));
assert!(wgsl.contains("5"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("SpeedLimit WGSL should be valid");
}
#[test]
fn test_wander_wgsl() {
let rule = Rule::Wander {
strength: 2.0,
frequency: 10.0,
};
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Wander"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("Wander WGSL should be valid");
}
// ========== Boundary Rules ==========
#[test]
fn test_bounce_walls_wgsl() {
let rule = Rule::BounceWalls { restitution: 0.8 };
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Bounce"));
assert!(wgsl.contains("restitution: 0.8"));
assert!(wgsl.contains("position.x"));
assert!(wgsl.contains("position.y"));
assert!(wgsl.contains("position.z"));
assert!(wgsl.contains("abs(p.velocity"));
assert!(wgsl.contains("* 0.8")); // restitution applied
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("BounceWalls WGSL should be valid");
}
#[test]
fn test_wrap_walls_wgsl() {
let rule = Rule::WrapWalls;
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Wrap"));
assert!(wgsl.contains("toroidal"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("WrapWalls WGSL should be valid");
}
// ========== Point Force Rules ==========
#[test]
fn test_attract_to_wgsl() {
let rule = Rule::AttractTo {
point: Vec3::new(0.0, 0.0, 0.0),
strength: 5.0,
};
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Attract"));
assert!(wgsl.contains("normalize"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("AttractTo WGSL should be valid");
}
#[test]
fn test_repel_from_wgsl() {
let rule = Rule::RepelFrom {
point: Vec3::new(0.0, 0.0, 0.0),
strength: 5.0,
radius: 1.0,
};
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Repel"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("RepelFrom WGSL should be valid");
}
#[test]
fn test_point_gravity_wgsl() {
let rule = Rule::PointGravity {
point: Vec3::ZERO,
strength: 10.0,
softening: 0.05,
};
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Point gravity"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("PointGravity WGSL should be valid");
}
#[test]
fn test_spring_wgsl() {
let rule = Rule::Spring {
anchor: Vec3::new(0.0, 1.0, 0.0),
stiffness: 10.0,
damping: 0.5,
};
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Spring"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("Spring WGSL should be valid");
}
// ========== Field Effect Rules ==========
#[test]
fn test_vortex_wgsl() {
let rule = Rule::Vortex {
center: Vec3::ZERO,
axis: Vec3::Y,
strength: 5.0,
};
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Vortex"));
assert!(wgsl.contains("cross"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("Vortex WGSL should be valid");
}
#[test]
fn test_turbulence_wgsl() {
let rule = Rule::Turbulence {
scale: 2.0,
strength: 1.0,
};
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Turbulence"));
assert!(wgsl.contains("noise3"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("Turbulence WGSL should be valid");
}
#[test]
fn test_orbit_wgsl() {
let rule = Rule::Orbit {
center: Vec3::ZERO,
strength: 5.0,
};
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Orbit"));
assert!(wgsl.contains("centripetal"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("Orbit WGSL should be valid");
}
#[test]
fn test_curl_wgsl() {
let rule = Rule::Curl {
scale: 3.0,
strength: 1.0,
};
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Curl"));
assert!(wgsl.contains("divergence-free"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("Curl WGSL should be valid");
}
// ========== Wave/Modulation Rules ==========
#[test]
fn test_oscillate_wgsl() {
let rule = Rule::Oscillate {
axis: Vec3::Y,
amplitude: 0.5,
frequency: 2.0,
spatial_scale: 0.0,
};
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Oscillate"));
assert!(wgsl.contains("sin"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("Oscillate WGSL should be valid");
}
#[test]
fn test_position_noise_wgsl() {
let rule = Rule::PositionNoise {
scale: 5.0,
strength: 0.1,
speed: 2.0,
};
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Position noise"));
assert!(wgsl.contains("noise3"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("PositionNoise WGSL should be valid");
}
// ========== Lifecycle Rules ==========
#[test]
fn test_age_wgsl() {
let rule = Rule::Age;
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("Age"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("Age WGSL should be valid");
}
// ========== Custom Rules ==========
#[test]
fn test_custom_wgsl() {
let rule = Rule::Custom("p.velocity.x += 1.0;".into());
let wgsl = rule.to_wgsl(1.0);
assert!(wgsl.contains("velocity.x += 1.0"));
let shader = wrap_in_shader(&wgsl);
validate_wgsl(&shader).expect("Custom WGSL should be valid");
}
// ========== Falloff ==========
#[test]
fn test_falloff_expressions() {
// Test all falloff types generate valid WGSL expressions
let falloffs = [
Falloff::Constant,
Falloff::Linear,
Falloff::Inverse,
Falloff::InverseSquare,
Falloff::Smooth,
];
for falloff in falloffs {
let expr = falloff.to_wgsl_expr();
assert!(!expr.is_empty(), "Falloff {:?} should have expression", falloff);
}
}
// ========== Rule Properties ==========
#[test]
fn test_requires_neighbors() {
// Rules that should need neighbors
let neighbor_rules = [
Rule::Separate { radius: 0.1, strength: 1.0 },
Rule::Cohere { radius: 0.5, strength: 1.0 },
Rule::Align { radius: 0.3, strength: 1.0 },
Rule::Collide { radius: 0.1, restitution: 0.8 },
Rule::NBodyGravity { radius: 1.0, strength: 1.0, softening: 0.01 },
];
for rule in &neighbor_rules {
assert!(
rule.requires_neighbors(),
"Rule {:?} should need neighbors",
std::mem::discriminant(rule)
);
}
// Rules that should NOT need neighbors
let solo_rules = [
Rule::Gravity(9.8),
Rule::Drag(1.0),
Rule::BounceWalls { restitution: 1.0 },
Rule::WrapWalls,
];
for rule in &solo_rules {
assert!(
!rule.requires_neighbors(),
"Rule {:?} should not need neighbors",
std::mem::discriminant(rule)
);
}
}
// ========== Bounds Substitution ==========
#[test]
fn test_bounds_substitution() {
let rule = Rule::BounceWalls { restitution: 1.0 };
// Test with bounds = 1.0
let wgsl_1 = rule.to_wgsl(1.0);
assert!(wgsl_1.contains("-1"));
assert!(wgsl_1.contains("1")); // positive bound
// Test with bounds = 2.5
let wgsl_2 = rule.to_wgsl(2.5);
assert!(wgsl_2.contains("-2.5"));
assert!(wgsl_2.contains("2.5"));
}
}