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
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
use std::{
    borrow::Cow,
    hash::{DefaultHasher, Hash, Hasher},
    marker::PhantomData,
    num::{NonZeroU32, NonZeroU64},
    ops::{Deref, DerefMut, Range},
    time::Duration,
    vec,
};

#[cfg(feature = "2d")]
use bevy::core_pipeline::core_2d::{Transparent2d, CORE_2D_DEPTH_FORMAT};
#[cfg(feature = "2d")]
use bevy::math::FloatOrd;
#[cfg(feature = "3d")]
use bevy::{
    core_pipeline::{
        core_3d::{
            AlphaMask3d, Opaque3d, Opaque3dBatchSetKey, Opaque3dBinKey, Transparent3d,
            CORE_3D_DEPTH_FORMAT,
        },
        prepass::{OpaqueNoLightmap3dBatchSetKey, OpaqueNoLightmap3dBinKey},
    },
    render::{
        mesh::allocator::MeshSlabs,
        render_phase::{BinnedPhaseItem, ViewBinnedRenderPhases},
    },
};
use bevy::{
    ecs::{
        change_detection::Tick,
        prelude::*,
        system::{lifetimeless::*, SystemParam, SystemState},
    },
    log::trace,
    mesh::MeshVertexBufferLayoutRef,
    platform::collections::HashMap,
    prelude::*,
    render::{
        mesh::{allocator::MeshAllocator, RenderMesh, RenderMeshBufferInfo},
        render_asset::RenderAssets,
        render_phase::{
            Draw, DrawError, DrawFunctions, PhaseItemExtraIndex, SortedPhaseItem,
            TrackedRenderPass, ViewSortedRenderPhases,
        },
        render_resource::{
            binding_types::{
                storage_buffer, storage_buffer_read_only, storage_buffer_read_only_sized,
                storage_buffer_sized, uniform_buffer,
            },
            *,
        },
        renderer::{RenderContext, RenderDevice, RenderGraph, RenderGraphSystems, RenderQueue},
        sync_world::{MainEntity, RenderEntity, TemporaryRenderEntity},
        texture::GpuImage,
        view::{
            ExtractedView, RenderVisibleEntities, ViewUniform, ViewUniformOffset, ViewUniforms,
        },
        Extract, MainWorld,
    },
};
use bitflags::bitflags;
use bytemuck::{Pod, Zeroable};
use effect_cache::{CachedEffect, EffectSlice, SlabState};
use event::{CachedChildInfo, CachedEffectEvents, CachedParentInfo, GpuChildInfo};
use fixedbitset::FixedBitSet;
use gpu_buffer::GpuBuffer;
use naga_oil::compose::{Composer, NagaModuleDescriptor};

use crate::{
    asset::{DefaultMesh, EffectAsset},
    calc_func_id,
    render::{
        batch::{BatchInput, EffectDrawBatch, EffectSorter, InitAndUpdatePipelineIds},
        effect_cache::{AnyDrawIndirectArgs, CachedDrawIndirectArgs, SlabId},
    },
    AlphaMode, Attribute, CompiledParticleEffect, EffectProperties, EffectShaders,
    EffectSimulation, EffectSpawner, EffectVisibilityClass, ParticleLayout, PropertyLayout,
    SimulationCondition, TextureLayout,
};

mod aligned_buffer_vec;
mod batch;
mod buffer_table;
mod effect_cache;
mod event;
mod gpu_buffer;
mod property;
mod shader_cache;
mod sort;

use aligned_buffer_vec::AlignedBufferVec;
use batch::BatchSpawnInfo;
pub(crate) use batch::SortedEffectBatches;
use buffer_table::{BufferTable, BufferTableId};
pub(crate) use effect_cache::EffectCache;
pub(crate) use event::{allocate_events, on_remove_cached_effect_events, EventCache};
pub(crate) use property::{
    allocate_properties, on_remove_cached_properties, prepare_property_buffers, PropertyBindGroups,
    PropertyCache,
};
use property::{CachedEffectProperties, PropertyBindGroupKey};
pub use shader_cache::ShaderCache;
pub(crate) use sort::SortBindGroups;

use self::batch::EffectBatch;

/// Plugin to add systems related to Hanabi rendering.
#[derive(Debug, Clone, Copy)]
pub struct HanabiRenderPlugin;

impl Plugin for HanabiRenderPlugin {
    fn name(&self) -> &str {
        "hanabi:render"
    }

    fn build(&self, app: &mut App) {
        let Some(render_app) = app.get_sub_app_mut(bevy::render::RenderApp) else {
            return;
        };

        render_app.add_systems(
            RenderGraph,
            simulate
                .in_set(RenderGraphSystems::Render)
                .before(bevy::core_pipeline::schedule::camera_driver),
        );
    }
}

/// GPU representation of a single entry in the indirect index buffer of
/// particles.
#[repr(C)]
#[derive(Debug, Copy, Clone, Pod, Zeroable, ShaderType)]
struct GpuIndirectIndex {
    /// Ping-pong indirection index for particles (ping).
    pub ping: u32,
    /// Ping-pong indirection index for particles (pong).
    pub pong: u32,
    /// Indirection index for dead particles, for recycling.
    pub dead: u32,
}

/// Helper to calculate a hash of a given hashable value.
fn calc_hash<H: Hash>(value: &H) -> u64 {
    let mut hasher = DefaultHasher::default();
    value.hash(&mut hasher);
    hasher.finish()
}

/// Source data (buffer and range inside the buffer) to create a buffer binding.
#[derive(Debug, Clone)]
pub(crate) struct BufferBindingSource {
    buffer: Buffer,
    offset: u32,
    size: NonZeroU32,
}

impl BufferBindingSource {
    /// Get a binding over the source data.
    pub fn as_binding(&self) -> BindingResource<'_> {
        BindingResource::Buffer(BufferBinding {
            buffer: &self.buffer,
            offset: self.offset as u64 * 4,
            size: Some(self.size.into()),
        })
    }
}

impl PartialEq for BufferBindingSource {
    fn eq(&self, other: &Self) -> bool {
        self.buffer.id() == other.buffer.id()
            && self.offset == other.offset
            && self.size == other.size
    }
}

impl<'a> From<&'a BufferBindingSource> for BufferBinding<'a> {
    fn from(value: &'a BufferBindingSource) -> Self {
        BufferBinding {
            buffer: &value.buffer,
            offset: value.offset as u64,
            size: Some(value.size.into()),
        }
    }
}

/// Simulation parameters, available to all shaders of all effects.
#[derive(Debug, Default, Clone, Copy, Resource)]
pub(crate) struct SimParams {
    /// Current effect system simulation time since startup, in seconds.
    /// This is based on the [`Time<EffectSimulation>`](EffectSimulation) clock.
    time: f64,
    /// Delta time, in seconds, since last effect system update.
    delta_time: f32,

    /// Current virtual time since startup, in seconds.
    /// This is based on the [`Time<Virtual>`](Virtual) clock.
    virtual_time: f64,
    /// Virtual delta time, in seconds, since last effect system update.
    virtual_delta_time: f32,

    /// Current real time since startup, in seconds.
    /// This is based on the [`Time<Real>`](Real) clock.
    real_time: f64,
    /// Real delta time, in seconds, since last effect system update.
    real_delta_time: f32,
}

/// GPU representation of [`SimParams`], as well as additional per-frame
/// effect-independent values.
#[repr(C)]
#[derive(Debug, Copy, Clone, Pod, Zeroable, ShaderType)]
struct GpuSimParams {
    /// Delta time, in seconds, since last effect system update.
    delta_time: f32,
    /// Current effect system simulation time since startup, in seconds.
    ///
    /// This is a lower-precision variant of [`SimParams::time`].
    time: f32,
    /// Virtual delta time, in seconds, since last effect system update.
    virtual_delta_time: f32,
    /// Current virtual time since startup, in seconds.
    ///
    /// This is a lower-precision variant of [`SimParams::time`].
    virtual_time: f32,
    /// Real delta time, in seconds, since last effect system update.
    real_delta_time: f32,
    /// Current real time since startup, in seconds.
    ///
    /// This is a lower-precision variant of [`SimParams::time`].
    real_time: f32,
    /// Total number of effects to update this frame. Used by the indirect
    /// compute pipeline to cap the compute thread to the actual number of
    /// effects to process.
    ///
    /// This is only used by the `vfx_indirect` compute shader.
    num_effects: u32,
}

impl Default for GpuSimParams {
    fn default() -> Self {
        Self {
            delta_time: 0.04,
            time: 0.0,
            virtual_delta_time: 0.04,
            virtual_time: 0.0,
            real_delta_time: 0.04,
            real_time: 0.0,
            num_effects: 0,
        }
    }
}

impl From<SimParams> for GpuSimParams {
    #[inline]
    fn from(src: SimParams) -> Self {
        Self::from(&src)
    }
}

impl From<&SimParams> for GpuSimParams {
    fn from(src: &SimParams) -> Self {
        Self {
            delta_time: src.delta_time,
            time: src.time as f32,
            virtual_delta_time: src.virtual_delta_time,
            virtual_time: src.virtual_time as f32,
            real_delta_time: src.real_delta_time,
            real_time: src.real_time as f32,
            ..default()
        }
    }
}

/// Compressed representation of a transform for GPU transfer.
///
/// The transform is stored as the three first rows of a transposed [`Mat4`],
/// assuming the last row is the unit row [`Vec4::W`]. The transposing ensures
/// that the three values are [`Vec4`] types which are naturally aligned and
/// without padding when used in WGSL. Without this, storing only the first
/// three components of each column would introduce padding, and would use the
/// same storage size on GPU as a full [`Mat4`].
#[repr(C)]
#[repr(align(16))] // alignof(mat3x4)
#[derive(Debug, Default, Clone, Copy, Pod, Zeroable, ShaderType)]
pub(crate) struct GpuCompressedTransform {
    pub x_row: [f32; 4],
    pub y_row: [f32; 4],
    pub z_row: [f32; 4],
}

impl From<Mat4> for GpuCompressedTransform {
    fn from(value: Mat4) -> Self {
        let tr = value.transpose();
        #[cfg(test)]
        crate::test_utils::assert_approx_eq!(tr.w_axis, Vec4::W);
        Self {
            x_row: tr.x_axis.to_array(),
            y_row: tr.y_axis.to_array(),
            z_row: tr.z_axis.to_array(),
        }
    }
}

impl From<&Mat4> for GpuCompressedTransform {
    fn from(value: &Mat4) -> Self {
        let tr = value.transpose();
        #[cfg(test)]
        crate::test_utils::assert_approx_eq!(tr.w_axis, Vec4::W);
        Self {
            x_row: tr.x_axis.to_array(),
            y_row: tr.y_axis.to_array(),
            z_row: tr.z_axis.to_array(),
        }
    }
}

impl GpuCompressedTransform {
    /// Returns the translation as represented by this transform.
    #[allow(dead_code)]
    pub fn translation(&self) -> Vec3 {
        Vec3 {
            x: self.x_row[3],
            y: self.y_row[3],
            z: self.z_row[3],
        }
    }
}

/// Extension trait for shader types stored in a WGSL storage buffer.
pub(crate) trait StorageType {
    /// Get the aligned size, in bytes, of this type such that it aligns to the
    /// given alignment, in bytes.
    ///
    /// This is mainly used to align GPU types to device requirements.
    fn aligned_size(alignment: u32) -> NonZeroU64;

    /// Get the WGSL padding code to append to the GPU struct to align it.
    ///
    /// This is useful if the struct needs to be bound directly with a dynamic
    /// bind group offset, which requires the offset to be a multiple of a GPU
    /// device specific alignment value.
    fn padding_code(alignment: u32) -> String;
}

impl<T: ShaderType> StorageType for T {
    fn aligned_size(alignment: u32) -> NonZeroU64 {
        NonZeroU64::new(T::min_size().get().next_multiple_of(alignment as u64)).unwrap()
    }

    fn padding_code(alignment: u32) -> String {
        let aligned_size = T::aligned_size(alignment);
        trace!(
            "Aligning {} to {} bytes as device limits requires. Orignal size: {} bytes. Aligned size: {} bytes.",
            std::any::type_name::<T>(),
            alignment,
            T::min_size().get(),
            aligned_size
        );

        // We need to pad the Spawner WGSL struct based on the device padding so that we
        // can use it as an array element but also has a direct struct binding.
        if T::min_size() != aligned_size {
            let padding_size = aligned_size.get() - T::min_size().get();
            assert!(padding_size % 4 == 0);
            format!("padding: array<u32, {}>", padding_size / 4)
        } else {
            "".to_string()
        }
    }
}

/// GPU representation of spawner parameters.
#[repr(C)]
#[derive(Debug, Default, Clone, Copy, Pod, Zeroable, ShaderType)]
pub(crate) struct GpuSpawnerParams {
    /// Transform of the effect (origin of the emitter). This is either added to
    /// emitted particles at spawn time, if the effect simulated in world
    /// space, or to all simulated particles during rendering if the effect is
    /// simulated in local space.
    transform: GpuCompressedTransform,
    /// Inverse of [`transform`], stored with the same convention.
    ///
    /// [`transform`]: Self::transform
    inverse_transform: GpuCompressedTransform,
    /// Number of particles to spawn this frame.
    spawn: i32,
    /// Spawn seed, for randomized modifiers.
    seed: u32,
    /// Index of the pong (read) buffer for indirect indices, used by the render
    /// shader to fetch particles and render them. Only temporarily stored
    /// between indirect and render passes, and overwritten each frame by CPU
    /// upload. This is mostly a hack to transfer a value between those 2
    /// compute passes.
    render_pong: u32,
    /// Index of the [`GpuEffectMetadata`] for this effect.
    effect_metadata_index: u32,
    /// Index of the [`GpuDrawIndirect`] or [`GpuDrawIndexedIndirect`] for this
    /// effect.
    draw_indirect_index: u32,
    /// Start offset of the particles and indirect indices into the effect's
    /// slab, in number of particles (row index).
    slab_offset: u32,
    /// Start offset of the particles and indirect indices into the parent
    /// effect's slab (if the effect has a parent effect), in number of
    /// particles (row index). This is ignored if the effect has no parent.
    parent_slab_offset: u32,
    // For Pod
    _padding0: u32,
}

impl GpuSpawnerParams {
    /// Create a new [`GpuSpawnerParams`] from gathered CPU data.
    pub fn new(
        global_transform: &GlobalTransform,
        spawn_count: u32,
        prng_seed: u32,
        slab_offset: u32,
        parent_slab_offset: Option<u32>,
        effect_metadata_buffer_table_id: BufferTableId,
        maybe_cached_draw_indirect_args: Option<&CachedDrawIndirectArgs>,
    ) -> Self {
        let transform = global_transform.to_matrix().into();
        let inverse_transform = Mat4::from(
            // Inverse the Affine3A first, then convert to Mat4. This is a lot more
            // efficient than inversing the Mat4.
            global_transform.affine().inverse(),
        )
        .into();
        Self {
            transform,
            inverse_transform,
            spawn: spawn_count as i32,
            seed: prng_seed,
            effect_metadata_index: effect_metadata_buffer_table_id.0,
            draw_indirect_index: maybe_cached_draw_indirect_args
                .map(|cdia| cdia.get_row().0)
                .unwrap_or_default(),
            slab_offset,
            parent_slab_offset: parent_slab_offset.unwrap_or(u32::MAX),
            ..default()
        }
    }
}

/// GPU representation of an indirect compute dispatch input.
///
/// Note that unlike most other data structure, this doesn't need to be aligned
/// (except for the default 4-byte align for most GPU types) to any uniform or
/// storage buffer offset alignment, because the buffer storing this is only
/// ever used as input to indirect dispatch commands, and never bound as a
/// shader resource.
///
/// See https://docs.rs/wgpu/latest/wgpu/util/struct.DispatchIndirectArgs.html.
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, ShaderType)]
pub struct GpuDispatchIndirectArgs {
    pub x: u32,
    pub y: u32,
    pub z: u32,
}

impl Default for GpuDispatchIndirectArgs {
    fn default() -> Self {
        Self { x: 0, y: 1, z: 1 }
    }
}

/// GPU representation of an indirect (non-indexed) render input.
///
/// Note that unlike most other data structure, this doesn't need to be aligned
/// (except for the default 4-byte align for most GPU types) to any uniform or
/// storage buffer offset alignment, because the buffer storing this is only
/// ever used as input to indirect render commands, and never bound as a shader
/// resource.
///
/// See https://docs.rs/wgpu/latest/wgpu/util/struct.DrawIndirectArgs.html.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Pod, Zeroable, ShaderType)]
pub struct GpuDrawIndirectArgs {
    pub vertex_count: u32,
    pub instance_count: u32,
    pub first_vertex: u32,
    pub first_instance: u32,
}

impl Default for GpuDrawIndirectArgs {
    fn default() -> Self {
        Self {
            vertex_count: 0,
            instance_count: 1,
            first_vertex: 0,
            first_instance: 0,
        }
    }
}

/// GPU representation of an indirect indexed render input.
///
/// Note that unlike most other data structure, this doesn't need to be aligned
/// (except for the default 4-byte align for most GPU types) to any uniform or
/// storage buffer offset alignment, because the buffer storing this is only
/// ever used as input to indirect render commands, and never bound as a shader
/// resource.
///
/// See https://docs.rs/wgpu/latest/wgpu/util/struct.DrawIndexedIndirectArgs.html.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Pod, Zeroable, ShaderType)]
pub struct GpuDrawIndexedIndirectArgs {
    pub index_count: u32,
    pub instance_count: u32,
    pub first_index: u32,
    pub base_vertex: i32,
    pub first_instance: u32,
}

impl Default for GpuDrawIndexedIndirectArgs {
    fn default() -> Self {
        Self {
            index_count: 0,
            instance_count: 1,
            first_index: 0,
            base_vertex: 0,
            first_instance: 0,
        }
    }
}

/// Shared info for a single batch (single shader invocation).
#[repr(C)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Pod, Zeroable, ShaderType)]
pub struct GpuBatchInfo {
    pub total_spawn_count: u32,
    pub total_update_count: u32,
    pub base_effect: u32,
    /// Offset to apply to the workgroup thread index to determine the global
    /// particle index in the currently bound slab. This is often (and ideally)
    /// zero, but may be > 0 if the entire slab cannot be processed with a
    /// single batch.
    pub base_particle: u32,
    /// Offset, in u32 count (4 bytes), into the prefix sum buffer where the
    /// first value for this batch is located.
    pub prefix_sum_offset: u32,
    /// Number of consecutive values in the prefix sum buffer for this batch.
    /// This is the number of effects batches together in the batch.
    pub prefix_sum_count: u32,
}

/// Metadata describing a single effect instance.
///
/// The metadata describes various effect settings, as well we the location in
/// GPU buffers of the piece of data associated with that instance.
///
/// This is the CPU representation equivalent to the WGSL structure on GPU
/// `EffectMetadata`.
#[repr(C)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Pod, Zeroable, ShaderType)]
pub struct GpuEffectMetadata {
    //
    // Some runtime variables modified on GPU only (capacity is constant)
    /// Effect capacity, in number of particles.
    pub capacity: u32,
    // Additional data not part of the required draw indirect args
    /// Number of alive particles.
    pub alive_count: u32,
    /// Cached value of `alive_count` to cap threads in update pass.
    pub max_update: u32,
    /// Cached value of `dead_count` to cap threads in init pass.
    pub max_spawn: u32,
    /// Index of the ping buffer for particle indices. Init and update compute
    /// passes always write into the ping buffer and read from the pong buffer.
    /// The buffers are swapped (ping = 1 - ping) during the indirect dispatch.
    pub indirect_write_index: u32,

    /// Index of the [`GpuDrawIndirect`] or [`GpuDrawIndexedIndirect`] struct
    /// inside the global [`EffectsMeta::draw_indirect_buffer`] or
    /// [`EffectsMeta::draw_indexed_indirect_buffer`]. The actual buffer depends
    /// on whether the mesh is indexed or not, which is stored in
    /// [`CachedMeshLocation`].
    pub indirect_draw_index: u32,
    /// Offset (in u32 count) of the init indirect dispatch struct inside its
    /// buffer. This avoids having to align those 16-byte structs to the GPU
    /// alignment (at least 32 bytes, even 256 bytes on some).
    pub init_indirect_dispatch_index: u32,
    /// Array index of the property block for this
    /// effect. This is ignored if the effect doesn't use properties.
    pub properties_array_index: u32,
    /// Index of this effect into its parent's ChildInfo array
    /// ([`EffectChildren::effect_cache_ids`] and its associated GPU
    /// array). This starts at zero for the first child of each effect, and is
    /// only unique per parent, not globally. Only available if this effect is a
    /// child of another effect (i.e. if it has a parent).
    pub local_child_index: u32,
    /// For children, global index of the ChildInfo into the shared array.
    pub global_child_index: u32,
    /// For parents, base index of the their first ChildInfo into the shared
    /// array.
    pub base_child_index: u32,

    /// Particle stride, in number of u32.
    pub particle_stride: u32,
    /// Offset from the particle start to the first sort key, in number of u32.
    pub sort_key_offset: u32,
    /// Offset from the particle start to the second sort key, in number of u32.
    pub sort_key2_offset: u32,

    //
    // Again some runtime-only GPU-mutated data
    /// Atomic counter incremented each time a particle spawns. Useful for
    /// things like RIBBON_ID or any other use where a unique value is needed.
    /// The value loops back after some time, but unless some particle lives
    /// forever there's little chance of repetition.
    pub particle_counter: u32,
}

/// Single init fill dispatch item in an [`InitFillDispatchQueue`].
#[derive(Debug)]
pub(super) struct InitFillDispatchItem {
    /// Index of the source [`GpuChildInfo`] entry to read the event count from.
    pub global_child_index: u32,
    /// Index of the [`GpuDispatchIndirect`] entry to write the workgroup count
    /// to.
    pub dispatch_indirect_index: u32,
}

/// Queue of fill dispatch operations for the init indirect pass.
///
/// The queue stores the init fill dispatch operations for the current frame,
/// without the reference to the source and destination buffers, which may be
/// reallocated later in the frame. This allows enqueuing operations during the
/// prepare rendering phase, while deferring GPU buffer (re-)allocation to a
/// later stage.
#[derive(Debug, Default, Resource)]
pub(super) struct InitFillDispatchQueue {
    queue: Vec<InitFillDispatchItem>,
    submitted_queue_index: Option<u32>,
}

impl InitFillDispatchQueue {
    /// Clear the queue.
    #[inline]
    pub fn clear(&mut self) {
        self.queue.clear();
        self.submitted_queue_index = None;
    }

    /// Check if the queue is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.queue.is_empty()
    }

    /// Enqueue a new operation.
    #[inline]
    pub fn enqueue(&mut self, global_child_index: u32, dispatch_indirect_index: u32) {
        assert!(global_child_index != u32::MAX);
        self.queue.push(InitFillDispatchItem {
            global_child_index,
            dispatch_indirect_index,
        });
    }

    /// Submit pending operations for this frame.
    pub fn submit(
        &mut self,
        src_buffer: &Buffer,
        dst_buffer: &Buffer,
        gpu_buffer_operations: &mut GpuBufferOperations,
    ) {
        if self.queue.is_empty() {
            return;
        }

        // Sort by source. We can only batch if the destination is also contiguous, so
        // we can check with a linear walk if the source is already sorted.
        self.queue
            .sort_unstable_by_key(|item| item.global_child_index);

        let mut fill_queue = GpuBufferOperationQueue::new();

        // Batch and schedule all init indirect dispatch operations
        assert!(
            self.queue[0].global_child_index != u32::MAX,
            "Global child index not initialized"
        );
        let mut src_start = self.queue[0].global_child_index;
        let mut dst_start = self.queue[0].dispatch_indirect_index;
        let mut src_end = src_start + 1;
        let mut dst_end = dst_start + 1;
        let src_stride = GpuChildInfo::min_size().get() as u32 / 4;
        let dst_stride = GpuDispatchIndirectArgs::SHADER_SIZE.get() as u32 / 4;
        for i in 1..self.queue.len() {
            let InitFillDispatchItem {
                global_child_index: src,
                dispatch_indirect_index: dst,
            } = self.queue[i];
            if src != src_end || dst != dst_end {
                let count = src_end - src_start;
                debug_assert_eq!(count, dst_end - dst_start);
                let args = GpuBufferOperationArgs {
                    src_offset: src_start * src_stride + 1,
                    src_stride,
                    dst_offset: dst_start * dst_stride,
                    dst_stride,
                    count,
                };
                trace!(
                "enqueue_init_fill(): src:global_child_index={} dst:init_indirect_dispatch_index={} args={:?} src_buffer={:?} dst_buffer={:?}",
                src_start,
                dst_start,
                args,
                src_buffer.id(),
                dst_buffer.id(),
            );
                fill_queue.enqueue(
                    GpuBufferOperationType::FillDispatchArgs,
                    args,
                    src_buffer.clone(),
                    0,
                    None,
                    dst_buffer.clone(),
                    0,
                    None,
                );
                src_start = src;
                dst_start = dst;
            }
            src_end = src + 1;
            dst_end = dst + 1;
        }
        if src_start != src_end || dst_start != dst_end {
            let count = src_end - src_start;
            debug_assert_eq!(count, dst_end - dst_start);
            let args = GpuBufferOperationArgs {
                src_offset: src_start * src_stride + 1,
                src_stride,
                dst_offset: dst_start * dst_stride,
                dst_stride,
                count,
            };
            trace!(
            "IFDA::submit(): src:global_child_index={} dst:init_indirect_dispatch_index={} args={:?} src_buffer={:?} dst_buffer={:?}",
            src_start,
            dst_start,
            args,
            src_buffer.id(),
            dst_buffer.id(),
        );
            fill_queue.enqueue(
                GpuBufferOperationType::FillDispatchArgs,
                args,
                src_buffer.clone(),
                0,
                None,
                dst_buffer.clone(),
                0,
                None,
            );
        }

        debug_assert!(self.submitted_queue_index.is_none());
        if !fill_queue.operation_queue.is_empty() {
            self.submitted_queue_index = Some(gpu_buffer_operations.submit(fill_queue));
        }
    }
}

/// Single sort fill dispatch item in a [`SortFillDispatchQueue`].
#[derive(Debug)]
pub(super) struct SortFillDispatchItem {
    /// Metadata table entry of the ribbon effect batch to read the
    /// [`GpuEffectMetadata::alive_count`] from.
    pub metadata_table_id: BufferTableId,
    /// Index of the [`GpuDispatchIndirect`] entry to write the workgroup count
    /// to.
    pub sort_fill_indirect_dispatch_index: u32,
}

/// Queue of fill dispatch operations for the ribbon particle sort pass.
///
/// The queue stores the sort fill dispatch operations for the current frame,
/// without the reference to the effect metadata buffer, which may be
/// reallocated later in the frame. This allows enqueuing operations during
/// batching, while deferring the buffer capture to after the metadata buffer is
/// (re-)allocated. Mirrors [`InitFillDispatchQueue`].
#[derive(Debug, Default, Resource)]
pub(super) struct SortFillDispatchQueue {
    queue: Vec<SortFillDispatchItem>,
}

impl SortFillDispatchQueue {
    /// Clear the queue.
    #[inline]
    pub fn clear(&mut self) {
        self.queue.clear();
    }

    /// Enqueue a new operation.
    #[inline]
    pub fn enqueue(
        &mut self,
        metadata_table_id: BufferTableId,
        sort_fill_indirect_dispatch_index: u32,
    ) {
        self.queue.push(SortFillDispatchItem {
            metadata_table_id,
            sort_fill_indirect_dispatch_index,
        });
    }

    /// Submit the queued operations, returning the index of the submitted queue
    /// (or `None` if there was nothing to submit). Must be called after
    /// `effect_metadata_buffer` has been (re-)allocated for the frame.
    pub fn submit(
        &self,
        effect_metadata_buffer: &BufferTable<GpuEffectMetadata>,
        effect_metadata_aligned_size: NonZeroU32,
        sort_bind_groups: &SortBindGroups,
        gpu_buffer_operations: &mut GpuBufferOperations,
    ) -> Option<u32> {
        if self.queue.is_empty() {
            return None;
        }

        let Some(src_buffer) = effect_metadata_buffer.buffer() else {
            error!("Failed to find effect metadata buffer. This is a bug.");
            return None;
        };
        let Some(dst_buffer) = sort_bind_groups.indirect_buffer() else {
            error!("Missing indirect dispatch buffer for sorting, cannot schedule particle sort for ribbons. This is a bug.");
            return None;
        };

        let src_offset = std::mem::offset_of!(GpuEffectMetadata, alive_count) as u32 / 4;
        debug_assert_eq!(
            src_offset, 1,
            "GpuEffectMetadata changed, update this assert."
        );
        let src_stride = effect_metadata_aligned_size.get() / 4;
        let dst_stride = GpuDispatchIndirectArgs::SHADER_SIZE.get() as u32 / 4;

        let mut fill_queue = GpuBufferOperationQueue::new();
        for item in &self.queue {
            let src_binding_offset = effect_metadata_buffer.dynamic_offset(item.metadata_table_id);
            // We bind the entire destination buffer (size `None`) and fold the row offset
            // into `dst_offset`, because the indirect dispatch structs are only
            // 12 bytes and so are not aligned to
            // `min_storage_buffer_offset_alignment` for use as a dynamic binding offset.
            let dst_offset = sort_bind_groups
                .get_indirect_dispatch_byte_offset(item.sort_fill_indirect_dispatch_index)
                / 4;
            trace!(
                "queue_sort_fill_dispatch(): src#{:?}@+{}B ({}B) -> dst#{:?}@+{}B (whole)",
                src_buffer.id(),
                src_binding_offset,
                effect_metadata_aligned_size.get(),
                dst_buffer.id(),
                dst_offset * 4,
            );
            fill_queue.enqueue(
                GpuBufferOperationType::FillDispatchArgs,
                GpuBufferOperationArgs {
                    src_offset,
                    src_stride,
                    dst_offset,
                    dst_stride,
                    count: 1,
                },
                src_buffer.clone(),
                src_binding_offset,
                Some(effect_metadata_aligned_size),
                dst_buffer.clone(),
                0,
                None,
            );
        }

        if fill_queue.operation_queue.is_empty() {
            None
        } else {
            Some(gpu_buffer_operations.submit(fill_queue))
        }
    }
}

/// Compute pipeline to run the `vfx_indirect` dispatch workgroup calculation
/// shader.
#[derive(Resource)]
pub(crate) struct DispatchIndirectPipeline {
    /// Layout of bind group sim_params@0.
    sim_params_bind_group_layout_desc: BindGroupLayoutDescriptor,
    /// Layout of bind group effect_metadata@1.
    effect_metadata_bind_group_layout_desc: BindGroupLayoutDescriptor,
    /// Layout of bind group spawner@2.
    spawner_bind_group_layout_desc: BindGroupLayoutDescriptor,
    /// Layout of bind group child_infos@3.
    child_infos_bind_group_layout_desc: BindGroupLayoutDescriptor,
    /// Shader when no GPU events are used (no bind group @3).
    indirect_shader_noevent: Handle<Shader>,
    /// Shader when GPU events are used (bind group @3 present).
    indirect_shader_events: Handle<Shader>,
}

impl FromWorld for DispatchIndirectPipeline {
    fn from_world(world: &mut World) -> Self {
        let render_device = world.get_resource::<RenderDevice>().unwrap();

        // Copy the indirect pipeline shaders to self, because we can't access anything
        // else during pipeline specialization.
        let (indirect_shader_noevent, indirect_shader_events) = {
            let effects_meta = world.get_resource::<EffectsMeta>().unwrap();
            (
                effects_meta.indirect_shader_noevent.clone(),
                effects_meta.indirect_shader_events.clone(),
            )
        };

        let storage_alignment = render_device.limits().min_storage_buffer_offset_alignment;
        let spawner_min_binding_size = GpuSpawnerParams::aligned_size(storage_alignment);

        // @group(0) @binding(0) var<uniform> sim_params : SimParams;
        trace!("GpuSimParams: min_size={}", GpuSimParams::min_size());
        let sim_params_bind_group_layout_desc = BindGroupLayoutDescriptor::new(
            "hanabi:bgl:dispatch_indirect:sim_params",
            &BindGroupLayoutEntries::single(
                ShaderStages::COMPUTE,
                uniform_buffer::<GpuSimParams>(false),
            ),
        );

        trace!(
            "GpuEffectMetadata: min_size={}",
            GpuEffectMetadata::min_size()
        );
        let effect_metadata_bind_group_layout_desc = BindGroupLayoutDescriptor::new(
            "hanabi:bgl:dispatch_indirect:effect_metadata@1",
            &BindGroupLayoutEntries::sequential(
                ShaderStages::COMPUTE,
                (
                    // @group(1) @binding(0) var<storage, read_write> effect_metadata_buffer :
                    // array<u32>;
                    storage_buffer::<GpuEffectMetadata>(false),
                    // @group(1) @binding(1) var<storage, read_write> dispatch_indirect_buffer :
                    // array<u32>;
                    storage_buffer::<GpuIndirectIndex>(false),
                    // @group(1) @binding(2) var<storage, read_write> draw_indirect_buffer :
                    // array<u32>;
                    storage_buffer::<GpuDrawIndexedIndirectArgs>(false),
                ),
            ),
        );

        trace!(
            "GpuSpawnerParams: min_size={} spawner_min_binding_size={}",
            GpuSpawnerParams::min_size(),
            spawner_min_binding_size
        );
        let spawner_bind_group_layout_desc = BindGroupLayoutDescriptor::new(
            "hanabi:bgl:dispatch_indirect:spawner@2",
            &BindGroupLayoutEntries::sequential(
                ShaderStages::COMPUTE,
                (
                    // @group(2) @binding(0) var<storage, read_write> spawner_buffer :
                    // array<Spawner>;
                    //storage_buffer::<GpuSpawnerParams>(false), // TODO - vfx_sort_fill still
                    // needs aligned
                    storage_buffer_sized(false, Some(spawner_min_binding_size)),
                    // @group(2) @binding(1) var<storage, read_write> prefix_sum : array<u32>;
                    storage_buffer::<u32>(false),
                ),
            ),
        );

        trace!("GpuChildInfo: min_size={}", GpuChildInfo::min_size());
        let child_infos_bind_group_layout_desc = BindGroupLayoutDescriptor::new(
            "hanabi:bgl:dispatch_indirect:child_infos@3",
            &BindGroupLayoutEntries::single(
                ShaderStages::COMPUTE,
                // @group(3) @binding(0) var<storage, read_write> child_info_buffer :
                // ChildInfoBuffer;
                storage_buffer::<GpuChildInfo>(false),
            ),
        );

        Self {
            sim_params_bind_group_layout_desc,
            effect_metadata_bind_group_layout_desc,
            spawner_bind_group_layout_desc,
            child_infos_bind_group_layout_desc,
            indirect_shader_noevent,
            indirect_shader_events,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct DispatchIndirectPipelineKey {
    /// True if any allocated effect uses GPU spawn events. In that case, the
    /// pipeline is specialized to clear all GPU events each frame after the
    /// indirect init pass consumed them to spawn particles, and before the
    /// update pass optionally produce more events.
    /// Key: HAS_GPU_SPAWN_EVENTS
    has_events: bool,
}

impl SpecializedComputePipeline for DispatchIndirectPipeline {
    type Key = DispatchIndirectPipelineKey;

    fn specialize(&self, key: Self::Key) -> ComputePipelineDescriptor {
        trace!(
            "Specializing indirect pipeline (has_events={})",
            key.has_events
        );

        let mut shader_defs = Vec::with_capacity(2);
        if key.has_events {
            shader_defs.push("HAS_GPU_SPAWN_EVENTS".into());
        }

        let mut layout = Vec::with_capacity(4);
        layout.push(self.sim_params_bind_group_layout_desc.clone());
        layout.push(self.effect_metadata_bind_group_layout_desc.clone());
        layout.push(self.spawner_bind_group_layout_desc.clone());
        if key.has_events {
            layout.push(self.child_infos_bind_group_layout_desc.clone());
        }

        let label = format!(
            "hanabi:compute_pipeline:dispatch_indirect{}",
            if key.has_events {
                "_events"
            } else {
                "_noevent"
            }
        );

        ComputePipelineDescriptor {
            label: Some(label.into()),
            layout,
            immediate_size: 0,
            shader: if key.has_events {
                self.indirect_shader_events.clone()
            } else {
                self.indirect_shader_noevent.clone()
            },
            shader_defs,
            entry_point: Some("main".into()),
            zero_initialize_workgroup_memory: false,
        }
    }
}

/// Compute pipeline to run the `vfx_prefix_sum` dispatch workgroup calculation
/// shader.
#[derive(Resource)]
pub(crate) struct PrefixSumPipeline {
    /// Layout of the (only) bind group.
    bind_group_layout_desc: BindGroupLayoutDescriptor,
    /// Shader.
    compute_shader: Handle<Shader>,
}

impl FromWorld for PrefixSumPipeline {
    fn from_world(world: &mut World) -> Self {
        // FIXME - we don't really need to keep this in EffectsMeta, could move here,
        // and replace the FromWorld with Default
        let compute_shader = {
            let effects_meta = world.get_resource::<EffectsMeta>().unwrap();
            effects_meta.prefix_sum_shader.clone()
        };
        let min_storage_buffer_offset_alignment = {
            let render_device = world.get_resource::<RenderDevice>().unwrap();
            render_device.limits().min_storage_buffer_offset_alignment
        };

        let bind_group_layout_desc = BindGroupLayoutDescriptor::new(
            "hanabi:bgl:prefix_sum:@0",
            &BindGroupLayoutEntries::sequential(
                ShaderStages::COMPUTE,
                (
                    // @group(0) @binding(0) var<storage, read_write> batch_infos :
                    // array<BatchInfo>;
                    storage_buffer_sized(
                        false,
                        Some(GpuBatchInfo::aligned_size(
                            min_storage_buffer_offset_alignment,
                        )),
                    ),
                    // @group(0) @binding(1) var<storage, read_write> prefix_sum : array<u32>;
                    storage_buffer::<u32>(false),
                    // @group(0) @binding(2) var<storage, read_write> dispatch_indirect_buffer :
                    // array<DispatchIndirectArgs>;
                    storage_buffer::<GpuDispatchIndirectArgs>(false),
                ),
            ),
        );

        Self {
            bind_group_layout_desc,
            compute_shader,
        }
    }
}

impl PrefixSumPipeline {
    pub fn make_pipeline_desc(&self) -> ComputePipelineDescriptor {
        trace!("Create prefix sum pipeline");

        ComputePipelineDescriptor {
            label: Some("hanabi:compute_pipeline:prefix_sum".into()),
            layout: vec![self.bind_group_layout_desc.clone()],
            immediate_size: 0,
            shader: self.compute_shader.clone(),
            shader_defs: vec![],
            entry_point: Some("main".into()),
            zero_initialize_workgroup_memory: false,
        }
    }
}

/// Type of GPU buffer operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum GpuBufferOperationType {
    /// Clear the destination buffer to zero.
    ///
    /// The source parameters [`src_offset`] and [`src_stride`] are ignored.
    ///
    /// [`src_offset`]: crate::GpuBufferOperationArgs::src_offset
    /// [`src_stride`]: crate::GpuBufferOperationArgs::src_stride
    #[allow(dead_code)]
    Zero,
    /// Copy a source buffer into a destination buffer.
    ///
    /// The source can have a stride between each `u32` copied. The destination
    /// is always a contiguous buffer.
    #[allow(dead_code)]
    Copy,
    /// Fill the arguments for a later indirect dispatch call.
    ///
    /// This is similar to a copy, but will round up the source value to the
    /// number of threads per workgroup (64) before writing it into the
    /// destination.
    FillDispatchArgs,
    /// Fill the arguments for a later indirect dispatch call.
    ///
    /// This is the same as [`FillDispatchArgs`], but the source element count
    /// is read from the fourth entry in the destination buffer directly,
    /// and the source buffer and source arguments are unused.
    #[allow(dead_code)]
    FillDispatchArgsSelf,
}

/// GPU representation of the arguments of a block operation on a buffer.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Pod, Zeroable, ShaderType)]
pub(super) struct GpuBufferOperationArgs {
    /// Offset, as u32 count, where the operation starts in the source buffer.
    src_offset: u32,
    /// Stride, as u32 count, between elements in the source buffer.
    src_stride: u32,
    /// Offset, as u32 count, where the operation starts in the destination
    /// buffer.
    dst_offset: u32,
    /// Stride, as u32 count, between elements in the destination buffer.
    dst_stride: u32,
    /// Number of u32 elements to process for this operation.
    count: u32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct QueuedOperationBindGroupKey {
    src_buffer: BufferId,
    src_binding_size: Option<NonZeroU32>,
    dst_buffer: BufferId,
    dst_binding_size: Option<NonZeroU32>,
}

#[derive(Debug, Clone)]
struct QueuedOperation {
    op: GpuBufferOperationType,
    args_index: u32,
    src_buffer: Buffer,
    src_binding_offset: u32,
    src_binding_size: Option<NonZeroU32>,
    dst_buffer: Buffer,
    dst_binding_offset: u32,
    dst_binding_size: Option<NonZeroU32>,
}

impl From<&QueuedOperation> for QueuedOperationBindGroupKey {
    fn from(value: &QueuedOperation) -> Self {
        Self {
            src_buffer: value.src_buffer.id(),
            src_binding_size: value.src_binding_size,
            dst_buffer: value.dst_buffer.id(),
            dst_binding_size: value.dst_binding_size,
        }
    }
}

/// Queue of GPU buffer operations.
///
/// The queue records a series of ordered operations on GPU buffers. It can be
/// submitted for this frame via [`GpuBufferOperations::submit()`], and
/// subsequently dispatched as a compute pass via
/// [`GpuBufferOperations::dispatch()`].
pub struct GpuBufferOperationQueue {
    /// Operation arguments.
    args: Vec<GpuBufferOperationArgs>,
    /// Queued operations.
    operation_queue: Vec<QueuedOperation>,
}

impl GpuBufferOperationQueue {
    /// Create a new empty queue.
    pub fn new() -> Self {
        Self {
            args: vec![],
            operation_queue: vec![],
        }
    }

    /// Enqueue a generic operation.
    pub fn enqueue(
        &mut self,
        op: GpuBufferOperationType,
        args: GpuBufferOperationArgs,
        src_buffer: Buffer,
        src_binding_offset: u32,
        src_binding_size: Option<NonZeroU32>,
        dst_buffer: Buffer,
        dst_binding_offset: u32,
        dst_binding_size: Option<NonZeroU32>,
    ) -> u32 {
        trace!(
            "Queue {:?} op: args={:?} src_buffer={:?} src_binding_offset={} src_binding_size={:?} dst_buffer={:?} dst_binding_offset={} dst_binding_size={:?}",
            op,
            args,
            src_buffer,
            src_binding_offset,
            src_binding_size,
            dst_buffer,
            dst_binding_offset,
            dst_binding_size,
        );
        let args_index = self.args.len() as u32;
        self.args.push(args);
        self.operation_queue.push(QueuedOperation {
            op,
            args_index,
            src_buffer,
            src_binding_offset,
            src_binding_size,
            dst_buffer,
            dst_binding_offset,
            dst_binding_size,
        });
        args_index
    }
}

/// GPU buffer operations for this frame.
///
/// This resource contains a list of submitted [`GpuBufferOperationQueue`] for
/// the current frame, and ensures the bind groups for those operations are up
/// to date.
#[derive(Resource)]
pub(super) struct GpuBufferOperations {
    /// Arguments for the buffer operations submitted this frame.
    args_buffer: AlignedBufferVec<GpuBufferOperationArgs>,

    /// Bind groups for the submitted operations.
    bind_groups: HashMap<QueuedOperationBindGroupKey, BindGroup>,

    /// Submitted queues for this frame.
    queues: Vec<Vec<QueuedOperation>>,
}

impl FromWorld for GpuBufferOperations {
    fn from_world(world: &mut World) -> Self {
        let render_device = world.get_resource::<RenderDevice>().unwrap();
        let align = render_device.limits().min_uniform_buffer_offset_alignment;
        Self::new(align)
    }
}

impl GpuBufferOperations {
    pub fn new(align: u32) -> Self {
        let args_buffer = AlignedBufferVec::new(
            BufferUsages::UNIFORM,
            Some(NonZeroU64::new(align as u64).unwrap()),
            Some("hanabi:buffer:gpu_operation_args".to_string()),
        );
        Self {
            args_buffer,
            bind_groups: default(),
            queues: vec![],
        }
    }

    /// Clear the queue and begin recording operations for a new frame.
    pub fn begin_frame(&mut self) {
        self.args_buffer.clear();
        self.bind_groups.clear(); // for now; might consider caching frame-to-frame
        self.queues.clear();
    }

    /// Submit a recorded queue.
    ///
    /// # Panics
    ///
    /// Panics if the queue submitted is empty.
    pub fn submit(&mut self, mut queue: GpuBufferOperationQueue) -> u32 {
        assert!(!queue.operation_queue.is_empty());
        let queue_index = self.queues.len() as u32;
        for qop in &mut queue.operation_queue {
            qop.args_index = self.args_buffer.push(queue.args[qop.args_index as usize]) as u32;
        }
        self.queues.push(queue.operation_queue);
        queue_index
    }

    /// Finish recording operations for this frame, and schedule buffer writes
    /// to GPU.
    pub fn end_frame(&mut self, device: &RenderDevice, render_queue: &RenderQueue) {
        assert_eq!(
            self.args_buffer.len(),
            self.queues.iter().fold(0, |len, q| len + q.len())
        );

        // Upload to GPU buffer
        self.args_buffer.write_buffer(device, render_queue);
    }

    /// Create all necessary bind groups for all queued operations.
    pub fn create_bind_groups(
        &mut self,
        render_device: &RenderDevice,
        utils_pipeline: &UtilsPipeline,
    ) {
        trace!(
            "Creating bind groups for {} operation queues...",
            self.queues.len()
        );
        for queue in &self.queues {
            for qop in queue {
                // For dynamic-offset operations the dynamic offset is applied at dispatch time
                // on top of the bound binding. Validate here that offset + size
                // fits the source buffer, to turn a stale/too-small buffer
                // capture into an actionable panic rather than a deep wgpu
                // validation error at set_bind_group time.
                #[cfg(debug_assertions)]
                if matches!(qop.op, GpuBufferOperationType::FillDispatchArgs) {
                    if let Some(size) = qop.src_binding_size {
                        debug_assert!(
                            qop.src_binding_offset as u64 + size.get() as u64
                                <= qop.src_buffer.size(),
                            "FillDispatchArgs src binding [{}..{}] overruns source buffer #{:?} of size {}.",
                            qop.src_binding_offset,
                            qop.src_binding_offset as u64 + size.get() as u64,
                            qop.src_buffer.id(),
                            qop.src_buffer.size(),
                        );
                    }
                }
                let key: QueuedOperationBindGroupKey = qop.into();
                self.bind_groups.entry(key).or_insert_with(|| {
                    let src_id: NonZeroU32 = qop.src_buffer.id().into();
                    let dst_id: NonZeroU32 = qop.dst_buffer.id().into();
                    let label = format!("hanabi:bg:util_{}_{}", src_id.get(), dst_id.get());
                    let use_dynamic_offset = matches!(qop.op, GpuBufferOperationType::FillDispatchArgs);
                    let bind_group_layout =
                        utils_pipeline.bind_group_layout(qop.op, use_dynamic_offset);
                    let (src_offset, dst_offset) = if use_dynamic_offset {
                        (0, 0)
                    } else {
                        (qop.src_binding_offset as u64, qop.dst_binding_offset as u64)
                    };
                    trace!(
                        "-> Creating new bind group '{}': src#{} (@+{}B:{:?}B) dst#{} (@+{}B:{:?}B)",
                        label,
                        src_id,
                        src_offset,
                        qop.src_binding_size,
                        dst_id,
                        dst_offset,
                        qop.dst_binding_size,
                    );
                    render_device.create_bind_group(
                        Some(&label[..]),
                        bind_group_layout,
                        &[
                            BindGroupEntry {
                                binding: 0,
                                resource: BindingResource::Buffer(BufferBinding {
                                    buffer: self.args_buffer.buffer().unwrap(),
                                    offset: 0,
                                    // We always bind exactly 1 row of arguments
                                    size: Some(
                                        NonZeroU64::new(self.args_buffer.aligned_size() as u64)
                                            .unwrap(),
                                    ),
                                }),
                            },
                            BindGroupEntry {
                                binding: 1,
                                resource: BindingResource::Buffer(BufferBinding {
                                    buffer: &qop.src_buffer,
                                    offset: src_offset,
                                    size: qop.src_binding_size.map(Into::into),
                                }),
                            },
                            BindGroupEntry {
                                binding: 2,
                                resource: BindingResource::Buffer(BufferBinding {
                                    buffer: &qop.dst_buffer,
                                    offset: dst_offset,
                                    size: qop.dst_binding_size.map(Into::into),
                                }),
                            },
                        ],
                    )
                });
            }
        }
    }

    /// Dispatch a submitted queue by index.
    ///
    /// This creates a new, optionally labelled, compute pass, and records to
    /// the render context a series of compute workgroup dispatch, one for each
    /// enqueued operation.
    ///
    /// The compute pipeline(s) used for each operation are fetched from the
    /// [`UtilsPipeline`], and the associated bind groups are used from a
    /// previous call to [`Self::create_bind_groups()`].
    pub fn dispatch(
        &self,
        index: u32,
        render_context: &mut RenderContext,
        utils_pipeline: &UtilsPipeline,
        compute_pass_label: Option<&str>,
    ) {
        let queue = &self.queues[index as usize];
        trace!(
            "Recording GPU commands for queue #{} ({} ops)...",
            index,
            queue.len(),
        );

        if queue.is_empty() {
            return;
        }

        let mut compute_pass =
            render_context
                .command_encoder()
                .begin_compute_pass(&ComputePassDescriptor {
                    label: compute_pass_label,
                    timestamp_writes: None,
                });

        let mut prev_op = None;
        for qop in queue {
            trace!("qop={:?}", qop);

            if Some(qop.op) != prev_op {
                compute_pass.set_pipeline(utils_pipeline.get_pipeline(qop.op));
                prev_op = Some(qop.op);
            }

            let key: QueuedOperationBindGroupKey = qop.into();
            if let Some(bind_group) = self.bind_groups.get(&key) {
                let args_offset = self.args_buffer.dynamic_offset(qop.args_index as usize);
                let use_dynamic_offset = matches!(qop.op, GpuBufferOperationType::FillDispatchArgs);
                let (src_offset, dst_offset) = if use_dynamic_offset {
                    (qop.src_binding_offset, qop.dst_binding_offset)
                } else {
                    (0, 0)
                };
                compute_pass.set_bind_group(0, bind_group, &[args_offset, src_offset, dst_offset]);
                trace!(
                    "set bind group with args_offset=+{}B src_offset=+{}B dst_offset=+{}B",
                    args_offset,
                    src_offset,
                    dst_offset
                );
            } else {
                error!("GPU fill dispatch buffer operation bind group not found for buffers src#{:?} dst#{:?}", qop.src_buffer.id(), qop.dst_buffer.id());
                continue;
            }

            // Dispatch the operations for this buffer
            const WORKGROUP_SIZE: u32 = 64;
            let num_ops = 1u32; // TODO - batching!
            let workgroup_count = num_ops.div_ceil(WORKGROUP_SIZE);
            compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
            trace!(
                "-> fill dispatch compute dispatched: num_ops={} workgroup_count={}",
                num_ops,
                workgroup_count
            );
        }
    }
}

/// Compute pipeline to run the `vfx_utils` shader.
#[derive(Resource)]
pub(crate) struct UtilsPipeline {
    #[allow(dead_code)]
    bind_group_layout: BindGroupLayout,
    bind_group_layout_dyn: BindGroupLayout,
    bind_group_layout_no_src: BindGroupLayout,
    pipelines: [ComputePipeline; 4],
}

impl FromWorld for UtilsPipeline {
    fn from_world(world: &mut World) -> Self {
        let render_device = world.get_resource::<RenderDevice>().unwrap();

        let bind_group_layout = render_device.create_bind_group_layout(
            "hanabi:bgl:utils",
            &BindGroupLayoutEntries::sequential(
                ShaderStages::COMPUTE,
                (
                    uniform_buffer::<GpuBufferOperationArgs>(false),
                    storage_buffer_read_only::<u32>(false),
                    storage_buffer::<u32>(false),
                ),
            ),
        );

        let pipeline_layout = render_device.create_pipeline_layout(&PipelineLayoutDescriptor {
            label: Some("hanabi:pipeline_layout:utils"),
            bind_group_layouts: &[Some(&bind_group_layout)],
            immediate_size: 0,
        });

        let bind_group_layout_dyn = render_device.create_bind_group_layout(
            "hanabi:bgl:utils_dyn",
            &BindGroupLayoutEntries::sequential(
                ShaderStages::COMPUTE,
                (
                    uniform_buffer::<GpuBufferOperationArgs>(true),
                    storage_buffer_read_only::<u32>(true),
                    storage_buffer::<u32>(true),
                ),
            ),
        );

        let pipeline_layout_dyn = render_device.create_pipeline_layout(&PipelineLayoutDescriptor {
            label: Some("hanabi:pipeline_layout:utils_dyn"),
            bind_group_layouts: &[Some(&bind_group_layout_dyn)],
            immediate_size: 0,
        });

        let bind_group_layout_no_src = render_device.create_bind_group_layout(
            "hanabi:bind_group_layout:utils_no_src",
            &[
                BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::COMPUTE,
                    ty: BindingType::Buffer {
                        ty: BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: Some(GpuBufferOperationArgs::min_size()),
                    },
                    count: None,
                },
                // (no binding #1)
                BindGroupLayoutEntry {
                    binding: 2,
                    visibility: ShaderStages::COMPUTE,
                    ty: BindingType::Buffer {
                        ty: BufferBindingType::Storage { read_only: false },
                        has_dynamic_offset: false,
                        min_binding_size: NonZeroU64::new(4),
                    },
                    count: None,
                },
            ],
        );

        let pipeline_layout_no_src =
            render_device.create_pipeline_layout(&PipelineLayoutDescriptor {
                label: Some("hanabi:pipeline_layout:utils_no_src"),
                bind_group_layouts: &[Some(&bind_group_layout_no_src)],
                immediate_size: 0,
            });

        let shader_code = include_str!("vfx_utils.wgsl");

        // Resolve imports. Because we don't insert this shader into Bevy' pipeline
        // cache, we don't get that part "for free", so we have to do it manually here.
        let shader_source = {
            let mut composer = Composer::default();

            let shader_defs = default();

            match composer.make_naga_module(NagaModuleDescriptor {
                source: shader_code,
                file_path: "vfx_utils.wgsl",
                shader_defs,
                ..Default::default()
            }) {
                Ok(naga_module) => ShaderSource::Naga(Cow::Owned(naga_module)),
                Err(compose_error) => panic!(
                    "Failed to compose vfx_utils.wgsl, naga_oil returned: {}",
                    compose_error.emit_to_string(&composer)
                ),
            }
        };

        debug!("Create utils shader module:\n{}", shader_code);
        #[allow(unsafe_code)]
        let shader_module = unsafe {
            render_device.create_shader_module(ShaderModuleDescriptor {
                label: Some("hanabi:shader:utils"),
                source: shader_source,
            })
        };

        trace!("Create vfx_utils pipelines...");
        let zero_pipeline = render_device.create_compute_pipeline(&RawComputePipelineDescriptor {
            label: Some("hanabi:compute_pipeline:zero_buffer"),
            layout: Some(&pipeline_layout),
            module: &shader_module,
            entry_point: Some("zero_buffer"),
            compilation_options: PipelineCompilationOptions {
                constants: &[],
                zero_initialize_workgroup_memory: false,
            },
            cache: None,
        });
        let copy_pipeline = render_device.create_compute_pipeline(&RawComputePipelineDescriptor {
            label: Some("hanabi:compute_pipeline:copy_buffer"),
            layout: Some(&pipeline_layout_dyn),
            module: &shader_module,
            entry_point: Some("copy_buffer"),
            compilation_options: PipelineCompilationOptions {
                constants: &[],
                zero_initialize_workgroup_memory: false,
            },
            cache: None,
        });
        let fill_dispatch_args_pipeline =
            render_device.create_compute_pipeline(&RawComputePipelineDescriptor {
                label: Some("hanabi:compute_pipeline:fill_dispatch_args"),
                layout: Some(&pipeline_layout_dyn),
                module: &shader_module,
                entry_point: Some("fill_dispatch_args"),
                compilation_options: PipelineCompilationOptions {
                    constants: &[],
                    zero_initialize_workgroup_memory: false,
                },
                cache: None,
            });
        let fill_dispatch_args_self_pipeline =
            render_device.create_compute_pipeline(&RawComputePipelineDescriptor {
                label: Some("hanabi:compute_pipeline:fill_dispatch_args_self"),
                layout: Some(&pipeline_layout_no_src),
                module: &shader_module,
                entry_point: Some("fill_dispatch_args_self"),
                compilation_options: PipelineCompilationOptions {
                    constants: &[],
                    zero_initialize_workgroup_memory: false,
                },
                cache: None,
            });

        Self {
            bind_group_layout,
            bind_group_layout_dyn,
            bind_group_layout_no_src,
            pipelines: [
                zero_pipeline,
                copy_pipeline,
                fill_dispatch_args_pipeline,
                fill_dispatch_args_self_pipeline,
            ],
        }
    }
}

impl UtilsPipeline {
    fn get_pipeline(&self, op: GpuBufferOperationType) -> &ComputePipeline {
        match op {
            GpuBufferOperationType::Zero => &self.pipelines[0],
            GpuBufferOperationType::Copy => &self.pipelines[1],
            GpuBufferOperationType::FillDispatchArgs => &self.pipelines[2],
            GpuBufferOperationType::FillDispatchArgsSelf => &self.pipelines[3],
        }
    }

    fn bind_group_layout(
        &self,
        op: GpuBufferOperationType,
        with_dynamic_offsets: bool,
    ) -> &BindGroupLayout {
        if op == GpuBufferOperationType::FillDispatchArgsSelf {
            assert!(
                !with_dynamic_offsets,
                "FillDispatchArgsSelf op cannot use dynamic offset (not implemented)"
            );
            &self.bind_group_layout_no_src
        } else if with_dynamic_offsets {
            &self.bind_group_layout_dyn
        } else {
            &self.bind_group_layout
        }
    }
}

#[derive(Resource)]
pub(crate) struct ParticlesInitPipeline {
    sim_params_layout_desc: BindGroupLayoutDescriptor,
}

impl Default for ParticlesInitPipeline {
    fn default() -> Self {
        let sim_params_layout_desc = BindGroupLayoutDescriptor::new(
            "hanabi:bgl:vfx_init:sim_params@0",
            // @group(0) @binding(0) var<uniform> sim_params: SimParams;
            &BindGroupLayoutEntries::single(
                ShaderStages::COMPUTE,
                uniform_buffer::<GpuSimParams>(false),
            ),
        );

        Self {
            sim_params_layout_desc,
        }
    }
}

bitflags! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct ParticleInitPipelineKeyFlags: u8 {
        //const CLONE = (1u8 << 0); // DEPRECATED
        const ATTRIBUTE_PREV = (1u8 << 1);
        const ATTRIBUTE_NEXT = (1u8 << 2);
        const CONSUME_GPU_SPAWN_EVENTS = (1u8 << 3);
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct ParticleInitPipelineKey {
    /// Compute shader, with snippets applied, but not preprocessed yet.
    shader: Handle<Shader>,
    /// Minimum binding size in bytes for the particle layout buffer.
    particle_layout_min_binding_size: NonZeroU32,
    /// Minimum binding size in bytes for the particle layout buffer of the
    /// parent effect, if any.
    /// Key: READ_PARENT_PARTICLE
    parent_particle_layout_min_binding_size: Option<NonZeroU32>,
    /// Pipeline flags.
    flags: ParticleInitPipelineKeyFlags,
    /// Layout of the particle@1 bind group this pipeline was specialized with.
    particle_bind_group_layout_desc: BindGroupLayoutDescriptor,
    /// Layout of the spawner@2 bind group this pipeline was specialized with.
    spawner_bind_group_layout_desc: BindGroupLayoutDescriptor,
    /// Layout of the metadata@3 bind group this pipeline was specialized with.
    metadata_bind_group_layout_desc: BindGroupLayoutDescriptor,
}

impl SpecializedComputePipeline for ParticlesInitPipeline {
    type Key = ParticleInitPipelineKey;

    fn specialize(&self, key: Self::Key) -> ComputePipelineDescriptor {
        // We use the hash to correlate the key content with the GPU resource name
        let hash = calc_hash(&key);
        trace!("Specializing init pipeline {hash:016X} with key {key:?}");

        let mut shader_defs = Vec::with_capacity(4);
        if key
            .flags
            .contains(ParticleInitPipelineKeyFlags::ATTRIBUTE_PREV)
        {
            shader_defs.push("ATTRIBUTE_PREV".into());
        }
        if key
            .flags
            .contains(ParticleInitPipelineKeyFlags::ATTRIBUTE_NEXT)
        {
            shader_defs.push("ATTRIBUTE_NEXT".into());
        }
        let consume_gpu_spawn_events = key
            .flags
            .contains(ParticleInitPipelineKeyFlags::CONSUME_GPU_SPAWN_EVENTS);
        if consume_gpu_spawn_events {
            shader_defs.push("CONSUME_GPU_SPAWN_EVENTS".into());
        }
        // FIXME - for now this needs to keep in sync with consume_gpu_spawn_events
        if key.parent_particle_layout_min_binding_size.is_some() {
            assert!(consume_gpu_spawn_events);
            shader_defs.push("READ_PARENT_PARTICLE".into());
        } else {
            assert!(!consume_gpu_spawn_events);
        }

        let label = format!("hanabi:pipeline:init_{hash:016X}");
        trace!(
            "-> creating pipeline '{}' with shader defs:{}",
            label,
            shader_defs
                .iter()
                .fold(String::new(), |acc, x| acc + &format!(" {x:?}"))
        );

        ComputePipelineDescriptor {
            label: Some(label.into()),
            layout: vec![
                self.sim_params_layout_desc.clone(),
                key.particle_bind_group_layout_desc.clone(),
                key.spawner_bind_group_layout_desc.clone(),
                key.metadata_bind_group_layout_desc.clone(),
            ],
            immediate_size: 0,
            shader: key.shader,
            shader_defs,
            entry_point: Some("main".into()),
            zero_initialize_workgroup_memory: false,
        }
    }
}

#[derive(Resource)]
pub(crate) struct ParticlesUpdatePipeline {
    sim_params_layout_desc: BindGroupLayoutDescriptor,
}

impl Default for ParticlesUpdatePipeline {
    fn default() -> Self {
        let sim_params_layout_desc = BindGroupLayoutDescriptor::new(
            "hanabi:bgl:vfx_update:sim_params@0",
            &BindGroupLayoutEntries::sequential(
                ShaderStages::COMPUTE,
                (
                    // @group(0) @binding(0) var<uniform> sim_params : SimParams;
                    uniform_buffer::<GpuSimParams>(false),
                    // @group(0) @binding(1) var<storage, read_write> draw_indirect_buffer :
                    // array<DrawIndexedIndirectArgs>;
                    storage_buffer::<GpuDrawIndexedIndirectArgs>(false),
                ),
            ),
        );

        Self {
            sim_params_layout_desc,
        }
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub(crate) struct ParticleUpdatePipelineKey {
    /// Compute shader, with snippets applied, but not preprocessed yet.
    shader: Handle<Shader>,
    /// Particle layout.
    particle_layout: ParticleLayout,
    /// Minimum binding size in bytes for the particle layout buffer of the
    /// parent effect, if any.
    /// Key: READ_PARENT_PARTICLE
    parent_particle_layout_min_binding_size: Option<NonZeroU32>,
    /// Key: EMITS_GPU_SPAWN_EVENTS
    num_event_buffers: u32,
    /// Layout of the particle@1 bind group this pipeline was specialized with.
    particle_bind_group_layout_desc: BindGroupLayoutDescriptor,
    /// Layout of the spawner@2 bind group this pipeline was specialized with.
    spawner_bind_group_layout_desc: BindGroupLayoutDescriptor,
    /// Layout of the metadata@3 bind group this pipeline was specialized with.
    metadata_bind_group_layout_desc: BindGroupLayoutDescriptor,
}

impl SpecializedComputePipeline for ParticlesUpdatePipeline {
    type Key = ParticleUpdatePipelineKey;

    fn specialize(&self, key: Self::Key) -> ComputePipelineDescriptor {
        // We use the hash to correlate the key content with the GPU resource name
        let hash = calc_hash(&key);
        trace!("Specializing update pipeline {hash:016X} with key {key:?}");

        let mut shader_defs = Vec::with_capacity(6);
        shader_defs.push("EM_MAX_SPAWN_ATOMIC".into());
        // ChildInfo needs atomic event_count because all threads append to the event
        // buffer(s) in parallel.
        shader_defs.push("CHILD_INFO_EVENT_COUNT_IS_ATOMIC".into());
        if key.particle_layout.contains(Attribute::PREV) {
            shader_defs.push("ATTRIBUTE_PREV".into());
        }
        if key.particle_layout.contains(Attribute::NEXT) {
            shader_defs.push("ATTRIBUTE_NEXT".into());
        }
        if key.parent_particle_layout_min_binding_size.is_some() {
            shader_defs.push("READ_PARENT_PARTICLE".into());
        }
        if key.num_event_buffers > 0 {
            shader_defs.push("EMITS_GPU_SPAWN_EVENTS".into());
        }

        let hash = calc_func_id(&key);
        let label = format!("hanabi:pipeline:update_{hash:016X}");
        trace!(
            "-> creating pipeline '{}' with shader defs:{}",
            label,
            shader_defs
                .iter()
                .fold(String::new(), |acc, x| acc + &format!(" {x:?}"))
        );

        ComputePipelineDescriptor {
            label: Some(label.into()),
            layout: vec![
                self.sim_params_layout_desc.clone(),
                key.particle_bind_group_layout_desc.clone(),
                key.spawner_bind_group_layout_desc.clone(),
                key.metadata_bind_group_layout_desc.clone(),
            ],
            immediate_size: 0,
            shader: key.shader,
            shader_defs,
            entry_point: Some("main".into()),
            zero_initialize_workgroup_memory: false,
        }
    }
}

#[derive(Resource)]
pub(crate) struct ParticlesRenderPipeline {
    view_layout_desc: BindGroupLayoutDescriptor,
    material_layout_descs: HashMap<TextureLayout, BindGroupLayoutDescriptor>,
}

impl ParticlesRenderPipeline {
    /// Cache a material, creating its bind group layout based on the texture
    /// layout.
    pub fn cache_material(&mut self, layout: &TextureLayout) {
        if layout.layout.is_empty() {
            return;
        }

        // FIXME - no current stable API to insert an entry into a HashMap only if it
        // doesn't exist, and without having to build a key (as opposed to a reference).
        // So do 2 lookups instead, to avoid having to clone the layout if it's already
        // cached (which should be the common case).
        if self.material_layout_descs.contains_key(layout) {
            return;
        }

        let mut entries = Vec::with_capacity(layout.layout.len() * 2);
        let mut index = 0;
        for _slot in &layout.layout {
            entries.push(BindGroupLayoutEntry {
                binding: index,
                visibility: ShaderStages::FRAGMENT,
                ty: BindingType::Texture {
                    multisampled: false,
                    sample_type: TextureSampleType::Float { filterable: true },
                    view_dimension: TextureViewDimension::D2,
                },
                count: None,
            });
            entries.push(BindGroupLayoutEntry {
                binding: index + 1,
                visibility: ShaderStages::FRAGMENT,
                ty: BindingType::Sampler(SamplerBindingType::Filtering),
                count: None,
            });
            index += 2;
        }
        debug!(
            "Creating material bind group with {} entries [{:?}] for layout {:?}",
            entries.len(),
            entries,
            layout
        );
        let material_bind_group_layout_desc =
            BindGroupLayoutDescriptor::new("hanabi:material_layout_render", &entries[..]);
        self.material_layout_descs
            .insert(layout.clone(), material_bind_group_layout_desc);
    }

    /// Retrieve a bind group layout for a cached material.
    pub fn get_material(&self, layout: &TextureLayout) -> Option<&BindGroupLayoutDescriptor> {
        // Prevent a hash and lookup for the trivial case of an empty layout
        if layout.layout.is_empty() {
            return None;
        }

        self.material_layout_descs.get(layout)
    }
}

impl FromWorld for ParticlesRenderPipeline {
    fn from_world(_world: &mut World) -> Self {
        let view_layout_desc = BindGroupLayoutDescriptor::new(
            "hanabi:bgl:render:view@0",
            &BindGroupLayoutEntries::sequential(
                ShaderStages::VERTEX_FRAGMENT,
                (
                    // @group(0) @binding(0) var<uniform> view: View;
                    uniform_buffer::<ViewUniform>(true),
                    // @group(0) @binding(1) var<uniform> sim_params : SimParams;
                    uniform_buffer::<GpuSimParams>(false),
                ),
            ),
        );

        Self {
            view_layout_desc,
            material_layout_descs: default(),
        }
    }
}

#[cfg(all(feature = "2d", feature = "3d"))]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
enum PipelineMode {
    Camera2d,
    Camera3d,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub(crate) struct ParticleRenderPipelineKey {
    /// Render shader, with snippets applied, but not preprocessed yet.
    shader: Handle<Shader>,
    /// Particle layout.
    particle_layout: ParticleLayout,
    mesh_layout: Option<MeshVertexBufferLayoutRef>,
    /// Texture layout.
    texture_layout: TextureLayout,
    /// Key: LOCAL_SPACE_SIMULATION
    /// The effect is simulated in local space, and during rendering all
    /// particles are transformed by the effect's [`GlobalTransform`].
    local_space_simulation: bool,
    /// Key: USE_ALPHA_MASK, OPAQUE
    /// The particle's alpha masking behavior.
    alpha_mask: ParticleRenderAlphaMaskPipelineKey,
    /// The effect needs Alpha blend.
    alpha_mode: AlphaMode,
    /// Key: FLIPBOOK
    /// The effect is rendered with flipbook texture animation based on the
    /// sprite index of each particle.
    flipbook: bool,
    /// Key: NEEDS_UV
    /// The effect needs UVs.
    needs_uv: bool,
    /// Key: NEEDS_NORMAL
    /// The effect needs normals.
    needs_normal: bool,
    /// Key: NEEDS_PARTICLE_IN_FRAGMENT
    /// The effect needs access to the particle index and buffer in the fragment
    /// shader.
    needs_particle_fragment: bool,
    /// Key: RIBBONS
    /// The effect has ribbons.
    ribbons: bool,
    /// For dual-mode configurations only, the actual mode of the current render
    /// pipeline. Otherwise the mode is implicitly determined by the active
    /// feature.
    #[cfg(all(feature = "2d", feature = "3d"))]
    pipeline_mode: PipelineMode,
    /// MSAA sample count.
    msaa_samples: u32,
    /// Camera output format.
    target_format: TextureFormat,
    /// Layout of the spawner@2 bind group this pipeline was specialized with.
    spawner_bind_group_layout_desc: BindGroupLayoutDescriptor,
}

#[derive(Clone, Copy, Default, Hash, PartialEq, Eq, Debug)]
pub(crate) enum ParticleRenderAlphaMaskPipelineKey {
    #[default]
    Blend,
    /// Key: USE_ALPHA_MASK
    /// The effect is rendered with alpha masking.
    AlphaMask,
    /// Key: OPAQUE
    /// The effect is rendered fully-opaquely.
    Opaque,
}

impl SpecializedRenderPipeline for ParticlesRenderPipeline {
    type Key = ParticleRenderPipelineKey;

    fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor {
        trace!("Specializing render pipeline for key: {key:?}");

        trace!("Creating layout for bind group particle@1 of render pass");
        // FIXME - duplicated in ParticleSlab::new()
        let particle_bind_group_layout_desc = BindGroupLayoutDescriptor::new(
            "hanabi:bgl:render:particle@1",
            &BindGroupLayoutEntries::sequential(
                ShaderStages::VERTEX,
                (
                    // @group(1) @binding(0) var<storage, read> particle_buffer : ParticleBuffer;
                    storage_buffer_read_only_sized(
                        false,
                        Some(key.particle_layout.min_binding_size()),
                    )
                    .visibility(ShaderStages::VERTEX_FRAGMENT),
                    // @group(1) @binding(1) var<storage, read> indirect_buffer : IndirectBuffer;
                    storage_buffer_read_only::<GpuIndirectIndex>(false),
                ),
            ),
        );

        let mut layout = vec![
            self.view_layout_desc.clone(),
            particle_bind_group_layout_desc,
            key.spawner_bind_group_layout_desc.clone(),
        ];
        let mut shader_defs = vec![];

        let vertex_buffer_layout = key.mesh_layout.as_ref().and_then(|mesh_layout| {
            mesh_layout
                .0
                .get_layout(&[
                    Mesh::ATTRIBUTE_POSITION.at_shader_location(0),
                    Mesh::ATTRIBUTE_UV_0.at_shader_location(1),
                    Mesh::ATTRIBUTE_NORMAL.at_shader_location(2),
                ])
                .ok()
        });

        if let Some(material_bind_group_layout) = self.get_material(&key.texture_layout) {
            layout.push(material_bind_group_layout.clone());
        }

        // Key: LOCAL_SPACE_SIMULATION
        if key.local_space_simulation {
            shader_defs.push("LOCAL_SPACE_SIMULATION".into());
        }

        match key.alpha_mask {
            ParticleRenderAlphaMaskPipelineKey::Blend => {}
            ParticleRenderAlphaMaskPipelineKey::AlphaMask => {
                // Key: USE_ALPHA_MASK
                shader_defs.push("USE_ALPHA_MASK".into())
            }
            ParticleRenderAlphaMaskPipelineKey::Opaque => {
                // Key: OPAQUE
                shader_defs.push("OPAQUE".into())
            }
        }

        // Key: FLIPBOOK
        if key.flipbook {
            shader_defs.push("FLIPBOOK".into());
        }

        // Key: NEEDS_UV
        if key.needs_uv {
            shader_defs.push("NEEDS_UV".into());
        }

        // Key: NEEDS_NORMAL
        if key.needs_normal {
            shader_defs.push("NEEDS_NORMAL".into());
        }

        if key.needs_particle_fragment {
            shader_defs.push("NEEDS_PARTICLE_FRAGMENT".into());
        }

        // Key: RIBBONS
        if key.ribbons {
            shader_defs.push("RIBBONS".into());
        }

        #[cfg(feature = "2d")]
        let depth_stencil_2d = DepthStencilState {
            format: CORE_2D_DEPTH_FORMAT,
            // Use depth buffer with alpha-masked particles, not with transparent ones
            depth_write_enabled: Some(false), // TODO - opaque/alphamask 2d
            // Bevy uses reverse-Z, so GreaterEqual really means closer
            depth_compare: Some(CompareFunction::GreaterEqual),
            stencil: StencilState::default(),
            bias: DepthBiasState::default(),
        };

        #[cfg(feature = "3d")]
        let depth_stencil_3d = DepthStencilState {
            format: CORE_3D_DEPTH_FORMAT,
            // Use depth buffer with alpha-masked or opaque particles, not
            // with transparent ones
            depth_write_enabled: Some(matches!(
                key.alpha_mask,
                ParticleRenderAlphaMaskPipelineKey::AlphaMask
                    | ParticleRenderAlphaMaskPipelineKey::Opaque
            )),
            // Bevy uses reverse-Z, so GreaterEqual really means closer
            depth_compare: Some(CompareFunction::GreaterEqual),
            stencil: StencilState::default(),
            bias: DepthBiasState::default(),
        };

        #[cfg(all(feature = "2d", feature = "3d"))]
        assert_eq!(CORE_2D_DEPTH_FORMAT, CORE_3D_DEPTH_FORMAT);
        #[cfg(all(feature = "2d", feature = "3d"))]
        let depth_stencil = match key.pipeline_mode {
            PipelineMode::Camera2d => Some(depth_stencil_2d),
            PipelineMode::Camera3d => Some(depth_stencil_3d),
        };

        #[cfg(all(feature = "2d", not(feature = "3d")))]
        let depth_stencil = Some(depth_stencil_2d);

        #[cfg(all(feature = "3d", not(feature = "2d")))]
        let depth_stencil = Some(depth_stencil_3d);

        let format = key.target_format;

        let hash = calc_func_id(&key);
        let label = format!("hanabi:pipeline:render_{hash:016X}");
        trace!(
            "-> creating pipeline '{}' with shader defs:{}",
            label,
            shader_defs
                .iter()
                .fold(String::new(), |acc, x| acc + &format!(" {x:?}"))
        );

        RenderPipelineDescriptor {
            label: Some(label.into()),
            layout,
            immediate_size: 0,
            vertex: VertexState {
                shader: key.shader.clone(),
                entry_point: Some("vertex".into()),
                shader_defs: shader_defs.clone(),
                buffers: vec![vertex_buffer_layout.expect("Vertex buffer layout not present")],
            },
            fragment: Some(FragmentState {
                shader: key.shader,
                shader_defs,
                entry_point: Some("fragment".into()),
                targets: vec![Some(ColorTargetState {
                    format,
                    blend: Some(key.alpha_mode.into()),
                    write_mask: ColorWrites::ALL,
                })],
            }),
            primitive: PrimitiveState {
                front_face: FrontFace::Ccw,
                cull_mode: None,
                unclipped_depth: false,
                polygon_mode: PolygonMode::Fill,
                conservative: false,
                topology: PrimitiveTopology::TriangleList,
                strip_index_format: None,
            },
            depth_stencil,
            multisample: MultisampleState {
                count: key.msaa_samples,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            zero_initialize_workgroup_memory: false,
        }
    }
}

/// A single effect instance extracted from a [`ParticleEffect`] as a
/// render world item.
///
/// [`ParticleEffect`]: crate::ParticleEffect
#[derive(Debug, Clone, PartialEq, Component)]
#[require(CachedPipelines, CachedReadyState, CachedEffectMetadata)]
pub(crate) struct ExtractedEffect {
    /// Handle to the effect asset this instance is based on.
    /// The handle is weak to prevent refcount cycles and gracefully handle
    /// assets unloaded or destroyed after a draw call has been submitted.
    pub handle: Handle<EffectAsset>,
    /// Particle layout for the effect.
    pub particle_layout: ParticleLayout,
    /// Effect capacity, in number of particles.
    pub capacity: u32,
    /// Layout flags.
    pub layout_flags: LayoutFlags,
    /// Texture layout.
    pub texture_layout: TextureLayout,
    /// Textures.
    pub textures: Vec<Handle<Image>>,
    /// Alpha mode.
    pub alpha_mode: AlphaMode,
    /// Effect shaders.
    pub effect_shaders: EffectShaders,
    /// Condition under which the effect is simulated.
    pub simulation_condition: SimulationCondition,
}

/// Extracted data for the [`GpuSpawnerParams`].
///
/// This contains all data which may change each frame during the regular usage
/// of the effect, but doesn't require any particular GPU resource update
/// (except re-uploading that new data to GPU, of course).
#[derive(Debug, Clone, PartialEq, Component)]
pub(crate) struct ExtractedSpawner {
    /// Number of particles to spawn this frame.
    ///
    /// This is ignored if the effect is a child effect consuming GPU spawn
    /// events.
    pub spawn_count: u32,
    /// PRNG seed.
    pub prng_seed: u32,
    /// Global transform of the effect origin.
    pub transform: GlobalTransform,
    /// Is the effect visible this frame?
    pub is_visible: bool,
}

/// Cache info for the metadata of the effect.
///
/// This manages the GPU allocation of the [`GpuEffectMetadata`] for this
/// effect.
#[derive(Debug, Default, Component)]
pub(crate) struct CachedEffectMetadata {
    /// Allocation ID.
    pub table_id: BufferTableId,
    /// Current metadata values, cached on CPU for change detection.
    pub metadata: GpuEffectMetadata,
}

/// Extracted parent information for a child effect.
///
/// This component is present on the [`RenderEntity`] of an extracted effect if
/// the effect has a parent effect. Otherwise, it's removed.
///
/// This components forms an ECS relationship with [`ChildrenEffects`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Component)]
#[relationship(relationship_target = ChildrenEffects)]
pub(crate) struct ChildEffectOf {
    /// Render entity of the parent.
    pub parent: Entity,
}

/// Extracted children information for a parent effect.
///
/// This component is present on the [`RenderEntity`] of an extracted effect if
/// the effect is a parent effect for one or more child effects. Otherwise, it's
/// removed.
///
/// This components forms an ECS relationship with [`ChildEffectOf`]. Note that
/// we don't use `linked_spawn` because:
/// 1. This would fight with the `SyncToRenderWorld` as the main world
///    parent-child hierarchy is by design not an ECS relationship (it's a lose
///    declarative coupling).
/// 2. The components on the render entity often store GPU resources or other
///    data we need to clean-up manually, and not all of them currently use
///    lifecycle hooks, so we want to manage despawning manually to prevent
///    leaks.
#[derive(Debug, Clone, PartialEq, Eq, Component)]
#[relationship_target(relationship = ChildEffectOf)]
pub(crate) struct ChildrenEffects(Vec<Entity>);

impl<'a> IntoIterator for &'a ChildrenEffects {
    type Item = <Self::IntoIter as Iterator>::Item;

    type IntoIter = std::slice::Iter<'a, Entity>;

    #[inline(always)]
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl Deref for ChildrenEffects {
    type Target = [Entity];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Extracted data for an effect's properties, if any.
///
/// This component is present on the [`RenderEntity`] of an extracted effect if
/// that effect has properties. It optionally contains new CPU data to
/// (re-)upload this frame. If the effect has no property, this component is
/// removed.
#[derive(Debug, Component)]
pub(crate) struct ExtractedProperties {
    /// Property layout for the effect.
    pub property_layout: PropertyLayout,
    /// Values of properties written in a binary blob according to
    /// [`property_layout`].
    ///
    /// This is `Some(blob)` if the data needs to be (re)uploaded to GPU, or
    /// `None` if nothing needs to be done for this frame.
    ///
    /// [`property_layout`]: crate::render::ExtractedEffect::property_layout
    pub property_data: Option<Vec<u8>>,
}

#[derive(Default, Resource)]
pub(crate) struct EffectAssetEvents {
    pub images: Vec<AssetEvent<Image>>,
}

/// System extracting all the asset events for the [`Image`] assets to enable
/// dynamic update of images bound to any effect.
///
/// This system runs in parallel of [`extract_effects`].
pub(crate) fn extract_effect_events(
    mut events: ResMut<EffectAssetEvents>,
    mut image_events: Extract<MessageReader<AssetEvent<Image>>>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("extract_effect_events").entered();
    trace!("extract_effect_events()");

    let EffectAssetEvents { ref mut images } = *events;
    *images = image_events.read().copied().collect();
}

/// Debugging settings.
///
/// Settings used to debug Hanabi. These have no effect on the actual behavior
/// of Hanabi, but may affect its performance.
///
/// # Example
///
/// ```
/// # use bevy::prelude::*;
/// # use bevy_hanabi::*;
/// fn startup(mut debug_settings: ResMut<DebugSettings>) {
///     // Each time a new effect is spawned, capture 2 frames
///     debug_settings.start_capture_on_new_effect = true;
///     debug_settings.capture_frame_count = 2;
/// }
/// ```
#[derive(Debug, Default, Clone, Copy, Resource)]
pub struct DebugSettings {
    /// Enable automatically starting a GPU debugger capture as soon as this
    /// frame starts rendering (extract phase).
    ///
    /// Enable this feature to automatically capture one or more GPU frames when
    /// the `extract_effects()` system runs next. This instructs any attached
    /// GPU debugger to start a capture; this has no effect if no debugger
    /// is attached.
    ///
    /// If a capture is already on-going this has no effect; the on-going
    /// capture needs to be terminated first. Note however that a capture can
    /// stop and another start in the same frame.
    ///
    /// This value is not reset automatically. If you set this to `true`, you
    /// should set it back to `false` on next frame to avoid capturing forever.
    pub start_capture_this_frame: bool,

    /// Enable automatically starting a GPU debugger capture when one or more
    /// effects are spawned.
    ///
    /// Enable this feature to automatically capture one or more GPU frames when
    /// a new effect is spawned (as detected by ECS change detection). This
    /// instructs any attached GPU debugger to start a capture; this has no
    /// effect if no debugger is attached.
    pub start_capture_on_new_effect: bool,

    /// Number of frames to capture with a GPU debugger.
    ///
    /// By default this value is zero, and a GPU debugger capture runs for a
    /// single frame. If a non-zero frame count is specified here, the capture
    /// will instead stop once the specified number of frames has been recorded.
    ///
    /// You should avoid setting this to a value too large, to prevent the
    /// capture size from getting out of control. A typical value is 1 to 3
    /// frames, or possibly more (up to 10) for exceptional contexts. Some GPU
    /// debuggers or graphics APIs might further limit this value on their own,
    /// so there's no guarantee the graphics API will honor this value.
    pub capture_frame_count: u32,
}

#[derive(Debug, Default, Clone, Copy, Resource)]
pub(crate) struct RenderDebugSettings {
    /// Is a GPU debugger capture on-going?
    is_capturing: bool,
    /// Start time of any on-going GPU debugger capture.
    capture_start: Duration,
    /// Number of frames captured so far for on-going GPU debugger capture.
    captured_frames: u32,
}

/// Manage GPU debug capture start/stop.
///
/// If any GPU debug capture is configured to start or stop in
/// [`DebugSettings`], they do so during this system's run. This ensures
/// that all GPU commands produced by Hanabi are recorded (but may miss some
/// from Bevy itself, if another Bevy system runs before this one).
///
/// We do this during extract to try and capture as close as possible to an
/// entire GPU frame.
pub(crate) fn start_stop_gpu_debug_capture(
    real_time: Extract<Res<Time<Real>>>,
    render_device: Res<RenderDevice>,
    debug_settings: Extract<Res<DebugSettings>>,
    mut render_debug_settings: ResMut<RenderDebugSettings>,
    q_added_effects: Extract<Query<(), Added<CompiledParticleEffect>>>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("start_stop_debug_capture").entered();
    trace!("start_stop_debug_capture()");

    // Stop any pending capture if needed
    if render_debug_settings.is_capturing {
        render_debug_settings.captured_frames += 1;

        if render_debug_settings.captured_frames >= debug_settings.capture_frame_count {
            #[expect(unsafe_code, reason = "Debugging only")]
            unsafe {
                render_device.wgpu_device().stop_graphics_debugger_capture();
            }
            render_debug_settings.is_capturing = false;
            warn!(
                "Stopped GPU debug capture after {} frames, at t={}s.",
                render_debug_settings.captured_frames,
                real_time.elapsed().as_secs_f64()
            );
        }
    }

    // If no pending capture, consider starting a new one
    if !render_debug_settings.is_capturing
        && (debug_settings.start_capture_this_frame
            || (debug_settings.start_capture_on_new_effect && !q_added_effects.is_empty()))
    {
        #[expect(unsafe_code, reason = "Debugging only")]
        unsafe {
            render_device
                .wgpu_device()
                .start_graphics_debugger_capture();
        }
        render_debug_settings.is_capturing = true;
        render_debug_settings.capture_start = real_time.elapsed();
        render_debug_settings.captured_frames = 0;
        warn!(
            "Started GPU debug capture of {} frames at t={}s.",
            debug_settings.capture_frame_count,
            render_debug_settings.capture_start.as_secs_f64()
        );
    }
}

/// Write the ready state of all render world effects back into their source
/// effect in the main world.
pub(crate) fn report_ready_state(
    mut main_world: ResMut<MainWorld>,
    q_ready_state: Query<&CachedReadyState>,
) {
    let mut q_effects = main_world.query::<(RenderEntity, &mut CompiledParticleEffect)>();
    for (render_entity, mut compiled_particle_effect) in q_effects.iter_mut(&mut main_world) {
        if let Ok(cached_ready_state) = q_ready_state.get(render_entity) {
            compiled_particle_effect.is_ready = cached_ready_state.is_ready();
        }
    }
}

/// System extracting data for rendering of all active [`ParticleEffect`]
/// components.
///
/// [`ParticleEffect`]: crate::ParticleEffect
pub(crate) fn extract_effects(
    mut commands: Commands,
    effects: Extract<Res<Assets<EffectAsset>>>,
    default_mesh: Extract<Res<DefaultMesh>>,
    // Main world effects to extract
    q_effects: Extract<
        Query<(
            Entity,
            RenderEntity,
            Option<&InheritedVisibility>,
            Option<&ViewVisibility>,
            &EffectSpawner,
            &CompiledParticleEffect,
            Option<Ref<EffectProperties>>,
            &GlobalTransform,
        )>,
    >,
    // Render world effects extracted from a previous frame, if any
    mut q_extracted_effects: Query<(
        &mut ExtractedEffect,
        Option<&mut ExtractedSpawner>,
        Option<&ChildEffectOf>, // immutable, because of relationship
        Option<&mut ExtractedEffectMesh>,
        Option<&mut ExtractedProperties>,
    )>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("extract_effects").entered();
    trace!("extract_effects()");

    // Loop over all existing effects to extract them
    trace!("Extracting {} effects...", q_effects.iter().len());
    for (
        main_entity,
        render_entity,
        maybe_inherited_visibility,
        maybe_view_visibility,
        effect_spawner,
        compiled_effect,
        maybe_properties,
        transform,
    ) in q_effects.iter()
    {
        // Check if shaders are configured
        let Some(effect_shaders) = compiled_effect.get_configured_shaders() else {
            trace!("Effect {:?}: no configured shader, skipped.", main_entity);
            continue;
        };

        // Check if asset is available, otherwise silently ignore
        let Some(asset) = effects.get(&compiled_effect.asset) else {
            trace!(
                "Effect {:?}: EffectAsset not ready, skipped. asset:{:?}",
                main_entity,
                compiled_effect.asset
            );
            continue;
        };

        let is_visible = maybe_inherited_visibility
            .map(|cv| cv.get())
            .unwrap_or(true)
            && maybe_view_visibility.map(|cv| cv.get()).unwrap_or(true);

        let mut cmd = commands.entity(render_entity);

        // Fetch the existing extraction compoennts, if any, which we need to update.
        // Because we use SyncToRenderWorld, there's always a render entity, but it may
        // miss all components. And because we can't query only optional components
        // (that would match all entities in the entire world), we force querying
        // ExtractedEffect, which means we get a miss if it's the first extraction and
        // it's not spawned yet. That's OK, we'll spawn it below.
        let (
            maybe_extracted_effect,
            maybe_extracted_spawner,
            maybe_child_of,
            maybe_extracted_mesh,
            maybe_extracted_properties,
        ) = q_extracted_effects
            .get_mut(render_entity)
            .map(|(extracted_effect, b, c, d, e)| (Some(extracted_effect), b, c, d, e))
            .unwrap_or((None, None, None, None, None));

        // Extract general effect data
        let texture_layout = asset.module().texture_layout();
        let layout_flags = compiled_effect.layout_flags;
        let alpha_mode = compiled_effect.alpha_mode;
        trace!(
            "Extracted instance of effect '{}' on entity {:?} (render entity {:?}): texture_layout_count={} texture_count={} layout_flags={:?}",
            asset.name,
            main_entity,
            render_entity,
            texture_layout.layout.len(),
            compiled_effect.textures.len(),
            layout_flags,
        );
        let new_extracted_effect = ExtractedEffect {
            handle: compiled_effect.asset.clone(),
            particle_layout: asset.particle_layout().clone(),
            capacity: asset.capacity(),
            layout_flags,
            texture_layout,
            textures: compiled_effect.textures.clone(),
            alpha_mode,
            effect_shaders: effect_shaders.clone(),
            simulation_condition: asset.simulation_condition,
        };
        if let Some(mut extracted_effect) = maybe_extracted_effect {
            extracted_effect.set_if_neq(new_extracted_effect);
        } else {
            trace!(
                "Inserting new ExtractedEffect component on {:?}",
                render_entity
            );
            cmd.insert(new_extracted_effect);
        }

        // Extract the spawner data
        let new_spawner = ExtractedSpawner {
            spawn_count: effect_spawner.spawn_count,
            prng_seed: compiled_effect.prng_seed,
            transform: *transform,
            is_visible,
        };
        trace!(
            "[Effect {}] spawn_count={} prng_seed={}",
            render_entity,
            new_spawner.spawn_count,
            new_spawner.prng_seed
        );
        if let Some(mut extracted_spawner) = maybe_extracted_spawner {
            extracted_spawner.set_if_neq(new_spawner);
        } else {
            trace!(
                "Inserting new ExtractedSpawner component on {}",
                render_entity
            );
            cmd.insert(new_spawner);
        }

        // Extract the effect mesh
        let mesh = compiled_effect
            .mesh
            .clone()
            .unwrap_or(default_mesh.0.clone());
        let new_mesh = ExtractedEffectMesh { mesh: mesh.id() };
        if let Some(mut extracted_mesh) = maybe_extracted_mesh {
            extracted_mesh.set_if_neq(new_mesh);
        } else {
            trace!(
                "Inserting new ExtractedEffectMesh component on {:?}",
                render_entity
            );
            cmd.insert(new_mesh);
        }

        // Extract the parent, if any, and resolve its render entity
        let parent_render_entity = if let Some(main_entity) = compiled_effect.parent {
            let Ok((_, render_entity, _, _, _, _, _, _)) = q_effects.get(main_entity) else {
                error!(
                    "Failed to resolve render entity of parent with main entity {:?}.",
                    main_entity
                );
                cmd.remove::<ChildEffectOf>();
                // TODO - prevent extraction altogether here, instead of just de-parenting?
                continue;
            };
            Some(render_entity)
        } else {
            None
        };
        if let Some(render_entity) = parent_render_entity {
            let new_child_of = ChildEffectOf {
                parent: render_entity,
            };
            // If there's already an ExtractedParent component, ensure we overwrite only if
            // different, to not trigger ECS change detection that we rely on.
            if let Some(child_effect_of) = maybe_child_of {
                // The relationship makes ChildEffectOf immutable, so re-insert to mutate
                if *child_effect_of != new_child_of {
                    cmd.insert(new_child_of);
                }
            } else {
                trace!(
                    "Inserting new ChildEffectOf component on {:?}",
                    render_entity
                );
                cmd.insert(new_child_of);
            }
        } else {
            cmd.remove::<ChildEffectOf>();
        }

        // Extract property data
        let property_layout = asset.property_layout();
        if property_layout.is_empty() {
            cmd.remove::<ExtractedProperties>();
        } else {
            // Re-extract CPU property data if any. Note that this data is not a "new value"
            // but instead a "value that must be uploaded this frame", and therefore is
            // empty when there's no change (as opposed to, having a constant value
            // frame-to-frame).
            let property_data = if let Some(properties) = maybe_properties {
                if properties.is_changed() {
                    trace!("Detected property change, re-serializing...");
                    Some(properties.serialize(&property_layout))
                } else {
                    None
                }
            } else {
                None
            };

            let new_properties = ExtractedProperties {
                property_layout,
                property_data,
            };
            trace!("new_properties = {new_properties:?}");

            if let Some(mut extracted_properties) = maybe_extracted_properties {
                // Always mutate if there's new CPU data to re-upload. Otherwise check for any
                // other change.
                if new_properties.property_data.is_some()
                    || (extracted_properties.property_layout != new_properties.property_layout)
                {
                    trace!(
                        "Updating existing ExtractedProperties (was: {:?})",
                        extracted_properties.as_ref()
                    );
                    *extracted_properties = new_properties;
                }
            } else {
                trace!(
                    "Inserting new ExtractedProperties component on {:?}",
                    render_entity
                );
                cmd.insert(new_properties);
            }
        }
    }
}

pub(crate) fn extract_sim_params(
    real_time: Extract<Res<Time<Real>>>,
    virtual_time: Extract<Res<Time<Virtual>>>,
    time: Extract<Res<Time<EffectSimulation>>>,
    mut sim_params: ResMut<SimParams>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("extract_sim_params").entered();
    trace!("extract_sim_params()");

    // Save simulation params into render world
    sim_params.time = time.elapsed_secs_f64();
    sim_params.delta_time = time.delta_secs();
    sim_params.virtual_time = virtual_time.elapsed_secs_f64();
    sim_params.virtual_delta_time = virtual_time.delta_secs();
    sim_params.real_time = real_time.elapsed_secs_f64();
    sim_params.real_delta_time = real_time.delta_secs();
    trace!(
        "SimParams: time={} delta_time={} vtime={} delta_vtime={} rtime={} delta_rtime={}",
        sim_params.time,
        sim_params.delta_time,
        sim_params.virtual_time,
        sim_params.virtual_delta_time,
        sim_params.real_time,
        sim_params.real_delta_time,
    );
}

/// Various GPU limits and aligned sizes computed once and cached.
struct GpuLimits {
    /// Value of [`WgpuLimits::min_storage_buffer_offset_alignment`].
    ///
    /// [`WgpuLimits::min_storage_buffer_offset_alignment`]: bevy::render::settings::WgpuLimits::min_storage_buffer_offset_alignment
    storage_buffer_align: NonZeroU32,

    /// Size of [`GpuEffectMetadata`] aligned to the contraint of
    /// [`WgpuLimits::min_storage_buffer_offset_alignment`].
    ///
    /// [`WgpuLimits::min_storage_buffer_offset_alignment`]: bevy::render::settings::WgpuLimits::min_storage_buffer_offset_alignment
    effect_metadata_aligned_size: NonZeroU32,
}

impl GpuLimits {
    pub fn from_device(render_device: &RenderDevice) -> Self {
        let storage_buffer_align =
            render_device.limits().min_storage_buffer_offset_alignment as u64;

        let effect_metadata_aligned_size = NonZeroU32::new(
            GpuEffectMetadata::min_size()
                .get()
                .next_multiple_of(storage_buffer_align) as u32,
        )
        .unwrap();

        trace!(
            "GPU-aligned sizes (align: {} B):\n- GpuEffectMetadata: {} B -> {} B",
            storage_buffer_align,
            GpuEffectMetadata::min_size().get(),
            effect_metadata_aligned_size.get(),
        );

        Self {
            storage_buffer_align: NonZeroU32::new(storage_buffer_align as u32).unwrap(),
            effect_metadata_aligned_size,
        }
    }

    /// Byte alignment for any storage buffer binding.
    pub fn storage_buffer_align(&self) -> NonZeroU32 {
        self.storage_buffer_align
    }

    /// Byte offset of the [`GpuEffectMetadata`] of a given buffer.
    pub fn effect_metadata_offset(&self, buffer_index: u32) -> u64 {
        self.effect_metadata_aligned_size.get() as u64 * buffer_index as u64
    }
}

/// Global render world resource containing the GPU data to draw all the
/// particle effects in all views.
///
/// The resource is populated by [`prepare_effects()`] with all the effects to
/// render for the current frame, for all views in the frame, and consumed by
/// [`queue_effects()`] to actually enqueue the drawning commands to draw those
/// effects.
#[derive(Resource)]
pub struct EffectsMeta {
    /// Bind group for the camera view, containing the camera projection and
    /// other uniform values related to the camera.
    view_bind_group: Option<BindGroup>,
    /// Bind group #0 of the vfx_update shader, for the simulation parameters
    /// like the current time and frame delta time.
    update_sim_params_bind_group: Option<BindGroup>,
    /// Bind group #0 of the vfx_init and vfx_indirect shaders, for the
    /// simulation parameters like the current time and frame delta time.
    init_and_indirect_sim_params_bind_group: Option<BindGroup>,
    /// Bind group #1 of the vfx_indirect shader, containing both the indirect
    /// compute dispatch and render buffers.
    indirect_metadata_bind_group: Option<BindGroup>,
    /// Bind group #2 of the vfx_indirect shader, containing the spawners.
    indirect_spawner_bind_group: Option<BindGroup>,
    /// Global shared GPU uniform buffer storing the simulation parameters,
    /// uploaded each frame from CPU to GPU.
    sim_params_uniforms: UniformBuffer<GpuSimParams>,
    /// Global shared GPU buffer storing the various spawner parameter structs
    /// for the active effect instances.
    // Note: we're still binding individual spawners in vfx_sort_fill.
    spawner_buffer: AlignedBufferVec<GpuSpawnerParams>,
    /// Global shared GPU buffer storing the various indirect dispatch structs
    /// for the indirect dispatch of the Update pass.
    dispatch_indirect_buffer: GpuBuffer<GpuDispatchIndirectArgs>,
    /// Global shared GPU buffer storing the various indirect draw structs
    /// for the indirect Render pass. Note that we use
    /// GpuDrawIndexedIndirectArgs as the largest of the two variants (the
    /// other being GpuDrawIndirectArgs). For non-indexed entries, we ignore
    /// the last `u32` value.
    draw_indirect_buffer: BufferTable<GpuDrawIndexedIndirectArgs>,
    /// Global shared GPU buffer storing the various `BatchInfo` structs for the
    /// active batches. This is dynamically updated each frame based on current
    /// batching, with one entry per batch (= one entry per dispatch/draw).
    batch_info_buffer: AlignedBufferVec<GpuBatchInfo>,
    /// Debug: was begin_batch() called without end_batch()?
    is_batch_open: bool,
    /// Buffer containing the prefix sums for all batches.
    prefix_sum_buffer: BufferVec<u32>,
    /// Global shared GPU buffer storing the various `EffectMetadata`
    /// structs for the active effect instances.
    effect_metadata_buffer: BufferTable<GpuEffectMetadata>,
    /// Various GPU limits and aligned sizes lazily allocated and cached for
    /// convenience.
    gpu_limits: GpuLimits,
    indirect_shader_noevent: Handle<Shader>,
    indirect_shader_events: Handle<Shader>,
    /// Pipeline cache ID of the two indirect dispatch pass pipelines (the
    /// -noevent and -events variants).
    indirect_pipeline_ids: [CachedComputePipelineId; 2],
    /// Pipeline cache ID of the active indirect dispatch pass pipeline, which
    /// is either the -noevent or -events variant depending on whether there's
    /// any child effect with GPU events currently active.
    active_indirect_pipeline_id: CachedComputePipelineId,

    prefix_sum_shader: Handle<Shader>,
    prefix_sum_bind_group: Option<BindGroup>,
    prefix_sum_pipeline_id: CachedComputePipelineId,
}

impl EffectsMeta {
    pub fn new(
        device: RenderDevice,
        indirect_shader_noevent: Handle<Shader>,
        indirect_shader_events: Handle<Shader>,
        prefix_sum_shader: Handle<Shader>,
    ) -> Self {
        let gpu_limits = GpuLimits::from_device(&device);

        // Ensure individual GpuSpawnerParams elements are properly aligned so they can
        // be addressed individually by the computer shaders.
        let item_align = gpu_limits.storage_buffer_align();
        trace!(
            "Aligning storage buffers to {} bytes as device limits requires.",
            item_align.get()
        );

        let mut prefix_sum_buffer = BufferVec::new(BufferUsages::STORAGE);
        prefix_sum_buffer.set_label(Some("prefix_sum_buffer"));

        Self {
            view_bind_group: None,
            update_sim_params_bind_group: None,
            init_and_indirect_sim_params_bind_group: None,
            indirect_metadata_bind_group: None,
            indirect_spawner_bind_group: None,
            sim_params_uniforms: UniformBuffer::default(),
            spawner_buffer: AlignedBufferVec::new(
                BufferUsages::STORAGE,
                Some(item_align.into()),
                Some("hanabi:buffer:spawner".to_string()),
            ),
            dispatch_indirect_buffer: GpuBuffer::new(
                BufferUsages::STORAGE | BufferUsages::INDIRECT,
                Some("hanabi:buffer:dispatch_indirect".to_string()),
            ),
            draw_indirect_buffer: BufferTable::new(
                BufferUsages::STORAGE | BufferUsages::INDIRECT,
                Some(GpuDrawIndexedIndirectArgs::SHADER_SIZE),
                Some("hanabi:buffer:draw_indirect".to_string()),
            ),
            batch_info_buffer: AlignedBufferVec::new(
                BufferUsages::STORAGE,
                Some(item_align.into()),
                Some("hanabi:buffer:batch_info".to_string()),
            ),
            is_batch_open: false,
            prefix_sum_buffer,
            effect_metadata_buffer: BufferTable::new(
                BufferUsages::STORAGE | BufferUsages::INDIRECT,
                Some(item_align.into()),
                Some("hanabi:buffer:effect_metadata".to_string()),
            ),
            gpu_limits,
            indirect_shader_noevent,
            indirect_shader_events,
            indirect_pipeline_ids: [
                CachedComputePipelineId::INVALID,
                CachedComputePipelineId::INVALID,
            ],
            active_indirect_pipeline_id: CachedComputePipelineId::INVALID,
            prefix_sum_shader,
            prefix_sum_bind_group: None,
            prefix_sum_pipeline_id: CachedComputePipelineId::INVALID,
        }
    }

    /// Begin a new batch of effects.
    pub fn begin_batch(&mut self, base_particle: u32, spawner_base: u32) -> u32 {
        assert!(!self.is_batch_open, "Duplicate call to begin_batch()");

        let prefix_sum_offset = self.prefix_sum_buffer.len() as u32;

        let batch_info_base = self.batch_info_buffer.len() as u32;
        let batch_info = GpuBatchInfo {
            total_spawn_count: 0,
            total_update_count: 0,
            base_effect: spawner_base,
            base_particle,
            prefix_sum_offset,
            prefix_sum_count: u32::MAX, // invalid; set in end_batch()
        };
        trace!("batch info = {:?}", batch_info);
        self.batch_info_buffer.push(batch_info);
        self.is_batch_open = true;

        // Ensure we allocate the DI entries with the same indexing as the batch info
        // ones, so that shaders can index them with the batch info index.
        let di_index = self.dispatch_indirect_buffer.allocate();
        assert_eq!(di_index, batch_info_base);

        batch_info_base
    }

    /// Add a single effect instance to the current batch.
    pub fn add_effect_to_batch(&mut self, slab_offset: u32) {
        assert!(
            self.is_batch_open,
            "Cannot add effect before calling begin_batch()"
        );
        self.prefix_sum_buffer.push(slab_offset);
    }

    /// End the current batch.
    pub fn end_batch(&mut self) {
        assert!(
            self.is_batch_open,
            "Call to end_batch() without begin_batch()"
        );

        let batch = self
            .batch_info_buffer
            .last_mut()
            .expect("No open batch. Missing begin_batch() call?");
        let end = self.prefix_sum_buffer.len() as u32;
        assert!(end >= batch.prefix_sum_offset);
        batch.prefix_sum_count = end - batch.prefix_sum_offset;

        self.is_batch_open = false;
    }

    /// Allocate a [`GpuSpawnerParams`] entry into the global shared GPU buffer.
    ///
    /// The entry is allocated for a single render frame. It's automatically
    /// deallocated at the end of this render frame.
    ///
    /// # Returns
    ///
    /// This returns the index of the entry into the global GPU buffer.
    pub fn allocate_spawner(&mut self, gpu_spawner_params: GpuSpawnerParams) -> u32 {
        let spawner_base = self.spawner_buffer.len() as u32;
        self.spawner_buffer.push(gpu_spawner_params);
        spawner_base
    }

    pub fn allocate_draw_indirect(
        &mut self,
        draw_args: &AnyDrawIndirectArgs,
    ) -> CachedDrawIndirectArgs {
        let row = self
            .draw_indirect_buffer
            .insert(draw_args.bitcast_to_row_entry());
        CachedDrawIndirectArgs {
            row,
            args: *draw_args,
        }
    }

    pub fn update_draw_indirect(&mut self, row_index: &CachedDrawIndirectArgs) {
        self.draw_indirect_buffer
            .update(row_index.get_row(), row_index.args.bitcast_to_row_entry());
    }

    pub fn free_draw_indirect(&mut self, row_index: &CachedDrawIndirectArgs) {
        self.draw_indirect_buffer.remove(row_index.get_row());
    }
}

bitflags! {
    /// Effect flags.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct LayoutFlags: u32 {
        /// No flags.
        const NONE = 0;
        // DEPRECATED - The effect uses an image texture.
        //const PARTICLE_TEXTURE = (1 << 0);
        /// The effect is simulated in local space.
        const LOCAL_SPACE_SIMULATION = (1 << 2);
        /// The effect uses alpha masking instead of alpha blending. Only used for 3D.
        const USE_ALPHA_MASK = (1 << 3);
        /// The effect is rendered with flipbook texture animation based on the
        /// [`Attribute::SPRITE_INDEX`] of each particle.
        const FLIPBOOK = (1 << 4);
        /// The effect needs UVs.
        const NEEDS_UV = (1 << 5);
        /// The effect has ribbons.
        const RIBBONS = (1 << 6);
        /// The effects needs normals.
        const NEEDS_NORMAL = (1 << 7);
        /// The effect is fully-opaque.
        const OPAQUE = (1 << 8);
        /// The (update) shader emits GPU spawn events to instruct another effect to spawn particles.
        const EMIT_GPU_SPAWN_EVENTS = (1 << 9);
        /// The (init) shader spawns particles by consuming GPU spawn events, instead of
        /// a single CPU spawn count.
        const CONSUME_GPU_SPAWN_EVENTS = (1 << 10);
        /// The (init or update) shader needs access to its parent particle. This allows
        /// a particle init or update pass to read the data of a parent particle, for
        /// example to inherit some of the attributes.
        const READ_PARENT_PARTICLE = (1 << 11);
        /// The effect access to the particle data in the fragment shader.
        const NEEDS_PARTICLE_FRAGMENT = (1 << 12);
    }
}

impl Default for LayoutFlags {
    fn default() -> Self {
        Self::NONE
    }
}

/// Observer raised when the [`CachedEffect`] component is removed, which
/// indicates that the effect instance was despawned.
pub(crate) fn on_remove_cached_effect(
    trigger: On<Remove, CachedEffect>,
    query: Query<(
        Entity,
        &MainEntity,
        &CachedEffect,
        Option<&CachedEffectProperties>,
        Option<&CachedParentInfo>,
        Option<&CachedEffectEvents>,
    )>,
    mut effect_cache: ResMut<EffectCache>,
    mut effect_bind_groups: ResMut<EffectBindGroups>,
    mut event_cache: ResMut<EventCache>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("on_remove_cached_effect").entered();

    // FIXME - review this Observer pattern; this triggers for each event one by
    // one, which could kill performance if many effects are removed.

    // Fecth the components of the effect being destroyed. Note that the despawn
    // command above is not yet applied, so this query should always succeed.
    let Ok((
        render_entity,
        main_entity,
        cached_effect,
        _opt_props,
        _opt_parent,
        opt_cached_effect_events,
    )) = query.get(trigger.event().entity)
    else {
        return;
    };

    // Dealllocate the effect slice in the event buffer, if any.
    if let Some(cached_effect_events) = opt_cached_effect_events {
        match event_cache.free(cached_effect_events) {
            Err(err) => {
                error!("Error while freeing effect event slice: {err:?}");
            }
            Ok(buffer_state) => {
                if buffer_state != SlabState::Used {
                    // Clear bind groups associated with the old buffer
                    effect_bind_groups.init_metadata_bind_groups.clear();
                    effect_bind_groups.update_metadata_bind_groups.clear();
                }
            }
        }
    }

    // Deallocate the effect slice in the GPU effect buffer, and if this was the
    // last slice, also deallocate the GPU buffer itself.
    trace!(
        "=> ParticleEffect on render entity {:?} associated with main entity {:?}, removing...",
        render_entity,
        main_entity,
    );
    let Ok(SlabState::Free) = effect_cache.remove(cached_effect) else {
        // Buffer was not affected, so all bind groups are still valid. Nothing else to
        // do.
        return;
    };

    // Clear bind groups associated with the removed buffer
    trace!(
        "=> GPU particle slab #{} gone, destroying its bind groups...",
        cached_effect.slab_id.index()
    );
    effect_bind_groups
        .particle_slabs
        .remove(&cached_effect.slab_id);
}

/// Observer raised when the [`CachedEffectMetadata`] component is removed, to
/// deallocate the GPU resources associated with the indirect draw args.
pub(crate) fn on_remove_cached_metadata(
    trigger: On<Remove, CachedEffectMetadata>,
    query: Query<&CachedEffectMetadata>,
    mut effects_meta: ResMut<EffectsMeta>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("on_remove_cached_metadata").entered();

    if let Ok(cached_metadata) = query.get(trigger.event().entity) {
        if cached_metadata.table_id.is_valid() {
            effects_meta
                .effect_metadata_buffer
                .remove(cached_metadata.table_id);
        }
    };
}

/// Observer raised when the [`CachedDrawIndirectArgs`] component is removed, to
/// deallocate the GPU resources associated with the indirect draw args.
pub(crate) fn on_remove_cached_draw_indirect_args(
    trigger: On<Remove, CachedDrawIndirectArgs>,
    query: Query<&CachedDrawIndirectArgs>,
    mut effects_meta: ResMut<EffectsMeta>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("on_remove_cached_draw_indirect_args").entered();

    if let Ok(cached_draw_args) = query.get(trigger.event().entity) {
        effects_meta.free_draw_indirect(cached_draw_args);
    };
}

/// Clear pending GPU resources left from previous frame.
///
/// Those generally are source buffers for buffer-to-buffer copies on capacity
/// growth, which need the source buffer to be alive until the copy is done,
/// then can be discarded here.
pub(crate) fn clear_previous_frame_resizes(
    mut effects_meta: ResMut<EffectsMeta>,
    mut sort_bind_groups: ResMut<SortBindGroups>,
    mut init_fill_dispatch_queue: ResMut<InitFillDispatchQueue>,
    mut sort_fill_dispatch_queue: ResMut<SortFillDispatchQueue>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("clear_previous_frame_resizes").entered();
    trace!("clear_previous_frame_resizes");

    init_fill_dispatch_queue.clear();
    sort_fill_dispatch_queue.clear();

    // Clear last frame's buffer resizes which may have occured during last frame,
    // during `Node::run()` while the `BufferTable` could not be mutated. This is
    // the first point at which we can do that where we're not blocking the main
    // world (so, excluding the extract system).
    effects_meta
        .dispatch_indirect_buffer
        .clear_previous_frame_resizes();
    effects_meta
        .draw_indirect_buffer
        .clear_previous_frame_resizes();
    effects_meta
        .effect_metadata_buffer
        .clear_previous_frame_resizes();
    sort_bind_groups.clear_previous_frame_resizes();
}

// Fixup the [`CachedChildInfo::global_child_index`] once all child infos have
// been allocated.
pub fn fixup_parents(
    q_changed_parents: Query<(Entity, Ref<CachedParentInfo>)>,
    mut q_children: Query<&mut CachedChildInfo>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("fixup_parents").entered();
    trace!("fixup_parents");

    // Once all parents are (re-)allocated, fix up the global index of all
    // children if the parent base index changed.
    trace!(
        "Updating the global index of children of parent effects whose child list just changed..."
    );
    for (parent_entity, cached_parent_info) in q_changed_parents.iter() {
        let base_index =
            cached_parent_info.byte_range.start / GpuChildInfo::SHADER_SIZE.get() as u32;
        let parent_changed = cached_parent_info.is_changed();
        trace!(
            "Updating {} children of parent effect {:?} with base child index {} (parent_changed:{})...",
            cached_parent_info.children.len(),
            parent_entity,
            base_index,
            parent_changed
        );
        for (child_entity, _) in &cached_parent_info.children {
            let Ok(mut cached_child_info) = q_children.get_mut(*child_entity) else {
                error!(
                    "Cannot find child {:?} declared by parent {:?}",
                    *child_entity, parent_entity
                );
                continue;
            };
            if !cached_child_info.is_changed() && !parent_changed {
                continue;
            }
            cached_child_info.global_child_index = base_index + cached_child_info.local_child_index;
            trace!(
                "+ Updated global index for child ID {:?} of parent {:?}: local={}, global={}",
                child_entity,
                parent_entity,
                cached_child_info.local_child_index,
                cached_child_info.global_child_index
            );
        }
    }
}

/// Allocate the GPU resources for all extracted effects.
///
/// This adds the [`CachedEffect`] component as needed, and update it with the
/// allocation in the [`EffectCache`].
pub fn allocate_effects(
    mut commands: Commands,
    mut q_extracted_effects: Query<
        (
            Entity,
            &ExtractedEffect,
            Has<ChildEffectOf>,
            Option<&mut CachedEffect>,
        ),
        Changed<ExtractedEffect>,
    >,
    mut effect_cache: ResMut<EffectCache>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("allocate_effects").entered();
    trace!("allocate_effects");

    for (entity, extracted_effect, has_parent, maybe_cached_effect) in &mut q_extracted_effects {
        // Insert or update the effect into the EffectCache
        if let Some(mut cached_effect) = maybe_cached_effect {
            trace!("Updating EffectCache entry for entity {entity:?}...");
            let _ = effect_cache.remove(cached_effect.as_ref());
            *cached_effect = effect_cache.insert(
                extracted_effect.handle.clone(),
                extracted_effect.capacity,
                &extracted_effect.particle_layout,
            );
        } else {
            trace!("Allocating new entry in EffectCache for entity {entity:?}...");
            let cached_effect = effect_cache.insert(
                extracted_effect.handle.clone(),
                extracted_effect.capacity,
                &extracted_effect.particle_layout,
            );
            commands.entity(entity).insert(cached_effect);
        }

        // Ensure the particle@1 bind group layout exists for the given configuration of
        // particle layout. We do this here only for effects without a parent; for those
        // with a parent, we'll do it after we resolved that parent.
        if !has_parent {
            let parent_min_binding_size = None;
            effect_cache.ensure_particle_bind_group_layout_desc(
                extracted_effect.particle_layout.min_binding_size32(),
                parent_min_binding_size,
            );
        }

        // Ensure the metadata@3 bind group layout exists for the init pass.
        {
            let consume_gpu_spawn_events = extracted_effect
                .layout_flags
                .contains(LayoutFlags::CONSUME_GPU_SPAWN_EVENTS);
            effect_cache.ensure_metadata_init_bind_group_layout_desc(consume_gpu_spawn_events);
        }
    }
}

/// Update any cached mesh info based on any relocation done by Bevy itself.
///
/// Bevy will merge small meshes into larger GPU buffers automatically. When
/// this happens, the mesh location changes, and we need to update our
/// references to it in order to know how to issue the draw commands.
///
/// This system updates both the [`CachedMeshLocation`] and the
/// [`CachedIndirectDrawArgs`] components.
pub fn update_mesh_locations(
    mut commands: Commands,
    mut effects_meta: ResMut<EffectsMeta>,
    mesh_allocator: Res<MeshAllocator>,
    render_meshes: Res<RenderAssets<RenderMesh>>,
    mut q_cached_effects: Query<(
        Entity,
        &ExtractedEffectMesh,
        Option<&mut CachedMeshLocation>,
        Option<&mut CachedDrawIndirectArgs>,
    )>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("update_mesh_locations").entered();
    trace!("update_mesh_locations");

    for (entity, extracted_mesh, maybe_cached_mesh_location, maybe_cached_draw_indirect_args) in
        &mut q_cached_effects
    {
        let mut cmds = commands.entity(entity);

        // Resolve the render mesh
        let Some(render_mesh) = render_meshes.get(extracted_mesh.mesh) else {
            warn!(
                "Cannot find render mesh of particle effect instance on entity {:?}, despite applying default mesh. Invalid asset handle: {:?}",
                entity, extracted_mesh.mesh
            );
            cmds.remove::<CachedMeshLocation>();
            continue;
        };

        // Find the location where the render mesh was allocated. This is handled by
        // Bevy itself in the allocate_and_free_meshes() system. Bevy might
        // re-batch the vertex and optional index data of meshes together at any point,
        // so we need to confirm that the location data we may have cached is still
        // valid.
        let Some(mesh_vertex_buffer_slice) = mesh_allocator.mesh_vertex_slice(&extracted_mesh.mesh)
        else {
            trace!(
                "Effect main_entity {:?}: cannot find vertex slice of render mesh {:?}",
                entity,
                extracted_mesh.mesh
            );
            cmds.remove::<CachedMeshLocation>();
            continue;
        };
        let mesh_index_buffer_slice = mesh_allocator.mesh_index_slice(&extracted_mesh.mesh);
        let indexed =
            if let RenderMeshBufferInfo::Indexed { index_format, .. } = render_mesh.buffer_info {
                if let Some(ref slice) = mesh_index_buffer_slice {
                    Some(MeshIndexSlice {
                        format: index_format,
                        buffer: slice.buffer.clone(),
                        range: slice.range.clone(),
                    })
                } else {
                    trace!(
                        "Effect main_entity {:?}: cannot find index slice of render mesh {:?}",
                        entity,
                        extracted_mesh.mesh
                    );
                    cmds.remove::<CachedMeshLocation>();
                    continue;
                }
            } else {
                None
            };

        // Calculate the new draw args and mesh location based on Bevy's info
        let new_draw_args = AnyDrawIndirectArgs::from_slices(
            &mesh_vertex_buffer_slice,
            mesh_index_buffer_slice.as_ref(),
        );
        let new_mesh_location = match &mesh_index_buffer_slice {
            // Indexed mesh rendering
            Some(mesh_index_buffer_slice) => CachedMeshLocation {
                vertex_buffer: mesh_vertex_buffer_slice.buffer.id(),
                vertex_or_index_count: mesh_index_buffer_slice.range.len() as u32,
                first_index_or_vertex_offset: mesh_index_buffer_slice.range.start,
                vertex_offset_or_base_instance: mesh_vertex_buffer_slice.range.start as i32,
                indexed,
            },
            // Non-indexed mesh rendering
            None => CachedMeshLocation {
                vertex_buffer: mesh_vertex_buffer_slice.buffer.id(),
                vertex_or_index_count: mesh_vertex_buffer_slice.range.len() as u32,
                first_index_or_vertex_offset: mesh_vertex_buffer_slice.range.start,
                vertex_offset_or_base_instance: 0,
                indexed: None,
            },
        };

        // We don't allocate the draw indirect args ahead of time because we need to
        // select the indexed vs. non-indexed buffer. Now that we know whether the mesh
        // is indexed, we can allocate it (or reallocate it if indexing mode changed).
        if let Some(mut cached_draw_indirect) = maybe_cached_draw_indirect_args {
            assert!(cached_draw_indirect.row.is_valid());

            // If the GPU draw args changed, re-upload to GPU.
            if new_draw_args != cached_draw_indirect.args {
                debug!(
                    "Indirect draw args changed for asset {:?}\nold:{:?}\nnew:{:?}",
                    entity, cached_draw_indirect.args, new_draw_args
                );
                cached_draw_indirect.args = new_draw_args;
                effects_meta.update_draw_indirect(cached_draw_indirect.as_ref());
            }
        } else {
            cmds.insert(effects_meta.allocate_draw_indirect(&new_draw_args));
        }

        // Compare to any cached data and update if necessary, or insert if missing.
        // This will trigger change detection in the ECS, which will in turn trigger
        // GpuEffectMetadata re-upload.
        if let Some(mut old_mesh_location) = maybe_cached_mesh_location {
            if *old_mesh_location != new_mesh_location {
                debug!(
                    "Mesh location changed for asset {:?}\nold:{:?}\nnew:{:?}",
                    entity, old_mesh_location, new_mesh_location
                );
                *old_mesh_location = new_mesh_location;
            }
        } else {
            cmds.insert(new_mesh_location);
        }
    }
}

/// Allocate an entry in the GPU table for any [`CachedEffectMetadata`] missing
/// one.
///
/// This system does NOT take care of (re-)uploading recent CPU data to GPU.
/// This is done much later in the frame, after batching and once all data for
/// it is ready. But it's necessary to ensure the allocation is determined
/// already ahead of time, in order to do batching of contiguous metadata
/// blocks (TODO; not currently used, also may end up using binary search in
/// shader, in which case we won't need continguous-ness and can maybe remove
/// this system).
// TODO - consider using observer OnAdd instead?
pub fn allocate_metadata(
    mut effects_meta: ResMut<EffectsMeta>,
    mut q_metadata: Query<&mut CachedEffectMetadata>,
) {
    for mut metadata in &mut q_metadata {
        if !metadata.table_id.is_valid() {
            metadata.table_id = effects_meta
                .effect_metadata_buffer
                .insert(metadata.metadata);
        } else {
            // Unless this is the first time we allocate the GPU entry (above),
            // we should never reach the beginning of this frame
            // with a changed metadata which has not
            // been re-uploaded last frame.
            // NO! We can only detect the change *since last run of THIS system*
            // so wont' see that a latter system the data.
            // assert!(!metadata.is_changed());
        }
    }
}

/// Update the [`CachedParentInfo`] of parent effects and the
/// [`CachedChildInfo`] of child effects.
pub fn allocate_parent_child_infos(
    mut commands: Commands,
    mut effect_cache: ResMut<EffectCache>,
    mut event_cache: ResMut<EventCache>,
    // All extracted child effects. May or may not already have a CachedChildInfo. If not, this
    // will be spawned below.
    mut q_child_effects: Query<(
        Entity,
        &ExtractedEffect,
        &ChildEffectOf,
        &CachedEffectEvents,
        Option<&mut CachedChildInfo>,
    )>,
    // All parent effects from a previous frame (already have CachedParentInfo), which can be
    // updated in-place without spawning a new CachedParentInfo.
    mut q_parent_effects: Query<(
        Entity,
        &ExtractedEffect,
        &CachedEffect,
        &ChildrenEffects,
        Option<&mut CachedParentInfo>,
    )>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("allocate_child_infos").entered();
    trace!("allocate_child_infos");

    // Loop on all child effects and ensure their CachedChildInfo is up-to-date.
    for (child_entity, _, child_effect_of, cached_effect_events, maybe_cached_child_info) in
        &mut q_child_effects
    {
        // Fetch the parent effect
        let parent_entity = child_effect_of.parent;
        let Ok((_, _, parent_cached_effect, children_effects, _)) =
            q_parent_effects.get(parent_entity)
        else {
            warn!("Unknown parent #{parent_entity:?} on child entity {child_entity:?}, removing CachedChildInfo.");
            if maybe_cached_child_info.is_some() {
                commands.entity(child_entity).remove::<CachedChildInfo>();
            }
            continue;
        };

        // Find the index of this child entity in its parent's storage
        let Some(local_child_index) = children_effects.0.iter().position(|e| *e == child_entity)
        else {
            warn!("Cannot find child entity {child_entity:?} in the children collection of parent entity {parent_entity:?}. Relationship desync?");
            if maybe_cached_child_info.is_some() {
                commands.entity(child_entity).remove::<CachedChildInfo>();
            }
            continue;
        };
        let local_child_index = local_child_index as u32;

        // Fetch the effect buffer of the parent effect
        let Some(parent_buffer_binding_source) = effect_cache
            .get_slab(&parent_cached_effect.slab_id)
            .map(|effect_buffer| effect_buffer.max_binding_source())
        else {
            warn!(
                "Unknown parent slab #{} on parent entity {:?}, removing CachedChildInfo.",
                parent_cached_effect.slab_id.index(),
                parent_entity
            );
            if maybe_cached_child_info.is_some() {
                commands.entity(child_entity).remove::<CachedChildInfo>();
            }
            continue;
        };

        let new_cached_child_info = CachedChildInfo {
            parent_slab_id: parent_cached_effect.slab_id,
            parent_slab_offset: parent_cached_effect.slice.range().start,
            parent_particle_layout: parent_cached_effect.slice.particle_layout.clone(),
            parent_buffer_binding_source,
            local_child_index,
            global_child_index: u32::MAX, // fixed up later by fixup_parents()
            init_indirect_dispatch_index: cached_effect_events.init_indirect_dispatch_index,
        };
        if let Some(mut cached_child_info) = maybe_cached_child_info {
            if !cached_child_info.is_locally_equal(&new_cached_child_info) {
                *cached_child_info = new_cached_child_info;
            }
        } else {
            commands.entity(child_entity).insert(new_cached_child_info);
        }
    }

    // Loop on all parent effects and ensure their CachedParentInfo is up-to-date.
    for (parent_entity, parent_extracted_effect, _, children_effects, maybe_cached_parent_info) in
        &mut q_parent_effects
    {
        let parent_min_binding_size = parent_extracted_effect.particle_layout.min_binding_size32();

        // Loop over children and gather GpuChildInfo
        let mut new_children = Vec::with_capacity(children_effects.0.len());
        let mut new_child_infos = Vec::with_capacity(children_effects.0.len());
        for child_entity in children_effects.0.iter() {
            // Fetch the child's event buffer allocation info
            let Ok((_, child_extracted_effect, _, cached_effect_events, _)) =
                q_child_effects.get(*child_entity)
            else {
                warn!("Child entity {child_entity:?} from parent entity {parent_entity:?} didnt't resolve to a child instance. The parent effect cannot be processed.");
                if maybe_cached_parent_info.is_some() {
                    commands.entity(parent_entity).remove::<CachedParentInfo>();
                }
                break;
            };

            // Fetch the GPU event buffer of the child
            let Some(event_buffer) = event_cache.get_buffer(cached_effect_events.buffer_index)
            else {
                warn!("Child entity {child_entity:?} from parent entity {parent_entity:?} doesn't have an allocated GPU event buffer. The parent effect cannot be processed.");
                break;
            };

            let buffer_binding_source = BufferBindingSource {
                buffer: event_buffer.clone(),
                offset: cached_effect_events.range.start,
                size: NonZeroU32::new(cached_effect_events.range.len() as u32).unwrap(),
            };
            new_children.push((*child_entity, buffer_binding_source));

            new_child_infos.push(GpuChildInfo {
                event_count: 0,
                init_indirect_dispatch_index: cached_effect_events.init_indirect_dispatch_index,
            });

            // Ensure the particle@1 bind group layout exists for the given configuration of
            // particle layout. We do this here only for effects with a parent; for those
            // without a parent, we already did this in allocate_effects().
            effect_cache.ensure_particle_bind_group_layout_desc(
                child_extracted_effect.particle_layout.min_binding_size32(),
                Some(parent_min_binding_size),
            );
        }

        // If we don't have all children, just abort this effect. We don't try to have
        // partial relationships, this is too complex for shader bindings.
        debug_assert_eq!(new_children.len(), new_child_infos.len());
        if (new_children.len() < children_effects.len()) && maybe_cached_parent_info.is_some() {
            warn!("One or more child effect(s) on parent effect {parent_entity:?} failed to configure. The parent effect cannot be processed.");
            commands.entity(parent_entity).remove::<CachedParentInfo>();
            continue;
        }

        // Insert or update the CachedParentInfo component of the parent effect
        if let Some(mut cached_parent_info) = maybe_cached_parent_info {
            if cached_parent_info.children != new_children {
                // FIXME - missing way to just update in-place without changing the allocation
                // size!
                // if cached_parent_info.children.len() == new_children.len() {
                //} else {
                event_cache.reallocate_child_infos(
                    parent_entity,
                    new_children,
                    &new_child_infos[..],
                    cached_parent_info.as_mut(),
                );
                //}
            }
        } else {
            let cached_parent_info =
                event_cache.allocate_child_infos(parent_entity, new_children, &new_child_infos[..]);
            commands.entity(parent_entity).insert(cached_parent_info);
        }
    }
}

/// Prepare the init and update compute pipelines for an effect.
///
/// This caches the pipeline IDs once resolved, and their compiling state when
/// it changes, to determine when an effect is ready to be used.
///
/// Note that we do that proactively even if the effect will be skipped this
/// frame (for example because it's not visible). This ensures we queue pipeline
/// compilations ASAP, as they can take a long time (10+ frames). We also use
/// the pipeline compiling state, which we query here, to inform whether the
/// effect is ready for this frame. So in general if this is a new pipeline, it
/// won't be ready this frame.
pub fn prepare_init_update_pipelines(
    mut q_effects: Query<(
        Entity,
        &ExtractedEffect,
        &CachedEffect,
        Option<&CachedChildInfo>,
        Option<&CachedParentInfo>,
        Option<&CachedEffectProperties>,
        &mut CachedPipelines,
    )>,
    // FIXME - need mut for bind group layout creation; shouldn't be create there though
    mut effect_cache: ResMut<EffectCache>,
    pipeline_cache: Res<PipelineCache>,
    property_cache: ResMut<PropertyCache>,
    init_pipeline: Res<ParticlesInitPipeline>,
    update_pipeline: Res<ParticlesUpdatePipeline>,
    mut specialized_init_pipelines: ResMut<SpecializedComputePipelines<ParticlesInitPipeline>>,
    mut specialized_update_pipelines: ResMut<SpecializedComputePipelines<ParticlesUpdatePipeline>>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("prepare_init_update_pipelines").entered();
    trace!("prepare_init_update_pipelines");

    // Note: As of Bevy 0.16 we can't evict old pipelines from the cache. They're
    // inserted forever. https://github.com/bevyengine/bevy/issues/19925

    for (
        entity,
        extracted_effect,
        cached_effect,
        maybe_cached_child_info,
        maybe_cached_parent_info,
        maybe_cached_properties,
        mut cached_pipelines,
    ) in &mut q_effects
    {
        trace!(
            "Preparing pipelines for effect {:?}... (flags: {:?})",
            entity,
            cached_pipelines.flags
        );

        let particle_layout = &cached_effect.slice.particle_layout;
        let particle_layout_min_binding_size = particle_layout.min_binding_size32();
        let has_event_buffer = maybe_cached_child_info.is_some();
        let parent_particle_layout_min_binding_size = maybe_cached_child_info
            .as_ref()
            .map(|cci| cci.parent_particle_layout.min_binding_size32());

        let Some(particle_bind_group_layout_desc) = effect_cache.particle_bind_group_layout_desc(
            particle_layout_min_binding_size,
            parent_particle_layout_min_binding_size,
        ) else {
            error!("Failed to find particle sim bind group @1 for min_binding_size={} parent_min_binding_size={:?}",
                particle_layout_min_binding_size, parent_particle_layout_min_binding_size);
            continue;
        };
        let particle_bind_group_layout_desc = particle_bind_group_layout_desc.clone();

        // This should always exist by the time we reach this point, because we should
        // have inserted any property in the cache, which would have allocated the
        // proper bind group layout (or the default no-property one).
        let property_layout_min_binding_size =
            maybe_cached_properties.map(|cp| cp.property_layout.min_binding_size());
        let spawner_bind_group_layout_desc = property_cache
            .bind_group_layout_desc(property_layout_min_binding_size)
            .unwrap_or_else(|| {
                panic!(
                    "Failed to find spawner@2 bind group layout for property binding size {:?}",
                    property_layout_min_binding_size,
                )
            });
        trace!(
            "Retrieved spawner@2 bind group layout desc for property binding size {}:  {:?}.",
            property_layout_min_binding_size
                .as_ref()
                .map(|size| size.get())
                .unwrap_or(0),
            spawner_bind_group_layout_desc,
        );

        // Resolve the init pipeline
        let init_pipeline_id = if let Some(init_pipeline_id) = cached_pipelines.init.as_ref() {
            *init_pipeline_id
        } else {
            // Clear flag just in case, to ensure consistency.
            cached_pipelines
                .flags
                .remove(CachedPipelineFlags::INIT_PIPELINE_READY);

            // Fetch the metadata@3 bind group layout from the cache
            let metadata_bind_group_layout_desc = effect_cache
                .metadata_init_bind_group_layout_desc(has_event_buffer)
                .unwrap()
                .clone();

            let init_pipeline_key_flags = {
                let mut flags = ParticleInitPipelineKeyFlags::empty();
                flags.set(
                    ParticleInitPipelineKeyFlags::ATTRIBUTE_PREV,
                    particle_layout.contains(Attribute::PREV),
                );
                flags.set(
                    ParticleInitPipelineKeyFlags::ATTRIBUTE_NEXT,
                    particle_layout.contains(Attribute::NEXT),
                );
                flags.set(
                    ParticleInitPipelineKeyFlags::CONSUME_GPU_SPAWN_EVENTS,
                    has_event_buffer,
                );
                flags
            };

            let init_pipeline_id: CachedComputePipelineId = specialized_init_pipelines.specialize(
                pipeline_cache.as_ref(),
                &init_pipeline,
                ParticleInitPipelineKey {
                    shader: extracted_effect.effect_shaders.init.clone(),
                    particle_layout_min_binding_size,
                    parent_particle_layout_min_binding_size,
                    flags: init_pipeline_key_flags,
                    particle_bind_group_layout_desc: particle_bind_group_layout_desc.clone(),
                    spawner_bind_group_layout_desc: spawner_bind_group_layout_desc.clone(),
                    metadata_bind_group_layout_desc,
                },
            );
            trace!("Init pipeline specialized: id={:?}", init_pipeline_id);

            cached_pipelines.init = Some(init_pipeline_id);
            init_pipeline_id
        };

        // Resolve the update pipeline
        let update_pipeline_id = if let Some(update_pipeline_id) = cached_pipelines.update.as_ref()
        {
            *update_pipeline_id
        } else {
            // Clear flag just in case, to ensure consistency.
            cached_pipelines
                .flags
                .remove(CachedPipelineFlags::UPDATE_PIPELINE_READY);

            let num_event_buffers = maybe_cached_parent_info
                .as_ref()
                .map(|p| p.children.len() as u32)
                .unwrap_or_default();

            // FIXME: currently don't hava a way to determine when this is needed, because
            // we know the number of children per parent only after resolving
            // all parents, but by that point we forgot if this is a newly added
            // effect or not. So since we need to re-ensure for all effects, not
            // only new ones, might as well do here...
            effect_cache.ensure_metadata_update_bind_group_layout_desc(num_event_buffers);

            // Fetch the bind group layouts from the cache
            let metadata_bind_group_layout_desc = effect_cache
                .metadata_update_bind_group_layout_desc(num_event_buffers)
                .unwrap()
                .clone();

            let update_pipeline_id = specialized_update_pipelines.specialize(
                pipeline_cache.as_ref(),
                &update_pipeline,
                ParticleUpdatePipelineKey {
                    shader: extracted_effect.effect_shaders.update.clone(),
                    particle_layout: particle_layout.clone(),
                    parent_particle_layout_min_binding_size,
                    num_event_buffers,
                    particle_bind_group_layout_desc: particle_bind_group_layout_desc.clone(),
                    spawner_bind_group_layout_desc: spawner_bind_group_layout_desc.clone(),
                    metadata_bind_group_layout_desc,
                },
            );
            trace!("Update pipeline specialized: id={:?}", update_pipeline_id);

            cached_pipelines.update = Some(update_pipeline_id);
            update_pipeline_id
        };

        // Never batch an effect with a pipeline not available; this will prevent its
        // init/update pass from running, but the vfx_indirect pass will run
        // nonetheless, which causes desyncs and leads to bugs.
        if pipeline_cache
            .get_compute_pipeline(init_pipeline_id)
            .is_none()
        {
            trace!(
                "Skipping effect from render entity {:?} due to missing or not ready init pipeline (status: {:?})",
                entity,
                pipeline_cache.get_compute_pipeline_state(init_pipeline_id)
            );
            cached_pipelines
                .flags
                .remove(CachedPipelineFlags::INIT_PIPELINE_READY);
            continue;
        }

        // PipelineCache::get_compute_pipeline() only returns a value if the pipeline is
        // ready
        cached_pipelines
            .flags
            .insert(CachedPipelineFlags::INIT_PIPELINE_READY);
        trace!("[Effect {:?}] Init pipeline ready.", entity);

        // Never batch an effect with a pipeline not available; this will prevent its
        // init/update pass from running, but the vfx_indirect pass will run
        // nonetheless, which causes desyncs and leads to bugs.
        if pipeline_cache
            .get_compute_pipeline(update_pipeline_id)
            .is_none()
        {
            trace!(
                "Skipping effect from render entity {:?} due to missing or not ready update pipeline (status: {:?})",
                entity,
                pipeline_cache.get_compute_pipeline_state(update_pipeline_id)
            );
            cached_pipelines
                .flags
                .remove(CachedPipelineFlags::UPDATE_PIPELINE_READY);
            continue;
        }

        // PipelineCache::get_compute_pipeline() only returns a value if the pipeline is
        // ready
        cached_pipelines
            .flags
            .insert(CachedPipelineFlags::UPDATE_PIPELINE_READY);
        trace!("[Effect {:?}] Update pipeline ready.", entity);
    }
}

pub fn prepare_indirect_pipeline(
    event_cache: Res<EventCache>,
    mut effects_meta: ResMut<EffectsMeta>,
    pipeline_cache: Res<PipelineCache>,
    indirect_pipeline: Res<DispatchIndirectPipeline>,
    mut specialized_indirect_pipelines: ResMut<
        SpecializedComputePipelines<DispatchIndirectPipeline>,
    >,
    prefix_sum_pipeline: Res<PrefixSumPipeline>,
) {
    // Queue the vfx_prefix_sum pipeline if not already ready
    // TODO - not really related to this system, should probably be moved?
    if effects_meta.prefix_sum_pipeline_id == CachedComputePipelineId::INVALID {
        effects_meta.prefix_sum_pipeline_id =
            pipeline_cache.queue_compute_pipeline(prefix_sum_pipeline.make_pipeline_desc())
    }

    // Ensure the 2 variants of the indirect pipelines are created.
    // TODO - move that elsewhere in some one-time setup?
    if effects_meta.indirect_pipeline_ids[0] == CachedComputePipelineId::INVALID {
        effects_meta.indirect_pipeline_ids[0] = specialized_indirect_pipelines.specialize(
            pipeline_cache.as_ref(),
            &indirect_pipeline,
            DispatchIndirectPipelineKey { has_events: false },
        );
    }
    if effects_meta.indirect_pipeline_ids[1] == CachedComputePipelineId::INVALID {
        effects_meta.indirect_pipeline_ids[1] = specialized_indirect_pipelines.specialize(
            pipeline_cache.as_ref(),
            &indirect_pipeline,
            DispatchIndirectPipelineKey { has_events: true },
        );
    }

    // Select the active one depending on whether there's any child info to consume
    let is_empty = event_cache.child_infos().is_empty();
    if effects_meta.active_indirect_pipeline_id == CachedComputePipelineId::INVALID {
        if is_empty {
            effects_meta.active_indirect_pipeline_id = effects_meta.indirect_pipeline_ids[0];
        } else {
            effects_meta.active_indirect_pipeline_id = effects_meta.indirect_pipeline_ids[1];
        }
    } else {
        // If this is the first time we insert an event buffer, we need to switch the
        // indirect pass from non-event to event mode. That is, we need to re-allocate
        // the pipeline with the child infos buffer binding. Conversely, if there's no
        // more effect using GPU spawn events, we can deallocate.
        let was_empty =
            effects_meta.active_indirect_pipeline_id == effects_meta.indirect_pipeline_ids[0];
        if was_empty && !is_empty {
            trace!("First event buffer inserted; switching indirect pass to event mode...");
            effects_meta.active_indirect_pipeline_id = effects_meta.indirect_pipeline_ids[1];
        } else if is_empty && !was_empty {
            trace!("Last event buffer removed; switching indirect pass to no-event mode...");
            effects_meta.active_indirect_pipeline_id = effects_meta.indirect_pipeline_ids[0];
        }
    }
}

// TEMP - Mark all cached effects as invalid for this frame until another system
// explicitly marks them as valid. Otherwise we early out in some parts, and
// reuse by mistake the previous frame's extraction.
pub fn clear_transient_batch_inputs(
    mut commands: Commands,
    mut q_cached_effects: Query<Entity, With<BatchInput>>,
) {
    for entity in &mut q_cached_effects {
        if let Ok(mut cmd) = commands.get_entity(entity) {
            cmd.remove::<BatchInput>();
        }
    }
}

/// Effect mesh extracted from the main world.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Component)]
pub(crate) struct ExtractedEffectMesh {
    /// Asset of the effect mesh to draw.
    pub mesh: AssetId<Mesh>,
}

/// Indexed mesh metadata for [`CachedMesh`].
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct MeshIndexSlice {
    /// Index format.
    pub format: IndexFormat,
    /// GPU buffer containing the indices.
    pub buffer: Buffer,
    /// Range inside [`Self::buffer`] where the indices are.
    pub range: Range<u32>,
}

impl PartialEq for MeshIndexSlice {
    fn eq(&self, other: &Self) -> bool {
        self.format == other.format
            && self.buffer.id() == other.buffer.id()
            && self.range == other.range
    }
}

impl Eq for MeshIndexSlice {}

/// Cached info about a mesh location in a Bevy buffer. This information is
/// uploaded to GPU into [`GpuEffectMetadata`] for indirect rendering, but is
/// also kept CPU side in this component to detect when Bevy relocated a mesh,
/// so we can invalidate that GPU data.
#[derive(Debug, Clone, PartialEq, Eq, Component)]
pub(crate) struct CachedMeshLocation {
    /// Vertex buffer.
    pub vertex_buffer: BufferId,
    /// See [`GpuEffectMetadata::vertex_or_index_count`].
    pub vertex_or_index_count: u32,
    /// See [`GpuEffectMetadata::first_index_or_vertex_offset`].
    pub first_index_or_vertex_offset: u32,
    /// See [`GpuEffectMetadata::vertex_offset_or_base_instance`].
    pub vertex_offset_or_base_instance: i32,
    /// Indexed rendering metadata.
    pub indexed: Option<MeshIndexSlice>,
}

bitflags! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct CachedPipelineFlags: u8 {
        const NONE = 0;
        /// The init pipeline for this effect is ready for use. This means the compute pipeline is compiled and cached.
        const INIT_PIPELINE_READY = (1u8 << 0);
        /// The update pipeline for this effect is ready for use. This means the compute pipeline is compiled and cached.
        const UPDATE_PIPELINE_READY = (1u8 << 1);
    }
}

impl Default for CachedPipelineFlags {
    fn default() -> Self {
        Self::NONE
    }
}

/// Render world cached shader pipelines for a [`CachedEffect`].
///
/// This is updated with the IDs of the pipelines when they are queued for
/// compiling, and with the state of those pipelines to detect when the effect
/// is ready to be used.
///
/// This component is always auto-inserted alongside [`ExtractedEffect`] as soon
/// as a new effect instance is spawned, because it contains the readiness state
/// of those pipelines, which we want to query each frame. The pipelines are
/// also mandatory, so this component is always needed.
#[derive(Debug, Default, Component)]
pub(crate) struct CachedPipelines {
    /// Caching flags indicating the pipelines readiness.
    pub flags: CachedPipelineFlags,
    /// ID of the cached init pipeline. This is valid once the pipeline is
    /// queued for compilation, but this doesn't mean the pipeline is ready for
    /// use. Readiness is encoded in [`Self::flags`].
    pub init: Option<CachedComputePipelineId>,
    /// ID of the cached update pipeline. This is valid once the pipeline is
    /// queued for compilation, but this doesn't mean the pipeline is ready for
    /// use. Readiness is encoded in [`Self::flags`].
    pub update: Option<CachedComputePipelineId>,
}

impl CachedPipelines {
    /// Check if all pipelines for this effect are ready.
    #[inline]
    pub fn is_ready(&self) -> bool {
        self.flags.contains(
            CachedPipelineFlags::INIT_PIPELINE_READY | CachedPipelineFlags::UPDATE_PIPELINE_READY,
        )
    }
}

/// Ready state for this effect.
///
/// An effect is ready if:
/// - Its init and update pipelines are ready, as reported by
///   [`CachedPipelines::is_ready()`].
///
/// This components holds the calculated ready state propagated from all
/// ancestor effects, if any. That propagation is done by the
/// [`propagate_ready_state()`] system.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Component)]
pub(crate) struct CachedReadyState {
    is_ready: bool,
}

impl CachedReadyState {
    #[inline(always)]
    pub fn new(is_ready: bool) -> Self {
        Self { is_ready }
    }

    #[inline(always)]
    pub fn and(mut self, ancestors_ready: bool) -> Self {
        self.and_with(ancestors_ready);
        self
    }

    #[inline(always)]
    pub fn and_with(&mut self, ancestors_ready: bool) {
        self.is_ready = self.is_ready && ancestors_ready;
    }

    #[inline(always)]
    pub fn is_ready(&self) -> bool {
        self.is_ready
    }
}

#[derive(SystemParam)]
pub struct PrepareEffectsReadOnlyParams<'w, 's> {
    sim_params: Res<'w, SimParams>,
    marker: PhantomData<&'s usize>,
}

/// Update the ready state of all effects, and propagate recursively to
/// children.
pub(crate) fn propagate_ready_state(
    mut q_root_effects: Query<
        (
            Entity,
            Option<&ChildrenEffects>,
            Ref<CachedPipelines>,
            &mut CachedReadyState,
        ),
        Without<ChildEffectOf>,
    >,
    mut orphaned: RemovedComponents<ChildEffectOf>,
    q_ready_state: Query<
        (
            Ref<CachedPipelines>,
            &mut CachedReadyState,
            Option<&ChildrenEffects>,
        ),
        With<ChildEffectOf>,
    >,
    q_child_effects: Query<(Entity, Ref<ChildEffectOf>), With<CachedReadyState>>,
    mut orphaned_entities: Local<Vec<Entity>>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("propagate_ready_state").entered();
    trace!("propagate_ready_state");

    // Update orphaned list for this frame, and sort it so we can efficiently binary
    // search it
    orphaned_entities.clear();
    orphaned_entities.extend(orphaned.read());
    orphaned_entities.sort_unstable();

    // Iterate in parallel over all root effects (those without any parent). This is
    // the most common case, so should take care of the heavy lifting of propagating
    // to most effects. For child effects, we then descend recursively.
    q_root_effects.par_iter_mut().for_each(
        |(entity, maybe_children, cached_pipelines, mut cached_ready_state)| {
            // Update the ready state of this root effect
            let changed = cached_pipelines.is_changed() || cached_ready_state.is_added() || orphaned_entities.binary_search(&entity).is_ok();
            trace!("[Entity {}] changed={} cached_pipelines={} ready_state={}", entity, changed, cached_pipelines.is_ready(), cached_ready_state.is_ready);
            if changed {
                // Root effects by default are ready since they have no ancestors to check. After that we check the ready conditions for this effect alone.
                let new_ready_state = CachedReadyState::new(cached_pipelines.is_ready());
                if *cached_ready_state != new_ready_state {
                    debug!(
                        "[Entity {}] Changed ready to: {}",
                        entity,
                        new_ready_state.is_ready()
                    );
                    *cached_ready_state = new_ready_state;
                }
            }

            // Recursively update the ready state of its descendants
            if let Some(children) = maybe_children {
                for (child, child_of) in q_child_effects.iter_many(children) {
                    assert_eq!(
                        child_of.parent, entity,
                        "Malformed hierarchy. This probably means that your hierarchy has been improperly maintained, or contains a cycle"
                    );
                    // SAFETY:
                    // - `child` must have consistent parentage, or the above assertion would panic.
                    //   Since `child` is parented to a root entity, the entire hierarchy leading to it
                    //   is consistent.
                    // - We may operate as if all descendants are consistent, since
                    //   `propagate_ready_state_recursive` will panic before continuing to propagate if it
                    //   encounters an entity with inconsistent parentage.
                    // - Since each root entity is unique and the hierarchy is consistent and
                    //   forest-like, other root entities' `propagate_ready_state_recursive` calls will not conflict
                    //   with this one.
                    // - Since this is the only place where `transform_query` gets used, there will be
                    //   no conflicting fetches elsewhere.
                    #[expect(unsafe_code, reason = "`propagate_ready_state_recursive()` is unsafe due to its use of `Query::get_unchecked()`.")]
                    unsafe {
                        propagate_ready_state_recursive(
                            &cached_ready_state,
                            &q_ready_state,
                            &q_child_effects,
                            child,
                            changed || child_of.is_changed(),
                        );
                    }
                }
            }
        },
    );
}

#[expect(
    unsafe_code,
    reason = "This function uses `Query::get_unchecked()`, which can result in multiple mutable references if the preconditions are not met."
)]
unsafe fn propagate_ready_state_recursive(
    parent_state: &CachedReadyState,
    q_ready_state: &Query<
        (
            Ref<CachedPipelines>,
            &mut CachedReadyState,
            Option<&ChildrenEffects>,
        ),
        With<ChildEffectOf>,
    >,
    q_child_of: &Query<(Entity, Ref<ChildEffectOf>), With<CachedReadyState>>,
    entity: Entity,
    mut changed: bool,
) {
    // Update this effect in-place by checking its own state and the state of its
    // parent (which has already been propagated from all the parent's ancestors, so
    // is correct for this frame).
    let (cached_ready_state, maybe_children) = {
        let Ok((cached_pipelines, mut cached_ready_state, maybe_children)) =
        // SAFETY: Copied from Bevy's transform propagation, same reasoning
        (unsafe { q_ready_state.get_unchecked(entity) }) else {
            return;
        };

        changed |= cached_pipelines.is_changed() || cached_ready_state.is_added();
        if changed {
            let new_ready_state =
                CachedReadyState::new(parent_state.is_ready()).and(cached_pipelines.is_ready());
            // Ensure we don't trigger ECS change detection here if state didn't change, so
            // we can avoid this effect branch on next iteration.
            if *cached_ready_state != new_ready_state {
                debug!(
                    "[Entity {}] Changed ready to: {}",
                    entity,
                    new_ready_state.is_ready()
                );
                *cached_ready_state = new_ready_state;
            }
        }
        (cached_ready_state, maybe_children)
    };

    // Recurse into descendants
    let Some(children) = maybe_children else {
        return;
    };
    for (child, child_of) in q_child_of.iter_many(children) {
        assert_eq!(
        child_of.parent, entity,
        "Malformed hierarchy. This probably means that your hierarchy has been improperly maintained, or contains a cycle"
    );
        // SAFETY: The caller guarantees that `transform_query` will not be fetched for
        // any descendants of `entity`, so it is safe to call
        // `propagate_recursive` for each child.
        //
        // The above assertion ensures that each child has one and only one unique
        // parent throughout the entire hierarchy.
        unsafe {
            propagate_ready_state_recursive(
                cached_ready_state.as_ref(),
                q_ready_state,
                q_child_of,
                child,
                changed || child_of.is_changed(),
            );
        }
    }
}

/// Once all effects are extracted and all cached components are updated, it's
/// time to prepare for sorting and batching. Collect all relevant data and
/// insert/update the [`BatchInput`] for each effect.
pub(crate) fn prepare_batch_inputs(
    mut commands: Commands,
    read_only_params: PrepareEffectsReadOnlyParams,
    pipeline_cache: Res<PipelineCache>,
    mut effects_meta: ResMut<EffectsMeta>,
    q_cached_effects: Query<(
        MainEntity,
        Entity,
        &ExtractedEffect,
        &ExtractedSpawner,
        &CachedEffect,
        &CachedEffectMetadata,
        &CachedReadyState,
        &CachedPipelines,
        Option<&CachedDrawIndirectArgs>,
        Option<&CachedParentInfo>,
        Option<&ChildEffectOf>,
        Option<&CachedChildInfo>,
        Option<&CachedEffectEvents>,
    )>,
    mut sort_bind_groups: ResMut<SortBindGroups>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("prepare_batch_inputs").entered();
    trace!("prepare_batch_inputs");

    // Workaround for too many params in system (TODO: refactor to split work?)
    let sim_params = read_only_params.sim_params.into_inner();

    // Clear per-instance buffers, which are filled below and re-uploaded each frame
    effects_meta.spawner_buffer.clear();
    effects_meta.dispatch_indirect_buffer.clear();

    // Build batcher inputs from extracted effects, updating all cached components
    // for each effect on the fly.
    let mut extracted_effect_count = 0;
    let mut prepared_effect_count = 0;
    for (
        main_entity,
        render_entity,
        extracted_effect,
        extracted_spawner,
        cached_effect,
        cached_effect_metadata,
        cached_ready_state,
        cached_pipelines,
        maybe_cached_draw_indirect_args,
        maybe_cached_parent_info,
        maybe_child_effect_of,
        maybe_cached_child_info,
        maybe_cached_effect_events,
    ) in &q_cached_effects
    {
        extracted_effect_count += 1;

        // Skip this effect if not ready
        if !cached_ready_state.is_ready() {
            trace!("Pipelines not ready for effect {}, skipped.", render_entity);
            continue;
        }

        // Skip this effect if not visible and not simulating when hidden
        if !extracted_spawner.is_visible
            && (extracted_effect.simulation_condition == SimulationCondition::WhenVisible)
        {
            trace!(
                "Effect {} not visible, and simulation condition is WhenVisible, so skipped.",
                render_entity
            );
            continue;
        }

        // Fetch the init and update pipelines.
        // SAFETY: If is_ready() returns true, this means the pipelines are cached and
        // ready, so the IDs must be valid.
        let init_and_update_pipeline_ids = InitAndUpdatePipelineIds {
            init: cached_pipelines.init.unwrap(),
            update: cached_pipelines.update.unwrap(),
        };

        let effect_slice = EffectSlice {
            slice: cached_effect.slice.range(),
            slab_id: cached_effect.slab_id,
            particle_layout: cached_effect.slice.particle_layout.clone(),
        };

        // Fetch the bind group layouts from the cache
        trace!("child_effect_of={:?}", maybe_child_effect_of);
        let parent_slab_id = if let Some(child_effect_of) = maybe_child_effect_of {
            let Ok((_, _, _, _, parent_cached_effect, _, _, _, _, _, _, _, _)) =
                q_cached_effects.get(child_effect_of.parent)
            else {
                // At this point we should have discarded invalid effects with a missing parent,
                // so if the parent is not found this is a bug.
                error!(
                    "Effect main_entity {:?}: parent render entity {:?} not found.",
                    main_entity, child_effect_of.parent
                );
                continue;
            };
            Some(parent_cached_effect.slab_id)
        } else {
            None
        };

        // For ribbons, we need the sorting pipeline to be ready to sort the ribbon's
        // particles by age in order to build a contiguous mesh.
        if extracted_effect.layout_flags.contains(LayoutFlags::RIBBONS) {
            // Ensure the bind group layout for sort-fill is ready. This will also ensure
            // the pipeline is created and queued if needed.
            if let Err(err) = sort_bind_groups.ensure_sort_fill_bind_group_layout_desc(
                &pipeline_cache,
                &extracted_effect.particle_layout,
            ) {
                error!(
                    "Failed to create bind group for ribbon effect sorting: {:?}",
                    err
                );
                continue;
            }

            // Check sort pipelines are ready, otherwise we might desync some buffers if
            // running only some of them but not all.
            if !sort_bind_groups
                .is_pipeline_ready(&extracted_effect.particle_layout, &pipeline_cache)
            {
                trace!(
                    "Sort pipeline not ready for effect on main entity {:?}; skipped.",
                    main_entity
                );
                continue;
            }
        }

        // Output some debug info
        trace!("init_shader = {:?}", extracted_effect.effect_shaders.init);
        trace!(
            "update_shader = {:?}",
            extracted_effect.effect_shaders.update
        );
        trace!(
            "render_shader = {:?}",
            extracted_effect.effect_shaders.render
        );
        trace!("layout_flags = {:?}", extracted_effect.layout_flags);
        trace!("particle_layout = {:?}", effect_slice.particle_layout);

        let parent_slab_offset = maybe_cached_child_info.map(|cci| cci.parent_slab_offset);

        assert!(cached_effect_metadata.table_id.is_valid());
        let gpu_spawner_params = GpuSpawnerParams::new(
            &extracted_spawner.transform,
            extracted_spawner.spawn_count,
            extracted_spawner.prng_seed,
            cached_effect.slice.range().start,
            parent_slab_offset,
            cached_effect_metadata.table_id,
            maybe_cached_draw_indirect_args,
        );

        trace!("Updating cached effect at entity {render_entity:?}...");
        let mut cmd = commands.entity(render_entity);
        // Inserting the BatchInput component marks the effect as ready for this frame
        cmd.insert(BatchInput {
            effect_slice,
            init_and_update_pipeline_ids,
            parent_slab_id,
            event_buffer_index: maybe_cached_effect_events.map(|cee| cee.buffer_index),
            child_effects: maybe_cached_parent_info
                .as_ref()
                .map(|cp| cp.children.clone())
                .unwrap_or_default(),
            gpu_spawner_params,
            init_indirect_dispatch_index: maybe_cached_child_info
                .as_ref()
                .map(|cc| cc.init_indirect_dispatch_index),
        });

        prepared_effect_count += 1;
    }
    trace!("Prepared {prepared_effect_count}/{extracted_effect_count} extracted effect(s)");

    // Update simulation parameters, including the total effect count for this frame
    {
        let mut gpu_sim_params: GpuSimParams = sim_params.into();
        gpu_sim_params.num_effects = prepared_effect_count;
        trace!(
            "Simulation parameters: time={} delta_time={} virtual_time={} \
                virtual_delta_time={} real_time={} real_delta_time={} num_effects={}",
            gpu_sim_params.time,
            gpu_sim_params.delta_time,
            gpu_sim_params.virtual_time,
            gpu_sim_params.virtual_delta_time,
            gpu_sim_params.real_time,
            gpu_sim_params.real_delta_time,
            gpu_sim_params.num_effects,
        );
        effects_meta.sim_params_uniforms.set(gpu_sim_params);
    }
}

/// Batch compatible effects together into a single pass.
///
/// For all effects marked as ready for this frame (have a BatchInput
/// component), sort the effects by grouping compatible effects together, then
/// batch those groups together. Each batch can be updated and rendered with a
/// single compute dispatch or draw call.
pub(crate) fn batch_effects(
    render_device: Res<RenderDevice>,
    render_queue: Res<RenderQueue>,
    mut commands: Commands,
    mut effects_meta: ResMut<EffectsMeta>,
    mut sort_bind_groups: ResMut<SortBindGroups>,
    mut q_cached_effects: Query<(
        Entity,
        &MainEntity,
        &ExtractedEffect,
        &ExtractedSpawner,
        &ExtractedEffectMesh,
        &CachedDrawIndirectArgs,
        &CachedEffectMetadata,
        Option<&CachedEffectEvents>,
        Option<&ChildEffectOf>,
        Option<&CachedChildInfo>,
        Option<&CachedEffectProperties>,
        // The presence of BatchInput ensure the effect is ready
        &mut BatchInput,
    )>,
    mut sorted_effect_batches: ResMut<SortedEffectBatches>,
    mut gpu_buffer_operations: ResMut<GpuBufferOperations>,
    mut effect_bind_groups: ResMut<EffectBindGroups>,
    mut property_bind_groups: ResMut<PropertyBindGroups>,
    mut sort_fill_dispatch_queue: ResMut<SortFillDispatchQueue>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("batch_effects").entered();
    trace!("batch_effects");

    // Sort effects in batching order, so that we can batch by simply doing a linear
    // scan of the effects in this order. Currently compatible effects mean:
    // - same effect slab (so we can bind the buffers once for all batched effects)
    // - in order of increasing sub-allocation inside those buffers (to make the
    //   sort stable)
    // - with parents before their children, to ensure ???? FIXME don't we need to
    //   opposite?!!!
    let mut effect_sorter = EffectSorter::new();
    for (entity, _, _, _, _, _, _, _, child_of, _, _, input) in &q_cached_effects {
        effect_sorter.insert(
            entity,
            input.effect_slice.slab_id,
            input.effect_slice.slice.start,
            child_of.map(|co| co.parent),
        );
    }
    effect_sorter.sort();

    // For now we re-create that buffer each frame. Since there's no CPU -> GPU
    // transfer, this is pretty cheap in practice.
    sort_bind_groups.clear_indirect_dispatch_buffer();

    effects_meta.prefix_sum_buffer.clear();
    effects_meta.batch_info_buffer.clear();

    // Loop on all extracted effects in sorted order, and try to batch them together
    // to reduce draw calls. -- currently does nothing, batching was broken and
    // never fixed, but at least we minimize the GPU state changes with the sorting!
    trace!("Batching {} effects...", q_cached_effects.iter().len());
    sorted_effect_batches.clear();
    for entity in effect_sorter.effects.iter().map(|e| e.entity) {
        let Ok((
            entity,
            main_entity,
            extracted_effect,
            extracted_spawner,
            extracted_effect_mesh,
            cached_draw_indirect_args,
            cached_effect_metadata,
            cached_effect_events,
            _,
            cached_child_info,
            cached_properties,
            mut input,
        )) = q_cached_effects.get_mut(entity)
        else {
            continue;
        };

        let translation = extracted_spawner.transform.translation();

        // Now that the effects are sorted in batching order, we can allocate the
        // GpuSpawnerParams in the GPU buffer, such that they're contiguous for a single
        // batch.
        let spawner_index = effects_meta.allocate_spawner(input.gpu_spawner_params);

        // Spawn one EffectBatch per instance (no batching; TODO). This contains
        // most of the data needed to drive rendering. However this doesn't drive
        // rendering; this is just storage.
        let mut effect_batch = EffectBatch::from_input(
            main_entity.id(),
            extracted_effect,
            extracted_spawner,
            extracted_effect_mesh,
            cached_effect_events,
            cached_child_info,
            spawner_index,
            &mut input,
            cached_draw_indirect_args.row,
            cached_effect_metadata.table_id,
            cached_properties.map(|cp| PropertyBindGroupKey {
                buffer_index: cp.buffer_index,
                binding_size: cp.property_layout.min_binding_size().get() as u32,
            }),
        );

        // If the batch has ribbons, we need to sort the particles by RIBBON_ID and AGE
        // for ribbon meshing, in order to avoid gaps when some particles in the middle
        // of the ribbon die (since we can't guarantee a linear lifetime through the
        // ribbon).
        if extracted_effect.layout_flags.contains(LayoutFlags::RIBBONS) {
            // Allocate a GpuDispatchIndirect entry
            let sort_fill_indirect_dispatch_index = sort_bind_groups.allocate_indirect_dispatch();
            effect_batch.sort_fill_indirect_dispatch_index =
                Some(sort_fill_indirect_dispatch_index);

            // Queue a fill dispatch op which reads GpuEffectMetadata::alive_count and
            // computes the workgroup count for the fill-sort pass. The op is
            // built later, in queue_sort_fill_dispatch_ops(), once the metadata
            // buffer is resized; see SortFillDispatchQueue.
            sort_fill_dispatch_queue.enqueue(
                effect_batch.metadata_table_id,
                sort_fill_indirect_dispatch_index,
            );
        }

        // Append the batch to the (sorted) set of batches to render. If that batch
        // couldn't be merged together with the previous one, then it creates a separate
        // draw call. In that case, spawn an EffectDrawBatch to render that new separate
        // batch.
        // if let Some(effect_batch_index) = sorted_effect_batches.push(effect_batch) {
        //     trace!(
        //         "Queued new effect batch #{:?} from cached instance on entity {:?}.",
        //         effect_batch_index,
        //         entity,
        //     );

        //     // Spawn an EffectDrawBatch, to actually drive rendering of that new
        // batch.     commands
        //         .spawn(EffectDrawBatch {
        //             effect_batch_index,
        //             translation,
        //             main_entity: *main_entity,
        //         })
        //         .insert(TemporaryRenderEntity);
        // } else {
        //     trace!("Cached instance on entity {entity:?} merged with last effect
        // batch"); }

        // FIXME - for now, no batching, so any new effect is a new batch...
        let batch_info_id =
            effects_meta.begin_batch(effect_batch.slice.start, effect_batch.spawner_base);
        effect_batch.batch_info_id = batch_info_id;
        effects_meta.add_effect_to_batch(effect_batch.slice.start);
        effects_meta.end_batch();

        let effect_batch_index = sorted_effect_batches.push(effect_batch);
        trace!(
            "Spawned effect batch #{:?} with batch-info-id {} from cached instance on entity {:?}.",
            effect_batch_index,
            batch_info_id,
            entity,
        );

        // Spawn an EffectDrawBatch, to actually drive rendering.
        commands
            .spawn(EffectDrawBatch {
                effect_batch_index,
                translation,
                main_entity: *main_entity,
            })
            .insert(TemporaryRenderEntity);
    }

    // Begin the GpuBufferOperations frame here; the matching submit()s happen in
    // queue_sort_fill_dispatch_ops() and queue_init_fill_dispatch_ops(), and
    // end_frame() at the tail of the latter. Render set ordering guarantees
    // this begin precedes all submits.
    gpu_buffer_operations.begin_frame();
    debug_assert!(sorted_effect_batches.dispatch_queue_index.is_none());

    // Write the entire spawner buffer for this frame, for all effects combined
    if effects_meta
        .spawner_buffer
        .write_buffer(&render_device, &render_queue)
    {
        // All property bind groups use the spawner buffer, which was reallocate
        effect_bind_groups.particle_slabs.clear();
        property_bind_groups.clear(true);
        effects_meta.indirect_spawner_bind_group = None;
    }

    // Write the entire batch info buffer for this frame, for all batches combined
    if effects_meta
        .batch_info_buffer
        .write_buffer(&render_device, &render_queue)
    {
        // All property bind groups use the spawner buffer, which was reallocate
        effect_bind_groups.particle_slabs.clear();
        property_bind_groups.clear(true);
        effects_meta.indirect_spawner_bind_group = None;
        effects_meta.prefix_sum_bind_group = None;
    }

    // Write the entire prefix sum buffer for this frame, for all batches combined
    {
        let cpu_len = effects_meta.prefix_sum_buffer.len();
        if cpu_len > 0 {
            let gpu_capacity = effects_meta.prefix_sum_buffer.capacity();
            if cpu_len > gpu_capacity {
                effects_meta
                    .prefix_sum_buffer
                    .reserve(cpu_len, &render_device);

                // Reallocated!
                // All property bind groups use the spawner buffer, which was reallocate
                effect_bind_groups.particle_slabs.clear();
                property_bind_groups.clear(true);
                effects_meta.indirect_spawner_bind_group = None;
                effects_meta.prefix_sum_bind_group = None;
            }
            assert!(effects_meta.prefix_sum_buffer.buffer().is_some());
            effects_meta
                .prefix_sum_buffer
                .write_buffer(&render_device, &render_queue);
        }
    }
}

/// Per-buffer bind groups for a GPU effect buffer.
///
/// This contains all bind groups specific to a single [`EffectBuffer`].
///
/// [`EffectBuffer`]: crate::render::effect_cache::EffectBuffer
pub(crate) struct BufferBindGroups {
    /// Bind group for the render shader.
    ///
    /// ```wgsl
    /// @binding(0) var<storage, read> particle_buffer : ParticleBuffer;
    /// @binding(1) var<storage, read> indirect_buffer : IndirectBuffer;
    /// ```
    render: BindGroup,
    // /// Bind group for filling the indirect dispatch arguments of any child init
    // /// pass.
    // ///
    // /// This bind group is optional; it's only created if the current effect has
    // /// a GPU spawn event buffer, irrelevant of whether it has child effects
    // /// (although normally the event buffer is not created if there's no
    // /// children).
    // ///
    // /// The source buffer is always the current effect's event buffer. The
    // /// destination buffer is the global shared buffer for indirect fill args
    // /// operations owned by the [`EffectCache`]. The uniform buffer of operation
    // /// args contains the data to index the relevant part of the global shared
    // /// buffer for this effect buffer; it may contain multiple entries in case
    // /// multiple effects are batched inside the current effect buffer.
    // ///
    // /// ```wgsl
    // /// @group(0) @binding(0) var<uniform> args : BufferOperationArgs;
    // /// @group(0) @binding(1) var<storage, read> src_buffer : array<u32>;
    // /// @group(0) @binding(2) var<storage, read_write> dst_buffer : array<u32>;
    // /// ```
    // init_fill_dispatch: Option<BindGroup>,
}

/// Combination of a texture layout and the bound textures.
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
struct Material {
    layout: TextureLayout,
    textures: Vec<AssetId<Image>>,
}

impl Material {
    /// Get the bind group entries to create a bind group.
    pub fn make_entries<'a>(
        &self,
        gpu_images: &'a RenderAssets<GpuImage>,
    ) -> Result<Vec<BindGroupEntry<'a>>, ()> {
        if self.textures.is_empty() {
            return Ok(vec![]);
        }

        let entries: Vec<BindGroupEntry<'a>> = self
            .textures
            .iter()
            .enumerate()
            .flat_map(|(index, id)| {
                let base_binding = index as u32 * 2;
                if let Some(gpu_image) = gpu_images.get(*id) {
                    vec![
                        BindGroupEntry {
                            binding: base_binding,
                            resource: BindingResource::TextureView(&gpu_image.texture_view),
                        },
                        BindGroupEntry {
                            binding: base_binding + 1,
                            resource: BindingResource::Sampler(&gpu_image.sampler),
                        },
                    ]
                } else {
                    vec![]
                }
            })
            .collect();
        if entries.len() == self.textures.len() * 2 {
            return Ok(entries);
        }
        Err(())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct BindingKey {
    pub buffer_id: BufferId,
    pub offset: u32,
    pub size: NonZeroU32,
}

impl<'a> From<BufferSlice<'a>> for BindingKey {
    fn from(value: BufferSlice<'a>) -> Self {
        Self {
            buffer_id: value.buffer.id(),
            offset: value.offset,
            size: value.size,
        }
    }
}

impl<'a> From<&BufferSlice<'a>> for BindingKey {
    fn from(value: &BufferSlice<'a>) -> Self {
        Self {
            buffer_id: value.buffer.id(),
            offset: value.offset,
            size: value.size,
        }
    }
}

impl From<&BufferBindingSource> for BindingKey {
    fn from(value: &BufferBindingSource) -> Self {
        Self {
            buffer_id: value.buffer.id(),
            offset: value.offset,
            size: value.size,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct ConsumeEventKey {
    child_infos_buffer_id: BufferId,
    events: BindingKey,
}

impl From<&ConsumeEventBuffers<'_>> for ConsumeEventKey {
    fn from(value: &ConsumeEventBuffers) -> Self {
        Self {
            child_infos_buffer_id: value.child_infos_buffer.id(),
            events: value.events.into(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct InitMetadataBindGroupKey {
    pub slab_id: SlabId,
    pub effect_metadata_buffer: BufferId,
    pub consume_event_key: Option<ConsumeEventKey>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct UpdateMetadataBindGroupKey {
    pub slab_id: SlabId,
    pub effect_metadata_buffer: BufferId,
    pub child_info_buffer_id: Option<BufferId>,
    pub event_buffers_keys: Vec<BindingKey>,
}

/// Bind group cached with an associated key.
///
/// The cached bind group is associated with the given key representing the
/// inputs that the bind group depends on. When those inputs change, the key
/// should change, indicating the bind group needs to be recreated.
///
/// This object manages a single bind group and its key.
struct CachedBindGroup<K: Eq> {
    /// Key the bind group was created from. Each time the key changes, the bind
    /// group should be re-created.
    key: K,
    /// Bind group created from the key.
    bind_group: BindGroup,
}

#[derive(Debug, Clone, Copy)]
struct BufferSlice<'a> {
    pub buffer: &'a Buffer,
    pub offset: u32,
    pub size: NonZeroU32,
}

impl<'a> From<BufferSlice<'a>> for BufferBinding<'a> {
    fn from(value: BufferSlice<'a>) -> Self {
        Self {
            buffer: value.buffer,
            offset: value.offset.into(),
            size: Some(value.size.into()),
        }
    }
}

impl<'a> From<&BufferSlice<'a>> for BufferBinding<'a> {
    fn from(value: &BufferSlice<'a>) -> Self {
        Self {
            buffer: value.buffer,
            offset: value.offset.into(),
            size: Some(value.size.into()),
        }
    }
}

impl<'a> From<&'a BufferBindingSource> for BufferSlice<'a> {
    fn from(value: &'a BufferBindingSource) -> Self {
        Self {
            buffer: &value.buffer,
            offset: value.offset,
            size: value.size,
        }
    }
}

/// Optional input to [`EffectBindGroups::get_or_create_init_metadata()`] when
/// the init pass consumes GPU events as a mechanism to spawn particles.
struct ConsumeEventBuffers<'a> {
    /// Entire buffer containing the [`GpuChildInfo`] entries for all effects.
    /// This is dynamically indexed inside the shader.
    child_infos_buffer: &'a Buffer,
    /// Slice of the [`EventBuffer`] where the GPU spawn events are stored.
    events: BufferSlice<'a>,
}

#[derive(Default, Resource)]
pub struct EffectBindGroups {
    /// Map from a slab ID to the bind groups shared among all effects that
    /// use that particle slab.
    particle_slabs: HashMap<SlabId, BufferBindGroups>,
    /// Map of bind groups for image assets used as particle textures.
    images: HashMap<AssetId<Image>, BindGroup>,
    /// Map from buffer index to its metadata bind group (group 3) for the init
    /// pass.
    // FIXME - doesn't work with batching; this should be the instance ID
    init_metadata_bind_groups: HashMap<SlabId, CachedBindGroup<InitMetadataBindGroupKey>>,
    /// Map from buffer index to its metadata bind group (group 3) for the
    /// update pass.
    // FIXME - doesn't work with batching; this should be the instance ID
    update_metadata_bind_groups: HashMap<SlabId, CachedBindGroup<UpdateMetadataBindGroupKey>>,
    /// Map from an effect material to its bind group.
    material_bind_groups: HashMap<Material, BindGroup>,
}

impl EffectBindGroups {
    pub fn particle_render(&self, slab_id: &SlabId) -> Option<&BindGroup> {
        self.particle_slabs.get(slab_id).map(|bg| &bg.render)
    }

    /// Retrieve the metadata@3 bind group for the init pass, creating it if
    /// needed.
    pub(self) fn get_or_create_init_metadata(
        &mut self,
        effect_batch: &EffectBatch,
        render_device: &RenderDevice,
        layout: &BindGroupLayout,
        effect_metadata_buffer: &Buffer,
        consume_event_buffers: Option<ConsumeEventBuffers>,
    ) -> Result<&BindGroup, ()> {
        assert!(effect_batch.metadata_table_id.is_valid());

        let key = InitMetadataBindGroupKey {
            slab_id: effect_batch.slab_id,
            effect_metadata_buffer: effect_metadata_buffer.id(),
            consume_event_key: consume_event_buffers.as_ref().map(Into::into),
        };

        let make_entry = || {
            let mut entries = Vec::with_capacity(3);
            entries.push(
                // @group(3) @binding(0) var<storage, read_write> effect_metadatas :
                // array<EffectMetadata>;
                BindGroupEntry {
                    binding: 0,
                    resource: effect_metadata_buffer.as_entire_binding(),
                },
            );
            if let Some(consume_event_buffers) = consume_event_buffers.as_ref() {
                entries.push(
                    // @group(3) @binding(1) var<storage, read> child_info_buffer :
                    // ChildInfoBuffer;
                    BindGroupEntry {
                        binding: 1,
                        resource: BindingResource::Buffer(BufferBinding {
                            buffer: consume_event_buffers.child_infos_buffer,
                            offset: 0,
                            size: None,
                        }),
                    },
                );
                entries.push(
                    // @group(3) @binding(2) var<storage, read> event_buffer : EventBuffer;
                    BindGroupEntry {
                        binding: 2,
                        resource: BindingResource::Buffer(consume_event_buffers.events.into()),
                    },
                );
            }

            let bind_group =
                render_device.create_bind_group("hanabi:bg:init:metadata@3", layout, &entries[..]);

            trace!(
                    "Created new metadata@3 bind group for init pass and buffer index {}: effect_metadata=#{}",
                    effect_batch.slab_id.index(),
                    effect_batch.metadata_table_id.0,
                );

            bind_group
        };

        Ok(&self
            .init_metadata_bind_groups
            .entry(effect_batch.slab_id)
            .and_modify(|cbg| {
                if cbg.key != key {
                    trace!(
                        "Bind group key changed for init metadata@3, re-creating bind group... old={:?} new={:?}",
                        cbg.key,
                        key
                    );
                    cbg.key = key;
                    cbg.bind_group = make_entry();
                }
            })
            .or_insert_with(|| {
                trace!("Inserting new bind group for init metadata@3 with key={:?}", key);
                CachedBindGroup {
                    key,
                    bind_group: make_entry(),
                }
            })
            .bind_group)
    }

    /// Retrieve the metadata@3 bind group for the update pass, creating it if
    /// needed.
    pub(self) fn get_or_create_update_metadata(
        &mut self,
        effect_batch: &EffectBatch,
        render_device: &RenderDevice,
        layout: &BindGroupLayout,
        effect_metadata_buffer: &Buffer,
        child_info_buffer: Option<&Buffer>,
        event_buffers: &[(Entity, BufferBindingSource)],
    ) -> Result<&BindGroup, ()> {
        assert!(effect_batch.metadata_table_id.is_valid());

        // Check arguments consistency
        assert_eq!(effect_batch.child_event_buffers.len(), event_buffers.len());
        let emits_gpu_spawn_events = !event_buffers.is_empty();
        let child_info_buffer_id = if emits_gpu_spawn_events {
            child_info_buffer.as_ref().map(|buffer| buffer.id())
        } else {
            // Note: child_info_buffer can be Some() if allocated, but we only consider it
            // if relevant, that is if the effect emits GPU spawn events.
            None
        };
        assert_eq!(emits_gpu_spawn_events, child_info_buffer_id.is_some());

        let event_buffers_keys = event_buffers
            .iter()
            .map(|(_, buffer_binding_source)| buffer_binding_source.into())
            .collect::<Vec<_>>();

        let key = UpdateMetadataBindGroupKey {
            slab_id: effect_batch.slab_id,
            effect_metadata_buffer: effect_metadata_buffer.id(),
            child_info_buffer_id,
            event_buffers_keys,
        };

        let make_entry = || {
            let mut entries = Vec::with_capacity(2 + event_buffers.len());
            // @group(3) @binding(0) var<storage, read_write> effect_metadatas :
            // array<EffectMetadata>;
            entries.push(BindGroupEntry {
                binding: 0,
                resource: effect_metadata_buffer.as_entire_binding(),
            });
            if emits_gpu_spawn_events {
                let child_info_buffer = child_info_buffer.unwrap();

                // @group(3) @binding(1) var<storage, read_write> child_info_buffer :
                // ChildInfoBuffer;
                entries.push(BindGroupEntry {
                    binding: 1,
                    resource: BindingResource::Buffer(BufferBinding {
                        buffer: child_info_buffer,
                        offset: 0,
                        size: None,
                    }),
                });

                for (index, (_, buffer_binding_source)) in event_buffers.iter().enumerate() {
                    // @group(3) @binding(2+N) var<storage, read_write> event_buffer_N :
                    // EventBuffer;
                    // FIXME - BufferBindingSource originally was for Events, counting in u32, but
                    // then moved to counting in bytes, so now need some conversion. Need to review
                    // all of this...
                    let mut buffer_binding: BufferBinding = buffer_binding_source.into();
                    buffer_binding.offset *= 4;
                    buffer_binding.size = buffer_binding
                        .size
                        .map(|sz| NonZeroU64::new(sz.get() * 4).unwrap());
                    entries.push(BindGroupEntry {
                        binding: 2 + index as u32,
                        resource: BindingResource::Buffer(buffer_binding),
                    });
                }
            }

            let bind_group = render_device.create_bind_group(
                "hanabi:bg:update:metadata@3",
                layout,
                &entries[..],
            );

            trace!(
                "Created new metadata@3 bind group for update pass and slab ID {}: effect_metadata={}",
                effect_batch.slab_id.index(),
                effect_batch.metadata_table_id.0,
            );

            bind_group
        };

        Ok(&self
            .update_metadata_bind_groups
            .entry(effect_batch.slab_id)
            .and_modify(|cbg| {
                if cbg.key != key {
                    trace!(
                        "Bind group key changed for update metadata@3, re-creating bind group... old={:?} new={:?}",
                        cbg.key,
                        key
                    );
                    cbg.key = key.clone();
                    cbg.bind_group = make_entry();
                }
            })
            .or_insert_with(|| {
                trace!(
                    "Inserting new bind group for update metadata@3 with key={:?}",
                    key
                );
                CachedBindGroup {
                    key: key.clone(),
                    bind_group: make_entry(),
                }
            })
            .bind_group)
    }
}

#[derive(SystemParam)]
pub struct QueueEffectsReadOnlyParams<'w, 's> {
    effects_meta: Res<'w, EffectsMeta>,
    property_cache: Res<'w, PropertyCache>,
    pipeline_cache: Res<'w, PipelineCache>,
    #[cfg(feature = "2d")]
    draw_functions_2d: Res<'w, DrawFunctions<Transparent2d>>,
    #[cfg(feature = "3d")]
    draw_functions_3d: Res<'w, DrawFunctions<Transparent3d>>,
    #[cfg(feature = "3d")]
    draw_functions_alpha_mask: Res<'w, DrawFunctions<AlphaMask3d>>,
    #[cfg(feature = "3d")]
    draw_functions_opaque: Res<'w, DrawFunctions<Opaque3d>>,
    marker: PhantomData<&'s usize>,
}

fn emit_sorted_draw<T, F>(
    views: &Query<(&RenderVisibleEntities, &ExtractedView, &Msaa)>,
    render_phases: &mut ResMut<ViewSortedRenderPhases<T>>,
    view_entities: &mut FixedBitSet,
    sorted_effect_batches: &SortedEffectBatches,
    effect_draw_batches: &Query<(Entity, &mut EffectDrawBatch)>,
    render_pipeline: &mut ParticlesRenderPipeline,
    mut specialized_render_pipelines: Mut<SpecializedRenderPipelines<ParticlesRenderPipeline>>,
    property_cache: &PropertyCache,
    render_meshes: &RenderAssets<RenderMesh>,
    pipeline_cache: &PipelineCache,
    make_phase_item: F,
    #[cfg(all(feature = "2d", feature = "3d"))] pipeline_mode: PipelineMode,
) where
    T: SortedPhaseItem,
    F: Fn(CachedRenderPipelineId, (Entity, MainEntity), &EffectDrawBatch, &ExtractedView) -> T,
{
    trace!("emit_sorted_draw() {} views", views.iter().len());

    for (visible_entities, view, msaa) in views.iter() {
        let Some(visible_effect_entities) = visible_entities.get::<EffectVisibilityClass>() else {
            continue;
        };
        trace!(
            "Process new sorted view with {} visible particle effect entities",
            visible_effect_entities.iter_visible().count()
        );

        let Some(render_phase) = render_phases.get_mut(&view.retained_view_entity) else {
            continue;
        };

        {
            #[cfg(feature = "trace")]
            let _span = bevy::log::info_span!("collect_view_entities").entered();

            view_entities.clear();
            view_entities.extend(
                visible_effect_entities
                    .iter_visible()
                    .map(|(_, main_entity)| main_entity.index_u32() as usize),
            );
        }

        // For each view, loop over all the effect batches to determine if the effect
        // needs to be rendered for that view, and enqueue a view-dependent
        // batch if so.
        for (draw_entity, draw_batch) in effect_draw_batches.iter() {
            #[cfg(feature = "trace")]
            let _span_draw = bevy::log::info_span!("draw_batch").entered();

            trace!(
                "Process draw batch: draw_entity={:?} effect_batch_index={:?}",
                draw_entity,
                draw_batch.effect_batch_index,
            );

            // Get the EffectBatches this EffectDrawBatch is part of.
            let Some(effect_batch) = sorted_effect_batches.get(draw_batch.effect_batch_index)
            else {
                continue;
            };

            trace!(
                "-> EffectBach: slab_id={} spawner_base={} layout_flags={:?}",
                effect_batch.slab_id.index(),
                effect_batch.spawner_base,
                effect_batch.layout_flags,
            );

            // AlphaMask is a binned draw, so no sorted draw can possibly use it
            if effect_batch
                .layout_flags
                .intersects(LayoutFlags::USE_ALPHA_MASK | LayoutFlags::OPAQUE)
            {
                trace!("Non-transparent batch. Skipped.");
                continue;
            }

            // Check if batch contains any entity visible in the current view. Otherwise we
            // can skip the entire batch. Note: This is O(n^2) but (unlike
            // the Sprite renderer this is inspired from) we don't expect more than
            // a handful of particle effect instances, so would rather not pay the memory
            // cost of a FixedBitSet for the sake of an arguable speed-up.
            // TODO - Profile to confirm.
            #[cfg(feature = "trace")]
            let _span_check_vis = bevy::log::info_span!("check_visibility").entered();
            let has_visible_entity = effect_batch
                .entities
                .iter()
                .any(|index| view_entities.contains(*index as usize));
            if !has_visible_entity {
                trace!("No visible entity for view, not emitting any draw call.");
                continue;
            }
            #[cfg(feature = "trace")]
            _span_check_vis.exit();

            // Create and cache the bind group layout for this texture layout
            render_pipeline.cache_material(&effect_batch.texture_layout);

            // FIXME - We draw the entire batch, but part of it may not be visible in this
            // view! We should re-batch for the current view specifically!

            let local_space_simulation = effect_batch
                .layout_flags
                .contains(LayoutFlags::LOCAL_SPACE_SIMULATION);
            let alpha_mask = ParticleRenderAlphaMaskPipelineKey::from(effect_batch.layout_flags);
            let flipbook = effect_batch.layout_flags.contains(LayoutFlags::FLIPBOOK);
            let needs_uv = effect_batch.layout_flags.contains(LayoutFlags::NEEDS_UV);
            let needs_normal = effect_batch
                .layout_flags
                .contains(LayoutFlags::NEEDS_NORMAL);
            let needs_particle_fragment = effect_batch
                .layout_flags
                .contains(LayoutFlags::NEEDS_PARTICLE_FRAGMENT);
            let ribbons = effect_batch.layout_flags.contains(LayoutFlags::RIBBONS);
            let image_count = effect_batch.texture_layout.layout.len() as u8;

            // FIXME - Maybe it's better to copy the mesh layout into the batch, instead of
            // re-querying here...?
            let Some(render_mesh) = render_meshes.get(effect_batch.mesh) else {
                trace!("Batch has no render mesh, skipped.");
                continue;
            };
            let mesh_layout = render_mesh.layout.clone();

            // Specialize the render pipeline based on the effect batch
            trace!(
                "Specializing render pipeline: render_shader={:?} image_count={} alpha_mask={:?} flipbook={:?} target_format={:?}",
                effect_batch.render_shader,
                image_count,
                alpha_mask,
                flipbook,
                view.target_format
            );

            // Add a draw pass for the effect batch
            trace!("Emitting individual draw for batch");

            let alpha_mode = effect_batch.alpha_mode;

            // This should always exist by the time we reach this point, because we should
            // have inserted any property in the cache, which would have allocated the
            // proper bind group layout (or the default no-property one).
            let property_layout_min_binding_size = effect_batch
                .property_key
                .map(|key| NonZeroU64::new(key.binding_size as u64).unwrap());
            let spawner_bind_group_layout_desc = property_cache
                .bind_group_layout_desc(property_layout_min_binding_size)
                .unwrap_or_else(|| {
                    panic!(
                        "Failed to find spawner@2 bind group layout for property binding size {:?}",
                        property_layout_min_binding_size,
                    )
                });

            #[cfg(feature = "trace")]
            let _span_specialize = bevy::log::info_span!("specialize").entered();
            let render_pipeline_id = specialized_render_pipelines.specialize(
                pipeline_cache,
                render_pipeline,
                ParticleRenderPipelineKey {
                    shader: effect_batch.render_shader.clone(),
                    mesh_layout: Some(mesh_layout),
                    particle_layout: effect_batch.particle_layout.clone(),
                    texture_layout: effect_batch.texture_layout.clone(),
                    local_space_simulation,
                    alpha_mask,
                    alpha_mode,
                    flipbook,
                    needs_uv,
                    needs_normal,
                    needs_particle_fragment,
                    ribbons,
                    #[cfg(all(feature = "2d", feature = "3d"))]
                    pipeline_mode,
                    msaa_samples: msaa.samples(),
                    target_format: view.target_format,
                    spawner_bind_group_layout_desc: spawner_bind_group_layout_desc.clone(),
                },
            );
            #[cfg(feature = "trace")]
            _span_specialize.exit();

            trace!("+ Render pipeline specialized: id={:?}", render_pipeline_id,);
            trace!(
                "+ Add Transparent for batch on draw_entity {:?}: slab_id={} \
                spawner_base={} handle={:?}",
                draw_entity,
                effect_batch.slab_id.index(),
                effect_batch.spawner_base,
                effect_batch.handle
            );
            render_phase.add_transient(make_phase_item(
                render_pipeline_id,
                (draw_entity, draw_batch.main_entity),
                draw_batch,
                view,
            ));
        }
    }
}

#[cfg(feature = "3d")]
fn emit_binned_draw<T, F, G>(
    views: &Query<(&RenderVisibleEntities, &ExtractedView, &Msaa)>,
    render_phases: &mut ResMut<ViewBinnedRenderPhases<T>>,
    view_entities: &mut FixedBitSet,
    sorted_effect_batches: &SortedEffectBatches,
    effect_draw_batches: &Query<(Entity, &mut EffectDrawBatch)>,
    render_pipeline: &mut ParticlesRenderPipeline,
    mut specialized_render_pipelines: Mut<SpecializedRenderPipelines<ParticlesRenderPipeline>>,
    property_cache: &PropertyCache,
    pipeline_cache: &PipelineCache,
    render_meshes: &RenderAssets<RenderMesh>,
    mesh_allocator: &MeshAllocator,
    make_batch_set_key: F,
    make_bin_key: G,
    #[cfg(all(feature = "2d", feature = "3d"))] pipeline_mode: PipelineMode,
    alpha_mask: ParticleRenderAlphaMaskPipelineKey,
) where
    T: BinnedPhaseItem,
    F: Fn(CachedRenderPipelineId, &EffectDrawBatch, &ExtractedView, MeshSlabs) -> T::BatchSetKey,
    G: Fn() -> T::BinKey,
{
    use bevy::render::render_phase::{BinnedRenderPhaseType, InputUniformIndex};

    trace!("emit_binned_draw() {} views", views.iter().len());

    for (visible_entities, view, msaa) in views.iter() {
        let Some(visible_effect_entities) = visible_entities.get::<EffectVisibilityClass>() else {
            continue;
        };
        trace!("Process new binned view (alpha_mask={:?})", alpha_mask);

        let Some(render_phase) = render_phases.get_mut(&view.retained_view_entity) else {
            continue;
        };

        {
            #[cfg(feature = "trace")]
            let _span = bevy::log::info_span!("collect_view_entities").entered();

            view_entities.clear();
            view_entities.extend(
                visible_effect_entities
                    .iter_visible()
                    .map(|(_, main_entity)| main_entity.index_u32() as usize),
            );
        }

        // For each view, loop over all the effect batches to determine if the effect
        // needs to be rendered for that view, and enqueue a view-dependent
        // batch if so.
        for (draw_entity, draw_batch) in effect_draw_batches.iter() {
            #[cfg(feature = "trace")]
            let _span_draw = bevy::log::info_span!("draw_batch").entered();

            trace!(
                "Process draw batch: draw_entity={:?} effect_batch_index={:?}",
                draw_entity,
                draw_batch.effect_batch_index,
            );

            // Get the EffectBatches this EffectDrawBatch is part of.
            let Some(effect_batch) = sorted_effect_batches.get(draw_batch.effect_batch_index)
            else {
                continue;
            };

            trace!(
                "-> EffectBaches: slab_id={} spawner_base={} layout_flags={:?}",
                effect_batch.slab_id.index(),
                effect_batch.spawner_base,
                effect_batch.layout_flags,
            );

            if ParticleRenderAlphaMaskPipelineKey::from(effect_batch.layout_flags) != alpha_mask {
                trace!(
                    "Mismatching alpha mask pipeline key (batches={:?}, expected={:?}). Skipped.",
                    effect_batch.layout_flags,
                    alpha_mask
                );
                continue;
            }

            // Check if batch contains any entity visible in the current view. Otherwise we
            // can skip the entire batch. Note: This is O(n^2) but (unlike
            // the Sprite renderer this is inspired from) we don't expect more than
            // a handful of particle effect instances, so would rather not pay the memory
            // cost of a FixedBitSet for the sake of an arguable speed-up.
            // TODO - Profile to confirm.
            #[cfg(feature = "trace")]
            let _span_check_vis = bevy::log::info_span!("check_visibility").entered();
            let has_visible_entity = effect_batch
                .entities
                .iter()
                .any(|index| view_entities.contains(*index as usize));
            if !has_visible_entity {
                trace!("No visible entity for view, not emitting any draw call.");
                continue;
            }
            #[cfg(feature = "trace")]
            _span_check_vis.exit();

            // Create and cache the bind group layout for this texture layout
            render_pipeline.cache_material(&effect_batch.texture_layout);

            // FIXME - We draw the entire batch, but part of it may not be visible in this
            // view! We should re-batch for the current view specifically!

            let local_space_simulation = effect_batch
                .layout_flags
                .contains(LayoutFlags::LOCAL_SPACE_SIMULATION);
            let alpha_mask = ParticleRenderAlphaMaskPipelineKey::from(effect_batch.layout_flags);
            let flipbook = effect_batch.layout_flags.contains(LayoutFlags::FLIPBOOK);
            let needs_uv = effect_batch.layout_flags.contains(LayoutFlags::NEEDS_UV);
            let needs_normal = effect_batch
                .layout_flags
                .contains(LayoutFlags::NEEDS_NORMAL);
            let needs_particle_fragment = effect_batch
                .layout_flags
                .contains(LayoutFlags::NEEDS_PARTICLE_FRAGMENT);
            let ribbons = effect_batch.layout_flags.contains(LayoutFlags::RIBBONS);
            let image_count = effect_batch.texture_layout.layout.len() as u8;
            let render_mesh = render_meshes.get(effect_batch.mesh);

            // Specialize the render pipeline based on the effect batch
            trace!(
                "Specializing render pipeline: render_shaders={:?} image_count={} alpha_mask={:?} flipbook={:?} target_format={:?}",
                effect_batch.render_shader,
                image_count,
                alpha_mask,
                flipbook,
                view.target_format
            );

            // Add a draw pass for the effect batch
            trace!("Emitting individual draw for batch");

            let alpha_mode = effect_batch.alpha_mode;

            let Some(mesh_layout) = render_mesh.map(|gpu_mesh| gpu_mesh.layout.clone()) else {
                trace!("Missing mesh vertex buffer layout. Skipped.");
                continue;
            };

            // This should always exist by the time we reach this point, because we should
            // have inserted any property in the cache, which would have allocated the
            // proper bind group layout (or the default no-property one).
            let property_layout_min_binding_size = effect_batch
                .property_key
                .map(|key| NonZeroU64::new(key.binding_size as u64).unwrap());
            let spawner_bind_group_layout_desc = property_cache
                .bind_group_layout_desc(property_layout_min_binding_size)
                .unwrap_or_else(|| {
                    panic!(
                        "Failed to find spawner@2 bind group layout for property binding size {:?}",
                        property_layout_min_binding_size,
                    )
                });

            #[cfg(feature = "trace")]
            let _span_specialize = bevy::log::info_span!("specialize").entered();
            let render_pipeline_id = specialized_render_pipelines.specialize(
                pipeline_cache,
                render_pipeline,
                ParticleRenderPipelineKey {
                    shader: effect_batch.render_shader.clone(),
                    mesh_layout: Some(mesh_layout),
                    particle_layout: effect_batch.particle_layout.clone(),
                    texture_layout: effect_batch.texture_layout.clone(),
                    local_space_simulation,
                    alpha_mask,
                    alpha_mode,
                    flipbook,
                    needs_uv,
                    needs_normal,
                    needs_particle_fragment,
                    ribbons,
                    #[cfg(all(feature = "2d", feature = "3d"))]
                    pipeline_mode,
                    msaa_samples: msaa.samples(),
                    target_format: view.target_format,
                    spawner_bind_group_layout_desc: spawner_bind_group_layout_desc.clone(),
                },
            );
            #[cfg(feature = "trace")]
            _span_specialize.exit();

            trace!("+ Render pipeline specialized: id={:?}", render_pipeline_id,);
            trace!(
                "+ Add Transparent for batch on draw_entity {:?}: slab_id={} \
                spawner_base={} handle={:?}",
                draw_entity,
                effect_batch.slab_id.index(),
                effect_batch.spawner_base,
                effect_batch.handle
            );
            let slabs = mesh_allocator
                .mesh_slabs(&effect_batch.mesh)
                .unwrap_or_default();
            render_phase.add(
                make_batch_set_key(render_pipeline_id, draw_batch, view, slabs),
                make_bin_key(),
                (draw_entity, draw_batch.main_entity),
                InputUniformIndex::default(),
                BinnedRenderPhaseType::NonMesh,
            );
        }
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn queue_effects(
    views: Query<(&RenderVisibleEntities, &ExtractedView, &Msaa)>,
    mut render_pipeline: ResMut<ParticlesRenderPipeline>,
    mut specialized_render_pipelines: ResMut<SpecializedRenderPipelines<ParticlesRenderPipeline>>,
    mut effect_bind_groups: ResMut<EffectBindGroups>,
    sorted_effect_batches: Res<SortedEffectBatches>,
    effect_draw_batches: Query<(Entity, &mut EffectDrawBatch)>,
    events: Res<EffectAssetEvents>,
    render_meshes: Res<RenderAssets<RenderMesh>>,
    #[cfg(feature = "3d")] mesh_allocator: Res<MeshAllocator>,
    read_params: QueueEffectsReadOnlyParams,
    mut view_entities: Local<FixedBitSet>,
    #[cfg(feature = "2d")] mut transparent_2d_render_phases: ResMut<
        ViewSortedRenderPhases<Transparent2d>,
    >,
    #[cfg(feature = "3d")] mut transparent_3d_render_phases: ResMut<
        ViewSortedRenderPhases<Transparent3d>,
    >,
    #[cfg(feature = "3d")] (mut opaque_3d_render_phases, mut alpha_mask_3d_render_phases): (
        ResMut<ViewBinnedRenderPhases<Opaque3d>>,
        ResMut<ViewBinnedRenderPhases<AlphaMask3d>>,
    ),
    mut change_tick: Local<Tick>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("hanabi:queue_effects").entered();

    trace!("queue_effects");

    let effects_meta = read_params.effects_meta.into_inner();
    let property_cache = read_params.property_cache.into_inner();
    let pipeline_cache = read_params.pipeline_cache.into_inner();

    // Bump the change tick so that Bevy is forced to rebuild the binned render
    // phase bins. We don't use the built-in caching so we don't want Bevy to
    // reuse stale data.
    let next_change_tick = change_tick.get() + 1;
    change_tick.set(next_change_tick);

    // If an image has changed, the GpuImage has (probably) changed
    for event in &events.images {
        match event {
            AssetEvent::Added { .. } => (),
            AssetEvent::LoadedWithDependencies { .. } => (),
            AssetEvent::Unused { .. } => (),
            AssetEvent::Modified { id } => {
                if effect_bind_groups.images.remove(id).is_some() {
                    trace!("Destroyed bind group of modified image asset {:?}", id);
                }
            }
            AssetEvent::Removed { id } => {
                if effect_bind_groups.images.remove(id).is_some() {
                    trace!("Destroyes bind group of removed image asset {:?}", id);
                }
            }
        };
    }

    if effects_meta.spawner_buffer.buffer().is_none() || effects_meta.spawner_buffer.is_empty() {
        // No spawners are active
        return;
    }

    // Loop over all 2D cameras/views that need to render effects
    #[cfg(feature = "2d")]
    {
        #[cfg(feature = "trace")]
        let _span_draw = bevy::log::info_span!("draw_2d").entered();

        let draw_effects_function_2d = read_params
            .draw_functions_2d
            .read()
            .get_id::<DrawEffects>()
            .unwrap();

        // Effects with full alpha blending
        if !views.is_empty() {
            trace!("Emit effect draw calls for alpha blended 2D views...");
            emit_sorted_draw(
                &views,
                &mut transparent_2d_render_phases,
                &mut view_entities,
                &sorted_effect_batches,
                &effect_draw_batches,
                &mut render_pipeline,
                specialized_render_pipelines.reborrow(),
                property_cache,
                &render_meshes,
                pipeline_cache,
                |id, entity, draw_batch, _view| Transparent2d {
                    sort_key: FloatOrd(draw_batch.translation.z),
                    entity,
                    pipeline: id,
                    draw_function: draw_effects_function_2d,
                    batch_range: 0..1,
                    extracted_index: 0, // ???
                    extra_index: PhaseItemExtraIndex::None,
                    indexed: true, // ???
                },
                #[cfg(feature = "3d")]
                PipelineMode::Camera2d,
            );
        }
    }

    // Loop over all 3D cameras/views that need to render effects
    #[cfg(feature = "3d")]
    {
        #[cfg(feature = "trace")]
        let _span_draw = bevy::log::info_span!("draw_3d").entered();

        // Effects with full alpha blending
        if !views.is_empty() {
            use bevy::core_pipeline::core_3d::TransparentSortingInfo3d;

            trace!("Emit effect draw calls for alpha blended 3D views...");

            let draw_effects_function_3d = read_params
                .draw_functions_3d
                .read()
                .get_id::<DrawEffects>()
                .unwrap();

            emit_sorted_draw(
                &views,
                &mut transparent_3d_render_phases,
                &mut view_entities,
                &sorted_effect_batches,
                &effect_draw_batches,
                &mut render_pipeline,
                specialized_render_pipelines.reborrow(),
                property_cache,
                &render_meshes,
                pipeline_cache,
                |id, entity, batch, view| Transparent3d {
                    sorting_info: TransparentSortingInfo3d::Sorted {
                        mesh_center: batch.translation,
                        depth_bias: 0.0,
                    },
                    distance: view.rangefinder3d().distance(&batch.translation),
                    pipeline: id,
                    entity,
                    draw_function: draw_effects_function_3d,
                    batch_range: 0..1,
                    extra_index: PhaseItemExtraIndex::None,
                    indexed: true, // ???
                },
                #[cfg(feature = "2d")]
                PipelineMode::Camera3d,
            );
        }

        // Effects with alpha mask
        if !views.is_empty() {
            #[cfg(feature = "trace")]
            let _span_draw = bevy::log::info_span!("draw_alphamask").entered();

            trace!("Emit effect draw calls for alpha masked 3D views...");

            let draw_effects_function_alpha_mask = read_params
                .draw_functions_alpha_mask
                .read()
                .get_id::<DrawEffects>()
                .unwrap();

            emit_binned_draw(
                &views,
                &mut alpha_mask_3d_render_phases,
                &mut view_entities,
                &sorted_effect_batches,
                &effect_draw_batches,
                &mut render_pipeline,
                specialized_render_pipelines.reborrow(),
                property_cache,
                pipeline_cache,
                &render_meshes,
                &mesh_allocator,
                |id, _batch, _view, slabs| OpaqueNoLightmap3dBatchSetKey {
                    pipeline: id,
                    draw_function: draw_effects_function_alpha_mask,
                    material_bind_group_index: None,
                    slabs,
                },
                // Unused for now
                || OpaqueNoLightmap3dBinKey {
                    asset_id: AssetId::<Mesh>::invalid().untyped(),
                },
                #[cfg(feature = "2d")]
                PipelineMode::Camera3d,
                ParticleRenderAlphaMaskPipelineKey::AlphaMask,
            );
        }

        // Opaque particles
        if !views.is_empty() {
            #[cfg(feature = "trace")]
            let _span_draw = bevy::log::info_span!("draw_opaque").entered();

            trace!("Emit effect draw calls for opaque 3D views...");

            let draw_effects_function_opaque = read_params
                .draw_functions_opaque
                .read()
                .get_id::<DrawEffects>()
                .unwrap();

            emit_binned_draw(
                &views,
                &mut opaque_3d_render_phases,
                &mut view_entities,
                &sorted_effect_batches,
                &effect_draw_batches,
                &mut render_pipeline,
                specialized_render_pipelines.reborrow(),
                property_cache,
                pipeline_cache,
                &render_meshes,
                &mesh_allocator,
                |id, _batch, _view, slabs| Opaque3dBatchSetKey {
                    pipeline: id,
                    draw_function: draw_effects_function_opaque,
                    material_bind_group_index: None,
                    slabs,
                    lightmap_slab: None,
                },
                // Unused for now
                || Opaque3dBinKey {
                    asset_id: AssetId::<Mesh>::invalid().untyped(),
                },
                #[cfg(feature = "2d")]
                PipelineMode::Camera3d,
                ParticleRenderAlphaMaskPipelineKey::Opaque,
            );
        }
    }
}

/// Once a child effect is batched, and therefore passed validations to be
/// updated and rendered this frame, dispatch a new GPU operation to fill the
/// indirect dispatch args of its init pass based on the number of GPU events
/// emitted in the previous frame and stored in its event buffer.
pub fn queue_init_indirect_workgroup_update(
    q_cached_effects: Query<(
        Entity,
        &CachedChildInfo,
        &CachedEffectEvents,
        &CachedReadyState,
    )>,
    mut init_fill_dispatch_queue: ResMut<InitFillDispatchQueue>,
) {
    debug_assert_eq!(
        GpuChildInfo::min_size().get() % 4,
        0,
        "Invalid GpuChildInfo alignment."
    );

    // Schedule some GPU buffer operation to update the number of workgroups to
    // dispatch during the indirect init pass of this effect based on the number of
    // GPU spawn events written in its buffer.
    for (entity, cached_child_info, cached_effect_events, cached_ready_state) in &q_cached_effects {
        if !cached_ready_state.is_ready() {
            trace!(
                "[Effect {:?}] Skipping init_fill_dispatch.enqueue() because effect is not ready.",
                entity
            );
            continue;
        }
        let init_indirect_dispatch_index = cached_effect_events.init_indirect_dispatch_index;
        let global_child_index = cached_child_info.global_child_index;
        trace!(
            "[Effect {:?}] init_fill_dispatch.enqueue(): src:global_child_index={} dst:init_indirect_dispatch_index={}",
            entity,
            global_child_index,
            init_indirect_dispatch_index,
        );
        assert!(global_child_index != u32::MAX);
        init_fill_dispatch_queue.enqueue(global_child_index, init_indirect_dispatch_index);
    }
}

/// Prepare GPU resources for effect rendering.
///
/// This system runs in the [`RenderSet::PrepareResources`] render set, after
/// Bevy has updated the [`ViewUniforms`], which need to be referenced to get
/// access to the current camera view.
pub(crate) fn prepare_gpu_resources(
    mut effects_meta: ResMut<EffectsMeta>,
    //mut effect_cache: ResMut<EffectCache>,
    mut event_cache: ResMut<EventCache>,
    mut effect_bind_groups: ResMut<EffectBindGroups>,
    mut sort_bind_groups: ResMut<SortBindGroups>,
    render_device: Res<RenderDevice>,
    render_queue: Res<RenderQueue>,
    view_uniforms: Res<ViewUniforms>,
    render_pipeline: Res<ParticlesRenderPipeline>,
    pipeline_cache: Res<PipelineCache>,
) {
    // Get the binding for the ViewUniform, the uniform data structure containing
    // the Camera data for the current view. If not available, we cannot render
    // anything.
    let Some(view_binding) = view_uniforms.uniforms.binding() else {
        return;
    };

    // Upload simulation parameters for this frame
    let prev_buffer_id = effects_meta.sim_params_uniforms.buffer().map(|b| b.id());
    effects_meta
        .sim_params_uniforms
        .write_buffer(&render_device, &render_queue);
    if prev_buffer_id != effects_meta.sim_params_uniforms.buffer().map(|b| b.id()) {
        // Buffer changed, invalidate bind groups
        effects_meta.update_sim_params_bind_group = None;
        effects_meta.init_and_indirect_sim_params_bind_group = None;
    }

    // Create the bind group for the camera/view parameters
    // FIXME - Not here!
    effects_meta.view_bind_group = Some(render_device.create_bind_group(
        "hanabi:bg:camera_view",
        &pipeline_cache.get_bind_group_layout(&render_pipeline.view_layout_desc),
        &BindGroupEntries::sequential((
            view_binding,
            effects_meta.sim_params_uniforms.binding().unwrap(),
        )),
    ));

    // Re-/allocate the draw indirect args buffer if needed
    if effects_meta
        .draw_indirect_buffer
        .allocate_gpu(&render_device, &render_queue)
    {
        // All those bind groups use the buffer so need to be re-created
        trace!("*** Draw indirect args buffer re-allocated; clearing all bind groups using it.");
        effects_meta.update_sim_params_bind_group = None;
        effects_meta.indirect_metadata_bind_group = None;
    }

    // Re-/allocate any GPU buffer if needed
    //effect_cache.prepare_buffers(&render_device, &render_queue, &mut
    // effect_bind_groups);
    event_cache.prepare_buffers(&render_device, &render_queue, &mut effect_bind_groups);
    sort_bind_groups.prepare_buffers(&render_device);
    if effects_meta
        .dispatch_indirect_buffer
        .prepare_buffers(&render_device)
    {
        // All those bind groups use the buffer so need to be re-created
        trace!("*** Dispatch indirect buffer for update pass re-allocated; clearing all bind groups using it.");
        effect_bind_groups.particle_slabs.clear();
    }
}

/// Update the [`GpuEffectMetadata`] of all the effects queued for update/render
/// this frame.
///
/// By this point, all effects should have a [`CachedEffectMetadata`] with a
/// valid allocation in the GPU table for a [`GpuEffectMetadata`] entry. This
/// system actually synchronize the CPU value with the GPU one in case of
/// change.
pub(crate) fn prepare_effect_metadata(
    render_device: Res<RenderDevice>,
    render_queue: Res<RenderQueue>,
    mut q_effects: Query<(
        MainEntity,
        Ref<ExtractedEffect>,
        Ref<CachedEffect>,
        Option<Ref<CachedChildInfo>>,
        Option<Ref<CachedParentInfo>>,
        Option<Ref<CachedDrawIndirectArgs>>,
        Option<Ref<CachedEffectEvents>>,
        Option<Ref<CachedEffectProperties>>,
        &mut CachedEffectMetadata,
    )>,
    mut effects_meta: ResMut<EffectsMeta>,
    mut effect_bind_groups: ResMut<EffectBindGroups>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("prepare_effect_metadata").entered();
    trace!("prepare_effect_metadata");

    for (
        main_entity,
        extracted_effect,
        cached_effect,
        maybe_cached_child_info,
        maybe_cached_parent_info,
        maybe_cached_draw_indirect_args,
        maybe_cached_effect_events,
        maybe_cached_effect_properties,
        mut cached_effect_metadata,
    ) in &mut q_effects
    {
        // Check if anything relevant to GpuEffectMetadata changed this frame; otherwise
        // early out and skip this effect.
        let is_changed_ee = extracted_effect.is_changed();
        let is_changed_ce = cached_effect.is_changed();
        let is_changed_cci = maybe_cached_child_info
            .as_ref()
            .map(|cci| cci.is_changed())
            .unwrap_or(false);
        let is_changed_cpi = maybe_cached_parent_info
            .as_ref()
            .map(|cpi| cpi.is_changed())
            .unwrap_or(false);
        let is_changed_cdia = maybe_cached_draw_indirect_args
            .as_ref()
            .map(|cdia| cdia.is_changed())
            .unwrap_or(false);
        let is_changed_cee = maybe_cached_effect_events
            .as_ref()
            .map(|cee| cee.is_changed())
            .unwrap_or(false);
        let is_changed_cep = maybe_cached_effect_properties
            .as_ref()
            .map(|cep| cep.is_changed())
            .unwrap_or(false);
        trace!(
            "Preparting GpuEffectMetadata for effect {:?}: is_changed[] = {} {} {} {} {} {} {}",
            main_entity,
            is_changed_ee,
            is_changed_ce,
            is_changed_cci,
            is_changed_cpi,
            is_changed_cdia,
            is_changed_cee,
            is_changed_cep
        );
        if !is_changed_ee
            && !is_changed_ce
            && !is_changed_cci
            && !is_changed_cpi
            && !is_changed_cdia
            && !is_changed_cee
            && !is_changed_cep
        {
            continue;
        }

        let capacity = cached_effect.slice.len();

        // Global and local indices of this effect as a child of another (parent) effect
        let (global_child_index, local_child_index) = maybe_cached_child_info
            .map(|cci| (cci.global_child_index, cci.local_child_index))
            .unwrap_or((u32::MAX, u32::MAX));

        // Base index of all children of this (parent) effect
        let base_child_index = maybe_cached_parent_info
            .map(|cpi| {
                debug_assert_eq!(
                    cpi.byte_range.start % GpuChildInfo::SHADER_SIZE.get() as u32,
                    0
                );
                cpi.byte_range.start / GpuChildInfo::SHADER_SIZE.get() as u32
            })
            .unwrap_or(u32::MAX);

        let particle_stride = extracted_effect.particle_layout.min_binding_size32().get() / 4;
        let sort_key_offset = extracted_effect
            .particle_layout
            .byte_offset(Attribute::RIBBON_ID)
            .map(|byte_offset| byte_offset / 4)
            .unwrap_or(u32::MAX);
        let sort_key2_offset = extracted_effect
            .particle_layout
            .byte_offset(Attribute::AGE)
            .map(|byte_offset| byte_offset / 4)
            .unwrap_or(u32::MAX);

        let gpu_effect_metadata = GpuEffectMetadata {
            capacity,
            alive_count: 0,
            max_update: 0,
            max_spawn: capacity,
            indirect_write_index: 0,
            indirect_draw_index: maybe_cached_draw_indirect_args
                .map(|cdia| cdia.get_row().0)
                .unwrap_or(u32::MAX),
            init_indirect_dispatch_index: maybe_cached_effect_events
                .map(|cee| cee.init_indirect_dispatch_index)
                .unwrap_or(u32::MAX),
            properties_array_index: maybe_cached_effect_properties
                .map(|cep| cep.array_index)
                .unwrap_or(u32::MAX),
            local_child_index,
            global_child_index,
            base_child_index,
            particle_stride,
            sort_key_offset,
            sort_key2_offset,
            ..default()
        };

        // Insert of update entry in GPU buffer table
        assert!(cached_effect_metadata.table_id.is_valid());
        if gpu_effect_metadata != cached_effect_metadata.metadata {
            effects_meta
                .effect_metadata_buffer
                .update(cached_effect_metadata.table_id, gpu_effect_metadata);

            cached_effect_metadata.metadata = gpu_effect_metadata;

            // This triggers on all new spawns and annoys everyone; silence until we can at
            // least warn only on non-first-spawn, and ideally split indirect data from that
            // struct so we don't overwrite it and solve the issue.
            debug!(
                "Updated metadata entry {} for effect {:?}, this will reset it.",
                cached_effect_metadata.table_id.0, main_entity
            );
        }
    }

    // Once all EffectMetadata values are written, schedule a GPU upload
    if effects_meta
        .effect_metadata_buffer
        .allocate_gpu(render_device.as_ref(), render_queue.as_ref())
    {
        // All those bind groups use the buffer so need to be re-created
        trace!("*** Effect metadata buffer re-allocated; clearing all bind groups using it.");
        effects_meta.indirect_metadata_bind_group = None;
        effect_bind_groups.init_metadata_bind_groups.clear();
        effect_bind_groups.update_metadata_bind_groups.clear();
    }
}

/// Read the queued ribbon sort fill dispatch operations and enqueue the
/// corresponding GPU buffer fill dispatch operations.
///
/// This system runs after [`prepare_effect_metadata()`] has (re-)allocated the
/// effect metadata buffer to this frame's effect count, so that it captures the
/// correctly-sized buffer and computes in-bounds dynamic offsets. It must run
/// before [`queue_init_fill_dispatch_ops()`], which uploads the shared
/// [`GpuBufferOperations`] args buffer to the GPU at the end of the frame.
pub(crate) fn queue_sort_fill_dispatch_ops(
    effects_meta: Res<EffectsMeta>,
    sort_bind_groups: Res<SortBindGroups>,
    sort_fill_dispatch_queue: Res<SortFillDispatchQueue>,
    mut gpu_buffer_operations: ResMut<GpuBufferOperations>,
    mut sorted_effect_batches: ResMut<SortedEffectBatches>,
) {
    #[cfg(feature = "trace")]
    let _span = bevy::log::info_span!("queue_sort_fill_dispatch_ops").entered();
    trace!("queue_sort_fill_dispatch_ops");

    debug_assert!(sorted_effect_batches.dispatch_queue_index.is_none());
    sorted_effect_batches.dispatch_queue_index = sort_fill_dispatch_queue.submit(
        &effects_meta.effect_metadata_buffer,
        effects_meta.gpu_limits.effect_metadata_aligned_size,
        &sort_bind_groups,
        &mut gpu_buffer_operations,
    );
}

/// Read the queued init fill dispatch operations, batch them together by
/// contiguous source and destination entries in the buffers, and enqueue
/// corresponding GPU buffer fill dispatch operations for all batches.
///
/// This system runs after the GPU buffers have been (re-)allocated in
/// [`prepare_gpu_resources()`], so that it can read the new buffer IDs and
/// reference them from the generic [`GpuBufferOperationQueue`].
pub(crate) fn queue_init_fill_dispatch_ops(
    event_cache: Res<EventCache>,
    render_device: Res<RenderDevice>,
    render_queue: Res<RenderQueue>,
    mut init_fill_dispatch_queue: ResMut<InitFillDispatchQueue>,
    mut gpu_buffer_operations: ResMut<GpuBufferOperations>,
) {
    // Submit all queued init fill dispatch operations with the proper buffers
    if !init_fill_dispatch_queue.is_empty() {
        let src_buffer = event_cache.child_infos().buffer();
        let dst_buffer = event_cache.init_indirect_dispatch_buffer();
        if let (Some(src_buffer), Some(dst_buffer)) = (src_buffer, dst_buffer) {
            init_fill_dispatch_queue.submit(src_buffer, dst_buffer, &mut gpu_buffer_operations);
        } else {
            if src_buffer.is_none() {
                warn!("Event cache has no allocated GpuChildInfo buffer, but there's {} init fill dispatch operation(s) queued. Ignoring those operations. This will prevent child particles from spawning.", init_fill_dispatch_queue.queue.len());
            }
            if dst_buffer.is_none() {
                warn!("Event cache has no allocated GpuDispatchIndirect buffer, but there's {} init fill dispatch operation(s) queued. Ignoring those operations. This will prevent child particles from spawning.", init_fill_dispatch_queue.queue.len());
            }
        }
    }

    // End the GpuBufferOperations frame and upload the args buffer to GPU, after
    // every submit() for the frame (the sort submit in
    // queue_sort_fill_dispatch_ops() is ordered before this system,
    // the init submit is just above). See begin_frame() in batch_effects() for the
    // full lifecycle.
    gpu_buffer_operations.end_frame(&render_device, &render_queue);
}

#[derive(SystemParam)]
pub struct PipelineParams<'w, 's> {
    dispatch_indirect_pipeline: Res<'w, DispatchIndirectPipeline>,
    prefix_sum_pipeline: Res<'w, PrefixSumPipeline>,
    utils_pipeline: Res<'w, UtilsPipeline>,
    init_pipeline: Res<'w, ParticlesInitPipeline>,
    update_pipeline: Res<'w, ParticlesUpdatePipeline>,
    render_pipeline: ResMut<'w, ParticlesRenderPipeline>,
    marker: PhantomData<&'s usize>,
}

pub(crate) fn prepare_bind_groups(
    mut effects_meta: ResMut<EffectsMeta>,
    mut effect_cache: ResMut<EffectCache>,
    mut event_cache: ResMut<EventCache>,
    mut effect_bind_groups: ResMut<EffectBindGroups>,
    mut property_bind_groups: ResMut<PropertyBindGroups>,
    mut sort_bind_groups: ResMut<SortBindGroups>,
    property_cache: Res<PropertyCache>,
    sorted_effect_batched: Res<SortedEffectBatches>,
    render_device: Res<RenderDevice>,
    pipeline_cache: Res<PipelineCache>,
    pipelines: PipelineParams,
    gpu_images: Res<RenderAssets<GpuImage>>,
    mut gpu_buffer_operation_queue: ResMut<GpuBufferOperations>,
) {
    // We can't simulate nor render anything without at least the spawner buffer
    if effects_meta.spawner_buffer.is_empty() {
        return;
    }
    let Some(spawner_buffer) = effects_meta.spawner_buffer.buffer().cloned() else {
        error!("Missing spawner GPU buffer!");
        return;
    };
    let Some(prefix_sum_buffer) = effects_meta.prefix_sum_buffer.buffer().cloned() else {
        error!("Missing prefix sum GPU buffer!");
        return;
    };
    let Some(batch_info_buffer) = effects_meta.batch_info_buffer.buffer().cloned() else {
        error!("Missing batch info GPU buffer!");
        return;
    };
    let Some(dispatch_indirect_buffer) = effects_meta.dispatch_indirect_buffer.buffer().cloned()
    else {
        error!("Missing dispatch indirect GPU buffer!");
        return;
    };

    // Workaround for too many params in system (TODO: refactor to split work?)
    let dispatch_indirect_pipeline = pipelines.dispatch_indirect_pipeline.into_inner();
    let prefix_sum_pipeline = pipelines.prefix_sum_pipeline.into_inner();
    let utils_pipeline = pipelines.utils_pipeline.into_inner();
    let init_pipeline = pipelines.init_pipeline.into_inner();
    let update_pipeline = pipelines.update_pipeline.into_inner();
    let render_pipeline = pipelines.render_pipeline.into_inner();

    // Ensure child_infos@3 bind group for the indirect pass is available if needed.
    // This returns `None` if the buffer is not ready, either because it's not
    // created yet or because it's not needed (no child effect).
    event_cache.ensure_indirect_child_info_buffer_bind_group(&render_device);

    {
        #[cfg(feature = "trace")]
        let _span = bevy::log::info_span!("shared_bind_groups").entered();

        // Create the sim_params@0 bind group for the global simulation parameters,
        // which is shared by the init and update passes.
        if effects_meta.update_sim_params_bind_group.is_none() {
            if let Some(draw_indirect_buffer) = effects_meta.draw_indirect_buffer.buffer() {
                effects_meta.update_sim_params_bind_group = Some(render_device.create_bind_group(
                    "hanabi:bg:vfx_update:sim_params@0",
                    &pipeline_cache.get_bind_group_layout(&update_pipeline.sim_params_layout_desc),
                    &BindGroupEntries::sequential((
                        // @group(0) @binding(0) var<uniform> sim_params : SimParams;
                        effects_meta.sim_params_uniforms.binding().unwrap(),
                        // @group(0) @binding(1) var<storage, read_write> draw_indirect_buffer :
                        // array<DrawIndexedIndirectArgs>;
                        draw_indirect_buffer.as_entire_binding(),
                    )),
                ));
            } else {
                debug!("Cannot allocate bind group for vfx_update:sim_params@0 - draw_indirect_buffer not ready");
            }
        }
        if effects_meta
            .init_and_indirect_sim_params_bind_group
            .is_none()
        {
            debug!("Re-creating init_and_indirect_sim_params_bind_group...");
            effects_meta.init_and_indirect_sim_params_bind_group =
                Some(render_device.create_bind_group(
                    "hanabi:bg:vfx_indirect:sim_params@0",
                    &pipeline_cache.get_bind_group_layout(&init_pipeline.sim_params_layout_desc), // FIXME - Shared with init
                    // @group(0) @binding(0) var<uniform> sim_params : SimParams;
                    &BindGroupEntries::single(effects_meta.sim_params_uniforms.binding().unwrap()),
                ));
        }

        // Create the @1 bind group for the indirect dispatch preparation pass of all
        // effects at once
        effects_meta.indirect_metadata_bind_group = match (
            effects_meta.effect_metadata_buffer.buffer(),
            effects_meta.draw_indirect_buffer.buffer(),
        ) {
            (Some(effect_metadata_buffer), Some(draw_indirect_buffer)) => {
                // Base bind group for indirect pass
                Some(render_device.create_bind_group(
                    "hanabi:bg:vfx_indirect:metadata@1",
                    &pipeline_cache.get_bind_group_layout(
                        &dispatch_indirect_pipeline.effect_metadata_bind_group_layout_desc,
                    ),
                    &BindGroupEntries::sequential((
                        // @group(1) @binding(0) var<storage, read_write> effect_metadata_buffer :
                        // array<u32>;
                        effect_metadata_buffer.as_entire_binding(),
                        // @group(1) @binding(1) var<storage, read_write> dispatch_indirect_buffer
                        // : array<DispatchIndirectArgs>;
                        dispatch_indirect_buffer.as_entire_binding(),
                        // @group(1) @binding(2) var<storage, read_write> draw_indirect_buffer :
                        // array<u32>;
                        draw_indirect_buffer.as_entire_binding(),
                    )),
                ))
            }

            // Some buffer is not yet available, can't create the bind group
            _ => None,
        };

        // Create the @2 bind group for the indirect dispatch preparation pass of all
        // effects at once
        if effects_meta.indirect_spawner_bind_group.is_none() {
            let bind_group = render_device.create_bind_group(
                "hanabi:bg:vfx_indirect:spawner@2",
                &pipeline_cache.get_bind_group_layout(
                    &dispatch_indirect_pipeline.spawner_bind_group_layout_desc,
                ),
                &BindGroupEntries::sequential((
                    // @group(2) @binding(0) var<storage, read> spawner_buffer : array<Spawner>;
                    spawner_buffer.as_entire_binding(),
                    // @group(2) @binding(1) var<storage, read_write> prefix_sum : array<u32>;
                    prefix_sum_buffer.as_entire_binding(),
                )),
            );

            effects_meta.indirect_spawner_bind_group = Some(bind_group);
        }

        // Create the @0 bind group for the prefix sum pass of all batches at once
        if effects_meta.prefix_sum_bind_group.is_none() {
            effects_meta.prefix_sum_bind_group = Some(render_device.create_bind_group(
                "hanabi:bind_group:vfx_prefix_sum:@0",
                &pipeline_cache.get_bind_group_layout(&prefix_sum_pipeline.bind_group_layout_desc),
                &BindGroupEntries::sequential((
                    // @group(0) @binding(0) var<storage, read> batch_infos :
                    // array<BatchInfo>;
                    batch_info_buffer.as_entire_binding(),
                    // @group(0) @binding(1) var<storage, read_write> prefix_sum :
                    // array<u32>;
                    prefix_sum_buffer.as_entire_binding(),
                    // @group(0) @binding(2) var<storage, read_write>
                    // dispatch_indirect_buffer : array<DispatchIndirectArgs>;
                    dispatch_indirect_buffer.as_entire_binding(),
                )),
            ));
        }
    }

    // Create the per-slab bind groups
    trace!("Create per-slab bind groups...");
    for (slab_index, particle_slab) in effect_cache.slabs().iter().enumerate() {
        #[cfg(feature = "trace")]
        let _span_buffer = bevy::log::info_span!("create_buffer_bind_groups").entered();

        let Some(particle_slab) = particle_slab else {
            trace!(
                "Particle slab index #{} has no allocated EffectBuffer, skipped.",
                slab_index
            );
            continue;
        };

        // Ensure all effects in this batch have a bind group for the entire buffer of
        // the group, since the update phase runs on an entire group/buffer at once,
        // with all the effect instances in it batched together.
        trace!("effect particle slab_index=#{}", slab_index);
        effect_bind_groups
            .particle_slabs
            .entry(SlabId::new(slab_index as u32))
            .or_insert_with(|| {
                // Bind group particle@1 for render pass
                trace!("Creating particle@1 bind group for buffer #{slab_index} in render pass");
                let render = render_device.create_bind_group(
                    &format!("hanabi:bg:render:particles@1:vfx{slab_index}")[..],
                    particle_slab.render_particles_buffer_layout(),
                    &BindGroupEntries::sequential((
                        // @group(1) @binding(0) var<storage, read> particle_buffer :
                        // ParticleBuffer;
                        particle_slab.as_entire_binding_particle(),
                        // @group(1) @binding(1) var<storage, read> indirect_buffer :
                        // IndirectBuffer;
                        particle_slab.as_entire_binding_indirect(),
                    )),
                );

                BufferBindGroups { render }
            });
    }

    // Create bind groups for queued GPU buffer operations
    gpu_buffer_operation_queue.create_bind_groups(&render_device, utils_pipeline);

    // Create the per-effect-batch bind groups
    for effect_batch in sorted_effect_batched.iter() {
        #[cfg(feature = "trace")]
        let _span_buffer = bevy::log::info_span!("create_batch_bind_groups").entered();

        // Create the property bind group @2 if needed
        if let Some(property_key) = &effect_batch.property_key {
            if let Err(err) = property_bind_groups.ensure_exists(
                property_key,
                &property_cache,
                &spawner_buffer,
                &prefix_sum_buffer,
                &batch_info_buffer,
                &render_device,
                &pipeline_cache,
            ) {
                error!("Failed to create property bind group for effect batch: {err:?}");
                continue;
            }
        } else if let Err(err) = property_bind_groups.ensure_exists_no_property(
            &property_cache,
            &spawner_buffer,
            &prefix_sum_buffer,
            &batch_info_buffer,
            &render_device,
            &pipeline_cache,
        ) {
            error!("Failed to create property bind group for effect batch: {err:?}");
            continue;
        }

        // Bind group particle@1 for the simulate compute shaders (init and udpate) to
        // simulate particles.
        if effect_cache
            .create_particle_sim_bind_group(
                &effect_batch.slab_id,
                &render_device,
                effect_batch.particle_layout.min_binding_size32(),
                effect_batch.parent_min_binding_size,
                effect_batch.parent_binding_source.as_ref(),
                &pipeline_cache,
            )
            .is_err()
        {
            error!("No particle buffer allocated for effect batch.");
            continue;
        }

        // Bind group @3 of init pass
        // FIXME - this is instance-dependent, not buffer-dependent
        {
            let consume_gpu_spawn_events = effect_batch
                .layout_flags
                .contains(LayoutFlags::CONSUME_GPU_SPAWN_EVENTS);
            let consume_event_buffers = if let BatchSpawnInfo::GpuSpawner { .. } =
                effect_batch.spawn_info
            {
                assert!(consume_gpu_spawn_events);
                let cached_effect_events = effect_batch.cached_effect_events.as_ref().unwrap();
                Some(ConsumeEventBuffers {
                    child_infos_buffer: event_cache.child_infos_buffer().unwrap(),
                    events: BufferSlice {
                        buffer: event_cache
                            .get_buffer(cached_effect_events.buffer_index)
                            .unwrap(),
                        // Note: event range is in u32 count, not bytes
                        offset: cached_effect_events.range.start * 4,
                        size: NonZeroU32::new(cached_effect_events.range.len() as u32 * 4).unwrap(),
                    },
                })
            } else {
                assert!(!consume_gpu_spawn_events);
                None
            };
            let Some(init_metadata_layout_desc) =
                effect_cache.metadata_init_bind_group_layout_desc(consume_gpu_spawn_events)
            else {
                continue;
            };
            if effect_bind_groups
                .get_or_create_init_metadata(
                    effect_batch,
                    &render_device,
                    &pipeline_cache.get_bind_group_layout(init_metadata_layout_desc),
                    effects_meta.effect_metadata_buffer.buffer().unwrap(),
                    consume_event_buffers,
                )
                .is_err()
            {
                continue;
            }
        }

        // Bind group @3 of update pass
        // FIXME - this is instance-dependent, not buffer-dependent#
        {
            let num_event_buffers = effect_batch.child_event_buffers.len() as u32;

            let Some(update_metadata_layout_desc) =
                effect_cache.metadata_update_bind_group_layout_desc(num_event_buffers)
            else {
                continue;
            };
            if effect_bind_groups
                .get_or_create_update_metadata(
                    effect_batch,
                    &render_device,
                    &pipeline_cache.get_bind_group_layout(update_metadata_layout_desc),
                    effects_meta.effect_metadata_buffer.buffer().unwrap(),
                    event_cache.child_infos_buffer(),
                    &effect_batch.child_event_buffers[..],
                )
                .is_err()
            {
                continue;
            }
        }

        if effect_batch.layout_flags.contains(LayoutFlags::RIBBONS) {
            let effect_buffer = effect_cache.get_slab(&effect_batch.slab_id).unwrap();

            // Bind group @0 of sort-fill pass
            let particle_buffer = effect_buffer.particle_buffer();
            let indirect_index_buffer = effect_buffer.indirect_index_buffer();
            let effect_metadata_buffer = effects_meta.effect_metadata_buffer.buffer().unwrap();
            if let Err(err) = sort_bind_groups.ensure_sort_fill_bind_group(
                &effect_batch.particle_layout,
                particle_buffer,
                indirect_index_buffer,
                effect_metadata_buffer,
                &spawner_buffer,
                &pipeline_cache,
            ) {
                error!(
                    "Failed to create sort-fill bind group @0 for ribbon effect: {:?}",
                    err
                );
                continue;
            }

            // Bind group @0 of sort pass
            if let Err(err) = sort_bind_groups.ensure_sort_bind_group(&pipeline_cache) {
                error!(
                    "Failed to create sort bind group @0 for ribbon effect: {:?}",
                    err
                );
                continue;
            }

            // Bind group @0 of sort-copy pass
            let indirect_index_buffer = effect_buffer.indirect_index_buffer();
            if let Err(err) = sort_bind_groups.ensure_sort_copy_bind_group(
                indirect_index_buffer,
                effect_metadata_buffer,
                &spawner_buffer,
                &pipeline_cache,
            ) {
                error!(
                    "Failed to create sort-copy bind group @0 for ribbon effect: {:?}",
                    err
                );
                continue;
            }
        }

        // Ensure the particle texture(s) are available as GPU resources and that a bind
        // group for them exists
        // FIXME fix this insert+get below
        if !effect_batch.texture_layout.layout.is_empty() {
            // This should always be available, as this is cached into the render pipeline
            // just before we start specializing it.
            let Some(material_bind_group_layout_desc) =
                render_pipeline.get_material(&effect_batch.texture_layout)
            else {
                error!(
                    "Failed to find material bind group layout for particle slab #{}",
                    effect_batch.slab_id.index()
                );
                continue;
            };

            // TODO = move
            let material = Material {
                layout: effect_batch.texture_layout.clone(),
                textures: effect_batch.textures.iter().map(|h| h.id()).collect(),
            };
            assert_eq!(material.layout.layout.len(), material.textures.len());

            //let bind_group_entries = material.make_entries(&gpu_images).unwrap();
            let Ok(bind_group_entries) = material.make_entries(&gpu_images) else {
                trace!(
                    "Temporarily ignoring material {:?} due to missing image(s)",
                    material
                );
                continue;
            };

            effect_bind_groups
                .material_bind_groups
                .entry(material.clone())
                .or_insert_with(|| {
                    debug!("Creating material bind group for material {:?}", material);
                    render_device.create_bind_group(
                        &format!(
                            "hanabi:material_bind_group_{}",
                            material.layout.layout.len()
                        )[..],
                        &pipeline_cache.get_bind_group_layout(material_bind_group_layout_desc),
                        &bind_group_entries[..],
                    )
                });
        }
    }
}

type DrawEffectsSystemState = SystemState<(
    SRes<EffectsMeta>,
    SRes<EffectBindGroups>,
    SRes<PropertyBindGroups>,
    SRes<PipelineCache>,
    SRes<RenderAssets<RenderMesh>>,
    SRes<MeshAllocator>,
    SQuery<Read<ViewUniformOffset>>,
    SRes<SortedEffectBatches>,
    SQuery<Read<EffectDrawBatch>>,
)>;

/// Draw function for rendering all active effects for the current frame.
///
/// Effects are rendered in the [`Transparent2d`] phase of the main 2D pass,
/// and the [`Transparent3d`] phase of the main 3D pass.
pub(crate) struct DrawEffects {
    params: DrawEffectsSystemState,
}

impl DrawEffects {
    pub fn new(world: &mut World) -> Self {
        Self {
            params: SystemState::new(world),
        }
    }
}

/// Draw all particles of a single effect in view, in 2D or 3D.
///
/// FIXME: use pipeline ID to look up which group index it is.
fn draw<'w>(
    world: &'w World,
    pass: &mut TrackedRenderPass<'w>,
    view: Entity,
    entity: (Entity, MainEntity),
    pipeline_id: CachedRenderPipelineId,
    params: &mut DrawEffectsSystemState,
) {
    let (
        effects_meta,
        effect_bind_groups,
        property_bind_groups,
        pipeline_cache,
        meshes,
        mesh_allocator,
        views,
        sorted_effect_batches,
        effect_draw_batches,
    ) = params.get(world).unwrap();
    let view_uniform = views.get(view).unwrap();
    let effects_meta = effects_meta.into_inner();
    let effect_bind_groups = effect_bind_groups.into_inner();
    let property_bind_groups = property_bind_groups.into_inner();
    let meshes = meshes.into_inner();
    let mesh_allocator = mesh_allocator.into_inner();
    let effect_draw_batch = effect_draw_batches.get(entity.0).unwrap();
    let effect_batch = sorted_effect_batches
        .get(effect_draw_batch.effect_batch_index)
        .unwrap();

    let Some(pipeline) = pipeline_cache.into_inner().get_render_pipeline(pipeline_id) else {
        return;
    };

    trace!("render pass");

    pass.set_render_pipeline(pipeline);

    let Some(render_mesh): Option<&RenderMesh> = meshes.get(effect_batch.mesh) else {
        return;
    };
    let Some(vertex_buffer_slice) = mesh_allocator.mesh_vertex_slice(&effect_batch.mesh) else {
        return;
    };

    // Vertex buffer containing the particle model to draw. Generally a quad.
    // FIXME - need to upload "vertex_buffer_slice.range.start as i32" into
    // "base_vertex" in the indirect struct...
    pass.set_vertex_buffer(0, vertex_buffer_slice.buffer.slice(..));

    // View properties (camera matrix, etc.)
    pass.set_bind_group(
        0,
        effects_meta.view_bind_group.as_ref().unwrap(),
        &[view_uniform.offset],
    );

    // Particles buffer
    pass.set_bind_group(
        1,
        effect_bind_groups
            .particle_render(&effect_batch.slab_id)
            .unwrap(),
        &[],
    );

    //
    let batch_info_aligned_size = effects_meta.batch_info_buffer.aligned_size();
    let batch_info_offset = effect_batch.batch_info_id * batch_info_aligned_size as u32;
    pass.set_bind_group(
        2,
        property_bind_groups
            .get(effect_batch.property_key.as_ref())
            .unwrap(),
        &[batch_info_offset],
    );

    // Effect materials (textures and samplers)
    // TODO = move
    let material = Material {
        layout: effect_batch.texture_layout.clone(),
        textures: effect_batch.textures.iter().map(|h| h.id()).collect(),
    };
    if !effect_batch.texture_layout.layout.is_empty() {
        if let Some(bind_group) = effect_bind_groups.material_bind_groups.get(&material) {
            pass.set_bind_group(3, bind_group, &[]);
        } else {
            // Texture(s) not ready; skip this drawing for now
            trace!(
                "Particle material bind group not available for batch slab_id={}. Skipping draw call.",
                effect_batch.slab_id.index(),
            );
            return;
        }
    }

    let draw_indirect_index = effect_batch.draw_indirect_buffer_row_index.0;
    assert_eq!(GpuDrawIndexedIndirectArgs::SHADER_SIZE.get(), 20);
    let draw_indirect_offset =
        draw_indirect_index as u64 * GpuDrawIndexedIndirectArgs::SHADER_SIZE.get();
    trace!(
        "Draw up to {} particles with {} vertices per particle for batch from particle slab #{} \
            (effect_metadata_index={}, draw_indirect_offset={}B).",
        effect_batch.slice.len(),
        render_mesh.vertex_count,
        effect_batch.slab_id.index(),
        draw_indirect_index,
        draw_indirect_offset,
    );

    let Some(indirect_buffer) = effects_meta.draw_indirect_buffer.buffer() else {
        trace!(
            "The draw indirect buffer containing the indirect draw args is not ready for batch slab_id=#{}. Skipping draw call.",
            effect_batch.slab_id.index(),
        );
        return;
    };

    match render_mesh.buffer_info {
        RenderMeshBufferInfo::Indexed { index_format, .. } => {
            let Some(index_buffer_slice) = mesh_allocator.mesh_index_slice(&effect_batch.mesh)
            else {
                trace!(
                    "The index buffer for indexed rendering is not ready for batch slab_id=#{}. Skipping draw call.",
                    effect_batch.slab_id.index(),
                );
                return;
            };

            pass.set_index_buffer(index_buffer_slice.buffer.slice(..), index_format);
            pass.draw_indexed_indirect(indirect_buffer, draw_indirect_offset);
        }
        RenderMeshBufferInfo::NonIndexed => {
            pass.draw_indirect(indirect_buffer, draw_indirect_offset);
        }
    }
}

#[cfg(feature = "2d")]
impl Draw<Transparent2d> for DrawEffects {
    fn draw<'w>(
        &mut self,
        world: &'w World,
        pass: &mut TrackedRenderPass<'w>,
        view: Entity,
        item: &Transparent2d,
    ) -> Result<(), DrawError> {
        trace!("Draw<Transparent2d>: view={:?}", view);
        draw(
            world,
            pass,
            view,
            item.entity,
            item.pipeline,
            &mut self.params,
        );
        Ok(())
    }
}

#[cfg(feature = "3d")]
impl Draw<Transparent3d> for DrawEffects {
    fn draw<'w>(
        &mut self,
        world: &'w World,
        pass: &mut TrackedRenderPass<'w>,
        view: Entity,
        item: &Transparent3d,
    ) -> Result<(), DrawError> {
        trace!("Draw<Transparent3d>: view={:?}", view);
        draw(
            world,
            pass,
            view,
            item.entity,
            item.pipeline,
            &mut self.params,
        );
        Ok(())
    }
}

#[cfg(feature = "3d")]
impl Draw<AlphaMask3d> for DrawEffects {
    fn draw<'w>(
        &mut self,
        world: &'w World,
        pass: &mut TrackedRenderPass<'w>,
        view: Entity,
        item: &AlphaMask3d,
    ) -> Result<(), DrawError> {
        trace!("Draw<AlphaMask3d>: view={:?}", view);
        draw(
            world,
            pass,
            view,
            item.representative_entity,
            item.batch_set_key.pipeline,
            &mut self.params,
        );
        Ok(())
    }
}

#[cfg(feature = "3d")]
impl Draw<Opaque3d> for DrawEffects {
    fn draw<'w>(
        &mut self,
        world: &'w World,
        pass: &mut TrackedRenderPass<'w>,
        view: Entity,
        item: &Opaque3d,
    ) -> Result<(), DrawError> {
        trace!("Draw<Opaque3d>: view={:?}", view);
        draw(
            world,
            pass,
            view,
            item.representative_entity,
            item.batch_set_key.pipeline,
            &mut self.params,
        );
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum HanabiPipelineId {
    Invalid,
    Cached(CachedComputePipelineId),
}

#[derive(Debug)]
pub(crate) enum ComputePipelineError {
    Queued,
    Creating,
    Error,
}

impl From<&CachedPipelineState> for ComputePipelineError {
    fn from(value: &CachedPipelineState) -> Self {
        match value {
            CachedPipelineState::Queued => Self::Queued,
            CachedPipelineState::Creating(_) => Self::Creating,
            CachedPipelineState::Err(_) => Self::Error,
            _ => panic!("Trying to convert Ok state to error."),
        }
    }
}

pub(crate) struct HanabiComputePass<'a> {
    /// Pipeline cache to fetch cached compute pipelines by ID.
    pipeline_cache: &'a PipelineCache,
    /// WGPU compute pass.
    compute_pass: ComputePass<'a>,
    /// Current pipeline (cached).
    pipeline_id: HanabiPipelineId,
}

impl<'a> Deref for HanabiComputePass<'a> {
    type Target = ComputePass<'a>;

    fn deref(&self) -> &Self::Target {
        &self.compute_pass
    }
}

impl DerefMut for HanabiComputePass<'_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.compute_pass
    }
}

impl<'a> HanabiComputePass<'a> {
    pub fn new(pipeline_cache: &'a PipelineCache, compute_pass: ComputePass<'a>) -> Self {
        Self {
            pipeline_cache,
            compute_pass,
            pipeline_id: HanabiPipelineId::Invalid,
        }
    }

    pub fn set_cached_compute_pipeline(
        &mut self,
        pipeline_id: CachedComputePipelineId,
    ) -> Result<(), ComputePipelineError> {
        if HanabiPipelineId::Cached(pipeline_id) == self.pipeline_id {
            trace!("set_cached_compute_pipeline() id={pipeline_id:?} -> already set; skipped");
            return Ok(());
        }
        trace!("set_cached_compute_pipeline() id={pipeline_id:?}");
        let Some(pipeline) = self.pipeline_cache.get_compute_pipeline(pipeline_id) else {
            let state = self.pipeline_cache.get_compute_pipeline_state(pipeline_id);
            if let CachedPipelineState::Err(err) = state {
                error!(
                    "Failed to find compute pipeline #{}: {:?}",
                    pipeline_id.id(),
                    err
                );
            } else {
                debug!("Compute pipeline not ready #{}", pipeline_id.id());
            }
            return Err(state.into());
        };
        self.compute_pass.set_pipeline(pipeline);
        self.pipeline_id = HanabiPipelineId::Cached(pipeline_id);
        Ok(())
    }
}

fn begin_hanabi_compute_pass<'encoder>(
    label: &str,
    pipeline_cache: &'encoder PipelineCache,
    render_context: &'encoder mut RenderContext,
) -> HanabiComputePass<'encoder> {
    let compute_pass =
        render_context
            .command_encoder()
            .begin_compute_pass(&ComputePassDescriptor {
                label: Some(label),
                timestamp_writes: None,
            });
    HanabiComputePass::new(pipeline_cache, compute_pass)
}

fn simulate(
    mut render_context: RenderContext,
    pipeline_cache: Res<PipelineCache>,
    effects_meta: Res<EffectsMeta>,
    effect_bind_groups: Res<EffectBindGroups>,
    property_bind_groups: Res<PropertyBindGroups>,
    sort_bind_groups: Res<SortBindGroups>,
    utils_pipeline: Res<UtilsPipeline>,
    effect_cache: Res<EffectCache>,
    event_cache: Res<EventCache>,
    gpu_buffer_operations: Res<GpuBufferOperations>,
    sorted_effect_batches: Res<SortedEffectBatches>,
    init_fill_dispatch_queue: Res<InitFillDispatchQueue>,
) {
    trace!("simulate()");

    // Make sure to schedule any buffer copy before accessing their content later in
    // the GPU commands below.
    {
        let command_encoder = render_context.command_encoder();
        effects_meta
            .dispatch_indirect_buffer
            .write_buffers(command_encoder);
        effects_meta
            .draw_indirect_buffer
            .write_buffer(command_encoder);
        effects_meta
            .effect_metadata_buffer
            .write_buffer(command_encoder);
        event_cache.write_buffers(command_encoder);
        sort_bind_groups.write_buffers(command_encoder);
    }

    // Compute init fill dispatch pass - Fill the indirect dispatch structs for any
    // upcoming init pass of this frame, based on the GPU spawn events emitted by
    // the update pass of their parent effect during the previous frame.
    if let Some(queue_index) = init_fill_dispatch_queue.submitted_queue_index.as_ref() {
        gpu_buffer_operations.dispatch(
            *queue_index,
            &mut render_context,
            &utils_pipeline,
            Some("hanabi:init_indirect_fill_dispatch"),
        );
    }

    // If there's no batch, there's nothing more to do. Avoid continuing because
    // some GPU resources are missing, which is expected when there's no effect but
    // is an error (and will log warnings/errors) otherwise.
    if sorted_effect_batches.is_empty() {
        return;
    }

    // Validate that the main buffers and other core resources are available. Avoid
    // dispatching partial work if not all passes will complete, as this generally
    // desynchronizes the buffers.
    let (
        Some(_),
        true,
        Some(indirect_metadata_bind_group),
        Some(init_and_indirect_sim_params_bind_group),
        Some(indirect_spawner_bind_group),
    ) = (
        effects_meta.spawner_buffer.buffer(),
        !effects_meta.spawner_buffer.is_empty(),
        &effects_meta.indirect_metadata_bind_group,
        &effects_meta.init_and_indirect_sim_params_bind_group,
        &effects_meta.indirect_spawner_bind_group,
    )
    else {
        trace!("WARN - Some resource not ready, can't simulate this frame.");
        return;
    };
    let Some(prefix_sum_bind_group) = &effects_meta.prefix_sum_bind_group else {
        trace!("WARN - Prefix sum bind group not ready, can't simulate this frame.");
        return;
    };
    let Some(indirect_buffer) = effects_meta.dispatch_indirect_buffer.buffer() else {
        trace!("WARN - Missing indirect buffer for update pass, can't simulate this frame.");
        // FIXME - Bevy doesn't allow returning custom errors here...
        return;
    };

    // Compute init pass
    {
        trace!("init: loop over effect batches...");

        let mut compute_pass =
            begin_hanabi_compute_pass("hanabi:init", &pipeline_cache, &mut render_context);

        // Bind group simparams@0 is common to everything, only set once per init pass
        compute_pass.set_bind_group(
            0,
            effects_meta
                .init_and_indirect_sim_params_bind_group
                .as_ref()
                .unwrap(),
            &[],
        );

        // Dispatch init compute jobs for all batches
        for effect_batch in sorted_effect_batches.iter() {
            // Do not dispatch any init work if there's nothing to spawn this frame for the
            // batch. Note that this hopefully should have been skipped earlier.
            {
                let use_indirect_dispatch = effect_batch
                    .layout_flags
                    .contains(LayoutFlags::CONSUME_GPU_SPAWN_EVENTS);
                match effect_batch.spawn_info {
                    BatchSpawnInfo::CpuSpawner { total_spawn_count } => {
                        assert!(!use_indirect_dispatch);
                        if total_spawn_count == 0 {
                            continue;
                        }
                    }
                    BatchSpawnInfo::GpuSpawner { .. } => {
                        assert!(use_indirect_dispatch);
                    }
                }
            }

            // Fetch bind group particle@1
            let Some(particle_bind_group) =
                effect_cache.particle_sim_bind_group(&effect_batch.slab_id)
            else {
                error!(
                    "Failed to find init particle@1 bind group for slab #{}",
                    effect_batch.slab_id.index()
                );
                continue;
            };

            // Fetch bind group metadata@3
            let Some(metadata_bind_group) = effect_bind_groups
                .init_metadata_bind_groups
                .get(&effect_batch.slab_id)
            else {
                error!(
                    "Failed to find init metadata@3 bind group for slab #{}",
                    effect_batch.slab_id.index()
                );
                continue;
            };

            if compute_pass
                .set_cached_compute_pipeline(effect_batch.init_and_update_pipeline_ids.init)
                .is_err()
            {
                error!("Failed to set init pipeline");
                continue;
            }

            // Compute dynamic offsets
            let spawner_base = effect_batch.spawner_base;
            let spawner_aligned_size = effects_meta.spawner_buffer.aligned_size();
            debug_assert!(spawner_aligned_size >= GpuSpawnerParams::min_size().get() as usize);
            let spawner_offset = spawner_base * spawner_aligned_size as u32;
            let batch_info_aligned_size = effects_meta.batch_info_buffer.aligned_size();
            let batch_info_offset = effect_batch.batch_info_id * batch_info_aligned_size as u32;

            // Setup init pass
            compute_pass.set_bind_group(1, particle_bind_group, &[]);
            compute_pass.set_bind_group(
                2,
                property_bind_groups
                    .get(effect_batch.property_key.as_ref())
                    .unwrap(),
                &[batch_info_offset],
            );
            compute_pass.set_bind_group(3, &metadata_bind_group.bind_group, &[]);

            // Dispatch init job
            match effect_batch.spawn_info {
                // Indirect dispatch via GPU spawn events
                BatchSpawnInfo::GpuSpawner {
                    init_indirect_dispatch_index,
                    ..
                } => {
                    assert!(effect_batch
                        .layout_flags
                        .contains(LayoutFlags::CONSUME_GPU_SPAWN_EVENTS));

                    // Note: the indirect offset of a dispatch workgroup only needs
                    // 4-byte alignment
                    assert_eq!(GpuDispatchIndirectArgs::min_size().get(), 12);
                    let indirect_offset = init_indirect_dispatch_index as u64 * 12;

                    trace!(
                        "record commands for indirect init pipeline of effect {:?} \
                                init_indirect_dispatch_index={} \
                                indirect_offset={} \
                                spawner_base={} \
                                spawner_offset={} \
                                property_key={:?}...",
                        effect_batch.handle,
                        init_indirect_dispatch_index,
                        indirect_offset,
                        spawner_base,
                        spawner_offset,
                        effect_batch.property_key,
                    );

                    compute_pass.dispatch_workgroups_indirect(
                        event_cache.init_indirect_dispatch_buffer().unwrap(),
                        indirect_offset,
                    );
                }

                // Direct dispatch via CPU spawn count
                BatchSpawnInfo::CpuSpawner {
                    total_spawn_count: spawn_count,
                } => {
                    assert!(!effect_batch
                        .layout_flags
                        .contains(LayoutFlags::CONSUME_GPU_SPAWN_EVENTS));

                    const WORKGROUP_SIZE: u32 = 64;
                    let workgroup_count = spawn_count.div_ceil(WORKGROUP_SIZE);

                    trace!(
                        "record commands for init pipeline of effect {:?} \
                                (spawn {} particles => {} workgroups) spawner_base={} \
                                spawner_offset={} \
                                property_key={:?}...",
                        effect_batch.handle,
                        spawn_count,
                        workgroup_count,
                        spawner_base,
                        spawner_offset,
                        effect_batch.property_key,
                    );

                    compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
                }
            }

            trace!("init compute dispatched");
        }
    }

    // Indirect dispatch compute pass
    {
        // Only start a compute pass if there's an effect; makes things clearer in
        // debugger.
        let mut compute_pass = begin_hanabi_compute_pass(
            "hanabi:indirect_dispatch",
            &pipeline_cache,
            &mut render_context,
        );

        // Dispatch indirect dispatch compute job
        trace!("record commands for indirect dispatch pipeline...");

        let has_gpu_spawn_events = !event_cache.child_infos().is_empty();
        if has_gpu_spawn_events {
            if let Some(indirect_child_info_buffer_bind_group) =
                event_cache.indirect_child_info_buffer_bind_group()
            {
                assert!(has_gpu_spawn_events);
                compute_pass.set_bind_group(3, indirect_child_info_buffer_bind_group, &[]);
            } else {
                error!("Missing child_info_buffer@3 bind group for the vfx_indirect pass.");
                compute_pass.insert_debug_marker("ERROR:MissingIndirectBindGroup3");
                // FIXME - Bevy doesn't allow returning custom errors here...
                return;
            }
        }

        if compute_pass
            .set_cached_compute_pipeline(effects_meta.active_indirect_pipeline_id)
            .is_err()
        {
            compute_pass.insert_debug_marker("ERROR:FailedToSetIndirectComputePipeline");
            // FIXME - Bevy doesn't allow returning custom errors here...
            return;
        }

        //error!("FIXME - effect_metadata_buffer has gaps!!!! this won't work. len() is
        // the size exluding gaps!");
        const WORKGROUP_SIZE: u32 = 64;
        //let total_effect_count = effects_meta.effect_metadata_buffer.len();
        let total_effect_count = effects_meta.spawner_buffer.len() as u32;
        let workgroup_count = total_effect_count.div_ceil(WORKGROUP_SIZE);

        // Setup vfx_indirect pass
        compute_pass.set_bind_group(0, init_and_indirect_sim_params_bind_group, &[]);
        compute_pass.set_bind_group(1, indirect_metadata_bind_group, &[]);
        compute_pass.set_bind_group(2, indirect_spawner_bind_group, &[]);
        compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
        trace!(
            "indirect dispatch compute dispatched: total_effect_count={} workgroup_count={}",
            total_effect_count,
            workgroup_count
        );
    }

    // Update prefix sum compute pass
    //
    // Compute the prefix sum of alive particles before the update pass, so that we
    // can dispatch batches of effects in the update pass. The alive count is
    // copied into the prefix sum buffer during the indirect dispatch pass just
    // before.
    {
        // Only start a compute pass if there's an effect; makes things clearer in
        // debugger.
        let mut compute_pass = begin_hanabi_compute_pass(
            "hanabi:update_prefix_sum",
            &pipeline_cache,
            &mut render_context,
        );

        trace!("record commands for update prefix sum pipeline...");

        if compute_pass
            .set_cached_compute_pipeline(effects_meta.prefix_sum_pipeline_id)
            .is_err()
        {
            // FIXME - Bevy doesn't allow returning custom errors here...
            trace!("ERROR - Failed to set prefix sum compute pipeline. Simulation aborted.");
            return;
        }

        // Dispatch one thread per effect batch
        const WORKGROUP_SIZE: u32 = 64;
        let total_batch_count = effects_meta.batch_info_buffer.len() as u32;
        let workgroup_count = total_batch_count.div_ceil(WORKGROUP_SIZE);

        // Setup vfx_prefix_sum pass
        compute_pass.set_bind_group(0, prefix_sum_bind_group, &[]);
        compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
        trace!(
            "prefix sum dispatched: total_batch_count={} workgroup_count={}",
            total_batch_count,
            workgroup_count
        );
    }

    // Update compute pass
    //
    // Simulate all alive particles.
    let mut needs_sort = false;
    {
        let mut compute_pass =
            begin_hanabi_compute_pass("hanabi:update", &pipeline_cache, &mut render_context);

        // Bind group simparams@0 is common to everything, only set once per update pass
        compute_pass.set_bind_group(
            0,
            effects_meta.update_sim_params_bind_group.as_ref().unwrap(),
            &[],
        );

        // Dispatch update compute jobs
        for effect_batch in sorted_effect_batches.iter() {
            // Remember if we need to sort any effect, for next pass
            if effect_batch.layout_flags.contains(LayoutFlags::RIBBONS) {
                needs_sort = true;
            }

            // Fetch bind group particle@1
            let Some(particle_bind_group) =
                effect_cache.particle_sim_bind_group(&effect_batch.slab_id)
            else {
                error!(
                    "Failed to find update particle@1 bind group for slab #{}",
                    effect_batch.slab_id.index()
                );
                compute_pass.insert_debug_marker("ERROR:MissingParticleSimBindGroup");
                continue;
            };

            // Fetch bind group metadata@3
            let Some(metadata_bind_group) = effect_bind_groups
                .update_metadata_bind_groups
                .get(&effect_batch.slab_id)
            else {
                error!(
                    "Failed to find update metadata@3 bind group for slab #{}",
                    effect_batch.slab_id.index()
                );
                compute_pass.insert_debug_marker("ERROR:MissingMetadataBindGroup");
                continue;
            };

            // Fetch compute pipeline
            if let Err(err) = compute_pass
                .set_cached_compute_pipeline(effect_batch.init_and_update_pipeline_ids.update)
            {
                compute_pass.insert_debug_marker(&format!(
                    "ERROR:FailedToSetCachedUpdatePipeline:{:?}",
                    err
                ));
                continue;
            }

            // Compute dynamic offsets
            let batch_info_aligned_size = effects_meta.batch_info_buffer.aligned_size();
            let batch_info_offset = effect_batch.batch_info_id * batch_info_aligned_size as u32;
            trace!(
                    "record commands for update pipeline of effect {:?} spawner_base={} batch_info_id={} batch_info_offset={}B",
                    effect_batch.handle,
                    effect_batch.spawner_base,
                    effect_batch.batch_info_id,
                    batch_info_offset,
                );

            // Setup update pass
            compute_pass.set_bind_group(1, particle_bind_group, &[]);
            compute_pass.set_bind_group(
                2,
                property_bind_groups
                    .get(effect_batch.property_key.as_ref())
                    .unwrap(),
                &[batch_info_offset],
            );
            compute_pass.set_bind_group(3, &metadata_bind_group.bind_group, &[]);

            // Dispatch update job
            let dispatch_indirect_offset =
                effect_batch.batch_info_id * GpuDispatchIndirectArgs::SHADER_SIZE.get() as u32;
            trace!(
                "dispatch_workgroups_indirect: buffer={:?} offset={}B",
                indirect_buffer,
                dispatch_indirect_offset,
            );
            compute_pass
                .dispatch_workgroups_indirect(indirect_buffer, dispatch_indirect_offset as u64);

            trace!("update compute dispatched");
        }
    }

    // Do sorting for ribbons
    if needs_sort {
        // Copy alive counts for sort prefix sum compute pass
        //
        // After the update pass (atomically) updated the particle alive count per
        // effect instance, copy that number into the prefix sum buffer, so that
        // the prefix sum pass can calculate the prefix sum for sorting.
        // if let Some(queue_index) = sorted_effect_batches
        //     .sort_fill_prefix_sum_queue_index
        //     .as_ref()
        // {
        //     gpu_buffer_operations.dispatch(
        //         *queue_index,
        //         render_context,
        //         utils_pipeline,
        //         Some("hanabi:sort_fill_prefix_sum"),
        //     );
        // }

        // Sort prefix sum compute pass
        //
        // Calculate the prefix sum of the number of alive particles to sort.
        {
            // Only start a compute pass if there's an effect; makes things clearer in
            // debugger.
            let mut compute_pass = begin_hanabi_compute_pass(
                "hanabi:sort_prefix_sum",
                &pipeline_cache,
                &mut render_context,
            );

            trace!("record commands for sort prefix sum pass...");

            if compute_pass
                .set_cached_compute_pipeline(effects_meta.prefix_sum_pipeline_id)
                .is_err()
            {
                // FIXME - Bevy doesn't allow returning custom errors here...
                trace!("ERROR - Failed to set prefix sum compute pipeline. Simulation aborted.");
                return;
            }

            // Dispatch one thread per init effect batch.
            const WORKGROUP_SIZE: u32 = 64;
            // Note: This only works because we use the same batches for the init and update
            // passes. A priori there's no reason why we couldn't split them, since likely
            // the batches would be different.
            let total_batch_count = effects_meta.batch_info_buffer.len() as u32;
            let workgroup_count = total_batch_count.div_ceil(WORKGROUP_SIZE);

            // Setup vfx_prefix_sum pass
            compute_pass.set_bind_group(0, prefix_sum_bind_group, &[]);
            compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
            trace!(
                "prefix sum dispatched: total_batch_count={} workgroup_count={}",
                total_batch_count,
                workgroup_count
            );
        }

        // Compute sort fill dispatch pass - Fill the indirect dispatch structs for any
        // batch of particles which needs sorting, based on the actual number of alive
        // particles in the batch after their update in the compute update pass. Since
        // particles may die during update, this may be different from the number of
        // particles updated.
        if let Some(queue_index) = sorted_effect_batches.dispatch_queue_index.as_ref() {
            gpu_buffer_operations.dispatch(
                *queue_index,
                &mut render_context,
                &utils_pipeline,
                Some("hanabi:sort_fill_dispatch"),
            );
        }

        // Compute sort pass
        {
            let mut compute_pass =
                begin_hanabi_compute_pass("hanabi:sort", &pipeline_cache, &mut render_context);

            let effect_metadata_buffer = effects_meta.effect_metadata_buffer.buffer().unwrap();
            let indirect_buffer = sort_bind_groups.indirect_buffer().unwrap();

            // Loop on batches and find those which need sorting
            for effect_batch in sorted_effect_batches.iter() {
                trace!("Processing effect batch for sorting...");
                if !effect_batch.layout_flags.contains(LayoutFlags::RIBBONS) {
                    continue;
                }
                assert!(effect_batch.particle_layout.contains(Attribute::RIBBON_ID));
                assert!(effect_batch.particle_layout.contains(Attribute::AGE)); // or is that optional?

                let Some(effect_buffer) = effect_cache.get_slab(&effect_batch.slab_id) else {
                    warn!("Missing sort-fill effect buffer.");
                    // render_context
                    //     .command_encoder()
                    //     .insert_debug_marker("ERROR:MissingEffectBatchBuffer");
                    continue;
                };

                let indirect_dispatch_index = *effect_batch
                    .sort_fill_indirect_dispatch_index
                    .as_ref()
                    .unwrap();
                let indirect_offset =
                    sort_bind_groups.get_indirect_dispatch_byte_offset(indirect_dispatch_index);

                // Fill the sort buffer with the key-value pairs to sort
                {
                    compute_pass.push_debug_group("hanabi:sort_fill");

                    // Fetch compute pipeline
                    let Some(pipeline_id) =
                        sort_bind_groups.get_sort_fill_pipeline_id(&effect_batch.particle_layout)
                    else {
                        warn!("Missing sort-fill pipeline.");
                        compute_pass.insert_debug_marker("ERROR:MissingSortFillPipeline");
                        continue;
                    };
                    if compute_pass
                        .set_cached_compute_pipeline(pipeline_id)
                        .is_err()
                    {
                        compute_pass.insert_debug_marker("ERROR:FailedToSetSortFillPipeline");
                        compute_pass.pop_debug_group();
                        // FIXME - Bevy doesn't allow returning custom errors here...
                        return;
                    }

                    let spawner_base = effect_batch.spawner_base;
                    let spawner_aligned_size = effects_meta.spawner_buffer.aligned_size();
                    assert!(spawner_aligned_size >= GpuSpawnerParams::min_size().get() as usize);
                    let spawner_offset = spawner_base * spawner_aligned_size as u32;

                    // Bind group sort_fill@0
                    let particle_buffer = effect_buffer.particle_buffer();
                    let indirect_index_buffer = effect_buffer.indirect_index_buffer();
                    // Part of the bind group key; reallocates as effects grow.
                    let Some(spawner_buffer) = effects_meta.spawner_buffer.buffer() else {
                        warn!("Missing spawner buffer for sort-fill.");
                        compute_pass.insert_debug_marker("ERROR:MissingSortFillSpawnerBuffer");
                        continue;
                    };
                    let Some(bind_group) = sort_bind_groups.sort_fill_bind_group(
                        particle_buffer.id(),
                        indirect_index_buffer.id(),
                        effect_metadata_buffer.id(),
                        spawner_buffer.id(),
                    ) else {
                        warn!("Missing sort-fill bind group.");
                        compute_pass.insert_debug_marker("ERROR:MissingSortFillBindGroup");
                        continue;
                    };
                    let effect_metadata_offset = effects_meta
                        .gpu_limits
                        .effect_metadata_offset(effect_batch.metadata_table_id.0)
                        as u32;
                    compute_pass.set_bind_group(
                        0,
                        bind_group,
                        &[effect_metadata_offset, spawner_offset],
                    );

                    compute_pass
                        .dispatch_workgroups_indirect(indirect_buffer, indirect_offset as u64);
                    trace!("Dispatched sort-fill with indirect offset +{indirect_offset}");

                    compute_pass.pop_debug_group();
                }

                // Do the actual sort
                {
                    compute_pass.push_debug_group("hanabi:sort");

                    if compute_pass
                        .set_cached_compute_pipeline(sort_bind_groups.sort_pipeline_id())
                        .is_err()
                    {
                        compute_pass.insert_debug_marker("ERROR:FailedToSetSortPipeline");
                        compute_pass.pop_debug_group();
                        // FIXME - Bevy doesn't allow returning custom errors here...
                        return;
                    }

                    let Some(bind_group) = sort_bind_groups.sort_bind_group() else {
                        warn!("Missing sort bind group.");
                        compute_pass.insert_debug_marker("ERROR:MissingSortBindGroup");
                        continue;
                    };
                    compute_pass.set_bind_group(0, bind_group, &[]);
                    compute_pass
                        .dispatch_workgroups_indirect(indirect_buffer, indirect_offset as u64);
                    trace!("Dispatched sort with indirect offset +{indirect_offset}");

                    compute_pass.pop_debug_group();
                }

                // Copy the sorted particle indices back into the indirect index buffer, where
                // the render pass will read them.
                {
                    compute_pass.push_debug_group("hanabi:copy_sorted_indices");

                    // Fetch compute pipeline
                    let pipeline_id = sort_bind_groups.get_sort_copy_pipeline_id();
                    if compute_pass
                        .set_cached_compute_pipeline(pipeline_id)
                        .is_err()
                    {
                        compute_pass.insert_debug_marker("ERROR:FailedToSetSortCopyPipeline");
                        compute_pass.pop_debug_group();
                        // FIXME - Bevy doesn't allow returning custom errors here...
                        return;
                    }

                    let spawner_base = effect_batch.spawner_base;
                    let spawner_aligned_size = effects_meta.spawner_buffer.aligned_size();
                    assert!(spawner_aligned_size >= GpuSpawnerParams::min_size().get() as usize);
                    let spawner_offset = spawner_base * spawner_aligned_size as u32;

                    // Bind group sort_copy@0
                    let indirect_index_buffer = effect_buffer.indirect_index_buffer();
                    // Part of the bind group key; reallocates as effects grow.
                    let Some(spawner_buffer) = effects_meta.spawner_buffer.buffer() else {
                        warn!("Missing spawner buffer for sort-copy.");
                        compute_pass.insert_debug_marker("ERROR:MissingSortCopySpawnerBuffer");
                        continue;
                    };
                    let Some(bind_group) = sort_bind_groups.sort_copy_bind_group(
                        indirect_index_buffer.id(),
                        effect_metadata_buffer.id(),
                        spawner_buffer.id(),
                    ) else {
                        warn!("Missing sort-copy bind group.");
                        compute_pass.insert_debug_marker("ERROR:MissingSortCopyBindGroup");
                        continue;
                    };
                    let effect_metadata_offset = effects_meta
                        .effect_metadata_buffer
                        .dynamic_offset(effect_batch.metadata_table_id);
                    compute_pass.set_bind_group(
                        0,
                        bind_group,
                        &[effect_metadata_offset, spawner_offset],
                    );

                    compute_pass
                        .dispatch_workgroups_indirect(indirect_buffer, indirect_offset as u64);
                    trace!("Dispatched sort-copy with indirect offset +{indirect_offset}");

                    compute_pass.pop_debug_group();
                }
            }
        }
    }
}

impl From<LayoutFlags> for ParticleRenderAlphaMaskPipelineKey {
    fn from(layout_flags: LayoutFlags) -> Self {
        if layout_flags.contains(LayoutFlags::USE_ALPHA_MASK) {
            ParticleRenderAlphaMaskPipelineKey::AlphaMask
        } else if layout_flags.contains(LayoutFlags::OPAQUE) {
            ParticleRenderAlphaMaskPipelineKey::Opaque
        } else {
            ParticleRenderAlphaMaskPipelineKey::Blend
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn layout_flags() {
        let flags = LayoutFlags::default();
        assert_eq!(flags, LayoutFlags::NONE);
    }

    #[cfg(feature = "gpu_tests")]
    #[test]
    fn gpu_limits() {
        use crate::test_utils::MockRenderer;

        let renderer = MockRenderer::new();
        let device = renderer.device();
        let limits = GpuLimits::from_device(&device);

        // assert!(limits.storage_buffer_align().get() >= 1);
        assert!(limits.effect_metadata_offset(256) >= 256 * GpuEffectMetadata::min_size().get());
    }

    #[cfg(feature = "gpu_tests")]
    #[test]
    fn gpu_ops_ifda() {
        use crate::test_utils::MockRenderer;

        let renderer = MockRenderer::new();
        let device = renderer.device();
        let render_queue = renderer.queue();

        let mut world = World::new();
        world.insert_resource(device.clone());
        let mut buffer_ops = GpuBufferOperations::from_world(&mut world);

        let src_buffer = device.create_buffer(&BufferDescriptor {
            label: None,
            size: 256,
            usage: BufferUsages::STORAGE,
            mapped_at_creation: false,
        });
        let dst_buffer = device.create_buffer(&BufferDescriptor {
            label: None,
            size: 256,
            usage: BufferUsages::STORAGE,
            mapped_at_creation: false,
        });

        // Two consecutive ops can be merged. This includes having contiguous slices
        // both in source and destination.
        buffer_ops.begin_frame();
        {
            let mut q = InitFillDispatchQueue::default();
            q.enqueue(0, 0);
            assert_eq!(q.queue.len(), 1);
            q.enqueue(1, 1);
            // Ops are not batched yet
            assert_eq!(q.queue.len(), 2);
            // On submit, the ops get batched together
            q.submit(&src_buffer, &dst_buffer, &mut buffer_ops);
            assert_eq!(buffer_ops.args_buffer.len(), 1);
        }
        buffer_ops.end_frame(&device, &render_queue);

        // Even if out of order, the init fill dispatch ops are batchable. Here the
        // offsets are enqueued inverted.
        buffer_ops.begin_frame();
        {
            let mut q = InitFillDispatchQueue::default();
            q.enqueue(1, 1);
            assert_eq!(q.queue.len(), 1);
            q.enqueue(0, 0);
            // Ops are not batched yet
            assert_eq!(q.queue.len(), 2);
            // On submit, the ops get batched together
            q.submit(&src_buffer, &dst_buffer, &mut buffer_ops);
            assert_eq!(buffer_ops.args_buffer.len(), 1);
        }
        buffer_ops.end_frame(&device, &render_queue);

        // However, both the source and destination need to be contiguous at the same
        // time. Here they are mixed so we can't batch.
        buffer_ops.begin_frame();
        {
            let mut q = InitFillDispatchQueue::default();
            q.enqueue(0, 1);
            assert_eq!(q.queue.len(), 1);
            q.enqueue(1, 0);
            // Ops are not batched yet
            assert_eq!(q.queue.len(), 2);
            // On submit, the ops cannot get batched together
            q.submit(&src_buffer, &dst_buffer, &mut buffer_ops);
            assert_eq!(buffer_ops.args_buffer.len(), 2);
        }
        buffer_ops.end_frame(&device, &render_queue);
    }
}