bevy_hanabi 0.19.0

Hanabi GPU particle system for the Bevy game engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
//! Effect attributes, like the position or velocity of a particle.
//!
//! An _effect attribute_ is a quantity stored per particle for all particles.
//! Unlike [properties](crate::properties), each particle can have a different
//! value for each attribute. Examples of particle attributes include the
//! particle's own position and its velocity. Attributes are represented by the
//! [`Attribute`] type.
//!
//! Attributes are indirectly added to an effect by adding [modifiers] requiring
//! them. Each modifier documents its required attributes. You can force a
//! single attribute by adding the [`SetAttributeModifier`].
//!
//! Note that 🎆 Hanabi provides a number of associated [`Attribute`] constants,
//! like [`Attribute::POSITION`]. You cannot build your own [`Attribute`]
//! instance. See [Built-in attributes](#built-in-attributes) and [Custom
//! attributes](#custom-attributes) for all available attributes.
//!
//! # Definition
//!
//! [`Attribute`] defines the attribute's unique name, the type of its value,
//! and a default value used to initialize the attribute if not otherwise
//! explicitly initialized.
//!
//! The attribute name is a string used to identify the attribute, and also as
//! the associated variable name in any WGSL shader code using that attribute.
//! Because it's unique, attributes can be compared by their name alone.
//!
//! The attribute type encodes the type of data stored in the attribute,
//! including the number of components for a vector or matrix type. It's stored
//! together with the default value for the attribute into a [`Value`] field.
//!
//! # Layout
//!
//! Each particle effect contains one or more attributes. The set of all
//! attributes makes a particle. Attributes are organized in memory into a
//! _layout_, which optimizes GPU RAM usage and access by packing types
//! together, and avoid any padding gaps. However this layout needs to follow
//! the rules of WGSL structs, therefore might introduce some gaps (wasted
//! space) nonetheless, depending on each attribute's required type alignment.
//!
//! Here's an example for the default particle attribute set, containing the
//! particle's position and velocity vectors (`vec3<f32>`), and its age and
//! lifetime (`f32`), packed into a 32 bytes struct:
//!
//! | Bytes  | 0..4 | 4..8 | 8..12 | 12..16 |
//! |--------|---|---|---|---|
//! |  0..16 | [`POSITION`](Attribute::POSITION).X | [`POSITION`](Attribute::POSITION).Y | [`POSITION`](Attribute::POSITION).Z | [`AGE`](Attribute::AGE) |
//! | 16..32 | [`VELOCITY`](Attribute::VELOCITY).X | [`VELOCITY`](Attribute::VELOCITY).Y | [`VELOCITY`](Attribute::VELOCITY).Z | [`LIFETIME`](Attribute::LIFETIME) |
//!
//! In WGSL code, this is represented by:
//!
//! ```wgsl
//! struct Particle {
//!   position: vec3<f32>,
//!   age: f32,
//!   velocity: vec3<f32>,
//!   lifetime: f32,
//! }
//! ```
//!
//! The layout of a particle effect is represented by the [`ParticleLayout`]
//! type, and built from a set of attributes via the [`ParticleLayoutBuilder`]
//! helper. This is done internally by 🎆 Hanabi for each effect, so in general
//! you don't have to use those types directly.
//!
//! # Built-in attributes
//!
//! 🎆 Hanabi provides a number of built-in attributes with a specified meaning.
//! Those attributes are interpreted by some built-in library systems in a way
//! specific to the attribute. For example, the [`Attribute::POSITION`]
//! represents the particle's own position, and will be used as the position
//! where to render the particle.
//!
//! In general those attributes can be read and written by the user, for example
//! via the [`SetAttributeModifier`], but are also read and/or modified by 🎆
//! Hanabi itself.
//!
//! | Attribute | Meaning |
//! |---|---|
//! | [`Attribute::POSITION`] | The particle's position in [simulation space](crate::SimulationSpace). |
//! | [`Attribute::VELOCITY`] | The particle's velocity in [simulation space](crate::SimulationSpace). |
//! | [`Attribute::AGE`] | The particle's age, in seconds. |
//! | [`Attribute::LIFETIME`] | The particle's total lifetime, in seconds. |
//! | [`Attribute::COLOR`] | The particle's LDR color as `u32`. |
//! | [`Attribute::HDR_COLOR`] | The particle's HDR color as `vec4<f32>`. |
//! | [`Attribute::ALPHA`] | The particle's opacity. |
//! | [`Attribute::SIZE`] | The particle's uniform size. |
//! | [`Attribute::SIZE2`] | The particle's non-uniform 2D size. |
//! | [`Attribute::SIZE3`] | The particle's non-uniform 3D size. |
//! | [`Attribute::AXIS_X`] | X axis of the particle frame. |
//! | [`Attribute::AXIS_Y`] | Y axis of the particle frame. |
//! | [`Attribute::AXIS_Z`] | Z axis of the particle frame. |
//! | [`Attribute::SPRITE_INDEX`] | Index of the current sprite for flipbook animation. |
//!
//! # Custom attributes
//!
//! In additon of the built-in attributes, 🎆 Hanabi provides a number of
//! _custom attributes_, which are attributes with a specified type but no
//! particular internal meaning. Users are free to use those attributes to store
//! any quantity they like, noting that each new attribute increases the
//! per-particle size and therefor the total RAM usage of the particle effect.
//!
//! | Attribute | Meaning |
//! |---|---|
//! | [`Attribute::F32_0`] | A custom `f32` attribute. |
//! | [`Attribute::F32_1`] | A custom `f32` attribute. |
//! | [`Attribute::F32_2`] | A custom `f32` attribute. |
//! | [`Attribute::F32_3`] | A custom `f32` attribute. |
//! | [`Attribute::F32X2_0`] | A custom `vec2<f32>` attribute. |
//! | [`Attribute::F32X2_1`] | A custom `vec2<f32>` attribute. |
//! | [`Attribute::F32X2_2`] | A custom `vec2<f32>` attribute. |
//! | [`Attribute::F32X2_3`] | A custom `vec2<f32>` attribute. |
//! | [`Attribute::F32X3_0`] | A custom `vec3<f32>` attribute. |
//! | [`Attribute::F32X3_1`] | A custom `vec3<f32>` attribute. |
//! | [`Attribute::F32X3_2`] | A custom `vec3<f32>` attribute. |
//! | [`Attribute::F32X3_3`] | A custom `vec3<f32>` attribute. |
//! | [`Attribute::F32X4_0`] | A custom `vec4<f32>` attribute. |
//! | [`Attribute::F32X4_1`] | A custom `vec4<f32>` attribute. |
//! | [`Attribute::F32X4_2`] | A custom `vec4<f32>` attribute. |
//! | [`Attribute::F32X4_3`] | A custom `vec4<f32>` attribute. |
//!
//! [modifiers]: crate::modifier
//! [`SetAttributeModifier`]: crate::modifier::SetAttributeModifier

use std::{
    any::Any,
    borrow::Cow,
    fmt::Display,
    num::{NonZeroU32, NonZeroU64},
};

use bevy::{
    math::{Vec2, Vec3, Vec4},
    reflect::{
        structs::{FieldIter, Struct, StructInfo},
        utility::{GenericTypePathCell, NonGenericTypeInfoCell},
        ApplyError, FromReflect, FromType, GetTypeRegistration, NamedField, PartialReflect,
        Reflect, ReflectDeserialize, ReflectFromReflect, ReflectMut, ReflectOwned, ReflectRef,
        ReflectSerialize, TypeInfo, TypePath, TypeRegistration, Typed,
    },
};
use serde::{Deserialize, Serialize};

use crate::{
    graph::{ScalarValue, Value, VectorValue},
    ToWgslString,
};

/// Scalar types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ScalarType {
    /// Boolean value (`bool`).
    ///
    /// The size of a `bool` is undefined in the WGSL specification, but fixed
    /// at 4 bytes here.
    Bool,
    /// Floating point value (`f32`).
    Float,
    /// Signed 32-bit integer value (`i32`).
    Int,
    /// Unsigned 32-bit integer value (`u32`).
    Uint,
}

impl Display for ScalarType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Bool => write!(f, "bool"),
            Self::Float => write!(f, "f32"),
            Self::Int => write!(f, "i32"),
            Self::Uint => write!(f, "u32"),
        }
    }
}

impl ScalarType {
    /// Check if this type is a numeric type.
    ///
    /// A numeric type can be used in various math operators etc. All scalar
    /// types are numeric, except `ScalarType::Bool`.
    pub fn is_numeric(&self) -> bool {
        !(matches!(self, ScalarType::Bool))
    }

    /// Size of a value of this type, in bytes.
    ///
    /// This corresponds to the size of a variable of that type when part of a
    /// struct in WGSL. For `bool`, this is always 4 bytes (undefined in WGSL
    /// spec).
    pub const fn size(&self) -> usize {
        4
    }

    /// Alignment of a value of this type, in bytes.
    ///
    /// This corresponds to the alignment of a variable of that type when part
    /// of a struct in WGSL. For `bool`, this is always 4 bytes (undefined in
    /// WGSL spec).
    pub const fn align(&self) -> usize {
        4
    }
}

impl ToWgslString for ScalarType {
    fn to_wgsl_string(&self) -> String {
        match self {
            ScalarType::Bool => "bool",
            ScalarType::Float => "f32",
            ScalarType::Int => "i32",
            ScalarType::Uint => "u32",
        }
        .to_string()
    }
}

/// Vector type (`vecN<T>`).
///
/// Describes the type of a vector, which is composed of 2 to 4 components of a
/// same scalar type. This type corresponds to one of the valid vector types in
/// the WGSL specification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
pub struct VectorType {
    /// Type of all elements (components) of the vector.
    elem_type: ScalarType,
    /// Number of components. Always 2/3/4.
    count: u8,
}

impl Display for VectorType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "vec{}<{}>", self.count, self.elem_type)
    }
}

impl VectorType {
    /// Boolean vector with 2 components (`vec2<bool>`).
    pub const VEC2B: VectorType = VectorType::new(ScalarType::Bool, 2);
    /// Boolean vector with 3 components (`vec3<bool>`).
    pub const VEC3B: VectorType = VectorType::new(ScalarType::Bool, 3);
    /// Boolean vector with 4 components (`vec4<bool>`).
    pub const VEC4B: VectorType = VectorType::new(ScalarType::Bool, 4);
    /// Floating-point vector with 2 components (`vec2<f32>`).
    pub const VEC2F: VectorType = VectorType::new(ScalarType::Float, 2);
    /// Floating-point vector with 3 components (`vec3<f32>`).
    pub const VEC3F: VectorType = VectorType::new(ScalarType::Float, 3);
    /// Floating-point vector with 4 components (`vec4<f32>`).
    pub const VEC4F: VectorType = VectorType::new(ScalarType::Float, 4);
    /// Vector with 2 signed integer components (`vec2<i32>`).
    pub const VEC2I: VectorType = VectorType::new(ScalarType::Int, 2);
    /// Vector with 3 signed integer components (`vec3<i32>`).
    pub const VEC3I: VectorType = VectorType::new(ScalarType::Int, 3);
    /// Vector with 4 signed integer components (`vec4<i32>`).
    pub const VEC4I: VectorType = VectorType::new(ScalarType::Int, 4);
    /// Vector with 2 unsigned integer components (`vec2<u32>`).
    pub const VEC2U: VectorType = VectorType::new(ScalarType::Uint, 2);
    /// Vector with 3 unsigned integer components (`vec3<u32>`).
    pub const VEC3U: VectorType = VectorType::new(ScalarType::Uint, 3);
    /// Vector with 4 unsigned integer components (`vec4<u32>`).
    pub const VEC4U: VectorType = VectorType::new(ScalarType::Uint, 4);

    /// Create a new vector type.
    ///
    /// # Panics
    ///
    /// Panics if the component `count` is not 2/3/4.
    pub const fn new(elem_type: ScalarType, count: u8) -> Self {
        assert!(count >= 2 && count <= 4);
        Self { elem_type, count }
    }

    /// Scalar type of the individual vector elements (components).
    pub const fn elem_type(&self) -> ScalarType {
        self.elem_type
    }

    /// Number of components.
    pub const fn count(&self) -> usize {
        self.count as usize
    }

    /// Is the type a numeric type?
    ///
    /// See [`ScalarType::is_numeric()`] for a definition of a numeric type.
    ///
    /// [`ScalarType::is_numeric()`]: crate::ScalarType::is_numeric
    pub fn is_numeric(&self) -> bool {
        self.elem_type.is_numeric()
    }

    /// Size of a value of this type, in bytes.
    ///
    /// This corresponds to the size of a variable of that type when part of a
    /// struct in WGSL.
    pub const fn size(&self) -> usize {
        // https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size
        self.count() * self.elem_type.size()
    }

    /// Alignment of a value of this type, in bytes.
    ///
    /// This corresponds to the alignment of a variable of that type when part
    /// of a struct in WGSL.
    pub const fn align(&self) -> usize {
        // https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size
        if self.count >= 3 {
            4 * self.elem_type.align()
        } else {
            2 * self.elem_type.align()
        }
    }
}

impl ToWgslString for VectorType {
    fn to_wgsl_string(&self) -> String {
        format!("vec{}<{}>", self.count, self.elem_type.to_wgsl_string())
    }
}

/// Floating-point matrix type (`matCxR<f32>`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
pub struct MatrixType {
    rows: u8,
    cols: u8,
}

impl Display for MatrixType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "mat{}x{}<f32>", self.cols, self.rows)
    }
}

impl MatrixType {
    /// Floating-point matrix of size 2x2 (`mat2x2<f32>`).
    pub const MAT2X2F: MatrixType = MatrixType::new(2, 2);
    /// Floating-point matrix of size 3x2 (`mat3x2<f32>`).
    pub const MAT3X2F: MatrixType = MatrixType::new(3, 2);
    /// Floating-point matrix of size 4x2 (`mat4x2<f32>`).
    pub const MAT4X2F: MatrixType = MatrixType::new(4, 2);
    /// Floating-point matrix of size 2x3 (`mat2x3<f32>`).
    pub const MAT2X3F: MatrixType = MatrixType::new(2, 3);
    /// Floating-point matrix of size 3x3 (`mat3x3<f32>`).
    pub const MAT3X3F: MatrixType = MatrixType::new(3, 3);
    /// Floating-point matrix of size 4x3 (`mat4x3<f32>`).
    pub const MAT4X3F: MatrixType = MatrixType::new(4, 3);
    /// Floating-point matrix of size 2x4 (`mat2x4<f32>`).
    pub const MAT2X4F: MatrixType = MatrixType::new(2, 4);
    /// Floating-point matrix of size 3x4 (`mat3x4<f32>`).
    pub const MAT3X4F: MatrixType = MatrixType::new(3, 4);
    /// Floating-point matrix of size 4x4 (`mat4x4<f32>`).
    pub const MAT4X4F: MatrixType = MatrixType::new(4, 4);

    /// Create a new matrix type.
    ///
    /// # Panics
    ///
    /// Panics if the number of columns or rows is not 2, 3, or 4.
    pub const fn new(cols: u8, rows: u8) -> Self {
        assert!(cols >= 2 && cols <= 4);
        assert!(rows >= 2 && rows <= 4);
        Self { cols, rows }
    }

    /// Number of columns in the matrix.
    pub const fn cols(&self) -> usize {
        self.cols as usize
    }

    /// Number of rows in the matrix.
    pub const fn rows(&self) -> usize {
        self.rows as usize
    }

    /// Size of a value of this type, in bytes.
    ///
    /// This corresponds to the size of a variable of that type when part of a
    /// struct in WGSL.
    pub const fn size(&self) -> usize {
        // SizeOf(array<vecR, C>), which means matCx3 and matCx4 have same size
        // https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size
        if self.rows >= 3 {
            self.cols() * VectorType::VEC4F.size()
        } else {
            self.cols() * VectorType::VEC2F.size()
        }
    }

    /// Alignment of a value of this type, in bytes.
    ///
    /// This corresponds to the alignment of a variable of that type when part
    /// of a struct in WGSL.
    pub const fn align(&self) -> usize {
        // AlignOf(vecR), which means matCx3 and matCx4 have same align
        // https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size
        VectorType::new(ScalarType::Float, self.rows).align()
    }
}

impl ToWgslString for MatrixType {
    fn to_wgsl_string(&self) -> String {
        format!(
            "mat{}x{}<{}>",
            self.cols,
            self.rows,
            ScalarType::Float.to_wgsl_string()
        )
    }
}

/// Type of an [`Attribute`]'s value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ValueType {
    /// A scalar type (single value).
    Scalar(ScalarType),
    /// A vector type with 2 to 4 components.
    Vector(VectorType),
    /// A floating-point matrix type of size between 2x2 and 4x4.
    Matrix(MatrixType),
}

impl Display for ValueType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // The enum variants are different enough we don't need to discriminate at this
        // level
        match self {
            ValueType::Scalar(s) => s.fmt(f),
            ValueType::Vector(v) => v.fmt(f),
            ValueType::Matrix(m) => m.fmt(f),
        }
    }
}

impl ValueType {
    /// Is the type a numeric type?
    pub fn is_numeric(&self) -> bool {
        match self {
            ValueType::Scalar(s) => s.is_numeric(),
            ValueType::Vector(v) => v.is_numeric(),
            ValueType::Matrix(_) => true,
        }
    }

    /// Is the type a scalar type?
    pub fn is_scalar(&self) -> bool {
        matches!(self, ValueType::Scalar(_))
    }

    /// Is the type a vector type?
    pub fn is_vector(&self) -> bool {
        matches!(self, ValueType::Vector(_))
    }

    /// Is the type a matrix type?
    pub fn is_matrix(&self) -> bool {
        matches!(self, ValueType::Matrix(_))
    }

    /// Size of a value of this type, in bytes.
    pub fn size(&self) -> usize {
        match self {
            ValueType::Scalar(s) => s.size(),
            ValueType::Vector(v) => v.size(),
            ValueType::Matrix(m) => m.size(),
        }
    }

    /// Alignment of a value of this type, in bytes.
    ///
    /// This corresponds to the alignment of a variable of that type when part
    /// of a struct in WGSL.
    pub fn align(&self) -> usize {
        match self {
            ValueType::Scalar(s) => s.align(),
            ValueType::Vector(v) => v.align(),
            ValueType::Matrix(m) => m.align(),
        }
    }
}

impl From<ScalarType> for ValueType {
    fn from(value: ScalarType) -> Self {
        ValueType::Scalar(value)
    }
}

impl From<VectorType> for ValueType {
    fn from(value: VectorType) -> Self {
        ValueType::Vector(value)
    }
}

impl From<MatrixType> for ValueType {
    fn from(value: MatrixType) -> Self {
        ValueType::Matrix(value)
    }
}

impl ToWgslString for ValueType {
    fn to_wgsl_string(&self) -> String {
        match self {
            ValueType::Scalar(s) => s.to_wgsl_string(),
            ValueType::Vector(v) => v.to_wgsl_string(),
            ValueType::Matrix(m) => m.to_wgsl_string(),
        }
    }
}

#[derive(Debug, Clone, Reflect)]
pub(crate) struct AttributeInner {
    name: Cow<'static, str>,
    default_value: Value,
}

impl PartialEq for AttributeInner {
    fn eq(&self, other: &Self) -> bool {
        // Compare attributes by name since it's unique.
        self.name == other.name
    }
}

impl Eq for AttributeInner {}

impl std::hash::Hash for AttributeInner {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        // Keep consistent with PartialEq and Eq
        self.name.hash(state);
    }
}

macro_rules! declare_custom_attr_inner {
    ($t:ident, $T:ty, $name:literal, $new_fn:ident) => {
        pub const $t: &'static AttributeInner = &AttributeInner::new(
            Cow::Borrowed($name),
            Value::Vector(VectorValue::$new_fn(<$T>::ZERO)),
        );
    };
}

macro_rules! declare_custom_attr_u32_inner {
    ($t:ident, $name:literal, $scalar_type:ident) => {
        pub const $t: &'static AttributeInner = &AttributeInner::new(
            Cow::Borrowed($name),
            Value::Scalar(ScalarValue::$scalar_type(0)),
        );
    };
}

impl AttributeInner {
    pub const ID: &'static AttributeInner =
        &AttributeInner::new(Cow::Borrowed("id"), Value::Scalar(ScalarValue::Uint(0)));

    pub const PARTICLE_COUNTER: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("particle_counter"),
        Value::Scalar(ScalarValue::Uint(0)),
    );

    pub const POSITION: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("position"),
        Value::Vector(VectorValue::new_vec3(Vec3::ZERO)),
    );

    pub const VELOCITY: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("velocity"),
        Value::Vector(VectorValue::new_vec3(Vec3::ZERO)),
    );

    pub const AGE: &'static AttributeInner =
        &AttributeInner::new(Cow::Borrowed("age"), Value::Scalar(ScalarValue::Float(0.)));

    pub const LIFETIME: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("lifetime"),
        Value::Scalar(ScalarValue::Float(1.)),
    );

    pub const COLOR: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("color"),
        Value::Scalar(ScalarValue::Uint(0xFFFFFFFFu32)),
    );

    pub const HDR_COLOR: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("hdr_color"),
        Value::Vector(VectorValue::new_vec4(Vec4::ONE)),
    );

    pub const ALPHA: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("alpha"),
        Value::Scalar(ScalarValue::Float(1.)),
    );

    pub const SIZE: &'static AttributeInner =
        &AttributeInner::new(Cow::Borrowed("size"), Value::Scalar(ScalarValue::Float(1.)));

    pub const SIZE2: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("size2"),
        Value::Vector(VectorValue::new_vec2(Vec2::ONE)),
    );

    pub const SIZE3: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("size3"),
        Value::Vector(VectorValue::new_vec3(Vec3::ONE)),
    );

    pub const PREV: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("prev"),
        Value::Scalar(ScalarValue::Uint(!0u32)),
    );

    pub const NEXT: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("next"),
        Value::Scalar(ScalarValue::Uint(!0u32)),
    );

    pub const AXIS_X: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("axis_x"),
        Value::Vector(VectorValue::new_vec3(Vec3::X)),
    );

    pub const AXIS_Y: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("axis_y"),
        Value::Vector(VectorValue::new_vec3(Vec3::Y)),
    );

    pub const AXIS_Z: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("axis_z"),
        Value::Vector(VectorValue::new_vec3(Vec3::Z)),
    );

    pub const SPRITE_INDEX: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("sprite_index"),
        Value::Scalar(ScalarValue::Int(0)),
    );

    pub const F32_0: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("f32_0"),
        Value::Scalar(ScalarValue::Float(0.)),
    );

    pub const F32_1: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("f32_1"),
        Value::Scalar(ScalarValue::Float(0.)),
    );

    pub const F32_2: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("f32_2"),
        Value::Scalar(ScalarValue::Float(0.)),
    );

    pub const F32_3: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("f32_3"),
        Value::Scalar(ScalarValue::Float(0.)),
    );

    declare_custom_attr_inner!(F32X2_0, Vec2, "f32x2_0", new_vec2);
    declare_custom_attr_inner!(F32X2_1, Vec2, "f32x2_1", new_vec2);
    declare_custom_attr_inner!(F32X2_2, Vec2, "f32x2_2", new_vec2);
    declare_custom_attr_inner!(F32X2_3, Vec2, "f32x2_3", new_vec2);
    declare_custom_attr_inner!(F32X3_0, Vec3, "f32x3_0", new_vec3);
    declare_custom_attr_inner!(F32X3_1, Vec3, "f32x3_1", new_vec3);
    declare_custom_attr_inner!(F32X3_2, Vec3, "f32x3_2", new_vec3);
    declare_custom_attr_inner!(F32X3_3, Vec3, "f32x3_3", new_vec3);
    declare_custom_attr_inner!(F32X4_0, Vec4, "f32x4_0", new_vec4);
    declare_custom_attr_inner!(F32X4_1, Vec4, "f32x4_1", new_vec4);
    declare_custom_attr_inner!(F32X4_2, Vec4, "f32x4_2", new_vec4);
    declare_custom_attr_inner!(F32X4_3, Vec4, "f32x4_3", new_vec4);

    declare_custom_attr_u32_inner!(U32_0, "u32_0", Uint);
    declare_custom_attr_u32_inner!(U32_1, "u32_1", Uint);
    declare_custom_attr_u32_inner!(U32_2, "u32_2", Uint);
    declare_custom_attr_u32_inner!(U32_3, "u32_3", Uint);

    pub const RIBBON_ID: &'static AttributeInner = &AttributeInner::new(
        Cow::Borrowed("ribbon_id"),
        Value::Scalar(ScalarValue::Uint(0u32)),
    );

    pub(crate) const PAD0: &'static AttributeInner =
        &AttributeInner::new(Cow::Borrowed("pad0"), Value::Scalar(ScalarValue::Uint(0)));
    pub(crate) const PAD1: &'static AttributeInner =
        &AttributeInner::new(Cow::Borrowed("pad1"), Value::Scalar(ScalarValue::Uint(0)));
    pub(crate) const PAD2: &'static AttributeInner =
        &AttributeInner::new(Cow::Borrowed("pad2"), Value::Scalar(ScalarValue::Uint(0)));
    pub(crate) const PAD3: &'static AttributeInner =
        &AttributeInner::new(Cow::Borrowed("pad3"), Value::Scalar(ScalarValue::Uint(0)));
    pub(crate) const PAD4: &'static AttributeInner =
        &AttributeInner::new(Cow::Borrowed("pad4"), Value::Scalar(ScalarValue::Uint(0)));

    #[inline]
    pub(crate) const fn new(name: Cow<'static, str>, default_value: Value) -> Self {
        Self {
            name,
            default_value,
        }
    }
}

/// An attribute of a particle simulated for an effect.
///
/// Effects are composed of many simulated particles. Each particle is in turn
/// composed of a set of attributes, which are used to simulate and render it.
/// Common attributes include the particle's position, its age, or its color.
/// See [`Attribute::all()`] for a list of supported attributes. User-created
/// attributes are not supported.
///
/// See also the [`attributes` module](crate::attributes) documentation for more
/// details about particle attributes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "&str", into = "&'static str")]
pub struct Attribute(pub(crate) &'static AttributeInner);

impl TryFrom<&str> for Attribute {
    type Error = &'static str;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Attribute::from_name(value).ok_or("Unknown attribute name.")
    }
}

impl From<Attribute> for &'static str {
    fn from(value: Attribute) -> Self {
        value.name()
    }
}

impl TypePath for Attribute {
    fn type_path() -> &'static str {
        static CELL: GenericTypePathCell = GenericTypePathCell::new();
        CELL.get_or_insert::<Self, _>(|| "bevy_hanabi::attribute::Attribute".to_owned())
    }

    fn short_type_path() -> &'static str {
        static CELL: GenericTypePathCell = GenericTypePathCell::new();
        CELL.get_or_insert::<Self, _>(|| "Attribute".to_owned())
    }

    fn type_ident() -> Option<&'static str> {
        Some("Attribute")
    }

    fn crate_name() -> Option<&'static str> {
        Some("bevy_hanabi")
    }

    fn module_path() -> Option<&'static str> {
        Some("bevy_hanabi::attribute")
    }
}

impl Typed for Attribute {
    fn type_info() -> &'static TypeInfo {
        static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
        CELL.get_or_set(|| {
            let fields = [
                NamedField::new::<Cow<str>>("name"),
                NamedField::new::<Value>("default_value"),
            ];
            let info = StructInfo::new::<Self>(&fields);
            TypeInfo::Struct(info)
        })
    }
}

impl Struct for Attribute {
    fn field(&self, name: &str) -> Option<&dyn PartialReflect> {
        match name {
            "name" => Some(&self.0.name),
            "default_value" => Some(&self.0.default_value),
            _ => None,
        }
    }

    fn field_mut(&mut self, _name: &str) -> Option<&mut dyn PartialReflect> {
        // Attributes are immutable
        None
    }

    fn field_at(&self, index: usize) -> Option<&dyn PartialReflect> {
        match index {
            0 => Some(&self.0.name),
            1 => Some(&self.0.default_value),
            _ => None,
        }
    }

    fn field_at_mut(&mut self, _index: usize) -> Option<&mut dyn PartialReflect> {
        // Attributes are immutable
        None
    }

    fn name_at(&self, index: usize) -> Option<&str> {
        match index {
            0 => Some("name"),
            1 => Some("default_value"),
            _ => None,
        }
    }

    fn index_of_name(&self, name: &str) -> Option<usize> {
        match name {
            "name" => Some(0),
            "default_value" => Some(1),
            _ => None,
        }
    }

    fn field_len(&self) -> usize {
        2
    }

    fn iter_fields(&self) -> FieldIter<'_> {
        FieldIter::new(self)
    }
}

impl GetTypeRegistration for Attribute {
    fn get_type_registration() -> TypeRegistration {
        let mut registration = TypeRegistration::of::<Self>();
        registration.insert::<ReflectDeserialize>(FromType::<Self>::from_type());
        registration.insert::<ReflectSerialize>(FromType::<Self>::from_type());
        registration.insert::<ReflectFromReflect>(FromType::<Self>::from_type());
        registration
    }
}

impl PartialReflect for Attribute {
    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
        Some(<Self as Typed>::type_info())
    }

    #[inline]
    fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
        self
    }

    #[inline]
    fn as_partial_reflect(&self) -> &dyn PartialReflect {
        self
    }

    #[inline]
    fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
        self
    }

    #[inline]
    fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
        Ok(self)
    }

    #[inline]
    fn try_as_reflect(&self) -> Option<&dyn Reflect> {
        Some(self)
    }

    #[inline]
    fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
        Some(self)
    }

    fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
        if let Some(value) = value.try_downcast_ref::<Self>() {
            *self = *value;
            Ok(())
        } else {
            Err(ApplyError::MismatchedTypes {
                from_type: value.reflect_type_path().into(),
                to_type: Self::type_path().into(),
            })
        }
    }

    #[inline]
    fn reflect_ref(&self) -> ReflectRef<'_> {
        ReflectRef::Struct(self)
    }

    #[inline]
    fn reflect_mut(&mut self) -> ReflectMut<'_> {
        ReflectMut::Struct(self)
    }

    #[inline]
    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
        ReflectOwned::Struct(self)
    }
}

impl Reflect for Attribute {
    #[inline]
    fn into_any(self: Box<Self>) -> Box<dyn Any> {
        self
    }

    #[inline]
    fn as_any(&self) -> &dyn Any {
        self
    }

    #[inline]
    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    #[inline]
    fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
        self
    }

    #[inline]
    fn as_reflect(&self) -> &dyn Reflect {
        self
    }

    #[inline]
    fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
        self
    }

    #[inline]
    fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
        *self = value.take()?;
        Ok(())
    }
}

impl FromReflect for Attribute {
    fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
        Attribute::from_name(
            reflect
                .try_as_reflect()?
                .as_any()
                .downcast_ref::<String>()?,
        )
    }
}

macro_rules! declare_custom_attr_pub {
    ($t: ident, $name: literal, $count: literal, $vector_type: ident) => {
        #[doc = concat!("A generic vector float attribute with ", $count, " components.\n\n This attribute can be used for anything. It has no specific meaning. You can store whatever per-particle value you want in it (for example, at spawn time) and read it back later.\n\n# Name\n\n`", $name, "`\n\n# Type\n\n[`VectorType::", stringify!($vector_type), "`]")]
        pub const $t: Attribute = Attribute(AttributeInner::$t);
    };
}

macro_rules! declare_custom_attr_u32_pub  {
    ($t: ident, $name: literal, $scalar_type: ident) => {
        #[doc = concat!("A generic scalar uint attribute.\n\n This attribute can be used for anything. It has no specific meaning. You can store whatever per-particle value you want in it (for example, at spawn time) and read it back later.\n\n# Name\n\n`", $name, "`\n\n# Type\n\n[`ScalarType::", stringify!($scalar_type), "`]")]
        pub const $t: Attribute = Attribute(AttributeInner::$t);
    };
}

impl Attribute {
    /// The particle unique ID.
    ///
    /// This is a pseudo-attribute, which doesn't require any storage in the
    /// particle layout, and is always available. It can be read but cannot be
    /// set. The particle ID is guaranteed to be unique within a single
    /// effect instance only; particles from different instances may have
    /// the same ID.
    ///
    /// # Name
    ///
    /// `id`
    ///
    /// # Type
    ///
    /// [`ScalarType::Uint`]
    pub const ID: Attribute = Attribute(AttributeInner::ID);

    /// A monotonically increasing counter.
    ///
    /// This is a pseudo-attribute, which doesn't require any storage in the
    /// particle layout, and is always available. It can be read but cannot be
    /// set. The counter is guaranteed to be unique each time a new particle
    /// spawns. It may loop after 2^32 values, but unless you store that value
    /// for a very long time you can consider the value unique.
    ///
    /// # Name
    ///
    /// `particle_counter`
    ///
    /// # Type
    ///
    /// [`ScalarType::Uint`]
    pub const PARTICLE_COUNTER: Attribute = Attribute(AttributeInner::PARTICLE_COUNTER);

    /// The particle position in [simulation space].
    ///
    /// # Name
    ///
    /// `position`
    ///
    /// # Type
    ///
    /// [`VectorType::VEC3F`] representing the XYZ coordinates of the position.
    ///
    /// [simulation space]: crate::SimulationSpace
    pub const POSITION: Attribute = Attribute(AttributeInner::POSITION);

    /// The particle velocity in [simulation space].
    ///
    /// # Name
    ///
    /// `velocity`
    ///
    /// # Type
    ///
    /// [`VectorType::VEC3F`] representing the XYZ coordinates of the velocity.
    ///
    /// [simulation space]: crate::SimulationSpace
    pub const VELOCITY: Attribute = Attribute(AttributeInner::VELOCITY);

    /// The age of the particle.
    ///
    /// Each time the particle is updated, the current simulation delta time is
    /// added to the particle's age. The age can be used to animate some other
    /// quantities; see the [`ColorOverLifetimeModifier`] for example.
    ///
    /// If the particle also has a lifetime (either a per-effect
    /// constant value, or a per-particle value stored in the
    /// [`Attribute::LIFETIME`] attribute), then when the age of the particle
    /// exceeds its lifetime, the particle dies and is not simulated nor
    /// rendered anymore.
    ///
    /// # Name
    ///
    /// `age`
    ///
    /// # Type
    ///
    /// [`ScalarType::Float`]
    ///
    /// [`ColorOverLifetimeModifier`]: crate::modifier::output::ColorOverLifetimeModifier
    pub const AGE: Attribute = Attribute(AttributeInner::AGE);

    /// The lifetime of the particle.
    ///
    /// This attribute stores a per-particle lifetime, which compared to the
    /// particle's age allows determining if the particle needs to be
    /// simulated and rendered. This requires the [`Attribute::AGE`]
    /// attribute to be used too.
    ///
    /// # Name
    ///
    /// `lifetime`
    ///
    /// # Type
    ///
    /// [`ScalarType::Float`]
    pub const LIFETIME: Attribute = Attribute(AttributeInner::LIFETIME);

    /// The particle's base color.
    ///
    /// This attribute stores a per-particle color, which can be used for
    /// various purposes, generally as the base color for rendering the
    /// particle.
    ///
    /// # Name
    ///
    /// `color`
    ///
    /// # Type
    ///
    /// [`ScalarType::Uint`] representing the RGBA components of the color
    /// encoded as `0xAABBGGRR`, with a single byte per component, where the
    /// alpha value is stored in the most significant byte and the red value in
    /// the least significant byte. Note that this representation is the
    /// same as the one returned by [`LinearRgba::as_u32()`].
    ///
    /// [`LinearRgba::as_u32()`]: bevy::color::LinearRgba::as_u32
    pub const COLOR: Attribute = Attribute(AttributeInner::COLOR);

    /// The particle's base color (HDR).
    ///
    /// This attribute stores a per-particle HDR color, which can be used for
    /// various purposes, generally as the base color for rendering the
    /// particle.
    ///
    /// # Name
    ///
    /// `hdr_color`
    ///
    /// # Type
    ///
    /// [`VectorType::VEC4F`] representing the RGBA components of the color.
    /// Values are not clamped, and can be outside the \[0:1\] range to
    /// represent HDR values.
    pub const HDR_COLOR: Attribute = Attribute(AttributeInner::HDR_COLOR);

    /// The particle's opacity (alpha).
    ///
    /// This is a value in \[0:1\], where `0` corresponds to a fully transparent
    /// particle, and `1` to a fully opaque one.
    ///
    /// # Name
    ///
    /// `alpha`
    ///
    /// # Type
    ///
    /// [`ScalarType::Float`]
    pub const ALPHA: Attribute = Attribute(AttributeInner::ALPHA);

    /// The particle's uniform size.
    ///
    /// The particle is uniformly scaled by this size.
    ///
    /// # Name
    ///
    /// `size`
    ///
    /// # Type
    ///
    /// [`ScalarType::Float`]
    pub const SIZE: Attribute = Attribute(AttributeInner::SIZE);

    /// The particle's 2D size.
    ///
    /// The particle is scaled along its local X and Y axes by these values. The
    /// Z axis is unaffected.
    ///
    /// # Name
    ///
    /// `size2`
    ///
    /// # Type
    ///
    /// [`VectorType::VEC2F`] representing the XY sizes of the particle.
    pub const SIZE2: Attribute = Attribute(AttributeInner::SIZE2);

    /// The particle's 3D size.
    ///
    /// The particle is scaled along its local X, Y, and Z axes by these values.
    ///
    /// # Name
    ///
    /// `size3`
    ///
    /// # Type
    ///
    /// [`VectorType::VEC3F`] representing the XYZ sizes of the particle.
    pub const SIZE3: Attribute = Attribute(AttributeInner::SIZE3);

    /// The previous particle in the ribbon chain.
    ///
    /// This is only present if there's a ribbon. Since there's only one linked
    /// list, we support at most one ribbon per effect.
    ///
    /// # Name
    ///
    /// `prev`
    ///
    /// # Type
    ///
    /// [`ScalarType::Uint`] representing the index of the previous particle in
    /// the chain.
    pub const PREV: Attribute = Attribute(AttributeInner::PREV);

    /// The next particle in the ribbon chain.
    ///
    /// This is only present if there's a ribbon. Since there's only one linked
    /// list, we support at most one ribbon per effect.
    ///
    /// # Name
    ///
    /// `next`
    ///
    /// # Type
    ///
    /// [`ScalarType::Uint`] representing the index of the next particle in the
    /// chain.
    pub const NEXT: Attribute = Attribute(AttributeInner::NEXT);

    /// The local X axis of the particle.
    ///
    /// This attribute stores a per-particle X axis, which defines the
    /// horizontal direction of a quad particle. This is generally used to
    /// re-orient the particle during rendering, for example to face the camera
    /// or another point of interest. For example, the [`OrientModifier`]
    /// modifies this attribute to make the particle face a specific item.
    ///
    /// # Name
    ///
    /// `axis_x`
    ///
    /// # Type
    ///
    /// [`VectorType::VEC3F`]
    ///
    /// [`OrientModifier`]: crate::modifier::output::OrientModifier
    pub const AXIS_X: Attribute = Attribute(AttributeInner::AXIS_X);

    /// The local Y axis of the particle.
    ///
    /// This attribute stores a per-particle Y axis, which defines the vertical
    /// direction of a quad particle. This is generally used to re-orient the
    /// particle during rendering, for example to face the camera or another
    /// point of interest. For example, the [`OrientModifier`] modifies this
    /// attribute to make the particle face a specific item.
    ///
    /// # Name
    ///
    /// `axis_y`
    ///
    /// # Type
    ///
    /// [`VectorType::VEC3F`]
    ///
    /// [`OrientModifier`]: crate::modifier::output::OrientModifier
    pub const AXIS_Y: Attribute = Attribute(AttributeInner::AXIS_Y);

    /// The local Z axis of the particle.
    ///
    /// This attribute stores a per-particle Z axis, which defines the normal to
    /// a quad particle's plane. This is generally used to re-orient the
    /// particle during rendering, for example to face the camera or another
    /// point of interest. For example, the [`OrientModifier`] modifies this
    /// attribute to make the particle face a specific item.
    ///
    /// # Name
    ///
    /// `axis_z`
    ///
    /// # Type
    ///
    /// [`VectorType::VEC3F`]
    ///
    /// [`OrientModifier`]: crate::modifier::output::OrientModifier
    pub const AXIS_Z: Attribute = Attribute(AttributeInner::AXIS_Z);

    /// The sprite index in a flipbook animation.
    ///
    /// This attribute stores the index of the sprite of a flipbook animation.
    /// This is used with the [`FlipbookModifier`].
    ///
    /// # Name
    ///
    /// `sprite_index`
    ///
    /// # Type
    ///
    /// [`ScalarType::Int`]
    ///
    /// [`FlipbookModifier`]: crate::modifier::output::FlipbookModifier
    pub const SPRITE_INDEX: Attribute = Attribute(AttributeInner::SPRITE_INDEX);

    /// A generic scalar float attribute.
    ///
    /// This attribute can be used for anything. It has no specific meaning. You
    /// can store whatever per-particle value you want in it (for example, at
    /// spawn time) and read it back later.
    ///
    /// # Name
    ///
    /// `f32_0`
    ///
    /// # Type
    ///
    /// [`ScalarType::Float`]
    pub const F32_0: Attribute = Attribute(AttributeInner::F32_0);

    /// A generic scalar float attribute.
    ///
    /// This attribute can be used for anything. It has no specific meaning. You
    /// can store whatever per-particle value you want in it (for example, at
    /// spawn time) and read it back later.
    ///
    /// # Name
    ///
    /// `f32_1`
    ///
    /// # Type
    ///
    /// [`ScalarType::Float`]
    pub const F32_1: Attribute = Attribute(AttributeInner::F32_1);

    /// A generic scalar float attribute.
    ///
    /// This attribute can be used for anything. It has no specific meaning. You
    /// can store whatever per-particle value you want in it (for example, at
    /// spawn time) and read it back later.
    ///
    /// # Name
    ///
    /// `f32_2`
    ///
    /// # Type
    ///
    /// [`ScalarType::Float`]
    pub const F32_2: Attribute = Attribute(AttributeInner::F32_2);

    /// A generic scalar float attribute.
    ///
    /// This attribute can be used for anything. It has no specific meaning. You
    /// can store whatever per-particle value you want in it (for example, at
    /// spawn time) and read it back later.
    ///
    /// # Name
    ///
    /// `f32_3`
    ///
    /// # Type
    ///
    /// [`ScalarType::Float`]
    pub const F32_3: Attribute = Attribute(AttributeInner::F32_3);

    declare_custom_attr_pub!(F32X2_0, "f32x2_0", 2, VEC2F);
    declare_custom_attr_pub!(F32X2_1, "f32x2_1", 2, VEC2F);
    declare_custom_attr_pub!(F32X2_2, "f32x2_2", 2, VEC2F);
    declare_custom_attr_pub!(F32X2_3, "f32x2_3", 2, VEC2F);
    declare_custom_attr_pub!(F32X3_0, "f32x3_0", 3, VEC3F);
    declare_custom_attr_pub!(F32X3_1, "f32x3_1", 3, VEC3F);
    declare_custom_attr_pub!(F32X3_2, "f32x3_2", 3, VEC3F);
    declare_custom_attr_pub!(F32X3_3, "f32x3_3", 3, VEC3F);
    declare_custom_attr_pub!(F32X4_0, "f32x4_0", 4, VEC4F);
    declare_custom_attr_pub!(F32X4_1, "f32x4_1", 4, VEC4F);
    declare_custom_attr_pub!(F32X4_2, "f32x4_2", 4, VEC4F);
    declare_custom_attr_pub!(F32X4_3, "f32x4_3", 4, VEC4F);

    declare_custom_attr_u32_pub!(U32_0, "u32_0", Uint);
    declare_custom_attr_u32_pub!(U32_1, "u32_1", Uint);
    declare_custom_attr_u32_pub!(U32_2, "u32_2", Uint);
    declare_custom_attr_u32_pub!(U32_3, "u32_3", Uint);

    /// ID of the ribbon a particle is part of.
    ///
    /// This attribute is used to group particles together by ribbon.
    ///
    /// # Name
    ///
    /// `ribbon_id`
    ///
    /// # Type
    ///
    /// [`ScalarType::Uint`]
    pub const RIBBON_ID: Attribute = Attribute(AttributeInner::RIBBON_ID);

    /// Collection of all the existing particle attributes.
    const ALL: [Attribute; 39] = [
        Attribute::ID,
        Attribute::PARTICLE_COUNTER,
        Attribute::POSITION,
        Attribute::VELOCITY,
        Attribute::AGE,
        Attribute::LIFETIME,
        Attribute::COLOR,
        Attribute::HDR_COLOR,
        Attribute::ALPHA,
        Attribute::SIZE,
        Attribute::SIZE2,
        Attribute::SIZE3,
        Attribute::PREV,
        Attribute::NEXT,
        Attribute::AXIS_X,
        Attribute::AXIS_Y,
        Attribute::AXIS_Z,
        Attribute::SPRITE_INDEX,
        Attribute::F32_0,
        Attribute::F32_1,
        Attribute::F32_2,
        Attribute::F32_3,
        Attribute::F32X2_0,
        Attribute::F32X2_1,
        Attribute::F32X2_2,
        Attribute::F32X2_3,
        Attribute::F32X3_0,
        Attribute::F32X3_1,
        Attribute::F32X3_2,
        Attribute::F32X3_3,
        Attribute::F32X4_0,
        Attribute::F32X4_1,
        Attribute::F32X4_2,
        Attribute::F32X4_3,
        Attribute::U32_0,
        Attribute::U32_1,
        Attribute::U32_2,
        Attribute::U32_3,
        Attribute::RIBBON_ID,
    ];

    // Internal fake attributes used for padding structs.
    pub(crate) const PAD0: Attribute = Attribute(AttributeInner::PAD0);
    pub(crate) const PAD1: Attribute = Attribute(AttributeInner::PAD1);
    pub(crate) const PAD2: Attribute = Attribute(AttributeInner::PAD2);
    pub(crate) const PAD3: Attribute = Attribute(AttributeInner::PAD3);
    pub(crate) const PAD4: Attribute = Attribute(AttributeInner::PAD4);

    /// Retrieve an attribute by its name.
    ///
    /// See [`Attribute::all()`] for the list of attributes, and the
    /// [`Attribute::name()`] method of each attribute for their name.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let attr = Attribute::from_name("position").unwrap();
    /// assert_eq!(attr, Attribute::POSITION);
    /// ```
    pub fn from_name(name: &str) -> Option<Attribute> {
        Attribute::ALL
            .iter()
            .find(|&attr| attr.name() == name)
            .copied()
    }

    /// Get the list of all existing attributes.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// for attr in Attribute::all() {
    ///     println!("{}", attr.name());
    /// }
    /// ```
    pub fn all() -> &'static [Attribute] {
        &Self::ALL
    }

    /// The attribute's name.
    ///
    /// The name of an attribute is unique, and corresponds to the name of the
    /// variable in the generated WGSL code.
    #[inline]
    pub fn name(&self) -> &'static str {
        self.0.name.as_ref()
    }

    /// The attribute's default value.
    #[inline]
    pub fn default_value(&self) -> Value {
        self.0.default_value
    }

    /// The attribute's type.
    ///
    /// This is a shortcut for `default_value().value_type()`.
    #[inline]
    pub fn value_type(&self) -> ValueType {
        self.0.default_value.value_type()
    }

    /// Size of this attribute, in bytes.
    ///
    /// This is a shortcut for `value_type().size()`.
    #[inline]
    pub fn size(&self) -> usize {
        self.value_type().size()
    }

    /// Alignment of this attribute, in bytes.
    ///
    /// This is a shortcut for `value_type().align()`.
    #[inline]
    pub fn align(&self) -> usize {
        self.value_type().align()
    }
}

/// Layout for a single [`Attribute`] inside a [`ParticleLayout`].
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct AttributeLayout {
    /// The particle attribute.
    pub attribute: Attribute,
    /// Offset, in bytes, from the start of the particle.
    pub offset: u32,
}

impl std::fmt::Debug for AttributeLayout {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // "(+offset) name: type"
        f.write_fmt(format_args!(
            "(+{}) {}: {}",
            self.offset,
            self.attribute.name(),
            self.attribute.value_type().to_wgsl_string(),
        ))
    }
}

/// Builder helper to create a new [`ParticleLayout`].
///
/// Use [`ParticleLayout::new()`] to create a new empty builder.
#[derive(Debug, Default, Clone)]
pub struct ParticleLayoutBuilder {
    layout: Vec<AttributeLayout>,
}

impl ParticleLayoutBuilder {
    /// Add a new attribute to the layout builder.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let mut builder = ParticleLayout::new();
    /// builder.append(Attribute::POSITION);
    /// ```
    pub fn append(mut self, attribute: Attribute) -> Self {
        self.layout.push(AttributeLayout {
            attribute,
            offset: 0, // fixed up by build()
        });
        self
    }

    /// Finalize the builder pattern and build the layout from the existing
    /// attributes.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let layout = ParticleLayout::new().append(Attribute::POSITION).build();
    /// ```
    pub fn build(mut self) -> ParticleLayout {
        let pads = [
            Attribute::PAD0,
            Attribute::PAD1,
            Attribute::PAD2,
            Attribute::PAD3,
            Attribute::PAD4,
        ];
        let mut next_pad = 0;

        // Remove duplicates
        self.layout.sort_unstable_by_key(|la| la.attribute.name());
        self.layout.dedup_by_key(|la| la.attribute.name());

        // Sort by size
        self.layout.sort_unstable_by_key(|la| la.attribute.size());

        let unpadded_len = self.layout.len() as u32;

        let mut layout = vec![];
        let mut offset = 0;
        let mut align = 4; // min valid align

        // Enqueue all Float4, which are already aligned
        let index4 = self
            .layout
            .partition_point(|attr| attr.attribute.size() < 16);
        for i in index4..self.layout.len() {
            let mut attr = self.layout[i];
            attr.offset = offset;
            offset += 16;
            layout.push(attr);
        }
        let num4 = self.layout.len() - index4;
        if num4 > 0 {
            align = 16;
        }

        let index2 = self
            .layout
            .partition_point(|attr| attr.attribute.size() < 8);
        let num1 = index2;
        let index3 = self
            .layout
            .partition_point(|attr| attr.attribute.size() < 12);
        let num2 = (index2..index3).len();
        let num3 = (index3..index4).len();
        if num3 > 0 {
            align = 16;
        } else if num2 > 0 {
            align = align.max(8);
        }

        // Enqueue paired { Float3 + Float1 }
        let num_pairs = num1.min(num3);
        for i in 0..num_pairs {
            // Float3
            let mut attr = self.layout[index3 + i];
            attr.offset = offset;
            offset += 12;
            layout.push(attr);

            // Float
            let mut attr = self.layout[i];
            attr.offset = offset;
            offset += 4;
            layout.push(attr);
        }
        let index1 = num_pairs;
        let index3 = index3 + num_pairs;
        let num1 = num1 - num_pairs;
        let num3 = num3 - num_pairs;

        // Enqueue paired { Float2 + Float2 }
        for i in 0..(num2 / 2) {
            for j in 0..2 {
                let mut attr = self.layout[index2 + i * 2 + j];
                attr.offset = offset;
                offset += 8;
                layout.push(attr);
            }
        }
        let index2 = index2 + (num2 / 2) * 2;
        let num2 = num2 % 2;

        // Here we're aligned at 16 byte boundary. We have no more Float4, at most one
        // Float2, and either some Float3 or some Float1 left (but never both).

        // Enqueue all the Float3 if any, since it requires the largest align.
        if num3 > 0 {
            debug_assert_eq!(num1, 0);

            for i in 0..num3 {
                // The attribute itself
                let mut attr = self.layout[index3 + i];
                attr.offset = offset;
                layout.push(attr);

                // The 32-bit padding after it. We know we don't have any Float1 to pad so we
                // need a dummy padding field.
                let pad = AttributeLayout {
                    attribute: pads[next_pad],
                    offset: offset + 12,
                };
                next_pad += 1;
                layout.push(pad);

                offset += 16;
            }
        }

        // Here we're aligned at 16 byte boundary. We have no more Float4, at most one
        // Float2, and possibly some Float1 left.

        // Enqueue the Float2 if any
        if num2 > 0 {
            debug_assert_eq!(num2, 1);

            let mut attr = self.layout[index2];
            attr.offset = offset;
            offset += 8;
            layout.push(attr);
        }

        // Enqueue all remaining Float1
        for i in 0..num1 {
            let mut attr = self.layout[index1 + i];
            attr.offset = offset;
            layout.push(attr);
            offset += 4;
        }

        // Pad the struct to its align. This is mandatory to work around https://github.com/gfx-rs/wgpu/issues/5262.
        let rem = offset.next_multiple_of(align) - offset;
        if rem > 0 {
            debug_assert_eq!(rem % 4, 0);
            let num = rem / 4;
            for _ in 0..num {
                debug_assert!(next_pad < 3);
                let pad = AttributeLayout {
                    attribute: pads[next_pad],
                    offset,
                };
                layout.push(pad);
                next_pad += 1;
                offset += 4;
            }
        }

        ParticleLayout {
            layout,
            align,
            unpadded_len,
        }
    }
}

impl From<&ParticleLayout> for ParticleLayoutBuilder {
    fn from(layout: &ParticleLayout) -> Self {
        Self {
            layout: layout.layout.clone(),
        }
    }
}

/// Particle layout of an effect.
///
/// The particle layout describes the set of attributes used by the particles of
/// an effect, and the relative positioning of those attributes inside the
/// particle GPU buffer.
///
/// Effects with a compatible particle layout can be simulated or rendered
/// together in a single call, therefore it is recommended to minimize the
/// layout variations across effects and attempt to reuse the same layout for
/// multiple effects, which can be benefical for performance.
///
/// # Construction
///
/// To create a particle layout you can either:
/// - Use [`ParticleLayout::default()`] to create the default layout, which
///   contains some default attributes commonly used for effects
///   ([`Attribute::POSITION`], [`Attribute::VELOCITY`], [`Attribute::AGE`],
///   [`Attribute::LIFETIME`]).
/// - Use [`ParticleLayout::empty()`] to create an empty layout without any
///   attribute.
/// - Use [`ParticleLayout::new()`] to create a [`ParticleLayoutBuilder`] and
///   append the necessary attributes manually then call [`build()`] to complete
///   the layout.
///
/// [`build()`]: crate::ParticleLayoutBuilder::build
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct ParticleLayout {
    layout: Vec<AttributeLayout>,
    align: u32,
    unpadded_len: u32,
}

impl std::fmt::Debug for ParticleLayout {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Output a compact list of all layout entries
        f.debug_list().entries(self.layout.iter()).finish()
    }
}

impl Default for ParticleLayout {
    fn default() -> Self {
        // Default layout: { position, age, velocity, lifetime }
        ParticleLayout::new()
            .append(Attribute::POSITION)
            .append(Attribute::AGE)
            .append(Attribute::VELOCITY)
            .append(Attribute::LIFETIME)
            .build()
    }
}

impl ParticleLayout {
    /// Create an empty finalized layout.
    ///
    /// The layout is immutable. This is mostly used as a placeholder while a
    /// valid layout is not available yet. To create a new non-finalized layout
    /// which can be mutated, use [`ParticleLayout::new()`] instead.
    pub const fn empty() -> ParticleLayout {
        Self {
            layout: vec![],
            align: 4,
            unpadded_len: 0,
        }
    }

    /// Create a new empty layout.
    ///
    /// This returns a builder for the particle layout. Use
    /// [`ParticleLayoutBuilder::build()`] to finalize the builder and create
    /// the actual (immutable) [`ParticleLayout`].
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let layout = ParticleLayout::new()
    ///     .append(Attribute::POSITION)
    ///     .append(Attribute::AGE)
    ///     .append(Attribute::LIFETIME)
    ///     .build();
    /// ```
    #[allow(clippy::new_ret_no_self)]
    pub fn new() -> ParticleLayoutBuilder {
        ParticleLayoutBuilder::default()
    }

    /// Build a new particle layout from the current one merged with a new set
    /// of attributes.
    pub fn merged_with(
        &self,
        // attributes: impl IntoIterator<Item = Attribute>,
        attributes: &[Attribute],
    ) -> ParticleLayout {
        let mut builder = ParticleLayoutBuilder::from(self);
        // for attr in attributes.into_iter() {
        for attr in attributes {
            builder = builder.append(*attr);
        }
        builder.build()
    }

    /// Check if this layout is empty.
    pub fn is_empty(&self) -> bool {
        self.unpadded_len == 0
    }

    /// Get the number of fields in the layout.
    ///
    /// Note: if internal padding field need to be added to the final WGSL
    /// struct, they're not counted here. This returns the number of unique
    /// attributes added to the layout.
    pub fn len(&self) -> u32 {
        self.unpadded_len
    }

    /// Get the size of the layout in bytes.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let layout = ParticleLayout::new()
    ///     .append(Attribute::POSITION) // vec3<f32>
    ///     .build();
    /// assert_eq!(layout.size(), 16);
    /// ```
    pub fn size(&self) -> u32 {
        if self.layout.is_empty() {
            0
        } else {
            let last_attr = self.layout.last().unwrap();
            last_attr.offset + last_attr.attribute.size() as u32
        }
    }

    /// Get the alignment of the layout in bytes.
    ///
    /// The alignment follows the rules of WGSL.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let layout = ParticleLayout::new()
    ///     .append(Attribute::POSITION) // vec3<f32>
    ///     .build();
    /// assert_eq!(layout.align(), 16);
    /// ```
    pub fn align(&self) -> u32 {
        self.align
    }

    /// Minimum binding size in bytes.
    ///
    /// This corresponds to the stride of the attribute struct in WGSL when
    /// contained inside an array.
    pub fn min_binding_size(&self) -> NonZeroU64 {
        let size = self.size();
        NonZeroU64::new(size.next_multiple_of(self.align) as u64).unwrap()
    }

    /// Minimum binding size in bytes.
    ///
    /// This corresponds to the stride of the attribute struct in WGSL when
    /// contained inside an array.
    pub fn min_binding_size32(&self) -> NonZeroU32 {
        let size = self.size();
        NonZeroU32::new(size.next_multiple_of(self.align)).unwrap()
    }

    /// Get the list of attributes forming this layout.
    pub fn attributes(&self) -> impl ExactSizeIterator<Item = &AttributeLayout> {
        self.layout.iter()
    }

    /// Check if the layout contains the specified [`Attribute`].
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let layout = ParticleLayout::new().append(Attribute::SIZE).build();
    /// let has_size = layout.contains(Attribute::SIZE);
    /// assert!(has_size);
    /// ```
    pub fn contains(&self, attribute: Attribute) -> bool {
        self.layout
            .iter()
            .any(|&entry| entry.attribute.name() == attribute.name())
    }

    /// Get the offset in bytes of the specified [`Attribute`], if it exists.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let layout = ParticleLayout::new()
    ///     .append(Attribute::POSITION)
    ///     .append(Attribute::SIZE)
    ///     .build();
    /// let size_offset = layout.byte_offset(Attribute::SIZE);
    /// assert_eq!(size_offset, Some(12));
    /// ```
    pub fn byte_offset(&self, attribute: Attribute) -> Option<u32> {
        self.layout.iter().find_map(|&entry| {
            if entry.attribute.name() == attribute.name() {
                Some(entry.offset)
            } else {
                None
            }
        })
    }

    /// Generate the WGSL attribute code corresponding to the layout.
    pub fn generate_code(&self) -> String {
        // assert!(self.layout.is_sorted_by_key(|entry| entry.offset));
        self.layout
            .iter()
            .map(|entry| {
                format!(
                    "    {}: {},",
                    entry.attribute.name(),
                    entry.attribute.value_type().to_wgsl_string()
                )
            })
            .fold(String::new(), |mut a, b| {
                a.reserve(b.len() + 1);
                a.push_str(&b);
                a.push('\n');
                a
            })
    }
}

#[cfg(test)]
mod tests {
    use bevy::reflect::TypeRegistration;
    use naga::{front::wgsl::Frontend, proc::Layouter};

    use super::*;

    // Ensure the size and alignment of all types conforms to the WGSL spec by
    // querying naga as a reference.
    #[test]
    fn value_type_align() {
        let mut frontend = Frontend::new();
        for (value_type, value) in &[
            (
                ValueType::Scalar(ScalarType::Float),
                Value::Scalar(ScalarValue::Float(0.)),
            ),
            // FIXME - We use a constant below, which has a size of 1 byte. For a field
            // inside a struct, the size of bool is undefined in WGSL/naga, and 4 bytes
            // in Hanabi. We probably can't test bool with naga here anyway.
            // (
            //     ValueType::Scalar(ScalarType::Bool),
            //     Value::Scalar(ScalarValue::Bool(true)),
            // ),
            (
                ValueType::Scalar(ScalarType::Int),
                Value::Scalar(ScalarValue::Int(-42)),
            ),
            (
                ValueType::Scalar(ScalarType::Uint),
                Value::Scalar(ScalarValue::Uint(999)),
            ),
            (
                ValueType::Vector(VectorType {
                    elem_type: ScalarType::Float,
                    count: 2,
                }),
                Value::Vector(VectorValue::new_vec2(Vec2::new(-0.5, 3.458))),
            ),
            (
                ValueType::Vector(VectorType {
                    elem_type: ScalarType::Float,
                    count: 3,
                }),
                Value::Vector(VectorValue::new_vec3(Vec3::new(-0.5, 3.458, -53.))),
            ),
            (
                ValueType::Vector(VectorType {
                    elem_type: ScalarType::Float,
                    count: 4,
                }),
                Value::Vector(VectorValue::new_vec4(Vec4::new(-0.5, 3.458, 0., -53.))),
            ),
        ] {
            //assert_eq!(value.value_type(), *value_type);

            // Create a tiny WGSL snippet with the Value(Type) and parse it
            let src = format!("fn main() {{\nlet x = {};\n}}", value.to_wgsl_string());
            let res = frontend.parse(&src);
            if let Err(err) = &res {
                println!("Error: {:?}", err);
            }
            assert!(res.is_ok());
            let m = res.unwrap();
            //println!("Module: {:?}", m);

            // Retrieve the "x" constant and the size/align of its type
            let (_main_handle, main) = m
                .functions
                .iter()
                .find(|c| c.1.name == Some("main".to_string()))
                .unwrap();
            let (expr_handle, _expr_name) =
                main.named_expressions.iter().find(|c| c.1 == "x").unwrap();
            let expr = main.expressions.try_get(*expr_handle).unwrap();

            match expr {
                naga::ir::Expression::Literal(lit) => {
                    // For the literals we support, this is true.
                    assert_eq!(lit.width(), value_type.size() as u8);
                    assert_eq!(lit.width(), value_type.align() as u8);
                }
                naga::ir::Expression::Compose { ty, .. } => {
                    let (size, align) = {
                        // Calculate the type layout according to WGSL
                        let mut layouter = Layouter::default();
                        assert!(layouter.update(m.to_ctx()).is_ok());
                        let layout = layouter[*ty];
                        (layout.size, layout.alignment)
                    };

                    // Compare WGSL layout with the one of Value(Type)
                    assert_eq!(size, value_type.size() as u32);
                    assert_eq!(
                        align,
                        naga::proc::Alignment::new(value_type.align() as u32).unwrap()
                    );
                }
                _ => panic!(),
            };
        }
    }

    #[test]
    fn value_type_is_numeric() {
        assert!(!ScalarType::Bool.is_numeric());
        assert!(ScalarType::Float.is_numeric());
        assert!(ScalarType::Int.is_numeric());
        assert!(ScalarType::Uint.is_numeric());

        assert!(!VectorType::VEC2B.is_numeric());
        assert!(!VectorType::VEC3B.is_numeric());
        assert!(!VectorType::VEC4B.is_numeric());
        assert!(VectorType::VEC2F.is_numeric());
        assert!(VectorType::VEC3F.is_numeric());
        assert!(VectorType::VEC4F.is_numeric());
        assert!(VectorType::VEC2I.is_numeric());
        assert!(VectorType::VEC3I.is_numeric());
        assert!(VectorType::VEC4I.is_numeric());
        assert!(VectorType::VEC2U.is_numeric());
        assert!(VectorType::VEC3U.is_numeric());
        assert!(VectorType::VEC4U.is_numeric());

        assert!(!ValueType::Scalar(ScalarType::Bool).is_numeric());
        assert!(ValueType::Scalar(ScalarType::Float).is_numeric());
        assert!(ValueType::Scalar(ScalarType::Int).is_numeric());
        assert!(ValueType::Scalar(ScalarType::Uint).is_numeric());

        assert!(!ValueType::Vector(VectorType::VEC2B).is_numeric());
        assert!(!ValueType::Vector(VectorType::VEC3B).is_numeric());
        assert!(!ValueType::Vector(VectorType::VEC4B).is_numeric());
        assert!(ValueType::Vector(VectorType::VEC2F).is_numeric());
        assert!(ValueType::Vector(VectorType::VEC3F).is_numeric());
        assert!(ValueType::Vector(VectorType::VEC4F).is_numeric());
        assert!(ValueType::Vector(VectorType::VEC2I).is_numeric());
        assert!(ValueType::Vector(VectorType::VEC3I).is_numeric());
        assert!(ValueType::Vector(VectorType::VEC4I).is_numeric());
        assert!(ValueType::Vector(VectorType::VEC2U).is_numeric());
        assert!(ValueType::Vector(VectorType::VEC3U).is_numeric());
        assert!(ValueType::Vector(VectorType::VEC4U).is_numeric());

        assert!(ValueType::Matrix(MatrixType::MAT2X2F).is_numeric());
        assert!(ValueType::Matrix(MatrixType::MAT3X2F).is_numeric());
        assert!(ValueType::Matrix(MatrixType::MAT4X2F).is_numeric());
        assert!(ValueType::Matrix(MatrixType::MAT2X3F).is_numeric());
        assert!(ValueType::Matrix(MatrixType::MAT3X3F).is_numeric());
        assert!(ValueType::Matrix(MatrixType::MAT4X3F).is_numeric());
        assert!(ValueType::Matrix(MatrixType::MAT2X4F).is_numeric());
        assert!(ValueType::Matrix(MatrixType::MAT3X4F).is_numeric());
        assert!(ValueType::Matrix(MatrixType::MAT4X4F).is_numeric());
    }

    #[test]
    #[should_panic]
    fn vector_type_invalid_rank_1() {
        let _ = VectorType::new(ScalarType::Float, 1);
    }

    #[test]
    #[should_panic]
    fn vector_type_invalid_rank_5() {
        let _ = VectorType::new(ScalarType::Float, 5);
    }

    #[test]
    #[should_panic]
    fn matrix_type_invalid_cols_1() {
        let _ = MatrixType::new(1, 3);
    }

    #[test]
    #[should_panic]
    fn matrix_type_invalid_cols_5() {
        let _ = MatrixType::new(5, 3);
    }

    #[test]
    #[should_panic]
    fn matrix_type_invalid_rows_1() {
        let _ = MatrixType::new(3, 1);
    }

    #[test]
    #[should_panic]
    fn matrix_type_invalid_rows_5() {
        let _ = MatrixType::new(3, 5);
    }

    #[test]
    fn matrix_type_size() {
        assert_eq!(MatrixType::MAT2X2F.size(), 16);
        assert_eq!(MatrixType::MAT3X2F.size(), 24);
        assert_eq!(MatrixType::MAT4X2F.size(), 32);

        // vec3 rows are aligned on 16 bytes
        assert_eq!(MatrixType::MAT2X3F.size(), 32);
        assert_eq!(MatrixType::MAT3X3F.size(), 48);
        assert_eq!(MatrixType::MAT4X3F.size(), 64);

        assert_eq!(MatrixType::MAT2X4F.size(), 32);
        assert_eq!(MatrixType::MAT3X4F.size(), 48);
        assert_eq!(MatrixType::MAT4X4F.size(), 64);
    }

    #[test]
    fn matrix_type_align() {
        assert_eq!(MatrixType::MAT2X2F.align(), 8);
        assert_eq!(MatrixType::MAT3X2F.align(), 8);
        assert_eq!(MatrixType::MAT4X2F.align(), 8);

        // vec3 rows are aligned on 16 bytes
        assert_eq!(MatrixType::MAT2X3F.align(), 16);
        assert_eq!(MatrixType::MAT3X3F.align(), 16);
        assert_eq!(MatrixType::MAT4X3F.align(), 16);

        assert_eq!(MatrixType::MAT2X4F.align(), 16);
        assert_eq!(MatrixType::MAT3X4F.align(), 16);
        assert_eq!(MatrixType::MAT4X4F.align(), 16);
    }

    #[test]
    fn value_type_is_type() {
        for t in [
            ScalarType::Bool,
            ScalarType::Float,
            ScalarType::Int,
            ScalarType::Uint,
        ] {
            assert!(ValueType::Scalar(t).is_scalar());
            assert!(!ValueType::Scalar(t).is_vector());
            assert!(!ValueType::Scalar(t).is_matrix());
            assert_eq!(ValueType::Scalar(t).size(), t.size());
            assert_eq!(ValueType::Scalar(t).align(), t.align());
        }

        for t in [
            VectorType::VEC2B,
            VectorType::VEC3B,
            VectorType::VEC4B,
            VectorType::VEC2F,
            VectorType::VEC3F,
            VectorType::VEC4F,
            VectorType::VEC2I,
            VectorType::VEC3I,
            VectorType::VEC4I,
            VectorType::VEC2U,
            VectorType::VEC3U,
            VectorType::VEC4U,
        ] {
            assert!(!ValueType::Vector(t).is_scalar());
            assert!(ValueType::Vector(t).is_vector());
            assert!(!ValueType::Vector(t).is_matrix());
            assert_eq!(ValueType::Vector(t).size(), t.size());
            assert_eq!(ValueType::Vector(t).align(), t.align());
        }

        for t in [
            MatrixType::MAT2X2F,
            MatrixType::MAT3X2F,
            MatrixType::MAT4X2F,
            MatrixType::MAT2X3F,
            MatrixType::MAT3X3F,
            MatrixType::MAT4X3F,
            MatrixType::MAT2X4F,
            MatrixType::MAT3X4F,
            MatrixType::MAT4X4F,
        ] {
            assert!(!ValueType::Matrix(t).is_scalar());
            assert!(!ValueType::Matrix(t).is_vector());
            assert!(ValueType::Matrix(t).is_matrix());
            assert_eq!(ValueType::Matrix(t).size(), t.size());
            assert_eq!(ValueType::Matrix(t).align(), t.align());
        }
    }

    const TEST_ATTR_NAME: &str = "test_attr";
    const TEST_ATTR_INNER: &AttributeInner = &AttributeInner::new(
        Cow::Borrowed(TEST_ATTR_NAME),
        Value::Vector(VectorValue::new_vec3(Vec3::ONE)),
    );

    #[test]
    fn attr_new() {
        let attr = Attribute(TEST_ATTR_INNER);
        assert_eq!(attr.name(), TEST_ATTR_NAME);
        assert_eq!(attr.size(), 12);
        assert_eq!(attr.align(), 16);
        assert_eq!(
            attr.value_type(),
            ValueType::Vector(VectorType {
                elem_type: ScalarType::Float,
                count: 3
            })
        );
        assert_eq!(
            attr.default_value(),
            Value::Vector(VectorValue::new_vec3(Vec3::ONE))
        );
    }

    #[test]
    fn attr_from_name() {
        for attr in Attribute::all() {
            assert_eq!(Attribute::from_name(attr.name()), Some(*attr));
        }
    }

    #[test]
    fn attr_reflect() {
        let mut attr = Attribute(TEST_ATTR_INNER);

        let r = attr.as_reflect();
        assert_eq!(TypeRegistration::of::<Attribute>().type_id(), r.type_id());
        match r.reflect_ref() {
            ReflectRef::Struct(s) => {
                assert_eq!(2, s.field_len());

                assert_eq!(Some("name"), s.name_at(0));
                assert_eq!(Some("default_value"), s.name_at(1));
                assert_eq!(None, s.name_at(2));
                assert_eq!(None, s.name_at(9999));

                assert_eq!(
                    Some("alloc::borrow::Cow<str>"),
                    s.field("name")
                        .map(|f| f.get_represented_type_info().unwrap().type_path())
                );
                assert_eq!(
                    Some("bevy_hanabi::graph::Value"),
                    s.field("default_value")
                        .map(|f| f.get_represented_type_info().unwrap().type_path())
                );
                assert!(s.field("DUMMY").is_none());
                assert!(s.field("").is_none());

                for (_, f) in s.iter_fields() {
                    let tp = f.get_represented_type_info().unwrap().type_path();
                    assert!(
                        tp.contains("alloc::borrow::Cow<str>")
                            || tp.contains("bevy_hanabi::graph::Value")
                    );
                }

                let d = s.to_dynamic_struct();
                assert_eq!(
                    TypeRegistration::of::<Attribute>().type_id(),
                    d.get_represented_type_info().unwrap().type_id()
                );
                assert_eq!(Some(0), d.index_of_name("name"));
                assert_eq!(Some(1), d.index_of_name("default_value"));
            }
            _ => panic!("Attribute should be reflected as a Struct"),
        }

        // Mutating operators are not implemented by design; only hard-coded built-in
        // attributes are supported. In any case that won't matter because you
        // cannot call `as_reflect_mut()` since you cannot obtain a mutable reference to
        // an attribute.
        let r = attr.as_reflect_mut();
        match r.reflect_mut() {
            ReflectMut::Struct(s) => {
                assert!(s.field_mut("name").is_none());
                assert!(s.field_mut("default_value").is_none());
                assert!(s.field_at_mut(0).is_none());
                assert!(s.field_at_mut(1).is_none());
            }
            _ => panic!("Attribute should be reflected as a Struct"),
        }
    }

    #[test]
    fn attr_from_reflect() {
        for attr in Attribute::ALL {
            let s: String = attr.name().into();
            let r = s.as_partial_reflect();
            let r_attr = Attribute::from_reflect(r).expect(
                "Cannot find
    attribute by name",
            );
            assert_eq!(r_attr, attr);
        }

        assert_eq!(
            None,
            Attribute::from_reflect("test".to_string().as_partial_reflect())
        );
    }

    #[test]
    fn attr_serde() {
        // All existing attributes can round-trip via serialization
        for attr in Attribute::ALL {
            // Serialize; this produces just the name of the attribute, which    uniquely
            // identifies it. The default value is never serialized.
            let ron = ron::to_string(&attr).unwrap();
            assert_eq!(ron, format!("\"{}\"", attr.name()));

            // Deserialize; this recovers the Attribute from its name using
            // Attribute::from_name().
            let s: Attribute = ron::from_str(&ron).unwrap();
            assert_eq!(s, attr);
        }

        // Any other attribute name cannot deserialize
        assert!(ron::from_str::<Attribute>("\"\"").is_err());
        assert!(ron::from_str::<Attribute>("\"UNKNOWN\"").is_err());
    }

    const F1_INNER: &AttributeInner =
        &AttributeInner::new(Cow::Borrowed("F1"), Value::Scalar(ScalarValue::Float(3.)));
    const F1B_INNER: &AttributeInner =
        &AttributeInner::new(Cow::Borrowed("F1B"), Value::Scalar(ScalarValue::Float(5.)));
    const F2_INNER: &AttributeInner = &AttributeInner::new(
        Cow::Borrowed("F2"),
        Value::Vector(VectorValue::new_vec2(Vec2::ZERO)),
    );
    const F2B_INNER: &AttributeInner = &AttributeInner::new(
        Cow::Borrowed("F2B"),
        Value::Vector(VectorValue::new_vec2(Vec2::ONE)),
    );
    const F3_INNER: &AttributeInner = &AttributeInner::new(
        Cow::Borrowed("F3"),
        Value::Vector(VectorValue::new_vec3(Vec3::ZERO)),
    );
    const F3B_INNER: &AttributeInner = &AttributeInner::new(
        Cow::Borrowed("F3B"),
        Value::Vector(VectorValue::new_vec3(Vec3::ONE)),
    );
    const F4_INNER: &AttributeInner = &AttributeInner::new(
        Cow::Borrowed("F4"),
        Value::Vector(VectorValue::new_vec4(Vec4::ZERO)),
    );
    const F4B_INNER: &AttributeInner = &AttributeInner::new(
        Cow::Borrowed("F4B"),
        Value::Vector(VectorValue::new_vec4(Vec4::ONE)),
    );

    const F1: Attribute = Attribute(F1_INNER);
    const F1B: Attribute = Attribute(F1B_INNER);
    const F2: Attribute = Attribute(F2_INNER);
    const F2B: Attribute = Attribute(F2B_INNER);
    const F3: Attribute = Attribute(F3_INNER);
    const F3B: Attribute = Attribute(F3B_INNER);
    const F4: Attribute = Attribute(F4_INNER);
    const F4B: Attribute = Attribute(F4B_INNER);

    /// Calculate the raw alignment based on the actual attributes in the layout
    /// vec, ignoring the value the layout stored. This is for fact-checking
    /// purpose.
    fn calc_raw_align(layout: &ParticleLayout) -> u32 {
        if layout.layout.is_empty() {
            0
        } else {
            layout
                .layout
                .iter()
                .map(|attr| attr.attribute.value_type().align())
                .max()
                .unwrap() as u32
        }
    }

    #[test]
    fn test_layout_build() {
        // empty
        let layout = ParticleLayout::new().build();
        assert_eq!(layout.layout.len(), 0);
        assert_eq!(layout.generate_code(), String::new());

        // single
        for attr in Attribute::ALL {
            let layout = ParticleLayout::new().append(attr).build();

            // This is the un-padded length, so exactly equal
            assert_eq!(layout.len(), 1);

            // There may be padding field(s)...
            assert!(!layout.layout.is_empty());
            let size = layout.size();
            let aligned_size = size.next_multiple_of(layout.align());
            assert_eq!(aligned_size % attr.align() as u32, 0);
            let attr_size = attr.size() as u32;
            if aligned_size != attr_size {
                // Padding
                assert!(aligned_size > attr_size);
                let pad_size = aligned_size - attr_size;
                assert_eq!(pad_size % 4, 0);
                let num_pad = pad_size / 4;
                assert_eq!(layout.layout.len() as u32, 1 + num_pad);
            } else {
                // No padding
                assert_eq!(layout.layout.len(), 1);
            }

            let attr0 = &layout.layout[0];
            assert_eq!(attr0.offset, 0);
            assert!(layout.generate_code().starts_with(&format!(
                "    {}: {},\n",
                attr0.attribute.name(),
                attr0.attribute.value_type().to_wgsl_string()
            )));

            // Align
            assert_eq!(layout.align(), calc_raw_align(&layout));
        }

        // dedup
        for attr in [F1, F2, F3, F4] {
            let mut layout = ParticleLayout::new();
            for _ in 0..3 {
                layout = layout.append(attr);
            }
            let layout = layout.build();
            assert_eq!(layout.len(), 1); // unique
            let attr = &layout.layout[0];
            assert_eq!(attr.offset, 0);
        }

        // homogenous
        for attrs in [[F1, F1B], [F2, F2B], [F3, F3B], [F4, F4B]] {
            let mut layout = ParticleLayout::new();
            for &attr in &attrs {
                layout = layout.append(attr);
            }
            let layout = layout.build();
            assert_eq!(layout.len(), 2);
            let attr_0 = &layout.layout[0];
            let size = attr_0.attribute.size();
            assert_eq!(attr_0.offset as usize, 0);
            if attr_0.attribute.size() != attr_0.attribute.align() {
                // Padding
                let attr_1 = &layout.layout[2]; // skip padding attr
                assert_eq!(
                    attr_1.offset as usize,
                    size.next_multiple_of(attr_0.attribute.align())
                );
                assert_eq!(attr_1.attribute.size(), size);
            } else {
                // No padding
                let attr_1 = &layout.layout[1];
                assert_eq!(
                    attr_1.offset as usize,
                    size.next_multiple_of(attr_0.attribute.align())
                );
                assert_eq!(attr_1.attribute.size(), size);
            }
        }

        // [3, 1, 3, 2] -> [3 1 3 - 2 - -]
        {
            let mut layout = ParticleLayout::new();
            for &attr in &[F1, F3, F2, F3B] {
                layout = layout.append(attr);
            }
            let layout = layout.build();
            assert_eq!(layout.len(), 4);
            assert_eq!(layout.layout.len(), 7);
            assert_eq!(layout.size(), 48);
            assert_eq!(layout.align(), 16);
            for (i, (off, a)) in [
                (0, F3),
                (12, F1),
                (16, F3B),
                (28, Attribute::PAD0),
                (32, F2),
                (40, Attribute::PAD1),
                (44, Attribute::PAD2),
            ]
            .iter()
            .enumerate()
            {
                let attr_i = layout.layout[i];
                assert_eq!(attr_i.offset, *off);
                assert_eq!(attr_i.attribute, *a);
            }
        }

        // [1, 4, 3, 2, 2, 3] -> [4 3 1 2 2 3 -]
        {
            let mut layout = ParticleLayout::new();
            for &attr in &[F1, F4, F3, F2, F2B, F3B] {
                layout = layout.append(attr);
            }
            let layout = layout.build();
            assert_eq!(layout.len(), 6);
            assert_eq!(layout.layout.len(), 7);
            assert_eq!(layout.size(), 64);
            assert_eq!(layout.align(), 16);
            for (i, (off, a)) in [
                (0, F4),
                (16, F3),
                (28, F1),
                (32, F2),
                (40, F2B),
                (48, F3B),
                (60, Attribute::PAD0),
            ]
            .iter()
            .enumerate()
            {
                let attr_i = layout.layout[i];
                assert_eq!(attr_i.offset, *off);
                assert_eq!(attr_i.attribute, *a);
            }
        }
    }
}