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
//! The world store: entities, typed components, opaque (unknown) components and world resources.
//!
//! Deliberately small and deterministic. Every column keeps its entities in ascending order, so iteration order is a
//! function of the world's contents, never of hashing or insertion timing; writers that walk the world produce the
//! same bytes for the same world.
use std::any::{Any, TypeId};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::Arc;
use crate::json::JsonError;
/// An entity: a plain id. Ids are never reused within one world, so a stale id finds nothing rather than another
/// entity's components.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Entity(u32);
impl Entity {
/// The entity's index in creation order (serialisation uses it).
pub fn index(self) -> u32 {
self.0
}
/// The entity with this index. For readers of serialised worlds: an index the world never spawned finds nothing.
pub fn from_index(index: u32) -> Self {
Entity(index)
}
}
/// JSON (and any serde form) shows an entity as its index.
impl serde::Serialize for Entity {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_u32(self.0)
}
}
/// An index is meaningful only in the World it came from. Deserializing does not create
/// an entity or relocate references: an importer must preserve or remap that identity
/// before absorbing data into another World.
impl<'de> serde::Deserialize<'de> for Entity {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
<u32 as serde::Deserialize>::deserialize(d).map(Entity::from_index)
}
}
#[cfg(test)]
mod entity_json_tests {
use super::Entity;
#[test]
fn entity_index_roundtrips_without_accepting_other_json_shapes() {
for index in [0, u32::MAX] {
let entity = Entity::from_index(index);
let value = serde_json::to_value(entity).unwrap();
assert_eq!(value, serde_json::json!(index));
assert_eq!(serde_json::from_value::<Entity>(value).unwrap(), entity);
}
for value in [
serde_json::json!(-1),
serde_json::json!(4294967296u64),
serde_json::json!(1.5),
serde_json::json!("1"),
serde_json::Value::Null,
] {
assert!(serde_json::from_value::<Entity>(value).is_err());
}
}
}
impl fmt::Debug for Entity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "e{}", self.0)
}
}
/// A name the world cannot give to what is being inserted: it already belongs to something of another kind.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error(
"{name} is {held}: a name is a typed component's, an opaque component's or a resource's, one kind of them"
)]
pub struct NameClash {
pub name: String,
/// What holds it (`a typed component's name`).
pub held: &'static str,
}
/// An entity id a world cannot take.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum IdError {
#[error("entity {0:?} is not above every id already used")]
NotAscending(Entity),
#[error("entity {0:?} is the last id: the world cannot number another")]
Exhausted(Entity),
#[error("entity {0:?} is alive in this world already")]
Alive(Entity),
}
/// A typed component. `NAME` is namespaced and stable (`core.transform`, a destination's `material`, a source's
/// `layered_material`): serialisation, pass declarations and reports use it, so renaming one is a format change.
pub trait Component: Any + Clone + fmt::Debug + Send + Sync {
const NAME: &'static str;
/// Schema version of the component's content. Bump it when the meaning or layout of a field changes.
const VERSION: u32 = 1;
/// What the value holds of its entity's mesh primitives and vertices ([`Geometry`]). Stated by every component,
/// with no default, so data that describes a mesh can't be left behind by an edit of it unawares: the World's edit
/// paths take it from there.
const GEOMETRY: Geometry;
/// The component as JSON, for glTF extras, the debug text form and golden tests; `Ok(None)` for components
/// that are not shown (bulk data, handles). The view must never lose a value: components that can be shown
/// derive `serde::Serialize` and return `crate::json::to_value(self).map(Some)`, which refuses non-finite
/// floats instead of writing them as `null`.
fn to_json(&self) -> Result<Option<serde_json::Value>, JsonError> {
Ok(None)
}
/// The component's own invariants on entity `e` (indices in range, stream lengths equal, ...). The pass manager
/// runs it on every component after the reader, after every pass and before the writer, together with the
/// world's own check that every entity of [`Component::references`] is alive. World-wide rules (one name -> one
/// payload) are `pass::Validator`s instead.
fn verify(&self, _e: Entity, _w: &World) -> Result<(), String> {
Ok(())
}
/// The entities this component refers to (a prototype, materials, textures), appended to `out`: the edges
/// [`World::closure`] follows. A component holding entity references must declare every one of them.
fn references(&self, _out: &mut Vec<Entity>) {}
/// The bytes of bulk payload the value holds (vertex streams and indices, texture levels, triangle soups), for
/// memory reports: element counts times element sizes, not allocated capacity. 0 for small components.
fn payload_bytes(&self) -> u64 {
0
}
/// The component after its entity's mesh primitives were rebuilt, for a component that holds something per
/// primitive ([`Geometry::PerPrimitive`], [`Geometry::PerVertex`]): new primitive `i` comes from old primitive
/// `from[i]` (a source may repeat, when a primitive is split, or be absent, when one is dropped). Such a component
/// always answers (a value holding nothing per primitive answers with itself); `None`, the default, is for
/// components of [`Geometry::None`], and [`World::remap_primitives`] refuses a dependent component that gives it.
/// An index the component does not have is an error. [`remap_list`] does the work for a list with one entry per
/// primitive.
fn remap_primitives(&self, _from: &[usize]) -> Option<Result<Self, String>> {
None
}
/// The component after the vertices of its entity's mesh primitive `primitive` were compacted or reordered, for a
/// component that holds something per vertex ([`Geometry::PerVertex`]): new vertex `i` of that primitive is old
/// vertex `from[i]` (a source may repeat or be absent). Such a component always answers (with itself when it holds
/// nothing for that primitive); `None`, the default, is for the others, and [`World::remap_vertices`] refuses a
/// per-vertex component that gives it. An index the component does not have is an error. Every pass that compacts
/// or reorders a primitive's vertices calls [`World::remap_vertices`]. After a rebuild of the primitive list
/// ([`World::rebuild_primitives`], [`Component::remap_primitives`]) a primitive's per-vertex data is its source
/// primitive's, and the vertex map is relative to that source.
fn remap_vertices(&self, _primitive: usize, _from: &[u32]) -> Option<Result<Self, String>> {
None
}
/// The component after the vertices of its entity's mesh primitive `primitive` were rebuilt as blends of old ones
/// ([`VertexBlend`]), for a component that holds something per vertex ([`Geometry::PerVertex`]): new vertex `i`
/// is the combination `from[i]` of old vertices, in whatever way the component's data combines (a morph target's
/// delta is interpolated, the way the surface it moves is). It answers as [`Component::remap_vertices`] does: with
/// itself when it holds nothing for that primitive; `None`, the default, is for a component that does not know how
/// to combine its data, and [`World::blend_vertices`] refuses a per-vertex component that gives it. An index the
/// component does not have is an error. A vertex that is a copy of one old vertex ([`VertexBlend::copy`]) is the
/// case [`Component::remap_vertices`] states, and a component answering one answers the other alike.
fn blend_vertices(&self, _primitive: usize, _from: &[VertexBlend]) -> Option<Result<Self, String>> {
None
}
/// The component after its entity's local space was mapped by `l` (a pass that bakes a placement's mirror or
/// shear into a copy of its geometry, so transforms stay rigid). [`World::apply_linear`] calls it for every
/// component of the entity. The default is [`Linearity::Unsupported`]: a component that holds local-space
/// geometry and does not say how it follows is never silently left behind; one without geometry says
/// [`Linearity::Invariant`].
fn apply_linear(&self, _l: &crate::Linear) -> Linearity<Self> {
Linearity::Unsupported
}
/// The component after `resolve-state` ([`crate::state::ResolveState`]) gave the axes in `resolved` their values: a
/// component that holds [`crate::state::Clause`]s of its own (a record of parts each present in some states) reduces
/// them as `core.condition` is reduced ([`crate::state::Resolved::reduce`]: a clause that fails is dropped, a clause
/// left with no literal holds whatever the other axes are). [`Restated::Absent`] says the entity is not present in
/// this state (every clause failed): it is despawned as one whose `core.condition` fails is. The default holds no
/// clause: [`Restated::Unchanged`].
fn restate(&self, _resolved: &crate::state::Resolved<'_>) -> Restated<Self> {
Restated::Unchanged
}
}
/// What a component becomes when `resolve-state` resolves axes ([`Component::restate`]).
#[derive(Clone, Debug, PartialEq)]
pub enum Restated<T> {
/// It names no resolved axis: kept as it is.
Unchanged,
/// Its clauses reduced.
Replaced(T),
/// Nothing of it is present in the resolved state: its entity is not.
Absent,
}
/// What a component's value holds of its entity's mesh ([`Component::GEOMETRY`]): whether an edit of the primitives
/// or vertices must carry it along. A component holding geometry of its own (`core.mesh`, `core.mesh_file`, a source
/// model a reader keeps beside it) describes no other component's primitives: [`Geometry::None`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Geometry {
/// Nothing per primitive or vertex of its entity's mesh: kept as it is whatever an edit does to them.
None,
/// Something per primitive of its entity's mesh (a material per primitive, provenance per part): it implements
/// [`Component::remap_primitives`], goes with the mesh ([`World::remove_mesh`]), and an edit that rebuilds the
/// primitives refuses it when it does not answer.
PerPrimitive,
/// Something per vertex of its entity's mesh primitives (and so per primitive): as [`Geometry::PerPrimitive`], and
/// it implements [`Component::remap_vertices`] too.
PerVertex,
}
impl Geometry {
/// Whether the value describes its entity's mesh, so it goes when the mesh does.
pub fn describes_mesh(self) -> bool {
self != Geometry::None
}
}
/// What a component becomes when its entity's local space is mapped by a [`crate::Linear`]
/// ([`Component::apply_linear`]).
#[derive(Clone, Debug, PartialEq)]
pub enum Linearity<T> {
/// It holds no local-space geometry: kept as it is.
Invariant,
/// It holds geometry, mapped.
Applied(T),
/// What it says is no longer true of the mapped geometry (a file the geometry was read from): removed.
Drop,
/// It cannot follow: the entity is left as it was.
Unsupported,
}
/// `list` (one entry per primitive) for primitives rebuilt from `from` ([`Component::remap_primitives`]).
pub fn remap_list<T: Clone>(list: &[T], from: &[usize]) -> Result<Vec<T>, String> {
from.iter()
.map(|&i| {
list.get(i)
.cloned()
.ok_or_else(|| format!("primitive {i} of {}", list.len()))
})
.collect()
}
/// A new vertex of a triangle primitive made as a weighted combination of up to three old vertices of it (the corners
/// of the triangle it lies in): `sum weights[k] * old vertex sources[k]`, the weights non-negative and summing to 1. A
/// copy of one old vertex has weight 1 on it; unused entries have weight 0. See [`Component::blend_vertices`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VertexBlend {
pub sources: [u32; 3],
pub weights: [f32; 3],
}
impl VertexBlend {
/// The old vertex `v` itself.
pub fn copy(v: u32) -> VertexBlend {
VertexBlend {
sources: [v; 3],
weights: [1.0, 0.0, 0.0],
}
}
/// The old vertices with a weight above zero, with their weights, in order.
pub fn terms(&self) -> impl Iterator<Item = (u32, f32)> + '_ {
self.sources
.iter()
.copied()
.zip(self.weights)
.filter(|&(_, w)| w > 0.0)
}
}
/// A component's value rebuilt for blended vertices, not stored yet, with the column's type.
type Blended = (TypeId, Box<dyn Any + Send>);
/// A world resource: one value per world (the frame, a game's archive index, a run's options, the environment).
pub trait Resource: Any + Clone + fmt::Debug + Send + Sync {
const NAME: &'static str;
const VERSION: u32 = 1;
/// As [`Component::to_json`].
fn to_json(&self) -> Result<Option<serde_json::Value>, JsonError> {
Ok(None)
}
/// The resource's own invariants in `w`; as [`Component::verify`], run by the pass manager's verifier.
fn verify(&self, _w: &World) -> Result<(), String> {
Ok(())
}
/// The entities this resource refers to, appended to `out`. A resource holding entity references must declare
/// every one of them and implement [`Resource::retain_references`].
fn references(&self, _out: &mut Vec<Entity>) {}
/// Forget every reference to an entity `keep` refuses (set it to "none"). The world calls it whenever entities
/// leave it ([`World::despawn`], [`World::retain`], [`World::move_components`]) and on the copy a
/// [`World::subset`] or [`World::split_off`] part gets, so a resource never refers to an entity its world lacks.
fn retain_references(&mut self, _keep: &dyn Fn(Entity) -> bool) {}
}
/// One component (or resource) as JSON, with the schema version it is written with.
#[derive(Clone, Debug, PartialEq)]
pub struct ComponentJson<'w> {
pub name: &'w str,
pub version: u32,
/// `None`: no JSON view (opaque bytes, typed components that are not shown).
pub value: Option<serde_json::Value>,
}
/// A component whose JSON view would lose a value.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("{component}{}: {message}", entity.map(|e| format!(" on {e:?}")).unwrap_or_default())]
pub struct ComponentJsonError {
pub component: String,
/// `None` for a resource.
pub entity: Option<Entity>,
pub message: String,
}
/// The content of a component this build does not know: carried through reading and writing untouched.
#[derive(Clone, Debug, PartialEq)]
pub enum OpaqueData {
Json(serde_json::Value),
Bytes(Vec<u8>),
}
/// An opaque component value with the schema version it was written with.
#[derive(Clone, Debug, PartialEq)]
pub struct Opaque {
pub version: u32,
pub data: OpaqueData,
}
/// The storage of one component type: entity -> value, ordered by entity. Each value is a shared handle: a clone of the
/// column (of the world) shares every value with it, and writing a value that is shared copies it first, so neither side
/// sees the other's writes ([`Column::get_shared`]).
#[derive(Clone, Debug)]
pub struct Column<T> {
values: BTreeMap<Entity, Arc<T>>,
}
impl<T> Default for Column<T> {
fn default() -> Self {
Column {
values: BTreeMap::new(),
}
}
}
impl<T> Column<T> {
pub fn get(&self, e: Entity) -> Option<&T> {
self.values.get(&e).map(Arc::as_ref)
}
/// `e`'s value as a shared handle: the column's own, not a copy. A later write through the column copies the value
/// first, so the handle keeps what it was given.
pub fn get_shared(&self, e: Entity) -> Option<Arc<T>> {
self.values.get(&e).cloned()
}
pub fn contains(&self, e: Entity) -> bool {
self.values.contains_key(&e)
}
pub fn len(&self) -> usize {
self.values.len()
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
/// Entities and values in ascending entity order.
pub fn iter(&self) -> impl DoubleEndedIterator<Item = (Entity, &T)> + ExactSizeIterator {
self.values.iter().map(|(e, v)| (*e, v.as_ref()))
}
pub fn entities(&self) -> impl DoubleEndedIterator<Item = Entity> + ExactSizeIterator + '_ {
self.values.keys().copied()
}
/// `e`'s value taken out as the shared handle: the column's own, never a copy, whoever else shares it.
fn remove_shared(&mut self, e: Entity) -> Option<Arc<T>> {
self.values.remove(&e)
}
}
impl<T: Clone> Column<T> {
/// `e`'s value to write: a value another clone of the column still shares is copied first.
pub fn get_mut(&mut self, e: Entity) -> Option<&mut T> {
self.values.get_mut(&e).map(Arc::make_mut)
}
/// Every value to write, in ascending entity order: each one still shared is copied first.
pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = (Entity, &mut T)> + ExactSizeIterator {
self.values.iter_mut().map(|(e, v)| (*e, Arc::make_mut(v)))
}
fn insert(&mut self, e: Entity, value: T) -> Option<T> {
self.values.insert(e, Arc::new(value)).map(Arc::unwrap_or_clone)
}
/// The value taken out: the column's own where nothing else shares it, else a copy.
fn remove(&mut self, e: Entity) -> Option<T> {
self.remove_shared(e).map(Arc::unwrap_or_clone)
}
}
/// Type-erased operations the world needs on every column.
trait AnyColumn: Any + Send + Sync {
fn name(&self) -> &'static str;
fn len(&self) -> usize;
fn contains(&self, e: Entity) -> bool;
fn remove_entity(&mut self, e: Entity);
fn version(&self) -> u32;
fn geometry(&self) -> Geometry;
/// `None` when the entity has no such component; else its JSON view.
fn json(&self, e: Entity) -> Option<Result<Option<serde_json::Value>, JsonError>>;
/// Every value's `Component::verify`, and that each entity its `Component::references` names is alive, as
/// (entity, message) for those that fail, in entity order.
fn verify(&self, w: &World) -> Vec<(Entity, String)>;
/// Every value through `Debug`, in entity order.
fn visit_debug(&self, f: &mut dyn FnMut(Entity, &dyn fmt::Debug));
fn entities(&self) -> Vec<Entity>;
/// [`Component::references`] of entity `e`'s value, if it has one.
fn references(&self, e: Entity, out: &mut Vec<Entity>);
/// The sum of every value's [`Component::payload_bytes`].
fn payload_bytes(&self) -> u64;
fn clone_box(&self) -> Box<dyn AnyColumn>;
/// A copy holding only the values of `keep`.
fn subset_box(&self, keep: &BTreeSet<Entity>) -> Box<dyn AnyColumn>;
/// Drop the values of entities outside `keep`.
fn retain(&mut self, keep: &BTreeSet<Entity>);
/// Move the values of `keep` out into a column of their own.
fn split_off_box(&mut self, keep: &BTreeSet<Entity>) -> Box<dyn AnyColumn>;
/// Move every value of `other`, a column of the same type, in.
fn absorb(&mut self, other: Box<dyn AnyColumn>);
/// Move `from`'s value, if it has one, onto `to` (replacing `to`'s).
fn move_entity(&mut self, from: Entity, to: Entity);
/// `e`'s value remapped to rebuilt primitives ([`Component::remap_primitives`]), not stored yet; `None` when `e`
/// has none or it does not follow primitives.
fn remapped(&self, e: Entity, from: &[usize]) -> Option<Result<Box<dyn Any + Send>, String>>;
/// `e`'s value with primitive `primitive`'s vertices remapped ([`Component::remap_vertices`]), not stored yet;
/// `None` when `e` has none or it holds nothing per vertex of that primitive.
fn vertices_remapped(
&self,
e: Entity,
primitive: usize,
from: &[u32],
) -> Option<Result<Box<dyn Any + Send>, String>>;
/// `e`'s value with primitive `primitive`'s vertices rebuilt as blends ([`Component::blend_vertices`]), not stored
/// yet; `None` when `e` has none or it cannot combine its vertices.
fn vertices_blended(
&self,
e: Entity,
primitive: usize,
from: &[VertexBlend],
) -> Option<Result<Box<dyn Any + Send>, String>>;
/// Store a value [`AnyColumn::remapped`], [`AnyColumn::vertices_remapped`], [`AnyColumn::vertices_blended`] or
/// [`AnyColumn::linear`] made.
fn put_remapped(&mut self, e: Entity, value: Box<dyn Any + Send>);
/// A copy of `from`'s value, if it has one, onto `to`.
fn copy_entity(&mut self, from: Entity, to: Entity);
/// `e`'s value under [`Component::apply_linear`], not stored yet; `None` when `e` has none.
fn linear(&self, e: Entity, l: &crate::Linear) -> Option<Linearity<Box<dyn Any + Send>>>;
/// Every value restated ([`Component::restate`]) in place; the entities whose value says they are not present.
fn restate_all(&mut self, resolved: &crate::state::Resolved<'_>) -> Vec<Entity>;
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
}
impl<T: Component> AnyColumn for Column<T> {
fn name(&self) -> &'static str {
T::NAME
}
fn len(&self) -> usize {
self.values.len()
}
fn contains(&self, e: Entity) -> bool {
self.values.contains_key(&e)
}
fn remove_entity(&mut self, e: Entity) {
self.values.remove(&e);
}
fn version(&self) -> u32 {
T::VERSION
}
fn geometry(&self) -> Geometry {
T::GEOMETRY
}
fn json(&self, e: Entity) -> Option<Result<Option<serde_json::Value>, JsonError>> {
self.values.get(&e).map(|v| v.to_json())
}
fn verify(&self, w: &World) -> Vec<(Entity, String)> {
let mut out = Vec::new();
let mut refs = Vec::new();
for (e, v) in &self.values {
if let Err(m) = v.verify(*e, w) {
out.push((*e, m));
}
refs.clear();
v.references(&mut refs);
if let Some(r) = refs.iter().find(|r| !w.alive.contains(r)) {
out.push((*e, format!("refers to {r:?}, which is not alive")));
}
}
out
}
fn visit_debug(&self, f: &mut dyn FnMut(Entity, &dyn fmt::Debug)) {
for (e, v) in &self.values {
f(*e, v);
}
}
fn entities(&self) -> Vec<Entity> {
self.values.keys().copied().collect()
}
fn references(&self, e: Entity, out: &mut Vec<Entity>) {
if let Some(v) = self.values.get(&e) {
v.references(out);
}
}
fn payload_bytes(&self) -> u64 {
self.values.values().map(|v| v.payload_bytes()).sum()
}
fn clone_box(&self) -> Box<dyn AnyColumn> {
Box::new(self.clone())
}
fn subset_box(&self, keep: &BTreeSet<Entity>) -> Box<dyn AnyColumn> {
Box::new(Column {
values: subset_of(&self.values, keep),
})
}
fn retain(&mut self, keep: &BTreeSet<Entity>) {
self.values.retain(|e, _| keep.contains(e));
}
fn split_off_box(&mut self, keep: &BTreeSet<Entity>) -> Box<dyn AnyColumn> {
Box::new(Column {
values: keep
.iter()
.filter_map(|e| self.values.remove(e).map(|v| (*e, v)))
.collect(),
})
}
fn absorb(&mut self, mut other: Box<dyn AnyColumn>) {
let other = other
.as_any_mut()
.downcast_mut::<Column<T>>()
.expect("absorbing a column of the same type");
self.values.append(&mut other.values);
}
fn move_entity(&mut self, from: Entity, to: Entity) {
if let Some(v) = self.values.remove(&from) {
self.values.insert(to, v);
}
}
fn remapped(&self, e: Entity, from: &[usize]) -> Option<Result<Box<dyn Any + Send>, String>> {
let r = self.values.get(&e)?.remap_primitives(from)?;
Some(r.map(|v| Box::new(v) as Box<dyn Any + Send>))
}
fn vertices_remapped(
&self,
e: Entity,
primitive: usize,
from: &[u32],
) -> Option<Result<Box<dyn Any + Send>, String>> {
let r = self.values.get(&e)?.remap_vertices(primitive, from)?;
Some(r.map(|v| Box::new(v) as Box<dyn Any + Send>))
}
fn vertices_blended(
&self,
e: Entity,
primitive: usize,
from: &[VertexBlend],
) -> Option<Result<Box<dyn Any + Send>, String>> {
let r = self.values.get(&e)?.blend_vertices(primitive, from)?;
Some(r.map(|v| Box::new(v) as Box<dyn Any + Send>))
}
fn put_remapped(&mut self, e: Entity, value: Box<dyn Any + Send>) {
let v = *(value as Box<dyn Any>)
.downcast::<T>()
.expect("a value remapped by this column");
self.values.insert(e, Arc::new(v));
}
fn copy_entity(&mut self, from: Entity, to: Entity) {
if let Some(v) = self.values.get(&from).cloned() {
self.values.insert(to, v);
}
}
fn linear(&self, e: Entity, l: &crate::Linear) -> Option<Linearity<Box<dyn Any + Send>>> {
Some(match self.values.get(&e)?.apply_linear(l) {
Linearity::Invariant => Linearity::Invariant,
Linearity::Applied(v) => Linearity::Applied(Box::new(v) as Box<dyn Any + Send>),
Linearity::Drop => Linearity::Drop,
Linearity::Unsupported => Linearity::Unsupported,
})
}
fn restate_all(&mut self, resolved: &crate::state::Resolved<'_>) -> Vec<Entity> {
let mut absent = Vec::new();
for (e, v) in &mut self.values {
match v.restate(resolved) {
Restated::Unchanged => {}
Restated::Replaced(restated) => *v = Arc::new(restated),
Restated::Absent => absent.push(*e),
}
}
absent
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
/// The entries of `values` whose entity is in `keep`, walking the smaller of the two.
fn subset_of<T: Clone>(values: &BTreeMap<Entity, T>, keep: &BTreeSet<Entity>) -> BTreeMap<Entity, T> {
if keep.len() < values.len() {
keep.iter()
.filter_map(|e| values.get(e).map(|v| (*e, v.clone())))
.collect()
} else {
values
.iter()
.filter(|(e, _)| keep.contains(e))
.map(|(e, v)| (*e, v.clone()))
.collect()
}
}
trait AnyResource: Any + Send + Sync {
fn name(&self) -> &'static str;
fn version(&self) -> u32;
fn json(&self) -> Result<Option<serde_json::Value>, JsonError>;
fn debug(&self) -> &dyn fmt::Debug;
fn verify(&self, w: &World) -> Result<(), String>;
fn references(&self, out: &mut Vec<Entity>);
/// Forget the references `keep` refuses; the first one still held afterwards, if any (the resource broke its
/// contract).
fn retain_references(&mut self, keep: &dyn Fn(Entity) -> bool) -> Option<Entity>;
fn clone_box(&self) -> Box<dyn AnyResource>;
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
}
impl<T: Resource> AnyResource for T {
fn name(&self) -> &'static str {
T::NAME
}
fn version(&self) -> u32 {
T::VERSION
}
fn json(&self) -> Result<Option<serde_json::Value>, JsonError> {
self.to_json()
}
fn debug(&self) -> &dyn fmt::Debug {
self
}
fn verify(&self, w: &World) -> Result<(), String> {
Resource::verify(self, w)
}
fn references(&self, out: &mut Vec<Entity>) {
Resource::references(self, out);
}
fn retain_references(&mut self, keep: &dyn Fn(Entity) -> bool) -> Option<Entity> {
Resource::retain_references(self, keep);
let mut left = Vec::new();
Resource::references(self, &mut left);
left.into_iter().find(|&e| !keep(e))
}
fn clone_box(&self) -> Box<dyn AnyResource> {
Box::new(self.clone())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
/// Entities with their components, opaque components and resources.
#[derive(Default)]
pub struct World {
next: u32,
/// Alive entities. Despawned ids stay out forever.
alive: std::collections::BTreeSet<Entity>,
columns: BTreeMap<TypeId, Box<dyn AnyColumn>>,
/// Component name -> owning type, to refuse two Rust types claiming one name.
names: BTreeMap<&'static str, TypeId>,
opaque: BTreeMap<String, BTreeMap<Entity, Opaque>>,
resources: BTreeMap<TypeId, Box<dyn AnyResource>>,
opaque_resources: BTreeMap<String, Opaque>,
/// While a pass runs with conservation diagnostics on ([`crate::ledger`]): per entity whose primitives it rebuilt
/// ([`World::rebuild_primitives`]), the rebuilds composed; `None` for an entity whose mesh was also replaced another
/// way in between (counted net).
rebuilds: Option<RebuildLog>,
/// While a pass runs ([`World::start_effects`]): what it did that the pass manager can't see by comparing the world
/// before and after (resources written in place or replaced, entities filled by copying another).
effects: Option<Effects>,
/// What entities leaving dropped to keep the world whole ([`World::retain`], [`World::despawn`],
/// [`World::move_components`]), until [`World::take_dropped`]: the pass manager counts it in the log of the pass
/// that made it.
dropped: Dropped,
}
/// What a world dropped to stay whole when entities left it: the render graph's steps that drew with an entity that
/// left ([`crate::render_graph::RenderGraph::retain_steps`]), and the step bindings and step draws that named the
/// draws only those steps made ([`crate::StepBindings`], [`crate::StepDraws`]), which would name draws the graph no
/// longer has.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Dropped {
pub graph: crate::render_graph::StepsDropped,
/// (material, draw), for each draw a material's step bindings named.
pub step_bindings: Vec<(Entity, String)>,
/// (placement, draw), for each draw a placement's step draws named.
pub step_draws: Vec<(Entity, String)>,
}
impl Dropped {
pub fn is_empty(&self) -> bool {
self.graph.is_empty() && self.step_bindings.is_empty() && self.step_draws.is_empty()
}
fn append(&mut self, mut other: Dropped) {
self.graph.steps.append(&mut other.graph.steps);
self.graph.lighting |= other.graph.lighting;
self.graph.picture |= other.graph.picture;
self.step_bindings.append(&mut other.step_bindings);
self.step_draws.append(&mut other.step_draws);
}
}
impl fmt::Display for Dropped {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut parts = Vec::new();
if !self.graph.steps.is_empty() {
let steps: Vec<String> = self
.graph
.steps
.iter()
.map(|(name, gone)| format!("{name} (drew with {gone:?})"))
.collect();
parts.push(format!("render graph steps {}", steps.join(", ")));
}
if self.graph.lighting {
parts.push("the render graph's lighting pipeline".to_owned());
}
if self.graph.picture {
parts.push("the render graph's picture".to_owned());
}
for (what, list) in [
("step bindings", &self.step_bindings),
("step draws", &self.step_draws),
] {
if !list.is_empty() {
let named: Vec<String> = list.iter().map(|(e, draw)| format!("{e:?} {draw}")).collect();
parts.push(format!("{what} {}", named.join(", ")));
}
}
write!(f, "{}", parts.join("; "))
}
}
/// Entities taken from a world into one of their own ([`World::part`], [`World::split_part`]), and what that world
/// dropped to stay whole.
#[derive(Debug)]
pub struct Part {
pub world: World,
pub dropped: Dropped,
}
/// What a pass did to a world that a before/after comparison of names doesn't show ([`World::start_effects`]).
#[derive(Clone, Debug, Default)]
pub(crate) struct Effects {
/// Resources it replaced or borrowed mutably (an existing one written, or written in place), by name.
pub(crate) resources_written: BTreeSet<String>,
/// Resources it took away ([`World::remove_resource`]), by name: one the world holds again afterwards was
/// replaced, a write as much as [`World::insert_resource`] over it.
pub(crate) resources_removed: BTreeSet<String>,
/// Copies it made: (source, target) for each [`World::duplicate`] and [`World::copy_components`]. An exemption,
/// not a check: a name a copy puts on its target is the source's, so it counts as no addition.
pub(crate) copies: Vec<(Entity, Entity)>,
/// What entities leaving made the world drop to stay whole ([`World::take_dropped`]): an exemption as copies are,
/// the step bindings and step draws it took counted in the pass's log, not declared by the pass.
pub(crate) dropped: Dropped,
}
/// The primitive rebuilds a pass made, per entity; `None` when its mesh was also replaced another way between two of
/// them.
pub(crate) type RebuildLog = BTreeMap<Entity, Option<Rebuilt>>;
/// One mesh's rebuilds in a pass, composed.
#[derive(Clone, Debug)]
pub(crate) struct Rebuilt {
/// The mesh the first rebuild started from ([`crate::Mesh`]'s identity) and its primitive count.
pub(crate) source: u64,
pub(crate) first: usize,
/// For each primitive of the mesh the last rebuild made, the source primitive it comes from.
pub(crate) from: Vec<usize>,
/// The mesh the last rebuild made.
pub(crate) made: u64,
}
impl Clone for World {
fn clone(&self) -> Self {
World {
next: self.next,
alive: self.alive.clone(),
columns: self.columns.iter().map(|(k, v)| (*k, v.clone_box())).collect(),
names: self.names.clone(),
opaque: self.opaque.clone(),
resources: self.resources.iter().map(|(k, v)| (*k, v.clone_box())).collect(),
opaque_resources: self.opaque_resources.clone(),
rebuilds: None,
effects: None,
dropped: Dropped::default(),
}
}
}
impl fmt::Debug for World {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
for c in self.columns.values() {
counts.insert(c.name(), c.len());
}
for (name, col) in &self.opaque {
counts.insert(name, col.len());
}
f.debug_struct("World")
.field("entities", &self.alive.len())
.field("components", &counts)
.finish()
}
}
impl World {
pub fn new() -> Self {
Self::default()
}
/// Every resource, copied, with its references to entities outside `alive` forgotten, and what the render graph
/// dropped doing so. A resource that keeps one breaks the contract of [`Resource::retain_references`]: a bug,
/// refused here (a part would refer to an entity it lacks), in release as in debug.
fn resources_for(
&self,
alive: &BTreeSet<Entity>,
) -> (
BTreeMap<TypeId, Box<dyn AnyResource>>,
crate::render_graph::StepsDropped,
) {
let mut graph = crate::render_graph::StepsDropped::default();
let resources = self
.resources
.iter()
.map(|(k, v)| {
let mut r = v.clone_box();
if let Some(g) = r.as_any_mut().downcast_mut::<crate::render_graph::RenderGraph>() {
graph = g.retain_steps(&|e| alive.contains(&e));
}
if let Some(e) = r.retain_references(&|e| alive.contains(&e)) {
panic!(
"{} keeps a reference to {e:?}, which it was told to forget",
r.name()
);
}
(*k, r)
})
.collect();
(resources, graph)
}
/// The step bindings and step draws naming the draws of the render graph's steps that went, taken away
/// ([`crate::step_bindings::retain_made`]), with what the graph dropped: nothing where it dropped nothing.
fn reconcile(&mut self, graph: crate::render_graph::StepsDropped) -> Dropped {
if graph.is_empty() {
return Dropped::default();
}
Dropped {
graph,
..crate::step_bindings::retain_made(self)
}
}
/// What entities leaving dropped since the last call ([`World::retain`], [`World::despawn`],
/// [`World::move_components`]); a [`World::part`] states its own.
pub fn take_dropped(&mut self) -> Dropped {
std::mem::take(&mut self.dropped)
}
/// Every resource forgets its references to the entities `gone` accepts. A whole selection leaving
/// (`strict`: [`World::retain`]) checks the contract of [`Resource::retain_references`] in release too; one
/// entity leaving ([`World::despawn`], [`World::move_components`]) only in debug builds, where checking each would
/// cost a pass over every resource's references per entity (the verifier names a dangling reference either way).
/// The render graph's steps that drew with one of them go, and the step bindings and step draws naming their draws
/// with them (on entities still alive), recorded until [`World::take_dropped`].
fn forget_in_resources(&mut self, gone: impl Fn(Entity) -> bool, strict: bool) {
let graph = self
.resources
.get_mut(&TypeId::of::<crate::render_graph::RenderGraph>())
.and_then(|r| r.as_any_mut().downcast_mut::<crate::render_graph::RenderGraph>())
.map(|g| g.retain_steps(&|e| !gone(e)))
.unwrap_or_default();
for r in self.resources.values_mut() {
if let Some(e) = r.retain_references(&|e| !gone(e)) {
let broken = format!(
"{} keeps a reference to {e:?}, which it was told to forget",
r.name()
);
assert!(!strict, "{broken}");
debug_assert!(false, "{broken}");
}
}
let dropped = self.reconcile(graph);
self.dropped.append(dropped);
}
pub fn spawn(&mut self) -> Entity {
let e = Entity(self.next);
self.next = self.next.checked_add(1).expect("more than u32::MAX entities");
self.alive.insert(e);
e
}
/// Spawn with an explicit id, for readers of serialised worlds that keep the file's ids. Ids must come in
/// ascending order (gaps allowed), so ids stay unique: an id at or below one already handed out, or the last id
/// (there is none to follow it), is an error and changes nothing.
pub fn spawn_at(&mut self, e: Entity) -> Result<Entity, IdError> {
if e.0 < self.next {
return Err(IdError::NotAscending(e));
}
let next = e.0.checked_add(1).ok_or(IdError::Exhausted(e))?;
self.alive.insert(e);
self.next = next;
Ok(e)
}
/// Remove an entity and all its components. Returns false if it was not alive.
pub fn despawn(&mut self, e: Entity) -> bool {
if !self.alive.remove(&e) {
return false;
}
for c in self.columns.values_mut() {
c.remove_entity(e);
}
for col in self.opaque.values_mut() {
col.remove(&e);
}
self.forget_in_resources(|x| x == e, false);
true
}
/// Every component of `from`, typed and opaque, moved onto `to`, replacing `to`'s of the same name (`to` keeps
/// the others), then `from` despawned: for a pass that swaps one form of an entity for another without knowing
/// its components (`select-lod`). `Ok(false)`, and nothing changed, unless both are alive and differ.
///
/// Refused, changing nothing, when it would leave data describing one mesh beside another
/// ([`Component::GEOMETRY`]): `from` brings a mesh (`core.mesh` or `core.mesh_file`) while `to` keeps such data
/// `from` has none of (take `to`'s away first: [`World::remove_mesh`]), or `from` brings such data without a mesh
/// onto a `to` that has one.
pub fn move_components(&mut self, from: Entity, to: Entity) -> Result<bool, String> {
if from == to || !self.alive.contains(&from) || !self.alive.contains(&to) {
return Ok(false);
}
let has_mesh = |e| self.has::<crate::Mesh>(e) || self.has::<crate::MeshFile>(e);
let (from_mesh, to_mesh) = (has_mesh(from), has_mesh(to));
let mut stale: Vec<&'static str> = self
.columns
.values()
.filter(|c| c.geometry().describes_mesh())
.filter(|c| {
let (at_from, at_to) = (c.contains(from), c.contains(to));
(from_mesh && at_to && !at_from) || (!from_mesh && to_mesh && at_from)
})
.map(|c| c.name())
.collect();
if !stale.is_empty() {
stale.sort_unstable();
return Err(format!(
"moving {from:?} onto {to:?} would leave data describing one mesh beside another: {stale:?}"
));
}
for c in self.columns.values_mut() {
c.move_entity(from, to);
}
for col in self.opaque.values_mut() {
if let Some(v) = col.remove(&from) {
col.insert(to, v);
}
}
self.alive.remove(&from);
self.forget_in_resources(|x| x == from, false);
self.note_copy(from, to);
Ok(true)
}
/// A new entity with a copy of every typed and opaque component of `e`; `None` when `e` is not alive. Shallow:
/// references in the copies still name the entities `e`'s did (a pass that needs referenced entities copied too,
/// LOD forms of a prototype, copies them itself).
pub fn duplicate(&mut self, e: Entity) -> Option<Entity> {
if !self.is_alive(e) {
return None;
}
let d = self.spawn();
for c in self.columns.values_mut() {
c.copy_entity(e, d);
}
for values in self.opaque.values_mut() {
if let Some(v) = values.get(&e).cloned() {
values.insert(d, v);
}
}
self.note_copy(e, d);
Some(d)
}
/// Every typed component restated for the axes `resolved` gave values ([`Component::restate`]): the entities some
/// component says are not present in that state, sorted and without repeats, for the caller to remove. The values
/// of every other component are replaced in place. Opaque components hold no clause a pass could read.
pub fn restate_components(&mut self, resolved: &crate::state::Resolved<'_>) -> Vec<Entity> {
let mut absent: Vec<Entity> = self
.columns
.values_mut()
.flat_map(|c| c.restate_all(resolved))
.collect();
absent.sort();
absent.dedup();
absent
}
/// Map `e`'s local space by `l`: every component of `e` through [`Component::apply_linear`]. All or nothing:
/// when a component is [`Linearity::Unsupported`] (opaque components always are) nothing changes and the error
/// names every such component, sorted. Otherwise the names of the components it dropped ([`Linearity::Drop`]),
/// sorted.
pub fn apply_linear(&mut self, e: Entity, l: &crate::Linear) -> Result<Vec<String>, Vec<String>> {
let mut unsupported: Vec<String> = self
.opaque
.iter()
.filter(|(_, values)| values.contains_key(&e))
.map(|(name, _)| name.clone())
.collect();
let mut done = Vec::new();
for (id, c) in &self.columns {
match c.linear(e, l) {
None | Some(Linearity::Invariant) => {}
Some(Linearity::Unsupported) => unsupported.push(c.name().to_string()),
Some(r) => done.push((*id, r)),
}
}
if !unsupported.is_empty() {
unsupported.sort();
return Err(unsupported);
}
let mut dropped = Vec::new();
for (id, r) in done {
if let Some(c) = self.columns.get_mut(&id) {
match r {
Linearity::Applied(v) => c.put_remapped(e, v),
Linearity::Drop => {
c.remove_entity(e);
dropped.push(c.name().to_string());
}
Linearity::Invariant | Linearity::Unsupported => {}
}
}
}
dropped.sort();
Ok(dropped)
}
/// Keep `e`'s per-primitive components in step with its rebuilt mesh: every typed component that follows
/// primitives ([`Component::remap_primitives`]) remapped by `from` (new primitive `i` from old `from[i]`). A pass
/// that splits, reorders or drops a mesh's primitives calls it once, so it need not know the dialects' components.
/// All or nothing: an error (an index a component does not have, or a component refusing the mapping) names the
/// component and changes nothing.
///
/// An opaque component (bytes a reader carried without a type) can't follow: whether it describes primitives
/// can't be known, so a mapping that changes the list (anything but `0..n` in order) is refused while `e` has
/// one, before anything changes, naming them. The program removes them (a selection, reported) or gives them a
/// typed form first.
pub fn remap_primitives(&mut self, e: Entity, from: &[usize]) -> Result<(), String> {
let identity = from.iter().enumerate().all(|(i, &f)| i == f)
&& self
.get::<crate::Mesh>(e)
.is_none_or(|m| m.primitives().len() == from.len());
if !identity {
let mut opaque: Vec<&String> = self
.opaque
.iter()
.filter(|(_, values)| values.contains_key(&e))
.map(|(name, _)| name)
.collect();
if !opaque.is_empty() {
opaque.sort();
return Err(format!(
"{e:?}: opaque components can't follow a change to its primitives: {opaque:?} (remove them, or \
give them a typed form, before the pass)"
));
}
}
let mut done = Vec::new();
// by name, so the error reported is always the same one
let mut columns: Vec<_> = self.columns.iter().collect();
columns.sort_by_key(|(_, c)| c.name());
for (name, c) in columns {
match c.remapped(e, from) {
None if c.contains(e) && c.geometry().describes_mesh() => {
return Err(format!(
"{}: holds data per primitive ({:?}) but does not follow a change to them",
c.name(),
c.geometry()
));
}
None => {}
Some(Ok(v)) => done.push((*name, v)),
Some(Err(m)) => return Err(format!("{}: {m}", c.name())),
}
}
for (name, v) in done {
if let Some(c) = self.columns.get_mut(&name) {
c.put_remapped(e, v);
}
}
Ok(())
}
/// Remap every per-vertex component of `e` ([`Component::remap_vertices`]) for its mesh primitive `primitive`,
/// whose vertices a pass compacted or reordered: new vertex `i` is old vertex `from[i]`. The pass changes the
/// primitive itself and calls this for every other component, so it need not know the dialects' components; it
/// calls it only when the vertices changed. All or nothing: an error (an index a component does not have, or a
/// component refusing the mapping) names the component and changes nothing. Refused, changing nothing, while `e`
/// has an opaque component, as [`World::remap_primitives`] refuses then (whether it describes vertices can't be
/// known).
pub fn remap_vertices(&mut self, e: Entity, primitive: usize, from: &[u32]) -> Result<(), String> {
let done = self.vertex_remapped_components(e, primitive, from)?;
for (name, v) in done {
if let Some(c) = self.columns.get_mut(&name) {
c.put_remapped(e, v);
}
}
Ok(())
}
/// Why [`World::remap_vertices`] would refuse, without changing anything: a pass checks every entity before it
/// changes any.
pub fn check_remap_vertices(&self, e: Entity, primitive: usize, from: &[u32]) -> Result<(), String> {
self.vertex_remapped_components(e, primitive, from).map(|_| ())
}
fn vertex_remapped_components(
&self,
e: Entity,
primitive: usize,
from: &[u32],
) -> Result<Vec<Blended>, String> {
let mut opaque: Vec<&String> = self
.opaque
.iter()
.filter(|(_, values)| values.contains_key(&e))
.map(|(name, _)| name)
.collect();
if !opaque.is_empty() {
opaque.sort();
return Err(format!(
"{e:?}: opaque components can't follow a change to a primitive's vertices: {opaque:?} (remove them, \
or give them a typed form, before the pass)"
));
}
let mut done = Vec::new();
// by name, so the error reported is always the same one
let mut columns: Vec<_> = self.columns.iter().collect();
columns.sort_by_key(|(_, c)| c.name());
for (name, c) in columns {
match c.vertices_remapped(e, primitive, from) {
None if c.contains(e) && c.geometry() == Geometry::PerVertex => {
return Err(format!(
"{}: holds data per vertex but does not follow a change to them",
c.name()
));
}
None => {}
Some(Ok(v)) => done.push((*name, v)),
Some(Err(m)) => return Err(format!("{}: {m}", c.name())),
}
}
Ok(done)
}
/// Rebuild every per-vertex component of `e` ([`Component::blend_vertices`]) for its mesh primitive `primitive`,
/// whose vertices a pass made as blends of the old ones: new vertex `i` is `from[i]`. The pass changes the primitive
/// itself and calls this for every other component, so it need not know the dialects' components. All or nothing,
/// like [`World::remap_vertices`]: an error (an index a component does not have, a component that cannot combine
/// its vertices, an opaque component on `e`) names the cause and changes nothing.
pub fn blend_vertices(
&mut self,
e: Entity,
primitive: usize,
from: &[VertexBlend],
) -> Result<(), String> {
let done = self.blended_components(e, primitive, from)?;
for (name, v) in done {
if let Some(c) = self.columns.get_mut(&name) {
c.put_remapped(e, v);
}
}
Ok(())
}
/// Why [`World::blend_vertices`] would refuse, without changing anything: a pass checks every entity before it
/// changes any.
pub fn check_blend_vertices(
&self,
e: Entity,
primitive: usize,
from: &[VertexBlend],
) -> Result<(), String> {
self.blended_components(e, primitive, from).map(|_| ())
}
fn blended_components(
&self,
e: Entity,
primitive: usize,
from: &[VertexBlend],
) -> Result<Vec<Blended>, String> {
let mut opaque: Vec<&String> = self
.opaque
.iter()
.filter(|(_, values)| values.contains_key(&e))
.map(|(name, _)| name)
.collect();
if !opaque.is_empty() {
opaque.sort();
return Err(format!(
"{e:?}: opaque components can't follow a change to a primitive's vertices: {opaque:?} (remove them, \
or give them a typed form, before the pass)"
));
}
let mut done = Vec::new();
// by name, so the error reported is always the same one
let mut columns: Vec<_> = self.columns.iter().collect();
columns.sort_by_key(|(_, c)| c.name());
for (name, c) in columns {
match c.vertices_blended(e, primitive, from) {
None if c.contains(e) && c.geometry() == Geometry::PerVertex => {
return Err(format!(
"{}: holds data per vertex but cannot combine vertices (it has no blend_vertices)",
c.name()
));
}
None => {}
Some(Ok(v)) => done.push((*name, v)),
Some(Err(m)) => return Err(format!("{}: {m}", c.name())),
}
}
Ok(done)
}
/// Take `e`'s mesh away with every component describing it (each typed component whose [`Component::GEOMETRY`]
/// says it holds something per primitive or vertex) and its file link (`core.mesh_file`, which a load would restore it
/// from): for an entity left drawing nothing, whose per-primitive data would describe no primitive, or one whose
/// geometry another replaces (`select-lod`). A mesh still only in its file (`core.mesh_file` without `core.mesh`, as
/// a world is before its load) goes the same way, with the per-primitive data describing it. Returns the names
/// taken, the mesh's first; none when `e` has neither. Refused, changing nothing, while `e` has an opaque component
/// ([`World::check_remove_mesh`]).
pub fn remove_mesh(&mut self, e: Entity) -> Result<Vec<&'static str>, String> {
let mesh = self.has::<crate::Mesh>(e);
if !mesh && !self.has::<crate::MeshFile>(e) {
return Ok(Vec::new());
}
self.check_remove_mesh(e)?;
let mut names: Vec<&'static str> = mesh.then_some(crate::Mesh::NAME).into_iter().collect();
let mut per_primitive: Vec<(&'static str, TypeId)> = self
.columns
.iter()
.filter(|(_, c)| c.contains(e) && c.geometry().describes_mesh())
.map(|(k, c)| (c.name(), *k))
.collect();
per_primitive.sort();
for (name, k) in per_primitive {
if let Some(c) = self.columns.get_mut(&k) {
c.remove_entity(e);
}
names.push(name);
}
self.remove::<crate::Mesh>(e);
if self.remove::<crate::MeshFile>(e).is_some() {
names.push(crate::MeshFile::NAME);
}
Ok(names)
}
/// Why [`World::remove_mesh`] would refuse `e`, so a pass can check every entity before it changes any: an opaque
/// component on it, as [`World::remap_primitives`] refuses a change to the primitives then (whether it describes
/// primitives can't be known).
pub fn check_remove_mesh(&self, e: Entity) -> Result<(), String> {
let mut opaque: Vec<&String> = self
.opaque
.iter()
.filter(|(_, values)| values.contains_key(&e))
.map(|(name, _)| name)
.collect();
if opaque.is_empty() {
return Ok(());
}
opaque.sort();
Err(format!(
"{e:?}: opaque components can't follow its mesh's removal: {opaque:?} (remove them, or give them a typed \
form, before the pass)"
))
}
/// The names of `e`'s typed components that hold something per vertex of its mesh ([`Geometry::PerVertex`]), in
/// name order: what a pass that joins primitives into one (whose vertices a source primitive's per-vertex data
/// does not cover) must refuse, since [`Component::remap_vertices`] maps only one source primitive's vertices.
pub fn per_vertex_components(&self, e: Entity) -> Vec<&'static str> {
let mut names: Vec<&'static str> = self
.columns
.values()
.filter(|c| c.contains(e) && c.geometry() == Geometry::PerVertex)
.map(|c| c.name())
.collect();
names.sort_unstable();
names
}
/// Every component of `from`, typed and opaque, copied onto `to`, replacing `to`'s of the same name (`to` keeps
/// the others): for a pass that makes another entity like one it knows only partly (a prototype per tint row,
/// keeping whatever dialect data the reader attached). References are copied as they are. False, and nothing
/// changed, unless both are alive and differ.
pub fn copy_components(&mut self, from: Entity, to: Entity) -> bool {
if from == to || !self.alive.contains(&from) || !self.alive.contains(&to) {
return false;
}
for c in self.columns.values_mut() {
c.copy_entity(from, to);
}
for col in self.opaque.values_mut() {
if let Some(v) = col.get(&from).cloned() {
col.insert(to, v);
}
}
self.note_copy(from, to);
true
}
/// Rebuild `e`'s mesh primitives: `f` returns the new primitives and, for each, the old primitive it comes from (a
/// source may repeat or be absent, as for [`World::remap_primitives`]). The new mesh and every per-primitive
/// component change together, or, when `f` fails or a component cannot follow, nothing does. The one way to change
/// a mesh's primitive list.
pub fn rebuild_primitives(
&mut self,
e: Entity,
f: impl FnOnce(&crate::Mesh) -> Result<(Vec<crate::Primitive>, Vec<usize>), String>,
) -> Result<(), String> {
let mesh = self
.get::<crate::Mesh>(e)
.ok_or_else(|| format!("{e:?} has no core.mesh"))?;
let (primitives, from) = f(mesh)?;
if primitives.len() != from.len() {
return Err(format!(
"{} primitives with {} sources",
primitives.len(),
from.len()
));
}
let (old, source) = (mesh.primitives().len(), mesh.id());
if let Some(&i) = from.iter().find(|&&i| i >= old) {
return Err(format!("source primitive {i} of {old}"));
}
self.remap_primitives(e, &from)?;
let made = crate::Mesh::new(primitives);
self.record_rebuild(e, source, old, from, made.id());
self.insert(e, made);
Ok(())
}
/// Edit `e`'s mesh with `f`, which may also rebuild its primitive list: `f` returns `None` when the list keeps its
/// primitives in order (edited in place at most: the mesh stays the same mesh, whatever `f` built to hold them),
/// else, for each primitive now, the one it comes from, as
/// [`World::rebuild_primitives`] (per-primitive components follow, and the conservation diagnostics count the
/// rebuild exactly). False when `e` has no mesh.
///
/// All or nothing: when `f` fails, its mapping is malformed, or a per-primitive component can't follow it, the
/// mesh and its components are as they were (the mesh is kept while `f` runs, to put back), and the error says
/// why.
pub fn edit_mesh(
&mut self,
e: Entity,
f: impl FnOnce(&mut crate::Mesh) -> Result<Option<Vec<usize>>, String>,
) -> Result<bool, String> {
// the edit works on a copy: `e` keeps the original until the edit is accepted
let Some(mut mesh) = self.get::<crate::Mesh>(e).cloned() else {
return Ok(false);
};
let (old, source) = (mesh.primitives().len(), mesh.id());
let from = f(&mut mesh)?;
let Some(from) = from else {
let n = mesh.primitives().len();
if n != old {
return Err(format!("{e:?}: {n} primitives from {old} without their sources"));
}
// its primitives kept in order: the same mesh, even when `f` built a new one to hold them
mesh.keep_id(source);
self.insert(e, mesh);
return Ok(true);
};
if mesh.primitives().len() != from.len() || from.iter().any(|&i| i >= old) {
let n = mesh.primitives().len();
return Err(format!(
"{e:?}: {n} primitives with {} sources of {old}",
from.len()
));
}
// all or nothing: a component that can't follow leaves the components and the original mesh as they were
self.remap_primitives(e, &from)?;
let made = crate::Mesh::new(mesh.into_primitives());
self.record_rebuild(e, source, old, from, made.id());
self.insert(e, made);
Ok(true)
}
/// Record a rebuild of `e`'s mesh `source` (`old` primitives) into `made` for the conservation diagnostics, when
/// they run.
fn record_rebuild(&mut self, e: Entity, source: u64, old: usize, from: Vec<usize>, made: u64) {
if let Some(log) = &mut self.rebuilds {
match log.entry(e) {
std::collections::btree_map::Entry::Vacant(v) => {
v.insert(Some(Rebuilt {
source,
first: old,
from,
made,
}));
}
// compose with the earlier rebuild, unless this one starts from another mesh (replaced in between)
std::collections::btree_map::Entry::Occupied(mut o) => {
let composed = o.get_mut().take().filter(|r| r.made == source).map(|r| Rebuilt {
from: from.iter().map(|&i| r.from[i]).collect(),
made,
..r
});
*o.get_mut() = composed;
}
}
}
}
/// Start recording primitive rebuilds (the pass manager, around a pass with conservation diagnostics on).
/// Record, until [`World::take_effects`], the resources written and the copies made.
pub(crate) fn start_effects(&mut self) {
self.effects = Some(Effects::default());
}
/// Stop recording and return what was recorded since [`World::start_effects`].
pub(crate) fn take_effects(&mut self) -> Effects {
self.effects.take().unwrap_or_default()
}
fn note_resource_write(&mut self, name: &str) {
if let Some(fx) = &mut self.effects {
fx.resources_written.insert(name.to_owned());
}
}
fn note_copy(&mut self, from: Entity, to: Entity) {
if let Some(fx) = &mut self.effects {
fx.copies.push((from, to));
}
}
pub(crate) fn start_rebuild_log(&mut self) {
self.rebuilds = Some(BTreeMap::new());
}
/// Stop recording and return what was recorded since [`World::start_rebuild_log`].
pub(crate) fn take_rebuild_log(&mut self) -> RebuildLog {
self.rebuilds.take().unwrap_or_default()
}
pub fn is_alive(&self, e: Entity) -> bool {
self.alive.contains(&e)
}
/// The index the next spawned entity gets: an entity with an index at or above it was made after this call
/// (ids are handed out in order and never reused; a part loaded with [`World::subset`] keeps its planning world's,
/// so what a pass makes in it is told from what was loaded).
pub fn next_index(&self) -> u32 {
self.next
}
/// Reserve every index below `next` without creating entities. A freshly re-read subset that will be absorbed
/// into a newer World uses that World's `next_index`, so passes cannot reuse its other entities' ids.
/// Never rewinds the allocator or changes which entities are alive.
pub fn reserve_indices_before(&mut self, next: u32) {
self.next = self.next.max(next);
}
/// The entities `e`'s components refer to (not its resources'), in no particular order, repeats possible.
pub fn references(&self, e: Entity) -> Vec<Entity> {
let mut out = Vec::new();
for c in self.columns.values() {
c.references(e, &mut out);
}
out
}
/// The entities nothing in the world refers to (through any entity's components): its independent content,
/// placements, markers, standalone soups, rather than the prototypes, materials and textures they reach.
pub fn unreferenced(&self) -> BTreeSet<Entity> {
let mut referenced = BTreeSet::new();
for &e in &self.alive {
referenced.extend(self.references(e));
}
self.alive
.iter()
.copied()
.filter(|e| !referenced.contains(e))
.collect()
}
/// `roots` and every alive entity they reach through [`Component::references`], transitively. Opaque
/// components declare no references: an entity's opaque components travel with it in [`World::subset`], but
/// nothing they may name is followed.
pub fn closure(&self, roots: impl IntoIterator<Item = Entity>) -> BTreeSet<Entity> {
let mut seen = BTreeSet::new();
let mut todo: Vec<Entity> = roots.into_iter().collect();
let mut out = Vec::new();
while let Some(e) = todo.pop() {
if !self.alive.contains(&e) || !seen.insert(e) {
continue;
}
for c in self.columns.values() {
c.references(e, &mut out);
}
todo.append(&mut out);
}
seen
}
/// Every typed reference ([`Component::references`]) to an entity of `targets`: (component name, the entity holding
/// it, the entity referred to), sorted. Opaque components declare no references, as in [`World::closure`].
pub(crate) fn references_to(&self, targets: &BTreeSet<Entity>) -> Vec<(&'static str, Entity, Entity)> {
let mut edges = Vec::new();
let mut refs = Vec::new();
for c in self.columns.values() {
for source in c.entities() {
refs.clear();
c.references(source, &mut refs);
edges.extend(
refs.iter()
.filter(|r| targets.contains(r))
.map(|&target| (c.name(), source, target)),
);
}
}
edges.sort_unstable();
edges.dedup();
edges
}
/// A world of only `keep`'s entities (those alive) with all their components, typed and opaque, under the
/// same ids, and every resource (forgetting its references to entities left out). Entities spawned in it get ids
/// above every id of `self`.
///
/// For a selection that keeps everything the world's render graph draws with: one that leaves some of it out drops
/// what [`World::part`] states, and panics naming it (take that part with [`World::part`] and count it).
#[track_caller]
pub fn subset(&self, keep: &BTreeSet<Entity>) -> World {
let Part { world, dropped } = self.part(keep);
assert!(
dropped.is_empty(),
"World::subset left out what the render graph draws with, and dropped {dropped}: take the part with \
World::part and count what it drops"
);
world
}
/// [`World::subset`]'s world, and what it dropped to stay whole: the render graph's steps that drew with an entity
/// left out, and the step bindings and step draws naming draws only they made ([`Dropped`]).
pub fn part(&self, keep: &BTreeSet<Entity>) -> Part {
let alive: BTreeSet<Entity> = self.alive.intersection(keep).copied().collect();
let (resources, graph) = self.resources_for(&alive);
let mut world = World {
next: self.next,
resources,
alive,
columns: self
.columns
.iter()
.map(|(k, v)| (*k, v.subset_box(keep)))
.collect(),
names: self.names.clone(),
opaque: self
.opaque
.iter()
.map(|(k, v)| (k.clone(), subset_of(v, keep)))
.collect(),
opaque_resources: self.opaque_resources.clone(),
rebuilds: None,
effects: None,
dropped: Dropped::default(),
};
let dropped = world.reconcile(graph);
Part { world, dropped }
}
/// Move `keep`'s entities (those alive), with all their components, out into a world of their own: what
/// [`World::subset`] copies, without copying. The part has every resource (copied, as a subset's) and spawns ids
/// above every id of `self`, as a subset does; [`World::absorb`] moves it back. This world's resources keep their
/// references to the moved entities, which come back with the part.
///
/// A loss is data that leaves the world and does not arrive. The part's render graph is a copy, and this world
/// keeps every step: the steps pruned from the copy (they draw with entities the part lacks) are not a loss, and
/// [`World::split_part`] counts them. The step bindings and step draws stripped from the moved entities (they named
/// draws only those steps made) leave with the entities and do not come back on [`World::absorb`]: a loss, and
/// split_off panics naming it (take the part with [`World::split_part`] and count it).
#[track_caller]
pub fn split_off(&mut self, keep: &BTreeSet<Entity>) -> World {
let Part { world, dropped } = self.split_part(keep);
assert!(
dropped.step_bindings.is_empty() && dropped.step_draws.is_empty(),
"World::split_off stripped from the entities it moved what named the draws of render graph steps the part \
could not keep, and the part dropped {dropped}: take it with World::split_part and count what it drops"
);
world
}
/// [`World::split_off`]'s part, and what it dropped to stay whole ([`World::part`]). The render graph steps in it
/// are pruned from the part's copy (this world keeps them all): counted, not a loss. The step bindings and step
/// draws in it were stripped from the moved entities: a loss ([`World::split_off`]), since absorbed back the
/// entities hold none of them.
pub fn split_part(&mut self, keep: &BTreeSet<Entity>) -> Part {
let alive: BTreeSet<Entity> = self.alive.intersection(keep).copied().collect();
for e in &alive {
self.alive.remove(e);
}
let (resources, graph) = self.resources_for(&alive);
let mut world = World {
next: self.next,
columns: self
.columns
.iter_mut()
.map(|(k, v)| (*k, v.split_off_box(&alive)))
.collect(),
names: self.names.clone(),
opaque: self
.opaque
.iter_mut()
.map(|(k, v)| {
let part = alive
.iter()
.filter_map(|e| v.remove(e).map(|o| (*e, o)))
.collect();
(k.clone(), part)
})
.collect(),
resources,
alive,
opaque_resources: self.opaque_resources.clone(),
rebuilds: None,
effects: None,
dropped: Dropped::default(),
};
let dropped = world.reconcile(graph);
Part { world, dropped }
}
/// Move every entity of `part` (a [`World::split_off`] of this world) back in, with its components; `part`'s
/// resources are dropped. Ids the part spawned and despawned again were never alive here and are not reserved, so
/// a split, written and absorbed part leaves this world as it was. An entity of `part` that is alive here is an
/// error, and so is an id with none after it; either changes nothing.
pub fn absorb(&mut self, part: World) -> Result<(), IdError> {
if let Some(e) = part.alive.iter().find(|e| self.alive.contains(e)) {
return Err(IdError::Alive(*e));
}
// ids the part spawned and despawned again are not taken here: the next id stays this world's own,
// unless the part brings back an entity at or above it
let next = match part.alive.last() {
Some(last) => self
.next
.max(last.0.checked_add(1).ok_or(IdError::Exhausted(*last))?),
None => self.next,
};
self.next = next;
self.alive.extend(part.alive);
for (k, col) in part.columns {
match self.columns.get_mut(&k) {
Some(mine) => mine.absorb(col),
None => {
self.names.insert(col.name(), k);
self.columns.insert(k, col);
}
}
}
for (k, mut col) in part.opaque {
self.opaque.entry(k).or_default().append(&mut col);
}
Ok(())
}
/// Despawn every entity outside `keep`: in place, what [`World::subset`] copies.
pub fn retain(&mut self, keep: &BTreeSet<Entity>) {
self.alive.retain(|e| keep.contains(e));
self.forget_in_resources(|e| !keep.contains(&e), true);
for c in self.columns.values_mut() {
c.retain(keep);
}
for col in self.opaque.values_mut() {
col.retain(|e, _| keep.contains(e));
}
}
/// Alive entities in ascending order.
pub fn entities(&self) -> impl DoubleEndedIterator<Item = Entity> + '_ {
self.alive.iter().copied()
}
pub fn entity_count(&self) -> usize {
self.alive.len()
}
/// Give component type `T` its name in this world, or say what holds it: another type, a resource or an opaque
/// component (the same answer whichever came first).
fn claim<T: Component>(&mut self) -> Result<(), NameClash> {
let id = TypeId::of::<T>();
let clash = |held| NameClash {
name: T::NAME.to_owned(),
held,
};
match self.names.get(T::NAME) {
Some(&owner) if owner == id => return Ok(()),
Some(_) => return Err(clash("another component type's name")),
None => {}
}
if self.is_resource_name(T::NAME) {
return Err(clash("a resource's name"));
}
if self.opaque.contains_key(T::NAME) {
return Err(clash("an opaque component's name"));
}
self.names.insert(T::NAME, id);
Ok(())
}
fn column_for<T: Component>(&mut self) -> &mut Column<T> {
self.columns
.entry(TypeId::of::<T>())
.or_insert_with(|| Box::new(Column::<T>::default()))
.as_any_mut()
.downcast_mut::<Column<T>>()
.expect("column type matches its TypeId")
}
fn register<T: Component>(&mut self) -> &mut Column<T> {
if let Err(clash) = self.claim::<T>() {
panic!("{clash}");
}
self.column_for::<T>()
}
/// Attach (or replace) a component. Panics if the entity is not alive: attaching to a dead entity is a bug.
/// Replacing a value an entity keeps is an in-place edit to the pass manager, as through [`World::get_mut`]:
/// declared in [`crate::pass::Pass::modifies`], not checked.
pub fn insert<T: Component>(&mut self, e: Entity, value: T) -> Option<T> {
assert!(self.alive.contains(&e), "insert {} on dead entity {e:?}", T::NAME);
self.register::<T>().insert(e, value)
}
/// [`World::insert`] for a name that may be taken: a clash (another type, a resource or an opaque component holds
/// the name) is an error and changes nothing, whichever of the two came first. For a reader that puts what a file
/// names in the world; [`World::insert`] is for a name the program chose and a clash there is its bug.
pub fn try_insert<T: Component>(&mut self, e: Entity, value: T) -> Result<Option<T>, NameClash> {
assert!(self.alive.contains(&e), "insert {} on dead entity {e:?}", T::NAME);
self.claim::<T>()?;
Ok(self.column_for::<T>().insert(e, value))
}
pub fn remove<T: Component>(&mut self, e: Entity) -> Option<T> {
self.column_mut_existing::<T>()?.remove(e)
}
pub fn get<T: Component>(&self, e: Entity) -> Option<&T> {
self.column::<T>()?.get(e)
}
/// `e`'s `T` as a shared handle: the world's own value, not a copy ([`Column::get_shared`]). A later write to it
/// through the world copies it first, so the handle keeps what it was given; a holder that only reads (a renderer
/// uploading a texture) keeps the bytes without a second copy.
pub fn get_shared<T: Component>(&self, e: Entity) -> Option<Arc<T>> {
self.column::<T>()?.get_shared(e)
}
/// `e`'s `T` taken out as the shared handle: the world's own value, never a copy, where [`World::remove`] copies a
/// value something else still shares. For a holder of [`World::get_shared`] handles that takes over their keeping
/// (a renderer that releases a texture's levels once its image is on the GPU): the bytes go when the last handle does.
pub fn remove_shared<T: Component>(&mut self, e: Entity) -> Option<Arc<T>> {
self.column_mut_existing::<T>()?.remove_shared(e)
}
pub fn get_mut<T: Component>(&mut self, e: Entity) -> Option<&mut T> {
self.column_mut_existing::<T>()?.get_mut(e)
}
pub fn has<T: Component>(&self, e: Entity) -> bool {
self.column::<T>().is_some_and(|c| c.contains(e))
}
/// The column of `T`, if any entity ever had one.
pub fn column<T: Component>(&self) -> Option<&Column<T>> {
self.columns
.get(&TypeId::of::<T>())
.map(|c| c.as_any().downcast_ref().expect("column type"))
}
fn column_mut_existing<T: Component>(&mut self) -> Option<&mut Column<T>> {
self.columns
.get_mut(&TypeId::of::<T>())
.map(|c| c.as_any_mut().downcast_mut().expect("column type"))
}
/// Mutable access to the values of `T` (entities cannot be added or removed through it).
pub fn column_mut<T: Component>(&mut self) -> Option<ColumnMut<'_, T>> {
self.column_mut_existing::<T>().map(ColumnMut)
}
/// Two different columns at once, e.g. writing `B` while reading `A` of the same entities.
/// Panics if `A` and `B` are the same type.
pub fn columns2_mut<A: Component, B: Component>(
&mut self,
) -> (Option<ColumnMut<'_, A>>, Option<ColumnMut<'_, B>>) {
let (a, b) = (TypeId::of::<A>(), TypeId::of::<B>());
assert!(a != b, "columns2_mut needs two different component types");
let (mut ca, mut cb) = (None, None);
for (k, c) in &mut self.columns {
if *k == a {
ca = Some(c);
} else if *k == b {
cb = Some(c);
}
}
(
ca.map(|c| ColumnMut(c.as_any_mut().downcast_mut().expect("column type"))),
cb.map(|c| ColumnMut(c.as_any_mut().downcast_mut().expect("column type"))),
)
}
/// Entities with `T`, in ascending order.
pub fn iter<T: Component>(&self) -> impl DoubleEndedIterator<Item = (Entity, &T)> {
self.column::<T>().into_iter().flat_map(|c| c.iter())
}
/// Entities with both `A` and `B`, in ascending order.
pub fn iter2<A: Component, B: Component>(&self) -> impl Iterator<Item = (Entity, &A, &B)> {
let b = self.column::<B>();
self.iter::<A>()
.filter_map(move |(e, va)| Some((e, va, b?.get(e)?)))
}
/// Names of every component kind present (typed and opaque), sorted.
pub fn component_names(&self) -> Vec<&str> {
let mut names: Vec<&str> = self
.columns
.values()
.filter(|c| c.len() > 0)
.map(|c| c.name())
.collect();
names.extend(
self.opaque
.iter()
.filter(|(_, c)| !c.is_empty())
.map(|(n, _)| n.as_str()),
);
names.sort_unstable();
names.dedup();
names
}
/// Whether any entity has a component of this name (typed or opaque).
pub fn has_component_named(&self, name: &str) -> bool {
self.columns.values().any(|c| c.name() == name && c.len() > 0)
|| self.opaque.get(name).is_some_and(|c| !c.is_empty())
}
/// Entities that have a component of this name (typed or opaque), ascending.
pub fn entities_named(&self, name: &str) -> Vec<Entity> {
let mut out: Vec<Entity> = self
.columns
.values()
.filter(|c| c.name() == name)
.flat_map(|c| c.entities())
.collect();
if let Some(col) = self.opaque.get(name) {
out.extend(col.keys().copied());
}
out.sort_unstable();
out.dedup();
out
}
/// Every typed component's [`Component::verify`], and that each entity it refers to ([`Component::references`])
/// is alive: (component name, entity, message) for each failure, by name then entity.
pub fn verify_components(&self) -> Vec<(&'static str, Entity, String)> {
let mut out: Vec<(&'static str, Entity, String)> = self
.columns
.values()
.flat_map(|c| c.verify(self).into_iter().map(|(e, m)| (c.name(), e, m)))
.collect();
out.sort_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1)));
out
}
/// Every typed resource's [`Resource::verify`], and that each entity it refers to is alive: (resource name,
/// message) for each failure, by name.
pub fn verify_resources(&self) -> Vec<(&'static str, String)> {
let mut out = Vec::new();
let mut refs = Vec::new();
for r in self.resources.values() {
if let Err(m) = r.verify(self) {
out.push((r.name(), m));
}
refs.clear();
r.references(&mut refs);
if let Some(e) = refs.iter().find(|e| !self.alive.contains(e)) {
out.push((r.name(), format!("refers to {e:?}, which is not alive")));
}
}
out.sort();
out
}
/// Bulk payload bytes by component name, for the names that hold any: typed components'
/// [`Component::payload_bytes`] and opaque byte payloads.
pub fn payload_bytes(&self) -> BTreeMap<&str, u64> {
let mut out: BTreeMap<&str, u64> = BTreeMap::new();
for c in self.columns.values() {
let n = c.payload_bytes();
if n > 0 {
*out.entry(c.name()).or_default() += n;
}
}
for (name, col) in &self.opaque {
let n: u64 = col
.values()
.map(|o| match &o.data {
OpaqueData::Bytes(b) => b.len() as u64,
OpaqueData::Json(_) => 0,
})
.sum();
if n > 0 {
*out.entry(name.as_str()).or_default() += n;
}
}
out
}
/// Names of the components (typed and opaque) this entity has, sorted.
pub fn component_names_of(&self, e: Entity) -> Vec<&str> {
let mut names: Vec<&str> = self
.columns
.values()
.filter(|c| c.contains(e))
.map(|c| c.name())
.collect();
names.extend(
self.opaque
.iter()
.filter(|(_, c)| c.contains_key(&e))
.map(|(n, _)| n.as_str()),
);
names.sort_unstable();
names
}
/// Whether this entity has a component of this name (typed or opaque).
pub fn entity_has_named(&self, e: Entity, name: &str) -> bool {
self.columns.values().any(|c| c.name() == name && c.contains(e))
|| self.opaque.get(name).is_some_and(|c| c.contains_key(&e))
}
/// Every component of an entity as JSON, sorted by name: typed ones through [`Component::to_json`], opaque JSON
/// ones as they are. Components without a JSON view (opaque bytes, typed ones that are not shown) are listed with
/// `None`, so callers can count them.
///
/// Fails, naming the component and the entity, when a view would lose a value (a non-finite float).
pub fn components_json(&self, e: Entity) -> Result<Vec<ComponentJson<'_>>, ComponentJsonError> {
let mut out = Vec::new();
for c in self.columns.values() {
if let Some(v) = c.json(e) {
out.push(ComponentJson {
name: c.name(),
version: c.version(),
value: v.map_err(|err| ComponentJsonError {
component: c.name().to_owned(),
entity: Some(e),
message: err.0,
})?,
});
}
}
for (name, col) in &self.opaque {
if let Some(o) = col.get(&e) {
out.push(ComponentJson {
name: name.as_str(),
version: o.version,
value: opaque_json(o),
});
}
}
out.sort_by(|a, b| a.name.cmp(b.name));
Ok(out)
}
/// Every resource (typed and opaque) as JSON, sorted by name; as [`World::components_json`].
pub fn resources_json(&self) -> Result<Vec<ComponentJson<'_>>, ComponentJsonError> {
let mut out = Vec::new();
for r in self.resources.values() {
out.push(ComponentJson {
name: r.name(),
version: r.version(),
value: r.json().map_err(|err| ComponentJsonError {
component: r.name().to_owned(),
entity: None,
message: err.0,
})?,
});
}
for (name, o) in &self.opaque_resources {
out.push(ComponentJson {
name: name.as_str(),
version: o.version,
value: opaque_json(o),
});
}
out.sort_by(|a, b| a.name.cmp(b.name));
Ok(out)
}
/// Every component (typed and opaque) with its schema version, for debugging tools: `f(name, version, entity,
/// value)`, by name then entity. Values are shown through `Debug`, which is not a format: its text may change
/// between builds and toolchains, so nothing that is gated, cached or compared across builds may depend on it.
pub fn visit_components_debug(&self, f: &mut dyn FnMut(&str, u32, Entity, &dyn fmt::Debug)) {
enum Kind<'a> {
Typed(&'a dyn AnyColumn),
Opaque(&'a BTreeMap<Entity, Opaque>),
}
let mut kinds: Vec<(&str, Kind<'_>)> = self
.columns
.values()
.filter(|c| c.len() > 0)
.map(|c| (c.name(), Kind::Typed(c.as_ref())))
.collect();
kinds.extend(
self.opaque
.iter()
.filter(|(_, c)| !c.is_empty())
.map(|(n, c)| (n.as_str(), Kind::Opaque(c))),
);
// a name is typed or opaque, never both (each insert refuses the other kind's names)
kinds.sort_unstable_by_key(|(n, _)| *n);
for (name, kind) in kinds {
match kind {
Kind::Typed(c) => {
let version = c.version();
c.visit_debug(&mut |e, v| f(name, version, e, v));
}
Kind::Opaque(c) => {
for (e, o) in c {
f(name, o.version, *e, &o.data);
}
}
}
}
}
/// Every resource (typed and opaque) with its schema version, by name, through `Debug`; as
/// [`World::visit_components_debug`], for debugging tools only.
pub fn visit_resources_debug(&self, f: &mut dyn FnMut(&str, u32, &dyn fmt::Debug)) {
let mut all: Vec<(&str, u32, &dyn fmt::Debug)> = self
.resources
.values()
.map(|r| (r.name(), r.version(), r.debug()))
.collect();
all.extend(
self.opaque_resources
.iter()
.map(|(n, o)| (n.as_str(), o.version, &o.data as &dyn fmt::Debug)),
);
all.sort_unstable_by_key(|(n, _, _)| *n);
for (name, version, value) in all {
f(name, version, value);
}
}
// ---- opaque components -------------------------------------------------------------------------------------
/// Attach a component this build does not model. A name a typed component or a resource holds (in this world so
/// far) is an error and changes nothing: a reader that knows the type must decode it. A typed insert of a name
/// held here by an opaque component is refused the same way ([`World::try_insert`]).
pub fn insert_opaque(
&mut self,
e: Entity,
name: &str,
value: Opaque,
) -> Result<Option<Opaque>, NameClash> {
assert!(self.alive.contains(&e), "insert {name} on dead entity {e:?}");
let clash = |held| NameClash {
name: name.to_owned(),
held,
};
if self.names.contains_key(name) {
return Err(clash("a typed component's name (decode it instead)"));
}
if self.is_resource_name(name) {
return Err(clash("a resource's name"));
}
Ok(self.opaque.entry(name.to_owned()).or_default().insert(e, value))
}
pub fn get_opaque(&self, e: Entity, name: &str) -> Option<&Opaque> {
self.opaque.get(name)?.get(&e)
}
pub fn remove_opaque(&mut self, e: Entity, name: &str) -> Option<Opaque> {
self.opaque.get_mut(name)?.remove(&e)
}
/// Every opaque component kind with its values, by name then entity.
pub fn opaque_components(&self) -> impl Iterator<Item = (&str, &BTreeMap<Entity, Opaque>)> {
self.opaque.iter().map(|(n, c)| (n.as_str(), c))
}
// ---- resources ---------------------------------------------------------------------------------------------
/// Insert (or replace) a resource. Panics if a component has its name: a name is a component's or a resource's,
/// not both, so pass declarations, which list both, stay unambiguous. [`World::try_insert_resource`] refuses
/// instead.
pub fn insert_resource<T: Resource>(&mut self, value: T) -> Option<T> {
match self.try_insert_resource(value) {
Ok(old) => old,
Err(clash) => panic!("{clash}"),
}
}
/// [`World::insert_resource`] for a name that may be taken: a component's name is an error and changes nothing.
pub fn try_insert_resource<T: Resource>(&mut self, value: T) -> Result<Option<T>, NameClash> {
if self.is_component_name(T::NAME) {
return Err(NameClash {
name: T::NAME.to_owned(),
held: "a component's name",
});
}
let Some(old) = self.resources.insert(TypeId::of::<T>(), Box::new(value)) else {
return Ok(None);
};
self.note_resource_write(T::NAME);
let any: Box<dyn Any> = old;
Ok(any.downcast::<T>().ok().map(|b| *b))
}
pub fn resource<T: Resource>(&self) -> Option<&T> {
self.resources
.get(&TypeId::of::<T>())
.and_then(|r| r.as_any().downcast_ref())
}
/// Borrowed to write: a pass that does declares the name in [`crate::pass::Pass::modifies`].
pub fn resource_mut<T: Resource>(&mut self) -> Option<&mut T> {
if self.resources.contains_key(&TypeId::of::<T>()) {
self.note_resource_write(T::NAME);
}
self.resources
.get_mut(&TypeId::of::<T>())
.and_then(|r| r.as_any_mut().downcast_mut())
}
/// Lend resource `T` read-only to `f` while `f` changes the rest of the world, then put it back as it was: a
/// borrow, not a write, so the pass manager records none. `f` gets `None` when the world holds no `T`. Panics if
/// `f` puts a `T` of its own into the world while one is lent: the one lent is the one that goes back.
pub fn resource_scope<T: Resource, R>(&mut self, f: impl FnOnce(&mut World, Option<&T>) -> R) -> R {
let held = self.resources.remove(&TypeId::of::<T>());
let out = f(self, held.as_ref().and_then(|b| b.as_any().downcast_ref::<T>()));
if let Some(b) = held {
let replaced = self.resources.insert(TypeId::of::<T>(), b);
assert!(
replaced.is_none(),
"{} was inserted while lent by resource_scope",
T::NAME
);
}
out
}
pub fn remove_resource<T: Resource>(&mut self) -> Option<T> {
let old = self.resources.remove(&TypeId::of::<T>())?;
if let Some(fx) = &mut self.effects {
fx.resources_removed.insert(T::NAME.to_owned());
}
let any: Box<dyn Any> = old;
any.downcast::<T>().ok().map(|b| *b)
}
/// As [`World::try_insert_resource`], for a resource this build does not model: a component's name is an error.
pub fn insert_opaque_resource(&mut self, name: &str, value: Opaque) -> Result<Option<Opaque>, NameClash> {
if self.is_component_name(name) {
return Err(NameClash {
name: name.to_owned(),
held: "a component's name",
});
}
let old = self.opaque_resources.insert(name.to_owned(), value);
if old.is_some() {
self.note_resource_write(name);
}
Ok(old)
}
/// Names of every resource (typed and opaque), sorted.
pub fn resource_names(&self) -> Vec<&str> {
let mut names: Vec<&str> = self
.resources
.values()
.map(|r| r.name())
.chain(self.opaque_resources.keys().map(String::as_str))
.collect();
names.sort_unstable();
names.dedup();
names
}
fn is_resource_name(&self, name: &str) -> bool {
self.resources.values().any(|r| r.name() == name) || self.opaque_resources.contains_key(name)
}
/// A component type or an opaque component has ever been stored under `name`.
fn is_component_name(&self, name: &str) -> bool {
self.names.contains_key(name) || self.opaque.contains_key(name)
}
pub fn opaque_resources(&self) -> impl Iterator<Item = (&str, &Opaque)> {
self.opaque_resources.iter().map(|(n, v)| (n.as_str(), v))
}
}
fn opaque_json(o: &Opaque) -> Option<serde_json::Value> {
match &o.data {
OpaqueData::Json(v) => Some(v.clone()),
OpaqueData::Bytes(_) => None,
}
}
/// Mutable access to one column's values without changing which entities it holds.
#[derive(Debug)]
pub struct ColumnMut<'w, T>(&'w mut Column<T>);
impl<T> ColumnMut<'_, T> {
pub fn get(&self, e: Entity) -> Option<&T> {
self.0.get(e)
}
pub fn iter(&self) -> impl DoubleEndedIterator<Item = (Entity, &T)> + ExactSizeIterator {
self.0.iter()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl<T: Clone> ColumnMut<'_, T> {
pub fn get_mut(&mut self, e: Entity) -> Option<&mut T> {
self.0.get_mut(e)
}
pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = (Entity, &mut T)> + ExactSizeIterator {
self.0.iter_mut()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Clone, Debug, PartialEq)]
struct A(u32);
impl Component for A {
const NAME: &'static str = "test.a";
const GEOMETRY: crate::Geometry = crate::Geometry::None;
}
#[derive(Clone, Debug, PartialEq)]
struct B(&'static str);
impl Component for B {
const NAME: &'static str = "test.b";
const GEOMETRY: crate::Geometry = crate::Geometry::None;
}
#[derive(Clone, Debug, PartialEq)]
struct Same;
impl Component for Same {
const NAME: &'static str = "test.a";
const GEOMETRY: crate::Geometry = crate::Geometry::None;
}
#[derive(Clone, Debug, PartialEq)]
struct R(i32);
impl Resource for R {
const NAME: &'static str = "test.r";
}
#[test]
fn a_shared_value_is_the_world_s_own_and_keeps_what_it_was_given() {
let mut w = World::new();
let e = w.spawn();
w.insert(e, A(1));
let shared = w.get_shared::<A>(e).unwrap();
assert!(
std::ptr::eq(shared.as_ref(), w.get::<A>(e).unwrap()),
"the handle is the world's value, not a copy"
);
w.get_mut::<A>(e).unwrap().0 = 2;
assert_eq!(
*shared,
A(1),
"a write through the world copies the shared value first"
);
assert_eq!(w.get::<A>(e), Some(&A(2)));
let unshared = w.get::<A>(e).unwrap() as *const A;
w.get_mut::<A>(e).unwrap().0 = 3;
assert_eq!(
w.get::<A>(e).unwrap() as *const A,
unshared,
"a value nothing shares is written in place"
);
assert_eq!(w.get_shared::<B>(e), None);
}
#[test]
fn a_clone_of_the_world_shares_its_values_until_either_writes() {
let mut w = World::new();
let es: Vec<Entity> = (0..3).map(|_| w.spawn()).collect();
for (i, &e) in es.iter().enumerate() {
w.insert(e, A(i as u32));
}
let mut clone = w.clone();
for &e in &es {
assert!(
std::ptr::eq(w.get::<A>(e).unwrap(), clone.get::<A>(e).unwrap()),
"shared after the clone"
);
}
clone.get_mut::<A>(es[0]).unwrap().0 = 10;
assert_eq!(w.get::<A>(es[0]), Some(&A(0)), "the original keeps its value");
assert!(!std::ptr::eq(
w.get::<A>(es[0]).unwrap(),
clone.get::<A>(es[0]).unwrap()
));
assert!(
std::ptr::eq(w.get::<A>(es[1]).unwrap(), clone.get::<A>(es[1]).unwrap()),
"an unwritten value stays shared"
);
// every value written through a column after the clone: the original sees none of it
for (_, a) in clone.column_mut::<A>().unwrap().iter_mut() {
a.0 += 100;
}
assert_eq!(w.iter::<A>().map(|(_, a)| a.0).collect::<Vec<_>>(), [0, 1, 2]);
assert_eq!(
clone.iter::<A>().map(|(_, a)| a.0).collect::<Vec<_>>(),
[110, 101, 102]
);
for (_, a) in w.column_mut::<A>().unwrap().iter_mut() {
a.0 += 1;
}
assert_eq!(w.iter::<A>().map(|(_, a)| a.0).collect::<Vec<_>>(), [1, 2, 3]);
assert_eq!(
clone.iter::<A>().map(|(_, a)| a.0).collect::<Vec<_>>(),
[110, 101, 102]
);
}
#[test]
fn removing_or_replacing_a_shared_value_leaves_its_sharers_theirs() {
let mut w = World::new();
let e = w.spawn();
w.insert(e, A(7));
let shared = w.get_shared::<A>(e).unwrap();
let clone = w.clone();
assert_eq!(
w.remove::<A>(e),
Some(A(7)),
"a shared value is taken out as a copy"
);
assert_eq!(*shared, A(7));
assert_eq!(clone.get::<A>(e), Some(&A(7)));
assert_eq!(w.get::<A>(e), None);
w.insert(e, A(8));
assert_eq!(
w.insert(e, A(9)),
Some(A(8)),
"the value replaced is returned whole"
);
assert_eq!(clone.get::<A>(e), Some(&A(7)));
// a value nothing else shares is moved out, not copied
let f = w.spawn();
w.insert(f, B("only"));
assert_eq!(w.remove::<B>(f), Some(B("only")));
}
#[test]
fn a_value_taken_out_shared_is_the_world_s_own_never_a_copy() {
let mut w = World::new();
let e = w.spawn();
w.insert(e, A(7));
let held = w.get_shared::<A>(e).unwrap();
let taken = w.remove_shared::<A>(e).unwrap();
assert!(
Arc::ptr_eq(&held, &taken),
"taken out while shared, the handle is the world's value, not a copy"
);
assert_eq!(w.get::<A>(e), None);
assert_eq!(w.remove_shared::<A>(e), None);
drop(held);
assert_eq!(
Arc::into_inner(taken),
Some(A(7)),
"the last handle owns the value alone"
);
assert_eq!(w.remove_shared::<B>(e), None, "a type the world never held");
}
#[test]
fn iteration_is_in_entity_order_regardless_of_insert_order() {
let mut w = World::new();
let es: Vec<Entity> = (0..5).map(|_| w.spawn()).collect();
for &e in es.iter().rev() {
w.insert(e, A(e.index() * 10));
}
let got: Vec<u32> = w.iter::<A>().map(|(_, a)| a.0).collect();
assert_eq!(got, [0, 10, 20, 30, 40]);
}
/// One value per vertex of each primitive: follows primitives and vertices.
#[derive(Clone, Debug, PartialEq)]
struct PerVertex(Vec<Vec<u8>>);
impl Component for PerVertex {
const NAME: &'static str = "test.per_vertex";
const GEOMETRY: crate::Geometry = crate::Geometry::PerVertex;
fn remap_primitives(&self, from: &[usize]) -> Option<Result<Self, String>> {
Some(remap_list(&self.0, from).map(PerVertex))
}
fn remap_vertices(&self, primitive: usize, from: &[u32]) -> Option<Result<Self, String>> {
let mut out = self.0.clone();
let Some(list) = self.0.get(primitive) else {
return Some(Err(format!("primitive {primitive} of {}", self.0.len())));
};
out[primitive] = match from
.iter()
.map(|&i| {
list.get(i as usize)
.copied()
.ok_or(format!("vertex {i} of {}", list.len()))
})
.collect()
{
Ok(v) => v,
Err(e) => return Some(Err(e)),
};
Some(Ok(PerVertex(out)))
}
}
/// States it holds something per primitive (or per vertex) but does not answer an edit: what a component that
/// forgot to follow its mesh looks like to the World.
#[derive(Clone, Debug, PartialEq)]
struct Unanswering(crate::Geometry);
impl Component for Unanswering {
const NAME: &'static str = "test.unanswering";
const GEOMETRY: crate::Geometry = crate::Geometry::PerVertex;
fn remap_primitives(&self, _from: &[usize]) -> Option<Result<Self, String>> {
(self.0 != crate::Geometry::PerPrimitive).then(|| Ok(self.clone()))
}
fn remap_vertices(&self, _primitive: usize, _from: &[u32]) -> Option<Result<Self, String>> {
None
}
}
fn points(n: usize) -> crate::Primitive {
crate::Primitive {
topology: crate::Topology::Points,
streams: [(crate::Semantic::Position, crate::Stream::F32x3(vec![[0.0; 3]; n]))].into(),
indices: None,
material: None,
}
}
/// A component stating it describes the mesh must answer the edits it describes: one that doesn't is refused,
/// naming it, and nothing changes. One stating `None` is kept as it is.
#[test]
fn edits_refuse_a_dependent_component_that_does_not_answer() {
let mut w = World::new();
let e = w.spawn();
w.insert(e, crate::Mesh::new(vec![points(2), points(2)]));
w.insert(e, A(7));
// per primitive: a rebuild of the list is refused
w.insert(e, Unanswering(crate::Geometry::PerPrimitive));
let err = w
.rebuild_primitives(e, |m| Ok((vec![m.primitives()[1].clone()], vec![1])))
.unwrap_err();
assert!(
err.contains("test.unanswering") && err.contains("per primitive"),
"{err}"
);
assert_eq!(
w.get::<crate::Mesh>(e).unwrap().primitives().len(),
2,
"nothing changed"
);
// per vertex: it answers the rebuild, but a compaction is refused
w.insert(e, Unanswering(crate::Geometry::PerVertex));
let err = w.remap_vertices(e, 0, &[1]).unwrap_err();
assert!(
err.contains("test.unanswering") && err.contains("per vertex"),
"{err}"
);
// a component of Geometry::None follows nothing and is never refused
w.remove::<Unanswering>(e);
w.rebuild_primitives(e, |m| Ok((vec![m.primitives()[1].clone()], vec![1])))
.unwrap();
w.remap_vertices(e, 0, &[1]).unwrap();
assert_eq!(w.get::<A>(e), Some(&A(7)));
}
/// Moving one form onto another can't leave data describing one mesh beside another: `from` bringing a mesh
/// while `to` keeps per-primitive data `from` lacks, or `from` bringing such data without a mesh onto `to`'s mesh,
/// is refused, changing nothing. With `to`'s mesh taken away first it moves.
#[test]
fn a_move_leaving_stale_mesh_data_is_refused() {
use crate::{MaterialVariants, Mesh};
let mut w = World::new();
let (to, from) = (w.spawn(), w.spawn());
w.insert(to, Mesh::new(vec![points(1)]));
w.insert(to, MaterialVariants(vec![Default::default()]));
w.insert(from, Mesh::new(vec![points(3), points(3)]));
let err = w.move_components(from, to).unwrap_err();
assert!(err.contains("core.material_variants"), "{err}");
assert!(w.is_alive(from) && w.get::<Mesh>(to).unwrap().primitives().len() == 1);
// data without a mesh onto a mesh
let bare = w.spawn();
w.insert(bare, MaterialVariants(vec![]));
let err = w.move_components(bare, to).unwrap_err();
assert!(err.contains("core.material_variants"), "{err}");
assert!(w.is_alive(bare));
// the old geometry taken away first: the move goes through
w.remove_mesh(to).unwrap();
assert!(w.move_components(from, to).unwrap());
assert_eq!(w.get::<Mesh>(to).unwrap().primitives().len(), 2);
}
/// A primitive's vertices compacted: a per-vertex component follows them (after a rebuild that kept only
/// primitive 1, from its source primitive's values); one that holds nothing per vertex is kept; an index the
/// component lacks fails naming it, and an opaque component refuses, each changing nothing.
#[test]
fn per_vertex_components_follow_a_compaction() {
let mut w = World::new();
let e = w.spawn();
w.insert(e, PerVertex(vec![vec![10, 11], vec![20, 21, 22, 23]]));
w.insert(e, A(7));
// keep primitive 1 only, then its vertices 3 and 1
w.remap_primitives(e, &[1]).unwrap();
w.remap_vertices(e, 0, &[3, 1]).unwrap();
assert_eq!(w.get::<PerVertex>(e), Some(&PerVertex(vec![vec![23, 21]])));
assert_eq!(w.get::<A>(e), Some(&A(7)));
let err = w.remap_vertices(e, 0, &[5]).unwrap_err();
assert!(
err.contains("test.per_vertex") && err.contains("vertex 5 of 2"),
"{err}"
);
assert_eq!(w.get::<PerVertex>(e), Some(&PerVertex(vec![vec![23, 21]])));
w.insert_opaque(
e,
"game.thing",
Opaque {
version: 1,
data: OpaqueData::Bytes(vec![1]),
},
)
.unwrap();
assert!(w.remap_vertices(e, 0, &[1]).unwrap_err().contains("game.thing"));
assert_eq!(w.get::<PerVertex>(e), Some(&PerVertex(vec![vec![23, 21]])));
}
/// `check_remap_vertices` states what `remap_vertices` would do and changes nothing.
#[test]
fn the_check_of_a_vertex_remap_changes_nothing() {
let mut w = World::new();
let e = w.spawn();
w.insert(e, PerVertex(vec![vec![10, 11]]));
w.check_remap_vertices(e, 0, &[1, 0, 1]).unwrap();
assert_eq!(w.get::<PerVertex>(e), Some(&PerVertex(vec![vec![10, 11]])));
let err = w.check_remap_vertices(e, 0, &[2]).unwrap_err();
assert!(err.contains("vertex 2 of 2"), "{err}");
w.insert(e, Unanswering(crate::Geometry::PerVertex));
let err = w.check_remap_vertices(e, 0, &[0]).unwrap_err();
assert!(err.contains("test.unanswering"), "{err}");
}
/// A mesh taken away goes with what follows its primitives; with an opaque component (which can't be known to
/// describe primitives or not) nothing changes.
#[test]
fn remove_mesh_takes_its_per_primitive_components_and_refuses_with_opaque_data() {
use crate::{MaterialVariants, Mesh, MeshFile};
let mut w = World::new();
let e = w.spawn();
w.insert(e, Mesh::new(Vec::new()));
w.insert(e, MaterialVariants(Vec::new()));
w.insert(
e,
MeshFile {
path: "a.glb".into(),
mesh: 0,
materials: Vec::new(),
},
);
w.insert(e, A(1));
w.insert_opaque(
e,
"game.thing",
Opaque {
version: 1,
data: OpaqueData::Bytes(vec![1]),
},
)
.unwrap();
assert!(w.remove_mesh(e).unwrap_err().contains("game.thing"));
assert!(w.has::<Mesh>(e) && w.has::<MaterialVariants>(e));
w.remove_opaque(e, "game.thing");
assert_eq!(
w.remove_mesh(e).unwrap(),
["core.mesh", "core.material_variants", "core.mesh_file"]
);
// nothing left to restore the mesh from
assert!(!w.has::<Mesh>(e) && !w.has::<MaterialVariants>(e) && !w.has::<MeshFile>(e));
// what does not follow primitives stays
assert!(w.has::<A>(e));
assert!(w.remove_mesh(e).unwrap().is_empty());
// a mesh still only in its file goes the same way, with the per-primitive data that describes it
w.insert(e, MaterialVariants(Vec::new()));
w.insert(
e,
MeshFile {
path: "a.glb".into(),
mesh: 0,
materials: Vec::new(),
},
);
assert_eq!(
w.remove_mesh(e).unwrap(),
["core.material_variants", "core.mesh_file"]
);
assert!(!w.has::<MaterialVariants>(e) && !w.has::<MeshFile>(e) && w.has::<A>(e));
}
#[test]
fn iter2_joins_and_despawn_removes_everything() {
let mut w = World::new();
let e0 = w.spawn();
let e1 = w.spawn();
w.insert(e0, A(1));
w.insert(e1, A(2));
w.insert(e1, B("x"));
w.insert_opaque(
e1,
"game.thing",
Opaque {
version: 3,
data: OpaqueData::Bytes(vec![1, 2]),
},
)
.unwrap();
assert_eq!(w.iter2::<A, B>().map(|(e, ..)| e).collect::<Vec<_>>(), [e1]);
assert!(w.entity_has_named(e1, "game.thing"));
assert_eq!(w.component_names(), ["game.thing", "test.a", "test.b"]);
assert!(w.despawn(e1));
assert!(!w.has::<A>(e1) && w.get_opaque(e1, "game.thing").is_none());
assert_eq!(w.component_names(), ["test.a"]);
let e2 = w.spawn();
assert_ne!(e2, e1, "ids are never reused");
}
#[test]
fn columns2_mut_reads_one_writes_another() {
let mut w = World::new();
let e = w.spawn();
w.insert(e, A(7));
w.insert(e, B("a"));
let (a, b) = w.columns2_mut::<A, B>();
let (a, mut b) = (a.unwrap(), b.unwrap());
if a.get(e).unwrap().0 == 7 {
*b.get_mut(e).unwrap() = B("seven");
}
assert_eq!(w.get::<B>(e), Some(&B("seven")));
}
#[test]
fn move_components_replaces_by_name_and_keeps_the_rest() {
let mut w = World::new();
let from = w.spawn();
let to = w.spawn();
w.insert(from, A(9));
w.insert(to, A(1));
w.insert(to, B("kept"));
let opaque = Opaque {
version: 4,
data: OpaqueData::Bytes(vec![3, 2, 1]),
};
w.insert_opaque(from, "game.form", opaque.clone()).unwrap();
assert!(!w.move_components(from, from).unwrap());
assert!(!w.move_components(from, Entity::from_index(999)).unwrap());
assert_eq!(w.get::<A>(from), Some(&A(9)), "a refused move changes nothing");
assert!(w.move_components(from, to).unwrap());
assert!(!w.is_alive(from));
assert_eq!(w.get::<A>(to), Some(&A(9)));
assert_eq!(w.get::<B>(to), Some(&B("kept")));
assert_eq!(w.get_opaque(to, "game.form"), Some(&opaque));
assert!(!w.move_components(from, to).unwrap());
assert_ne!(w.spawn(), from, "the moved-from id is not reused");
}
#[derive(Clone, Debug, PartialEq)]
struct NamedLikeA;
impl Resource for NamedLikeA {
const NAME: &'static str = "test.a";
}
#[test]
#[should_panic(expected = "one kind of them")]
fn a_resource_cannot_take_a_component_name() {
let mut w = World::new();
let e = w.spawn();
w.insert(e, A(1));
w.insert_resource(NamedLikeA);
}
#[test]
#[should_panic(expected = "one kind of them")]
fn a_component_cannot_take_a_resource_name() {
let mut w = World::new();
w.insert_resource(NamedLikeA);
let e = w.spawn();
w.insert(e, A(1));
}
#[test]
fn resource_names_list_typed_and_opaque_sorted() {
let mut w = World::new();
w.insert_resource(R(1));
w.insert_opaque_resource(
"game.settings",
Opaque {
version: 1,
data: OpaqueData::Bytes(vec![]),
},
)
.unwrap();
assert_eq!(w.resource_names(), ["game.settings", "test.r"]);
}
#[test]
fn copy_components_replaces_by_name_keeps_the_rest_and_the_source() {
let mut w = World::new();
let from = w.spawn();
let to = w.spawn();
w.insert(from, A(9));
w.insert(to, A(1));
w.insert(to, B("kept"));
let opaque = Opaque {
version: 4,
data: OpaqueData::Bytes(vec![3, 2, 1]),
};
w.insert_opaque(from, "game.form", opaque.clone()).unwrap();
assert!(!w.copy_components(from, from));
assert!(!w.copy_components(from, Entity::from_index(999)));
assert!(w.copy_components(from, to));
assert!(w.is_alive(from));
assert_eq!(w.get::<A>(from), Some(&A(9)));
assert_eq!(w.get_opaque(from, "game.form"), Some(&opaque));
assert_eq!(w.get::<A>(to), Some(&A(9)));
assert_eq!(w.get::<B>(to), Some(&B("kept")));
assert_eq!(w.get_opaque(to, "game.form"), Some(&opaque));
}
#[test]
#[should_panic(expected = "another component type's name")]
fn two_types_cannot_share_a_name() {
let mut w = World::new();
let e = w.spawn();
w.insert(e, A(1));
w.insert(e, Same);
}
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
struct Shown {
x: u32,
of: Entity,
}
impl Component for Shown {
const NAME: &'static str = "test.shown";
const GEOMETRY: crate::Geometry = crate::Geometry::None;
const VERSION: u32 = 2;
fn to_json(&self) -> Result<Option<serde_json::Value>, JsonError> {
crate::json::to_value(self).map(Some)
}
}
#[test]
fn components_json_lists_every_component_sorted() {
let mut w = World::new();
let e0 = w.spawn();
let e = w.spawn();
w.insert(e, Shown { x: 3, of: e0 });
w.insert(e, A(1));
w.insert_opaque(
e,
"game.bytes",
Opaque {
version: 1,
data: OpaqueData::Bytes(vec![9]),
},
)
.unwrap();
w.insert_opaque(
e,
"game.json",
Opaque {
version: 1,
data: OpaqueData::Json(serde_json::json!({"k": 1})),
},
)
.unwrap();
let got: Vec<(&str, u32, Option<serde_json::Value>)> = w
.components_json(e)
.unwrap()
.into_iter()
.map(|c| (c.name, c.version, c.value))
.collect();
assert_eq!(
got,
[
("game.bytes", 1, None),
("game.json", 1, Some(serde_json::json!({"k": 1}))),
("test.a", 1, None),
("test.shown", 2, Some(serde_json::json!({"x": 3, "of": 0}))),
]
);
assert!(w.components_json(e0).unwrap().is_empty());
}
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
struct F(f32);
impl Component for F {
const NAME: &'static str = "test.f";
const GEOMETRY: crate::Geometry = crate::Geometry::None;
fn to_json(&self) -> Result<Option<serde_json::Value>, JsonError> {
crate::json::to_value(self).map(Some)
}
}
impl Resource for F {
const NAME: &'static str = "test.res";
const VERSION: u32 = 4;
fn to_json(&self) -> Result<Option<serde_json::Value>, JsonError> {
crate::json::to_value(self).map(Some)
}
}
#[test]
fn a_json_view_that_would_lose_a_value_is_an_error() {
let mut w = World::new();
let e = w.spawn();
w.insert(e, F(f32::NAN));
assert_eq!(
w.components_json(e).unwrap_err().to_string(),
"test.f on e0: NaN at the value: JSON has no non-finite numbers"
);
w.insert_resource(F(0.5));
let r = w.resources_json().unwrap();
assert_eq!(
(r[0].name, r[0].version, r[0].value.clone()),
("test.res", 4, Some(serde_json::json!(0.5)))
);
w.insert_resource(F(f32::INFINITY));
assert_eq!(
w.resources_json().unwrap_err().to_string(),
"test.res: inf at the value: JSON has no non-finite numbers"
);
}
#[derive(Clone, Debug, PartialEq)]
struct Points(Entity);
impl Component for Points {
const NAME: &'static str = "test.points";
const GEOMETRY: crate::Geometry = crate::Geometry::None;
fn references(&self, out: &mut Vec<Entity>) {
out.push(self.0);
}
}
#[test]
fn a_reference_to_a_despawned_entity_fails_verification() {
let mut w = World::new();
let target = w.spawn();
let holder = w.spawn();
w.insert(holder, Points(target));
assert!(w.verify_components().is_empty());
w.despawn(target);
assert_eq!(
w.verify_components(),
[(
"test.points",
holder,
format!("refers to {target:?}, which is not alive")
)]
);
}
#[test]
#[should_panic(expected = "opaque component")]
fn a_typed_component_cannot_take_an_opaque_name() {
let mut w = World::new();
let e = w.spawn();
w.insert_opaque(
e,
"test.a",
Opaque {
version: 1,
data: OpaqueData::Bytes(vec![]),
},
)
.unwrap();
w.insert(e, A(1));
}
#[test]
fn resources_and_clone() {
let mut w = World::new();
assert!(w.insert_resource(R(1)).is_none());
assert_eq!(w.insert_resource(R(2)), Some(R(1)));
let e = w.spawn();
w.insert(e, A(5));
let w2 = w.clone();
w.get_mut::<A>(e).unwrap().0 = 6;
assert_eq!(w2.get::<A>(e), Some(&A(5)));
assert_eq!(w2.resource::<R>(), Some(&R(2)));
}
fn opaque() -> Opaque {
Opaque {
version: 1,
data: OpaqueData::Bytes(vec![]),
}
}
/// A name a typed component, an opaque component and a resource could each take is one kind's: the second to
/// claim it is refused, an error, whichever came first.
#[test]
fn a_name_clash_is_an_error_whichever_claimed_it_first() {
// typed, then opaque
let mut w = World::new();
let e = w.spawn();
w.insert(e, A(1));
let clash = w.insert_opaque(e, "test.a", opaque()).unwrap_err();
assert_eq!(clash.name, "test.a");
assert!(clash.held.contains("typed component"), "{clash}");
assert!(w.get_opaque(e, "test.a").is_none(), "a refusal changes nothing");
// opaque, then typed
let mut w = World::new();
let e = w.spawn();
w.insert_opaque(e, "test.a", opaque()).unwrap();
let clash = w.try_insert(e, A(1)).unwrap_err();
assert!(clash.held.contains("opaque component"), "{clash}");
assert!(!w.has::<A>(e), "a refusal changes nothing");
// the same for a resource and a component
let mut w = World::new();
w.insert_resource(NamedLikeA);
let e = w.spawn();
assert!(w.try_insert(e, A(1)).unwrap_err().held.contains("resource"));
assert!(
w.insert_opaque(e, "test.a", opaque())
.unwrap_err()
.held
.contains("resource")
);
let mut w = World::new();
let e = w.spawn();
w.insert(e, A(1));
assert!(
w.try_insert_resource(NamedLikeA)
.unwrap_err()
.held
.contains("component")
);
assert!(
w.insert_opaque_resource("test.a", opaque())
.unwrap_err()
.held
.contains("component")
);
// two types for one name
assert!(
w.try_insert(e, Same)
.unwrap_err()
.held
.contains("another component type")
);
// a free name is taken
assert_eq!(w.try_insert(e, B("x")).unwrap(), None);
}
/// Ids from a file: ascending, with gaps; one at or below one already used, or the last id, is an error.
#[test]
fn an_id_from_a_file_is_an_error_not_a_panic() {
let mut w = World::new();
assert_eq!(w.spawn_at(Entity::from_index(5)), Ok(Entity::from_index(5)));
assert_eq!(w.spawn(), Entity::from_index(6));
assert_eq!(
w.spawn_at(Entity::from_index(6)),
Err(IdError::NotAscending(Entity::from_index(6)))
);
assert_eq!(
w.spawn_at(Entity::from_index(2)),
Err(IdError::NotAscending(Entity::from_index(2)))
);
assert_eq!(w.entity_count(), 2, "a refusal changes nothing");
let last = Entity::from_index(u32::MAX);
assert_eq!(w.spawn_at(last), Err(IdError::Exhausted(last)));
assert!(!w.is_alive(last));
assert_eq!(w.spawn(), Entity::from_index(7));
}
#[test]
fn reserving_indices_for_a_reloaded_part_never_rewinds_or_spawns_entities() {
let mut world = World::new();
let first = world.spawn();
world.reserve_indices_before(100);
assert_eq!(world.entity_count(), 1);
assert!(world.is_alive(first));
assert_eq!(world.spawn().index(), 100);
world.reserve_indices_before(5);
assert_eq!(world.spawn().index(), 101);
}
/// A part with an entity alive in the world it is absorbed into is an error that changes nothing.
#[test]
fn absorbing_a_part_that_overlaps_is_an_error() {
let mut w = World::new();
let e = w.spawn();
w.insert(e, A(1));
let part = w.clone();
let before = format!("{w:?}");
assert_eq!(w.absorb(part), Err(IdError::Alive(e)));
assert_eq!(format!("{w:?}"), before);
}
/// A resource that keeps a reference it was told to forget breaks its contract: caught in release when a whole
/// selection leaves, not only in debug builds.
#[derive(Clone, Debug, PartialEq)]
struct Stubborn(Entity);
impl Resource for Stubborn {
const NAME: &'static str = "test.stubborn";
fn references(&self, out: &mut Vec<Entity>) {
out.push(self.0);
}
}
#[test]
#[should_panic(expected = "keeps a reference")]
fn a_resource_that_keeps_a_reference_is_refused_when_a_selection_leaves() {
let mut w = World::new();
let (a, b) = (w.spawn(), w.spawn());
w.insert_resource(Stubborn(b));
w.retain(&BTreeSet::from([a]));
}
}