siecs 0.1.2

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

/* This generated file contains includes for project dependencies. */
/*
                                   )
                                  (.)
                                  .|.
                                  | |
                              _.--| |--._
                           .-';  ;`-'& ; `&.
                          \   &  ;    &   &_/
                           |"""---...---"""|
                           \ | | | | | | | /
                            `---.|.|.|.---'

 * This file is generated by bake.lang.c for your convenience. Headers of
 * dependencies will automatically show up in this file. Include bake_config.h
 * in your main project file. Do not edit! */

#ifndef SIREFLECT_BAKE_CONFIG_H
#define SIREFLECT_BAKE_CONFIG_H

/* Headers of public dependencies */
/* No dependencies */

/* Convenience macro for exporting symbols */
#ifndef sireflect_STATIC
#if defined(sireflect_EXPORTS) && (defined(_MSC_VER) || defined(__MINGW32__))
  #define SIREFLECT_API __declspec(dllexport)
#elif defined(sireflect_EXPORTS)
  #define SIREFLECT_API __attribute__((__visibility__("default")))
#elif defined(_MSC_VER)
  #define SIREFLECT_API __declspec(dllimport)
#else
  #define SIREFLECT_API
#endif
#else
  #define SIREFLECT_API
#endif

#endif

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

/* Marks generated helper symbols as intentionally unused. */
#if defined(__GNUC__) || defined(__clang__)
#define SIREFLECT_UNUSED __attribute__((unused))
#else
#define SIREFLECT_UNUSED
#endif

/* Primitive aliases understood by the parser. */
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef int8_t i8;
typedef int16_t i16;
typedef int32_t i32;
typedef int64_t i64;
typedef float f32;
typedef double f64;
typedef void *ptr;

/* Opaque registry that owns reflected type metadata. */
typedef struct sireflect_registry_t sireflect_registry_t;

/* Type handle. Valid handles start at 1. */
typedef uint64_t sireflect_handle_t;

/* Invalid type handle. */
#define SIREFLECT_INVALID_HANDLE ((sireflect_handle_t)0)

/* Reports a failed Sireflect debug assertion. */
#ifndef NDEBUG
void sireflect_assert_fail(
    const char *condition,
    const char *message,
    const char *file,
    int line,
    const char *function
);

#define sireflect_assert(condition, message)                                                       \
    ((condition) ? (void)0                                                                         \
                 : sireflect_assert_fail(#condition, message, __FILE__, __LINE__, __func__))
#define sireflect_indebug(...) __VA_ARGS__
#else
#define sireflect_assert(condition, message) ((void)0)
#define sireflect_indebug(...)
#endif

/* Built-in kind of a reflected type. */
typedef enum {
    sireflect_kind_u8,
    sireflect_kind_u16,
    sireflect_kind_u32,
    sireflect_kind_u64,
    sireflect_kind_i8,
    sireflect_kind_i16,
    sireflect_kind_i32,
    sireflect_kind_i64,
    sireflect_kind_f32,
    sireflect_kind_f64,
    sireflect_kind_bool,
    sireflect_kind_char,
    sireflect_kind_short,
    sireflect_kind_int,
    sireflect_kind_long,
    sireflect_kind_ptr,
    sireflect_kind_struct,
    sireflect_kind_array,
    sireflect_kind_pointer,
    sireflect_kind_signed_char,
    sireflect_kind_unsigned_char,
    sireflect_kind_unsigned_short,
    sireflect_kind_unsigned_int,
    sireflect_kind_unsigned_long,
    sireflect_kind_long_long,
    sireflect_kind_unsigned_long_long
} sireflect_kind_t;

/* Returns a stable string for a kind, or "unknown" for an invalid kind value.
 */
const char *sireflect_kind_name(sireflect_kind_t kind);

/* Returns true for integer and floating-point kinds. */
bool sireflect_is_numeric(sireflect_kind_t kind);

/* Qualifier flags stored on reflected fields. */
typedef enum {
    SIREFLECT_QUAL_CONST = 1u << 0,
    SIREFLECT_QUAL_VOLATILE = 1u << 1
} sireflect_qualifier_t;

/* Metadata for a single reflected field. */
typedef struct {
    /* Field name as written in the reflected struct. */
    const char *name;

    /* Handle of the field type. Primitive types also have handles. */
    sireflect_handle_t type;

    /* Byte offset of the field from the start of the object. */
    size_t offset;

    /* Size of the field in bytes. */
    size_t size;

    /* Alignment of the field in bytes. */
    size_t align;

    /* Bitmask of sireflect_qualifier_t flags. */
    uint32_t qualifiers;
} sireflect_field_info_t;

/* Borrowed view over the fields of a reflected type. */
typedef struct {
    sireflect_field_info_t *fields;
    size_t field_count;
} sireflect_fields_t;

/* Metadata for a reflected type. */
typedef struct {
    /* Type name. */
    const char *name;

    /* Built-in kind of this type. */
    sireflect_kind_t kind;

    /* Size of the type in bytes. */
    size_t size;

    /* Alignment of the type in bytes. */
    size_t align;

    /* Fields owned by this type. Empty for non-struct types. */
    sireflect_fields_t fields;

    /* Element type for array types or pointee type for pointer types. */
    sireflect_handle_t element_type;

    /* Element count for array types, otherwise 0. */
    size_t element_count;
} sireflect_type_info_t;

typedef struct {
    const char *name;
    const char *fields;
    size_t size;
    size_t align;
} sireflect_struct_desc_t;

/* Transforms a struct type name into its descriptor symbol name. */
#define sireflect_desc(type) __##type##_desc

/*
 * Declares a struct and stores its source field list for registration.
 * Use sireflect(reg, name) to register the generated metadata.
 */
#define SIREFLECT_STRUCT(type_name, ...)                                                           \
    typedef struct __VA_ARGS__ type_name;                                                          \
    SIREFLECT_UNUSED static const sireflect_struct_desc_t sireflect_desc(type_name) = {            \
        .name = #type_name,                                                                        \
        .fields = #__VA_ARGS__,                                                                    \
        .size = sizeof(type_name),                                                                 \
        .align = _Alignof(type_name)                                                               \
    }

/* Registers a struct declared with SIREFLECT_STRUCT. */
#define sireflect(reg, name) sireflect_register_struct(reg, &sireflect_desc(name))

/* Creates a reflection registry. */
sireflect_registry_t *sireflect_registry_init(void);

/* Destroys a registry and all metadata it owns. */
void sireflect_registry_fini(sireflect_registry_t *reg);

/*
 * Returns the current recoverable error message, or NULL if there is no error.
 * The returned pointer is owned by Sireflect and remains valid until the next
 * public sireflect_* call except sireflect_error(), or until sireflect_registry_fini().
 */
const char *sireflect_error(void);

/*
 * Registers a struct type from its textual field list.
 * Returns the existing handle if the same type was already registered.
 */
sireflect_handle_t
sireflect_register_struct(sireflect_registry_t *reg, const sireflect_struct_desc_t *desc);

/*
 * Tries to register a struct type from its textual field list.
 * Returns SIREFLECT_INVALID_HANDLE when the descriptor or reflected field syntax is invalid.
 */
sireflect_handle_t
sireflect_try_register_struct(sireflect_registry_t *reg, const sireflect_struct_desc_t *desc);

/* Finds a type handle by name, or SIREFLECT_INVALID_HANDLE if missing. */
sireflect_handle_t sireflect_type_by_name(const sireflect_registry_t *reg, const char *name);

/* Returns metadata for a type handle. */
const sireflect_type_info_t *
sireflect_type_info(const sireflect_registry_t *reg, sireflect_handle_t ref);

/* Returns the fields of a type. */
const sireflect_fields_t *
sireflect_type_fields(const sireflect_registry_t *reg, sireflect_handle_t ref);

/* Returns the size of a type in bytes. */
size_t sireflect_type_size(const sireflect_registry_t *reg, sireflect_handle_t ref);

/* Returns the name of a type. */
const char *sireflect_type_name(const sireflect_registry_t *reg, sireflect_handle_t ref);

/* Returns true when type metadata describes a struct type. */
bool sireflect_type_is_struct(const sireflect_type_info_t *info);

/* Returns true when type metadata describes an array type. */
bool sireflect_type_is_array(const sireflect_type_info_t *info);

/* Returns true when type metadata describes a typed pointer type. */
bool sireflect_type_is_pointer(const sireflect_type_info_t *info);

/* Returns the element type handle of an array type. */
sireflect_handle_t sireflect_type_element(const sireflect_registry_t *reg, sireflect_handle_t ref);

/* Returns the element count of an array type. */
size_t sireflect_type_element_count(const sireflect_registry_t *reg, sireflect_handle_t ref);

/* Returns the pointee type handle of a typed pointer type. */
sireflect_handle_t sireflect_type_pointee(const sireflect_registry_t *reg, sireflect_handle_t ref);

/* Finds metadata for a field by name. */
const sireflect_field_info_t *
sireflect_field_info(const sireflect_registry_t *reg, sireflect_handle_t type, const char *field);

/* Returns the type handle of a field. */
sireflect_handle_t
sireflect_field_type(const sireflect_registry_t *reg, sireflect_handle_t type, const char *field);

/* Returns the size of a field in bytes. */
size_t
sireflect_field_size(const sireflect_registry_t *reg, sireflect_handle_t ref, const char *field);

/* Returns a const pointer to a field inside an object. */
const void *sireflect_field_ptr(
    const sireflect_registry_t *reg,
    sireflect_handle_t type,
    const void *obj,
    const char *field
);

/* Returns a mutable pointer to a field inside an object. */
void *sireflect_field_mut_ptr(
    const sireflect_registry_t *reg,
    sireflect_handle_t type,
    void *obj,
    const char *field
);

/* Copies value bytes into a field. Returns 0 on success. */
int sireflect_field_copy(
    const sireflect_registry_t *reg,
    sireflect_handle_t type,
    void *obj,
    const char *field,
    const void *value
);

#ifdef __cplusplus
}
#endif

#endif

#ifndef SIJSON_H
#define SIJSON_H

/* This generated file contains includes for project dependencies. */
#include <stdbool.h>
#include <stddef.h>

/*
 * sijson is a tiny JSON serialization layer built on top of sireflect.
 *
 * Public usage is intentionally macro based:
 *
 *     SIJSON(Position, {
 *         float x;
 *         float y;
 *     });
 *
 *     char *json = sijson_to_json(Position, { .x = 1, .y = 2 });
 *     Position pos = sijson_from_json(Position, json);
 *
 * Strings returned by sijson_to_json are owned by the caller.
 * Values returned by sijson_from_json are copied out of an internal temporary
 * buffer before the expression ends. Heap-owned fields inside that value, such
 * as char *, must be released with sijson_free(type, &value).
 */

/* Internal reflected type handle symbol for a user type. */
#define sijson_handle(type) __sijson__##type##__handle

/*
 * Declare a JSON-reflectable type in a header.
 *
 * Pair this with SIJSON_DEFINE(type) in exactly one source file.
 */
#define SIJSON_DECLARE(type, ...)                                                                  \
    SIREFLECT_STRUCT(type, __VA_ARGS__);                                                           \
    extern sireflect_handle_t sijson_handle(type);

/* Define storage for a type declared with SIJSON_DECLARE. */
#define SIJSON_DEFINE(type) sireflect_handle_t sijson_handle(type) = 0;

/*
 * Declare and define a JSON-reflectable type in the current translation unit.
 *
 * This is the simplest form and is ideal for examples, tests, and small
 * programs.
 */
#define SIJSON(type, ...)                                                                          \
    SIJSON_DECLARE(type, __VA_ARGS__);                                                             \
    SIJSON_DEFINE(type);

/*
 * Default reflection registry used by the convenience macros.
 *
 * The implementation initializes it lazily when a type is first used.
 */
sireflect_registry_t *sijson_default_registry(void);

/*
 * Opaque handle for arbitrary JSON values.
 *
 * A sijson_value_t can hold null, bool, number, string, array, or object.
 * Values are allocated in sijson's internal arena unless documented otherwise.
 * They stay valid until sijson_clean() or sijson_release().
 */
typedef struct sijson_value *sijson_value_t;

typedef enum sijson_type {
    SIJSON_NULL,
    SIJSON_BOOL,
    SIJSON_NUMBER,
    SIJSON_STRING,
    SIJSON_ARRAY,
    SIJSON_OBJECT,
} sijson_type_t;

/*
 * Parse/stringify dynamic JSON without a reflected C type.
 *
 * sijson_parse returns a value allocated in sijson's internal arena.
 * sijson_stringify returns a newly allocated JSON string owned by the
 * caller.
 */
sijson_value_t sijson_parse(const char *json);
char *sijson_stringify(sijson_value_t value);

/*
 * Reset or release the internal arena used by sijson_value_t values.
 * sijson_clean keeps allocated capacity for reuse.
 * sijson_release frees the arena storage.
 */
void sijson_clean(void);
void sijson_release(void);

/* Inspect a dynamic JSON value. */
sijson_type_t sijson_type(sijson_value_t value);

/* Read scalar values. The value must have the matching sijson_type_t. */
bool sijson_bool(sijson_value_t value);
double sijson_number(sijson_value_t value);
const char *sijson_string(sijson_value_t value);

/* Read arrays. */
size_t sijson_array_len(sijson_value_t value);
sijson_value_t sijson_array_get(sijson_value_t value, size_t index);

/* Read objects. */
size_t sijson_object_len(sijson_value_t value);
const char *sijson_object_key(sijson_value_t value, size_t index);
sijson_value_t sijson_object_get(sijson_value_t value, const char *key);

/* Build dynamic JSON values in sijson's internal arena. */
sijson_value_t sijson_make_null(void);
sijson_value_t sijson_make_bool(bool value);
sijson_value_t sijson_make_number(double value);
sijson_value_t sijson_make_string(const char *value);
sijson_value_t sijson_make_array(void);
sijson_value_t sijson_make_object(void);

/* Mutate arrays and objects created as dynamic JSON values. */
bool sijson_array_push(sijson_value_t array, sijson_value_t value);
bool sijson_object_set(sijson_value_t object, const char *key, sijson_value_t value);

/*
 * Serialize a value written as a compound initializer.
 *
 * Example:
 *
 *     char *json = sijson_to_json(Position, { .x = 1, .y = 2 });
 *
 *     Position pos = { .x = 1, .y = 2 };
 *     char *json2 = sijson_to_json_ptr(Position, &pos);
 */
#define sijson_to_json(type, ...)                                                                  \
    sijson_to_json_impl(&sijson_handle(type), &sireflect_desc(type), &(type)__VA_ARGS__)

#define sijson_to_json_ptr(type, ptr)                                                              \
    sijson_to_json_impl(&sijson_handle(type), &sireflect_desc(type), (ptr))

/*
 * Low-level serialization entry point.
 *
 * Registers desc on first use through ref, then serializes ptr.
 * Returns a newly allocated JSON string owned by the caller.
 */
char *
sijson_to_json_impl(sireflect_handle_t *ref, const sireflect_struct_desc_t *desc, const void *ptr);

/*
 * Deserialize JSON into a value of name.
 *
 * Example:
 *
 *     Position pos = sijson_from_json(Position, json);
 *
 * The returned value is copied from an internal temporary buffer. A later
 * sijson_from_json call may reuse that buffer, but previously copied structs
 * remain valid as long as they do not contain pointers into sijson memory.
 */
#define sijson_from_json(type, json)                                                               \
    *((type *)sijson_from_json_impl(&sijson_handle(type), &sireflect_desc(type), json))

/*
 * Low-level deserialization entry point.
 *
 * Registers desc on first use through ref, grows the internal temporary buffer
 * if needed, writes the parsed value into it, and returns that buffer.
 */
void *sijson_from_json_impl(
    sireflect_handle_t *ref,
    const sireflect_struct_desc_t *desc,
    const char *json
);

/*
 * Free heap-owned fields inside a value produced by sijson_from_json.
 *
 * This does not free the struct pointer itself.
 */
#define sijson_free(type, ptr) sijson_free_impl(&sijson_handle(type), &sireflect_desc(type), (ptr))

void sijson_free_impl(sireflect_handle_t *ref, const sireflect_struct_desc_t *desc, void *ptr);

/*
 * Returns the error message from the last failed operation.
 */
const char *sijson_error(void);

#endif
#ifndef SIHTTP_H
#define SIHTTP_H


#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

#if defined(__GNUC__) || defined(__clang__)
#define SIHTTP_PRINTF_FORMAT(fmt, args) __attribute__((format(printf, fmt, args)))
#else
#define SIHTTP_PRINTF_FORMAT(fmt, args)
#endif

/* Opaque HTTP server handle. */
typedef struct sihttp_server_s sihttp_server_t;

/* User-defined application state.
 * Define struct sihttp_app_state_s in your application before accessing req->state fields.
 * The state is owned by the user and must outlive the server.
 */
typedef struct sihttp_app_state_s sihttp_app_state_t;

/* Response content type. AUTO defaults to text/plain for string bodies. */
typedef enum {
    SIHTTP_CONTENT_AUTO = 0,
    SIHTTP_CONTENT_TEXT,
    SIHTTP_CONTENT_JSON,
    SIHTTP_CONTENT_HTML,
    SIHTTP_CONTENT_BINARY,
} sihttp_content_type_t;

/* Handler response.
 * status defaults to 200 when set to 0.
 * body must be heap-allocated; the server takes ownership and frees it.
 */
typedef struct {
    int status;
    char *body;
    sihttp_content_type_t content_type;
} sihttp_response_t;

/* Incoming HTTP request passed to route handlers. */
typedef struct {
    const char *method;
    const char *path;
    const char *body;
    sihttp_app_state_t *state;
} sihttp_request_t;

typedef sihttp_response_t (*sihttp_handler_t)(const sihttp_request_t *);

/* HTTP methods. GET is the default method when the value is 0. */
typedef enum {
    SIHTTP_METHOD_GET = 0,
    SIHTTP_METHOD_POST,
    SIHTTP_METHOD_PUT,
    SIHTTP_METHOD_DELETE,
    SIHTTP_METHOD_OPTIONS,
} sihttp_method_t;

/* Route descriptor used by sihttp_route. */
typedef struct {
    sihttp_method_t method;
    sihttp_handler_t callback;
} sihttp_handler_desc_t;

/* Server configuration.
 * state is owned by the user and must outlive the server.
 * port 0 lets the OS choose a port; backlog uses a library default when set to 0.
 * max_requests_per_poll limits per-frame work; 0 uses a library default.
 */
typedef struct {
    int port;
    sihttp_app_state_t *state;
    int backlog;
    int max_requests_per_poll;
} sihttp_server_desc_t;

/* Server lifecycle. */
#define sihttp_server(...) sihttp_server_init(&(sihttp_server_desc_t)__VA_ARGS__)

SIHTTP_API sihttp_server_t *sihttp_server_init(const sihttp_server_desc_t *desc);
SIHTTP_API void sihttp_server_fini(sihttp_server_t *server);

/* Server runtime. host may be NULL to bind all IPv4 interfaces. */
SIHTTP_API int sihttp_server_listen(sihttp_server_t *server, const char *host, uint16_t port);
SIHTTP_API int sihttp_server_start(sihttp_server_t *server);
SIHTTP_API int sihttp_server_poll(sihttp_server_t *server);
SIHTTP_API int sihttp_server_run(sihttp_server_t *server);
SIHTTP_API void sihttp_server_stop(sihttp_server_t *server);
SIHTTP_API uint16_t sihttp_server_port(const sihttp_server_t *server);

/* Route registration. */
#define sihttp_route(server, path, ...)                                                            \
    sihttp_route_impl(server, path, &(sihttp_handler_desc_t)__VA_ARGS__)

SIHTTP_API void
sihttp_route_impl(sihttp_server_t *server, const char *path, const sihttp_handler_desc_t *desc);

SIHTTP_API void sihttp_get(sihttp_server_t *server, const char *path, sihttp_handler_t callback);
SIHTTP_API void sihttp_post(sihttp_server_t *server, const char *path, sihttp_handler_t callback);
SIHTTP_API void sihttp_put(sihttp_server_t *server, const char *path, sihttp_handler_t callback);
SIHTTP_API void sihttp_delete(sihttp_server_t *server, const char *path, sihttp_handler_t callback);

/* Route parameters are intentionally parsed as integers only. */
SIHTTP_API int64_t sihttp_param(const sihttp_request_t *req, const char *name);

/* Last library error for the current process. */
SIHTTP_API const char *sihttp_error(void);

/* printf-like formatter. Returns a heap-allocated string. */
SIHTTP_API char *siformat(const char *fmt, ...) SIHTTP_PRINTF_FORMAT(1, 2);

/* Build a response value with designated initializers. */
#define sihttp_response(...) ((sihttp_response_t)__VA_ARGS__)

#ifdef __cplusplus
}
#endif

#endif
// Comment out this line when using as DLL
#define siecs_STATIC
#ifndef SIECS_H
#define SIECS_H

#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L
#endif

/*
                                   )
                                  (.)
                                  .|.
                                  | |
                              _.--| |--._
                           .-';  ;`-'& ; `&.
                          \   &  ;    &   &_/
                           |"""---...---"""|
                           \ | | | | | | | /
                            `---.|.|.|.---'

 * This file is generated by bake.lang.c for your convenience. Headers of
 * dependencies will automatically show up in this file. Include bake_config.h
 * in your main project file. Do not edit! */

#ifndef SIECS_BAKE_CONFIG_H
#define SIECS_BAKE_CONFIG_H

/* Headers of public dependencies */

/* Convenience macro for exporting symbols */
#ifndef siecs_STATIC
#if defined(siecs_EXPORTS) && (defined(_MSC_VER) || defined(__MINGW32__))
  #define SIECS_API __declspec(dllexport)
#elif defined(siecs_EXPORTS)
  #define SIECS_API __attribute__((__visibility__("default")))
#elif defined(_MSC_VER)
  #define SIECS_API __declspec(dllimport)
#else
  #define SIECS_API
#endif
#else
  #define SIECS_API
#endif

#endif

#ifdef __cplusplus
#ifndef _Alignof
#define _Alignof alignof
#endif
#endif

#include <stdbool.h>
#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Public id symbol generated for a component type.
 *
 * Users normally do not call this macro directly. It is used by the typed
 * helpers such as ecs_add(world, entity, Position).
 */
#define ecs_id(name) _ecs_id_##name##__

/* Opaque ECS world. Create with ecs_init and destroy with ecs_fini. */
struct ecs_world_s;
typedef struct ecs_world_s ecs_world_t;

/* Public handle types. A zero id is reserved internally and is not user data.
 */
typedef uint64_t ecs_entity_t;
typedef uint16_t ecs_component_t;
typedef uint16_t ecs_query_id_t;
typedef uint16_t ecs_system_id_t;
typedef uint16_t ecs_event_t;
typedef uint16_t ecs_module_id_t;
typedef uint16_t ecs_resource_t;
typedef uint32_t ecs_observer_id_t;

#define ECS_QUERY_TERM_CAPACITY 64
#define ECS_SYSTEM_AFTER_CAPACITY 16

/*
 * Module import callback.
 *
 * Called the first time the module is imported into the active world. The
 * callback is expected to register the module's components, systems, observers,
 * and nested modules. Registrations made while the callback runs are recorded
 * under the importing module so ecs_module_enable/ecs_module_disable can toggle
 * its systems and observers later.
 *
 * desc is the user props pointer from ecs_module_desc_t. The library does not
 * retain or copy it; it is only valid for the duration of this call.
 */
typedef void (*ecs_module_import_t)(ecs_world_t *world, const void *desc);

/*
 * Module registration descriptor.
 *
 * name and import are required.
 *
 * id points to the module id storage used as the import cache. If *id is not 0,
 * ecs_module_init returns it and does not call import again. If *id is 0,
 * ecs_module_init creates the module and stores the new id in *id. The typed
 * ECS_MODULE_* macros pass the generated ecs_id(module_name) storage here.
 *
 * This module cache is process-global by design. SIECS supports one active
 * world owning a given typed module at a time; ecs_fini resets imported module
 * ids to 0 so a later world can import them again.
 *
 * desc/desc_size describe optional import props. desc_size is informational in
 * the current C API and is kept for validation/introspection compatibility.
 *
 * disabled imports the module and immediately disables the systems and
 * observers captured during import. Components remain registered.
 */
typedef struct {
    const char *name;
    ecs_module_id_t *id;
    ecs_module_import_t import;
    const void *desc;
    uint32_t desc_size;
    bool disabled;
} ecs_module_desc_t;

/*
 * Event payload passed to observer callbacks.
 *
 * trigger_data is event-specific:
 * - EcsOnAdd: pointer to the added component storage.
 * - EcsOnRemove: pointer to the component storage before removal.
 * - EcsOnSet: pointer to the new value passed to ecs_set/ecs_set_cid.
 * - Custom events: pointer passed to ecs_observer_trigger.
 */
typedef struct {
    ecs_world_t *world;
    ecs_entity_t entity;
    ecs_event_t event;
    uintptr_t user_data;
    const void *trigger_data;
} ecs_observer_event_t;

typedef void (*ecs_observer_callback_t)(ecs_observer_event_t *event);

/* Called after a component slot is added and zero-initialized. */
typedef void (*ecs_component_on_add_t)(
    ecs_world_t *world,
    ecs_entity_t entity,
    ecs_component_t component,
    void *value
);

/*
 * Called before ecs_set_cid copies new_value into current_value.
 *
 * current_value is the component slot currently stored on the entity. Hooks can
 * inspect the old value there, and may mutate it before the final copy.
 */
typedef void (*ecs_component_on_set_t)(
    ecs_world_t *world,
    ecs_entity_t entity,
    ecs_component_t component,
    const void *new_value,
    void *current_value
);

/* Called before a component slot is removed. */
typedef void (*ecs_component_on_remove_t)(
    ecs_world_t *world,
    ecs_entity_t entity,
    ecs_component_t component,
    void *value
);

/*
 * Value lifecycle operations for non-trivial component/resource storage.
 *
 * ctor initializes count values at dst. dtor destroys count live values at ptr.
 * copy_ctor initializes dst from live src values. copy replaces live dst values
 * from live src values. move_ctor initializes dst by consuming live src values.
 * move replaces live dst values by consuming live src values.
 *
 * Any NULL operation falls back to plain C storage behavior: zero initialize for
 * ctor, no-op for dtor, and memcpy for copy/move operations.
 */
typedef void (*ecs_type_ctor_t)(void *dst, uint32_t count);
typedef void (*ecs_type_dtor_t)(void *ptr, uint32_t count);
typedef void (*ecs_type_copy_t)(void *dst, const void *src, uint32_t count);
typedef void (*ecs_type_move_t)(void *dst, void *src, uint32_t count);

typedef struct {
    ecs_type_ctor_t ctor;
    ecs_type_dtor_t dtor;
    ecs_type_copy_t copy_ctor;
    ecs_type_copy_t copy;
    ecs_type_move_t move_ctor;
    ecs_type_move_t move;
} ecs_type_ops_t;

/*
 * Relation behavior flags used by ECS_RELATION_DEFINE.
 *
 * EcsRelationTarget marks the relation component stored on the source entity.
 * EcsRelationSource marks the internal reverse-link component stored on target
 * entities. EcsRelationCascadeDelete kills related source entities when the
 * target entity is killed.
 */
typedef enum {
    EcsRelationTarget = 1 << 0,
    EcsRelationSource = 1 << 1,
    EcsRelationCascadeDelete = 1 << 2,
    EcsRelationOneToOne = 1 << 3,
    EcsRelationOneToMany = 1 << 4
} ecs_relation_flags_t;

/*
 * Component registration descriptor.
 *
 * name is used for reflection/debug/introspection. size is sizeof(T) for data
 * components and 0 for tags. Hooks are optional lifecycle callbacks.
 * struct_desc enables reflection for ECS_COMPONENT_* generated types.
 *
 * relation_flags is normally set only by ECS_RELATION_DEFINE.
 */
typedef struct {
    const char *name;
    uint64_t size;
    ecs_type_ops_t ops;
    ecs_component_on_set_t on_set;
    ecs_component_on_remove_t on_remove;
    ecs_component_on_add_t on_add;
    uint32_t relation_flags;
    const sireflect_struct_desc_t *struct_desc;
} ecs_component_desc_t;

/*
 * Resource hook function type.
 *
 * ptr points to the resource value being set or removed. The pointer is only
 * valid for the duration of the callback.
 */
typedef void (*ecs_resource_hook_t)(ecs_world_t *world, const void *ptr);

/*
 * Resource registration descriptor.
 *
 * Resources are per-world singleton values with their own id space. name and
 * size are required; hooks are optional.
 */
typedef struct {
    const char *name;
    uint64_t size;
    ecs_type_ops_t ops;
    ecs_resource_hook_t on_set;
    ecs_resource_hook_t on_remove;
} ecs_resource_desc_t;

/* Query term access mode. */
typedef enum {
    EcsIn,            /* Component must exist and is returned by ecs_field for reading. */
    EcsOut,           /* Component must exist and is returned by ecs_field for writing. */
    EcsInOut,         /* Component must exist and is returned by ecs_field for read/write.
                       */
    EcsInOptional,    /* Component is returned by ecs_field if present, NULL
                         otherwise. */
    EcsInOutOptional, /* Component is returned by ecs_field if present, NULL
                         otherwise. */
    EcsFilter,        /* Component must exist but is not returned by ecs_field. */
    EcsNot,           /* Component must not exist and is not returned by ecs_field. */
} ecs_term_access_t;

/*
 * Query term descriptor.
 *
 * Prefer ecs_in/ecs_out/ecs_inout/ecs_filter/ecs_not helpers in user code.
 * Fill this manually only for dynamic component ids.
 */
typedef struct {
    ecs_component_t id;
    ecs_term_access_t access;
} ecs_query_term_t;

/*
 * Query descriptor.
 *
 * terms is a zero-terminated component term list. Terms with EcsIn, EcsOut,
 * EcsInOut, EcsInOptional and EcsInOutOptional are returned by ecs_field in
 * declaration order. Optional fields return NULL for tables without the
 * component. EcsFilter and EcsNot only affect table matching.
 *
 * A query must contain at least one term or an is_a target.
 */
typedef struct {
    ecs_query_term_t terms[ECS_QUERY_TERM_CAPACITY];
    ecs_entity_t is_a;
} ecs_query_desc_t;

/*
 * Typed query term helpers.
 *
 * Example:
 *   ecs_query_id_t q = ecs_query(world, {
 *       .terms = { ecs_inout(Position), ecs_in(Velocity), ecs_filter(Player) }
 *   });
 */
#ifdef __cplusplus
#define ecs_in(cname)                                                                              \
    ecs_query_term_t { ecs_id(cname), EcsIn }
#define ecs_out(cname)                                                                             \
    ecs_query_term_t { ecs_id(cname), EcsOut }
#define ecs_inout(cname)                                                                           \
    ecs_query_term_t { ecs_id(cname), EcsInOut }
#define ecs_in_optional(cname)                                                                     \
    ecs_query_term_t { ecs_id(cname), EcsInOptional }
#define ecs_inout_optional(cname)                                                                  \
    ecs_query_term_t { ecs_id(cname), EcsInOutOptional }
#define ecs_filter(cname)                                                                          \
    ecs_query_term_t { ecs_id(cname), EcsFilter }
#define ecs_not(cname)                                                                             \
    ecs_query_term_t { ecs_id(cname), EcsNot }
#else
#define ecs_in(cname) ((ecs_query_term_t){ ecs_id(cname), EcsIn })
#define ecs_out(cname) ((ecs_query_term_t){ ecs_id(cname), EcsOut })
#define ecs_inout(cname) ((ecs_query_term_t){ ecs_id(cname), EcsInOut })
#define ecs_in_optional(cname) ((ecs_query_term_t){ ecs_id(cname), EcsInOptional })
#define ecs_inout_optional(cname) ((ecs_query_term_t){ ecs_id(cname), EcsInOutOptional })
#define ecs_filter(cname) ((ecs_query_term_t){ ecs_id(cname), EcsFilter })
#define ecs_not(cname) ((ecs_query_term_t){ ecs_id(cname), EcsNot })
#endif

/* Create an ECS world. */
SIECS_API ecs_world_t *ecs_init(void);

/* World feature descriptor. */
typedef struct {
    /* Start the REST explorer server when the rest addon is built in. */
    bool rest;

    /* Target frames per second for the world's update loop. */
    uint16_t target_fps;
} ecs_world_feat_desc_t;

/* Create a world with the given features. */
#define ecs_with_features(...) ecs_init_w_features(&(ecs_world_feat_desc_t)__VA_ARGS__)

/* Initialize a world with the given features. */
SIECS_API ecs_world_t *ecs_init_w_features(const ecs_world_feat_desc_t *features);

/* Destroy a world and all ECS storage owned by it. world must not be NULL. */
SIECS_API void ecs_fini(ecs_world_t *world);

/* Request that future ecs_progress calls return false. */
SIECS_API void ecs_quit(ecs_world_t *world);

/*
 * Declare a component type and its public component id.
 *
 * Use in headers:
 *   ECS_COMPONENT_DECLARE(Position, { float x; float y; });
 */
#define ECS_COMPONENT_DECLARE(cname, ...)                                                          \
    SIJSON_DECLARE(cname, __VA_ARGS__)                                                             \
    extern ecs_component_t ecs_id(cname);                                                          \
    extern ecs_component_desc_t ecs_id(cname##_desc)

/*
 * Define a component declared with ECS_COMPONENT_DECLARE.
 *
 * Use once in a C file:
 *   ECS_COMPONENT_DEFINE(Position);
 */
#define ECS_COMPONENT_DEFINE(cname, ...)                                                           \
    SIJSON_DEFINE(cname)                                                                           \
    ecs_component_desc_t ecs_id(cname##_desc) = { .name = #cname,                                  \
                                                  .size = sizeof(cname),                           \
                                                  .struct_desc = &sireflect_desc(cname),           \
                                                  __VA_ARGS__ };                                   \
    ecs_component_t ecs_id(cname) = 0

/*
 * Register a component type in a world.
 *
 * Must be called before using the typed helpers for that component with this
 * world. Stores the generated component id in ecs_id(cname).
 */
#define ECS_COMPONENT_REGISTER(world, cname)                                                       \
    ecs_component_register(world, &ecs_id(cname), &ecs_id(cname##_desc))

/*
 * Declare and define a component type in one translation unit.
 *
 * Example:
 *   ECS_COMPONENT(Position, { float x; float y; });
 */
#define ECS_COMPONENT(cname, ...)                                                                  \
    ECS_COMPONENT_DECLARE(cname, __VA_ARGS__);                                                     \
    ECS_COMPONENT_DEFINE(cname);

/*
 * Declare a typed module.
 *
 * Use in a header:
 *   ECS_MODULE_DECLARE(physics, { float gravity; });
 *
 * This declares physics_props_t, the public module id symbol ecs_id(physics),
 * an import wrapper, and the user-defined import function:
 *   void physics_import(ecs_world_t *world, const physics_props_t *props);
 */
#define ECS_MODULE_DECLARE(module_name, ...)                                                       \
    typedef struct module_name##_props_t __VA_ARGS__ module_name##_props_t;                        \
    extern ecs_module_id_t ecs_id(module_name);                                                    \
    void ecs_id(module_name##_import_wrapper)(ecs_world_t * world, const void *desc);              \
    void module_name##_import(ecs_world_t *world, const module_name##_props_t *props)

/*
 * Define a typed module declared with ECS_MODULE_DECLARE.
 *
 * Use once in a C file before implementing module_name_import.
 */
#define ECS_MODULE_DEFINE(module_name)                                                             \
    ecs_module_id_t ecs_id(module_name) = 0;                                                       \
    void ecs_id(module_name##_import_wrapper)(ecs_world_t * world, const void *desc) {             \
        module_name##_import(world, (const module_name##_props_t *)desc);                          \
    }

/*
 * Import a typed module into a world.
 *
 * The first import calls module_name_import and stores the returned module id
 * in ecs_id(module_name). Later imports of the same module in the same world
 * return the existing id without calling module_name_import again; the first
 * props value wins.
 */
#define ECS_MODULE_IMPORT(world, module_name, ...)                                                 \
    (ecs_id(module_name) = ecs_module_init(                                                        \
         world,                                                                                    \
         &(ecs_module_desc_t){                                                                     \
             .name = #module_name,                                                                 \
             .id = &ecs_id(module_name),                                                           \
             .import = ecs_id(module_name##_import_wrapper),                                       \
             .desc = &(module_name##_props_t)__VA_ARGS__,                                          \
             .desc_size = sizeof(module_name##_props_t),                                           \
         }                                                                                         \
     ))

/*
 * Register/import a module with a raw descriptor.
 *
 * Prefer ECS_MODULE_IMPORT for typed modules. Use this when module properties
 * or ids are built dynamically.
 */
#define ecs_module(world, ...) ecs_module_init(world, &(ecs_module_desc_t)__VA_ARGS__)

/* Register/import a module descriptor and return its module id. */
SIECS_API ecs_module_id_t ecs_module_init(ecs_world_t *world, const ecs_module_desc_t *desc);

/*
 * Find an already imported module by its id storage.
 *
 * For typed modules, pass &ecs_id(module_name). Returns 0 if the
 * module has not been imported into this world.
 */
SIECS_API ecs_module_id_t ecs_module_find(ecs_world_t *world, const ecs_module_id_t *id);

/* Enable systems and observers recorded during module import. */
SIECS_API void ecs_module_enable(ecs_world_t *world, ecs_module_id_t module);

/* Disable systems and observers recorded during module import. */
SIECS_API void ecs_module_disable(ecs_world_t *world, ecs_module_id_t module);

/* Return whether a module is currently enabled in this world. */
SIECS_API bool ecs_module_is_enabled(const ecs_world_t *world, ecs_module_id_t module);

/*
 * Define a relation component.
 *
 * A relation stores an entity target. The implementation also creates a source
 * component used internally to track reverse links.
 *
 * Example:
 *   ECS_RELATION_DECLARE(ParentOf);
 *   ECS_RELATION_DEFINE(ParentOf, EcsRelationCascadeDelete);
 */
#define ECS_RELATION_DEFINE(cname, flags)                                                          \
    ecs_component_desc_t ecs_id(cname##_desc) = {                                                  \
        .name = #cname,                                                                            \
        .size = sizeof(cname),                                                                     \
        .relation_flags = EcsRelationTarget | (flags),                                             \
    };                                                                                             \
    ecs_component_t ecs_id(cname) = 0

#define ECS_RELATION(cname, flags)                                                                 \
    ECS_RELATION_DECLARE(cname);                                                                   \
    ECS_RELATION_DEFINE(cname, flags)

/* Return the internal source component id associated with a relation id. */
#define ecs_source(name) (ecs_id(name) + 1)

/*
 * Declare a relation type. The generated struct contains ecs_entity_t target.
 *
 * Example:
 *   ECS_RELATION_DECLARE(Targets);
 *   ecs_set(world, entity, Targets, { target });
 */
#define ECS_RELATION_DECLARE(name) ECS_COMPONENT_DECLARE(name, { ecs_entity_t target; })

/* Builtin relation for parent/child relationships. */
ECS_RELATION_DECLARE(ChildOf);

/* Builtin component for entity names. */
ECS_COMPONENT_DECLARE(Name, { char *value; });

/* Builtin component excluded from queries by default. */
ECS_COMPONENT_DECLARE(Disabled, {});

/* Builtin component for abstract entity. */
ECS_COMPONENT_DECLARE(Abstract, {});

/*
 * Register a component from an inline descriptor.
 *
 * Example:
 *   ecs_component_t Position = ecs_component(world, {
 *       .name = "Position",
 *       .size = sizeof(Position)
 *   });
 */
#define ecs_component(world, ...) ecs_component_init(world, &(ecs_component_desc_t)__VA_ARGS__)

/* Register a component descriptor and return its component id. */
SIECS_API ecs_component_t ecs_component_init(ecs_world_t *world, const ecs_component_desc_t *desc);

/* Register a typed component descriptor using stable process-wide id storage.
 */
SIECS_API ecs_component_t
ecs_component_register(ecs_world_t *world, ecs_component_t *id, const ecs_component_desc_t *desc);

/* Create a new alive entity in world. world must not be NULL. */
SIECS_API ecs_entity_t ecs_new(ecs_world_t *world);

/* Begin deferring ECS mutations into the world's command buffer. */
SIECS_API void ecs_defer_begin(ecs_world_t *world);

/* End a defer scope. The outermost end flushes the command buffer. */
SIECS_API void ecs_defer_end(ecs_world_t *world);

/* Return whether mutations are currently being deferred or flushed. */
SIECS_API bool ecs_is_deferred(const ecs_world_t *world);

/*
 * Return whether entity is alive in world.
 *
 * entity must be a handle created by this world. Passing arbitrary ids is not a
 * supported validity check.
 */
SIECS_API bool ecs_is_alive(const ecs_world_t *world, ecs_entity_t entity);

bool ecs_is(ecs_world_t *world, ecs_entity_t entity, ecs_entity_t target);

SIECS_API void ecs_is_a(ecs_world_t *world, ecs_entity_t entity, ecs_entity_t target);

/* Destroy an alive entity and remove all of its components. */
SIECS_API void ecs_kill(ecs_world_t *world, ecs_entity_t entity);

/*
 * Create a query from an inline descriptor.
 *
 * Example:
 *   ecs_query_id_t q = ecs_query(world, {
 *       .terms = { ecs_in(Position), ecs_in(Velocity) }
 *   });
 */
#define ecs_query(world, ...) ecs_query_init(world, &(ecs_query_desc_t)__VA_ARGS__)

/*
 * Convenience query loop for short-lived queries.
 *
 * This macro creates a temporary query, iterates it, then destroys it. Prefer a
 * persistent ecs_query_id_t for systems, hot paths, or repeated frame work.
 *
 * Example:
 *   ecs_query_each(world, it, i, ecs_in(Position), ecs_in(Velocity)) {
 *       Position *p = ecs_field(&it, 0);
 *       Velocity *v = ecs_field(&it, 1);
 *       p[i].x += v[i].x;
 *   }
 */
#define ecs_query_each(world, it, i, ...)                                                          \
    for (ecs_query_id_t _q = ecs_query((world), { { __VA_ARGS__ } }); _q;                          \
         ecs_query_fini((world), _q), _q = 0)                                                      \
        for (ecs_iter_t it = ecs_query_iter((world), _q); ecs_iter_next(&it);)                     \
            for (uint32_t i = 0; i < it.count; i++)

/* Create a query. The query descriptor must read at least one component. */
SIECS_API ecs_query_id_t ecs_query_init(ecs_world_t *world, const ecs_query_desc_t *query);

/* Destroy a query id created by ecs_query/ecs_query_init. */
SIECS_API void ecs_query_fini(ecs_world_t *world, ecs_query_id_t qid);

/* Add a typed component tag/storage to an alive entity. */
#define ecs_add(world, entity, cname) ecs_add_cid(world, entity, ecs_id(cname))

/*
 * Add a component id to an alive entity.
 *
 * If the component is already present, this is currently treated as a no-op by
 * table migration. The component id must be registered in the same world.
 */
SIECS_API void ecs_add_cid(ecs_world_t *world, ecs_entity_t entity, ecs_component_t id);

/* Remove a typed component from an alive entity. */
#define ecs_remove(world, entity, cname) ecs_remove_cid(world, entity, ecs_id(cname))

/*
 * Remove a component id from an alive entity.
 *
 * Removing a component that is not present is a no-op.
 */
SIECS_API void ecs_remove_cid(ecs_world_t *world, ecs_entity_t entity, ecs_component_t id);

/* Return whether an alive entity has a typed component. */
#define ecs_has(world, entity, cname) ecs_has_cid(world, entity, ecs_id(cname))

/* Return whether an alive entity has a component id. */
SIECS_API bool ecs_has_cid(const ecs_world_t *world, ecs_entity_t entity, ecs_component_t id);
bool ecs_has_cid_owned(const ecs_world_t *world, ecs_entity_t entity, ecs_component_t id);

/*
 * Get a typed component pointer from an alive entity.
 *
 * The component is assumed to exist. Use ecs_try_get when the component may be
 * absent.
 */
#define ecs_get(world, entity, cname) ((cname *)ecs_get_cid(world, entity, ecs_id(cname)))

/*
 * Get a component pointer by id.
 *
 * The component is assumed to exist on the entity. Use ecs_try_get_cid when the
 * component may be absent.
 */
SIECS_API void *ecs_get_cid(ecs_world_t *world, ecs_entity_t entity, ecs_component_t id);

/* Get a typed component pointer, or NULL if the entity does not have it. */
#define ecs_try_get(world, entity, cname) ((cname *)ecs_try_get_cid(world, entity, ecs_id(cname)))

/* Get a component pointer by id, or NULL if the entity does not have it. */
SIECS_API void *ecs_try_get_cid(ecs_world_t *world, ecs_entity_t entity, ecs_component_t cid);

/*
 * Set a typed component value on an alive entity.
 *
 * Adds the component if needed, then emits EcsOnSet. Component on_set hooks
 * receive the new value and current storage before the copy. EcsOnSet observers
 * receive the new value before it is copied into storage.
 */
#define ecs_set(world, entity, cname, ...)                                                         \
    ecs_set_cid(world, entity, ecs_id(cname), &(cname)__VA_ARGS__)

/*
 * Set a component value by id.
 *
 * data must point to at least the registered component size. Adds the component
 * if needed.
 */
SIECS_API void
ecs_set_cid(ecs_world_t *world, ecs_entity_t entity, ecs_component_t id, const void *data);
SIECS_API void
ecs_move_cid(ecs_world_t *world, ecs_entity_t entity, ecs_component_t id, void *data);

/*
 * Declare and define a resource type.
 *
 * Resources use their own id space and are stored once per world. They are not
 * components, do not appear in queries, and do not consume component ids.
 *
 * Use ECS_RESOURCE_DECLARE in headers and ECS_RESOURCE_DEFINE once in a C file,
 * or ECS_RESOURCE for local examples/tests.
 *
 * Example:
 *   ECS_RESOURCE(Time, { float dt; float elapsed; });
 */
#define ECS_RESOURCE_DECLARE(rname, ...)                                                           \
    typedef struct rname rname;                                                                    \
    struct rname __VA_ARGS__;                                                                      \
    extern ecs_resource_t ecs_id(rname);                                                           \
    extern ecs_resource_desc_t ecs_id(rname##_desc)

#define ECS_RESOURCE_DEFINE(rname, ...)                                                            \
    ecs_resource_desc_t ecs_id(rname##_desc) = { .name = #rname,                                   \
                                                 .size = sizeof(rname),                            \
                                                 __VA_ARGS__ };                                    \
    ecs_resource_t ecs_id(rname) = 0

#define ECS_RESOURCE_REGISTER(world, rname)                                                        \
    ecs_resource_register(world, &ecs_id(rname), &ecs_id(rname##_desc))

#define ECS_RESOURCE(rname, ...)                                                                   \
    ECS_RESOURCE_DECLARE(rname, __VA_ARGS__);                                                      \
    ECS_RESOURCE_DEFINE(rname)

/*
 * Set or replace a world resource.
 *
 * Example:
 *   ecs_set_resource(world, Time, { .dt = 0.016f, .elapsed = 0.0f });
 */
#define ecs_set_resource(world, rname, ...)                                                        \
    ecs_set_resource_rid(world, ecs_id(rname), &(rname)__VA_ARGS__)

/* Get a world resource. The resource must exist. */
#define ecs_get_resource(world, rname) ((rname *)ecs_resource_rid(world, ecs_id(rname)))
#define ecs_get_resource_read(world, rname) ((const rname *)ecs_resource_rid(world, ecs_id(rname)))

/* Get a world resource, or NULL if it does not exist. */
#define ecs_try_get_resource(world, rname) ((rname *)ecs_try_resource_rid(world, ecs_id(rname)))
#define ecs_try_get_resource_read(world, rname)                                                    \
    ((const rname *)ecs_try_resource_rid(world, ecs_id(rname)))

/* Return whether a world resource exists. */
#define ecs_has_resource(world, rname) ecs_has_resource_rid(world, ecs_id(rname))

/* Remove a world resource if it exists. */
#define ecs_remove_resource(world, rname) ecs_remove_resource_rid(world, ecs_id(rname))

/* Backward-compatible resource aliases. Prefer the ecs_get_resource names in
 * new code. */
#define ecs_resource(world, rname) ecs_get_resource(world, rname)
#define ecs_resource_read(world, rname) ecs_get_resource_read(world, rname)
#define ecs_try_resource(world, rname) ecs_try_get_resource(world, rname)
#define ecs_try_resource_read(world, rname) ecs_try_get_resource_read(world, rname)

SIECS_API ecs_resource_t ecs_resource_init(ecs_world_t *world, const ecs_resource_desc_t *desc);
SIECS_API ecs_resource_t
ecs_resource_register(ecs_world_t *world, ecs_resource_t *id, const ecs_resource_desc_t *desc);
SIECS_API ecs_resource_t ecs_resource_find(ecs_world_t *world, const char *name);
SIECS_API bool ecs_resource_is_registered_rid(const ecs_world_t *world, ecs_resource_t id);
SIECS_API void ecs_set_resource_rid(ecs_world_t *world, ecs_resource_t id, const void *data);
SIECS_API void ecs_move_resource_rid(ecs_world_t *world, ecs_resource_t id, void *data);
SIECS_API void *ecs_resource_rid(ecs_world_t *world, ecs_resource_t id);
SIECS_API void *ecs_try_resource_rid(ecs_world_t *world, ecs_resource_t id);
SIECS_API bool ecs_has_resource_rid(const ecs_world_t *world, ecs_resource_t id);
SIECS_API void ecs_remove_resource_rid(ecs_world_t *world, ecs_resource_t id);

/*
 * Declare that adding component also adds require first.
 *
 * Requirement cycles are debug assertion failures when declared.
 *
 * Example:
 *   ecs_with(world, ecs_id(Renderable), ecs_id(Transform));
 *   ecs_add(world, entity, Renderable); // also adds Transform
 */
SIECS_API void ecs_with(ecs_world_t *world, ecs_component_t component, ecs_component_t require);

/* Builtin observer events. */
#define EcsOnAdd 0
#define EcsOnRemove 1
#define EcsOnSet 2

/*
 * Observer descriptor.
 *
 * callback is required. query describes which entities can receive the event.
 * user_data is copied into ecs_observer_event_t for the callback.
 */
typedef struct {
    ecs_event_t on;
    ecs_query_desc_t query;
    ecs_observer_callback_t callback;
    uintptr_t user_data;
} ecs_observer_desc_t;

/*
 * Create an observer from an inline descriptor.
 *
 * Example:
 *   ecs_observer(world, {
 *       .on = EcsOnSet,
 *       .query.terms = { ecs_in(Position) },
 *       .callback = on_position_set,
 *   });
 */
#define ecs_observer(world, ...) ecs_observer_init(world, &(ecs_observer_desc_t)__VA_ARGS__)

/* Allocate and return a custom event id for ecs_observer_trigger. */
SIECS_API ecs_event_t ecs_event(ecs_world_t *world);

/*
 * Register a process-wide typed event id in this world.
 *
 * If *id is UINT16_MAX, allocates a new custom event id and stores it in *id.
 * Otherwise, reserves the existing id in this world so future ecs_event calls
 * cannot collide with the typed event.
 */
SIECS_API ecs_event_t ecs_event_register(ecs_world_t *world, ecs_event_t *id);

/* Create an observer. desc->callback must not be NULL. */
SIECS_API ecs_observer_id_t ecs_observer_init(ecs_world_t *world, const ecs_observer_desc_t *desc);

SIECS_API void ecs_observer_enable(ecs_world_t *world, ecs_observer_id_t id);
SIECS_API void ecs_observer_disable(ecs_world_t *world, ecs_observer_id_t id);

/*
 * Trigger an event for an alive entity.
 *
 * Observers matching the entity's current table and event id will be called.
 */
SIECS_API void ecs_observer_trigger(
    ecs_world_t *world,
    ecs_entity_t entity,
    ecs_event_t event,
    const void *trigger_data
);

/*
 * Query iterator.
 *
 * Users may read world and count. The other fields are implementation details
 * and should not be accessed directly.
 *
 * entities points to the current batch after ecs_iter_next returns true.
 */
typedef enum {
    EcsFieldNone,
    EcsFieldOwned,
    EcsFieldShared,
} ecs_field_kind_t;

typedef struct {
    ecs_world_t *world;
    uint32_t count;
    ecs_entity_t *entities;
    void **ptrs;
    float delta_time;
    struct ecs_query_cache_s *cache;
    ecs_field_kind_t *field_kinds;
    uintptr_t user_data;
    uint16_t table_idx;
    uint16_t table_count;
} ecs_iter_t;

/*
 * Create a stack iterator for a query id.
 *
 * Example:
 *   ecs_iter_t it = ecs_query_iter(world, query);
 *   while (ecs_iter_next(&it)) {
 *       Position *p = ecs_field(&it, 0);
 *   }
 */
SIECS_API ecs_iter_t ecs_query_iter(ecs_world_t *world, ecs_query_id_t query_id);

/*
 * Advance an iterator to the next non-empty batch.
 *
 * Returns false when iteration is finished. it->count is the number of entities
 * in the current batch.
 */
SIECS_API bool ecs_iter_next(ecs_iter_t *it);

/*
 * Return the component array for a read term in the current iterator batch.
 *
 * field_index is zero-based among EcsIn, EcsOut, EcsInOut, EcsInOptional and
 * EcsInOutOptional terms only. Optional fields return NULL when the current
 * table does not have the component. EcsFilter and EcsNot terms affect matching
 * but are not returned as fields.
 */
static inline void *ecs_field(ecs_iter_t *it, uint16_t field_index) {
    void *field = it->ptrs[field_index];
    return it->field_kinds[field_index] == EcsFieldOwned ? *(void **)field : field;
}

static inline bool ecs_field_is_shared(ecs_iter_t *it, uint16_t field_index) {
    return it->field_kinds[field_index] == EcsFieldShared;
}

/* System phases run in enum order when ecs_progress is called. */
typedef enum {
    EcsPreStart,
    EcsStart,
    EcsPostStart,
    EcsOnLoad,
    EcsPostLoad,
    EcsPreUpdate,
    EcsOnUpdate,
    EcsPostUpdate,
    EcsPreRender,
    EcsOnRender,
    EcsPostRender,
    EcsPhaseCount,
} ecs_phase_t;

/* Backward-compatible phase aliases. Prefer the Ecs* names in new code. */
#define OnPreUpdate EcsPreUpdate
#define OnUpdate EcsOnUpdate
#define OnPostUpdate EcsPostUpdate
#define OnRender EcsOnRender

/*
 * System descriptor.
 *
 * If query has terms, callback is called once per non-empty iterator batch
 * matching query. If query has no terms, the system runs once with an empty
 * iterator. phase controls when ecs_progress/ecs_run_phase executes the system.
 * after contains up to four system ids that must run before this system in the
 * same phase.
 */
typedef struct {
    const char *name;
    ecs_query_desc_t query;
    void (*callback)(ecs_iter_t *);
    uintptr_t user_data;
    void (*user_data_dtor)(uintptr_t user_data);
    ecs_phase_t phase;
    ecs_system_id_t after[ECS_SYSTEM_AFTER_CAPACITY];
    bool disabled;
} ecs_system_desc_t;

/*
 * Create a system from an inline descriptor.
 *
 * Example:
 *   ecs_system(world, {
 *       .name = "Move",
 *       .phase = EcsOnUpdate,
 *       .query.terms = { ecs_inout(Position), ecs_in(Velocity) },
 *       .callback = Move,
 *   });
 */
#define ecs_system(world, ...) ecs_system_init(world, &(ecs_system_desc_t)__VA_ARGS__)

/* Register a system and return its id. System id 0 is reserved. */
SIECS_API ecs_system_id_t ecs_system_init(ecs_world_t *world, const ecs_system_desc_t *desc);

/* Run all enabled systems in phase order. */
SIECS_API bool ecs_progress(ecs_world_t *world);

/* Run all enabled systems from one phase. */
SIECS_API void ecs_run_phase(ecs_world_t *world, ecs_phase_t phase);

/* Run one enabled system immediately. */
SIECS_API void ecs_run_system(ecs_world_t *world, ecs_system_id_t system);

/* Enable or disable a system. Disabled systems stay registered but do not run.
 */
SIECS_API void ecs_system_enable(ecs_world_t *world, ecs_system_id_t system);
SIECS_API void ecs_system_disable(ecs_world_t *world, ecs_system_id_t system);

#ifdef __cplusplus
}
#endif

#if defined(__cplusplus) && !defined(SIECS_NO_CPP)
#ifndef SIECS_PUBLIC_CPP_HPP
#define SIECS_PUBLIC_CPP_HPP

#pragma once
#pragma once

#pragma once
#include <string_view>

namespace ecs {

template <class T> consteval std::string_view type_name() {
    constexpr std::string_view func = __PRETTY_FUNCTION__;
    constexpr std::string_view key = "T = ";

    constexpr auto start = func.find(key) + key.size();
    constexpr auto end_semi = func.find(';', start);
    constexpr auto end_bracket = func.find(']', start);

    constexpr auto end = end_semi == std::string_view::npos ? end_bracket : end_semi;

    return func.substr(start, end - start);
}

} // namespace ecs

#include <cstddef>
#include <cstdio>
#include <memory>
#include <new>
#include <string.h>
#include <string>
#include <type_traits>
#include <utility>

namespace ecs {

namespace detail {

template <typename T> struct component_type {
    static inline ecs_component_t id = 0;
};

template <typename T, typename = void> struct is_complete : std::false_type {};

template <typename T> struct is_complete<T, std::void_t<decltype(sizeof(T))>> : std::true_type {};

template <typename T> consteval size_t sisizeof() {
    if constexpr (is_complete<T>::value) {
        return sizeof(T);
    } else {
        return 0;
    }
}

template <typename T> static void ecs_cpp_set_component_id(ecs_component_t cid) {
    detail::component_type<T>::id = cid;
}

template <typename T> static void value_ctor(void *ptr, uint32_t count) {
    T *values = static_cast<T *>(ptr);
    for (uint32_t i = 0; i < count; i++) {
        std::construct_at(&values[i]);
    }
}

template <typename T> static void value_dtor(void *ptr, uint32_t count) {
    T *values = static_cast<T *>(ptr);
    for (uint32_t i = 0; i < count; i++) {
        std::destroy_at(&values[i]);
    }
}

template <typename T> static void value_copy_ctor(void *dst, const void *src, uint32_t count) {
    T *out = static_cast<T *>(dst);
    const T *in = static_cast<const T *>(src);
    for (uint32_t i = 0; i < count; i++) {
        std::construct_at(&out[i], in[i]);
    }
}

template <typename T> static void value_copy(void *dst, const void *src, uint32_t count) {
    T *out = static_cast<T *>(dst);
    const T *in = static_cast<const T *>(src);
    for (uint32_t i = 0; i < count; i++) {
        if constexpr (std::is_copy_assignable_v<T>) {
            out[i] = in[i];
        } else {
            std::destroy_at(&out[i]);
            std::construct_at(&out[i], in[i]);
        }
    }
}

template <typename T> static void value_move_ctor(void *dst, void *src, uint32_t count) {
    T *out = static_cast<T *>(dst);
    T *in = static_cast<T *>(src);
    for (uint32_t i = 0; i < count; i++) {
        std::construct_at(&out[i], std::move(in[i]));
        std::destroy_at(&in[i]);
    }
}

template <typename T> static void value_move(void *dst, void *src, uint32_t count) {
    T *out = static_cast<T *>(dst);
    T *in = static_cast<T *>(src);
    for (uint32_t i = 0; i < count; i++) {
        if constexpr (std::is_move_assignable_v<T>) {
            out[i] = std::move(in[i]);
        } else {
            std::destroy_at(&out[i]);
            std::construct_at(&out[i], std::move(in[i]));
        }
        std::destroy_at(&in[i]);
    }
}

template <typename T> consteval ecs_type_ops_t value_ops() {
    if constexpr (!is_complete<T>::value) {
        return {};
    } else if constexpr (sizeof(T) == 0 || std::is_trivially_copyable_v<T>) {
        return {};
    } else {
        return {
            .ctor = std::is_default_constructible_v<T> ? value_ctor<T> : nullptr,
            .dtor = std::is_destructible_v<T> ? value_dtor<T> : nullptr,
            .copy_ctor = std::is_copy_constructible_v<T> ? value_copy_ctor<T> : nullptr,
            .copy = std::is_copy_constructible_v<T> ? value_copy<T> : nullptr,
            .move_ctor = std::is_move_constructible_v<T> ? value_move_ctor<T> : nullptr,
            .move = std::is_move_constructible_v<T> ? value_move<T> : nullptr,
        };
    }
}

template <typename T> static ecs_component_t ecs_cpp_component_id(ecs_world_t *world) {
    ecs_component_t &cid = detail::component_type<T>::id;

    if (cid != 0) {
        return cid;
    }

    static sireflect_struct_desc_t reflection = {
        .name = strdup(std::string(type_name<T>()).c_str()),
        .fields = "{}",
        .size = 0,
        .align = 1,
    };

    if constexpr (requires {
                      { T::fields } -> std::convertible_to<const char *>;
                  }) {
        reflection.fields = T::fields;
        reflection.size = sisizeof<T>();
        reflection.align = _Alignof(T);
    }

    ecs_component_desc_t desc = {
        .name = reflection.name,
        .size = sisizeof<T>(),
        .ops = value_ops<T>(),
        .on_set = nullptr,
        .on_remove = nullptr,
        .on_add = nullptr,
        .relation_flags = 0,
        .struct_desc = &reflection,
    };

    cid = ecs_component_init(world, &desc);

    return cid;
}

#define fields_str(...) #__VA_ARGS__

#define reflected(...)                                                                             \
    static constexpr const char *fields = fields_str({ __VA_ARGS__ });                             \
    __VA_ARGS__

} // namespace detail

} // namespace ecs

#pragma once

namespace ecs {

class entity {
    ecs_entity_t _entity;
    ecs_world_t *_world;

  public:
    static ecs::entity null() { return entity(nullptr, 0); }

    entity(ecs_world_t *world, ecs_entity_t entity) : _entity(entity), _world(world) {}

    [[nodiscard]] ecs_entity_t id() const noexcept { return _entity; }

    template <typename T> entity add() {
        ecs_add_cid(_world, _entity, detail::ecs_cpp_component_id<T>(_world));
        return *this;
    }

    operator ecs_entity_t() const noexcept { return _entity; }

    entity abstract() {
        ecs_add(_world, _entity, Abstract);
        return *this;
    }

    template <typename T> entity remove() {
        ecs_remove_cid(_world, _entity, detail::ecs_cpp_component_id<T>(_world));
        return *this;
    }

    template <typename T> [[nodiscard]] bool has() const {
        return ecs_has_cid(_world, _entity, detail::ecs_cpp_component_id<T>(_world));
    }

    template <typename T> entity set(const T &value) {
        ecs_set_cid(_world, _entity, detail::ecs_cpp_component_id<T>(_world), &value);
        return *this;
    }

    template <typename T> entity set(T &&value)
        requires(!std::is_lvalue_reference_v<T>)
    {
        using type = std::remove_cvref_t<T>;
        ecs_move_cid(_world, _entity, detail::ecs_cpp_component_id<type>(_world), &value);
        return *this;
    }

    entity is_a(entity target) {
        ecs_is_a(_world, _entity, target._entity);
        return *this;
    }

    bool is(entity target) { return ecs_is(_world, _entity, target._entity); }

    entity child_of(entity parent) {
        const ChildOf desc = { .target = parent._entity };
        ecs_set_cid(_world, _entity, ecs_id(ChildOf), &desc);
        return *this;
    }

    entity enable() {
        ecs_remove_cid(_world, _entity, ecs_id(Disabled));
        return *this;
    }

    entity disable() {
        ecs_add_cid(_world, _entity, ecs_id(Disabled));
        return *this;
    }

    [[nodiscard]] bool is_enabled() const {
        return !ecs_has_cid(_world, _entity, ecs_id(Disabled));
    }

    [[nodiscard]] bool is_disabled() const {
        return ecs_has_cid(_world, _entity, ecs_id(Disabled));
    }
};

} // namespace ecs

#pragma once

#include <cassert>
#include <concepts>

namespace ecs {

class world;

template <typename T> class module_ref {
    ecs_world_t *_world = nullptr;
    ecs_module_id_t _id = 0;

  public:
    constexpr module_ref() noexcept = default;
    constexpr module_ref(ecs_world_t *world, ecs_module_id_t id) noexcept
        : _world(world), _id(id) {}

    [[nodiscard]] constexpr ecs_module_id_t id() const noexcept { return _id; }
    [[nodiscard]] constexpr explicit operator bool() const noexcept { return _id != 0; }

    void enable() const noexcept {
        assert(_world != nullptr);
        assert(_id != 0);
        ecs_module_enable(_world, _id);
    }

    void disable() const noexcept {
        assert(_world != nullptr);
        assert(_id != 0);
        ecs_module_disable(_world, _id);
    }

    [[nodiscard]] bool is_enabled() const noexcept {
        assert(_world != nullptr);
        assert(_id != 0);
        return ecs_module_is_enabled(_world, _id);
    }
};

namespace detail {

template <typename T> struct module_type {
    static inline ecs_module_id_t id;
};

template <typename T>
concept module_importable = requires(T module, ecs::world &world) {
    { module.import(world) } -> std::same_as<void>;
};

template <typename T, typename... Args>
concept module_list_initializable =
    requires(Args &&...args) { T{ static_cast<Args &&>(args)... }; };

} // namespace detail

} // namespace ecs

#pragma once

#pragma once
#include <tuple>
#include <type_traits>
#include <utility>

namespace ecs {

    template <typename T> struct function_traits;

    // function pointer
    template <typename R, typename... Args> struct function_traits<R (*)(Args...)> {
        using return_type = R;
        using args_tuple = std::tuple<Args...>;
    };

    // function reference
    template <typename R, typename... Args> struct function_traits<R (&)(Args...)> {
        using return_type = R;
        using args_tuple = std::tuple<Args...>;
    };

    // member function pointer const
    template <typename C, typename R, typename... Args>
    struct function_traits<R (C::*)(Args...) const> {
        using return_type = R;
        using args_tuple = std::tuple<Args...>;
    };

    // member function pointer non-const
    template <typename C, typename R, typename... Args> struct function_traits<R (C::*)(Args...)> {
        using return_type = R;
        using args_tuple = std::tuple<Args...>;
    };

    // lambda / functor
    template <typename F>
    struct function_traits : function_traits<decltype(&std::remove_reference_t<F>::operator())> {};

    template <typename Tuple, typename Fn, std::size_t... I>
    constexpr void for_each_type_impl(Fn &&fn, std::index_sequence<I...>) {
        (fn.template operator()<std::tuple_element_t<I, Tuple>>(), ...);
    }

    template <typename Tuple, typename Fn> constexpr void for_each_type(Fn &&fn) {
        constexpr std::size_t N = std::tuple_size_v<Tuple>;
        for_each_type_impl<Tuple>(std::forward<Fn>(fn), std::make_index_sequence<N>{});
    }

}

#pragma once
#pragma once

#include <cassert>
#include <string>
#include <tuple>
#include <type_traits>

namespace ecs {

template <typename T> class res {
    T *_ptr = nullptr;

  public:
    explicit res(T *ptr) noexcept : _ptr(ptr) { assert(ptr != nullptr); }

    [[nodiscard]] T *operator->() const noexcept { return _ptr; }
    [[nodiscard]] T &operator*() const noexcept { return *_ptr; }
    [[nodiscard]] T *get() const noexcept { return _ptr; }
};

namespace detail {

template <typename T> struct resource_type {
    static inline ecs_resource_t id;
};

template <typename T> struct is_res : std::false_type {};
template <typename T> struct is_res<ecs::res<T>> : std::true_type {};

template <typename T> inline constexpr bool is_res_v = is_res<std::remove_cvref_t<T>>::value;

template <typename T> struct res_value;
template <typename T> struct res_value<ecs::res<T>> {
    using type = T;
};

template <typename T>
using res_value_t = typename res_value<std::remove_cvref_t<T>>::type;

template <typename T>
using resource_value_t = std::remove_cv_t<res_value_t<T>>;

struct no_resource {};

} // namespace detail

template <typename T> static ecs_resource_t ecs_cpp_resource_id(ecs_world_t *world) {
    using type = std::remove_cv_t<T>;
    ecs_resource_t &rid = detail::resource_type<type>::id;

    if (rid != 0 && ecs_resource_is_registered_rid(world, rid)) {
        return rid;
    }

    std::string name = std::string(type_name<type>());
    rid = ecs_resource_find(world, name.c_str());
    if (rid != 0) {
        return rid;
    }

    ecs_resource_desc_t desc = {
        .name = name.c_str(),
        .size = sizeof(type),
        .ops = detail::value_ops<type>(),
        .on_set = nullptr,
        .on_remove = nullptr,
    };

    rid = ecs_resource_init(world, &desc);
    return rid;
}

template <typename T> static ecs_resource_t ecs_cpp_try_resource_id(ecs_world_t *world) {
    using type = std::remove_cv_t<T>;
    ecs_resource_t &rid = detail::resource_type<type>::id;

    if (rid != 0 && ecs_resource_is_registered_rid(world, rid)) {
        return rid;
    }

    std::string name = std::string(type_name<type>());
    rid = ecs_resource_find(world, name.c_str());
    return rid;
}

namespace detail {

template <typename Arg> inline auto make_resource_arg(ecs_world_t *world) {
    if constexpr (is_res_v<Arg>) {
        using value_type = res_value_t<Arg>;
        using resource_type = std::remove_cv_t<value_type>;

        ecs_resource_t id = ecs::ecs_cpp_resource_id<resource_type>(world);
        return ecs::res<value_type>(static_cast<value_type *>(ecs_resource_rid(world, id)));
    } else {
        return no_resource{};
    }
}

template <typename Args, std::size_t... Is>
inline auto make_resources(ecs_world_t *world, std::index_sequence<Is...>) {
    (void)world;
    return std::tuple{ make_resource_arg<std::tuple_element_t<Is, Args>>(world)... };
}

template <typename Args> inline auto make_resources(ecs_world_t *world) {
    constexpr std::size_t N = std::tuple_size_v<Args>;
    return make_resources<Args>(world, std::make_index_sequence<N>{});
}

} // namespace detail

} // namespace ecs

#include <cstdint>
#include <functional>
#include <tuple>
#include <type_traits>
#include <utility>

namespace ecs {

namespace detail {

template <typename T> consteval ecs_term_access_t term_access();

template <typename Args, std::size_t I, std::size_t... Is>
consteval std::size_t field_index_before_impl(std::index_sequence<Is...>) {
    return ((Is < I && !is_res_v<std::tuple_element_t<Is, Args>> ? 1U : 0U) + ... + 0U);
}

template <typename Args, std::size_t I> consteval std::size_t field_index_before() {
    return field_index_before_impl<Args, I>(std::make_index_sequence<std::tuple_size_v<Args>>{});
}

template <typename Args, std::size_t... Is>
consteval std::size_t component_arg_count_impl(std::index_sequence<Is...>) {
    return ((!is_res_v<std::tuple_element_t<Is, Args>> ? 1U : 0U) + ... + 0U);
}

template <typename Args> consteval std::size_t component_arg_count() {
    return component_arg_count_impl<Args>(std::make_index_sequence<std::tuple_size_v<Args>>{});
}

template <typename Args, std::size_t I, typename Resources>
inline auto make_batch_arg(ecs_iter_t *it, Resources &resources) {
    using arg = std::tuple_element_t<I, Args>;

    if constexpr (is_res_v<arg>) {
        return std::get<I>(resources);
    } else {
        using value_type = std::remove_reference_t<arg>;
        return static_cast<value_type *>(
            ecs_field(it, static_cast<uint16_t>(field_index_before<Args, I>()))
        );
    }
}

template <typename Args, typename Resources, std::size_t... Is>
inline auto make_fields(ecs_iter_t *it, Resources &resources, std::index_sequence<Is...>) {
    (void)it;
    return std::tuple{ make_batch_arg<Args, Is>(it, resources)... };
}

template <std::size_t I, typename Args, typename Tuple>
inline decltype(auto) row_arg(Tuple &fields, uint32_t row) {
    auto &field = std::get<I>(fields);

    using arg = std::tuple_element_t<I, Args>;
    if constexpr (is_res_v<arg>) {
        (void)row;
        return field;
    } else {
        return field[row];
    }
}

template <std::size_t I, typename Args, typename Tuple>
inline decltype(auto) row_arg_shared(Tuple &fields) {
    auto &field = std::get<I>(fields);
    using arg = std::tuple_element_t<I, Args>;
    if constexpr (is_res_v<arg>) {
        return field;
    } else {
        return field[0];
    }
}

template <typename F, typename Args, typename Tuple, std::size_t... Is>
inline void call_fields_impl(
    F &func,
    Tuple &fields,
    uint32_t count,
    std::uint64_t shared_mask,
    std::index_sequence<Is...>
) {
    (void)shared_mask;
    for (uint32_t i = 0; i < count; i++) {
        std::invoke(
            func,
            ((shared_mask & (1ULL << field_index_before<Args, Is>()))
                 ? row_arg_shared<Is, Args>(fields)
                 : row_arg<Is, Args>(fields, i))...
        );
    }
}

template <typename F, typename Args, typename Tuple>
inline void call_fields(F &func, Tuple &fields, uint32_t count, std::uint64_t shared_mask) {
    constexpr std::size_t N = std::tuple_size_v<std::remove_reference_t<Tuple>>;
    constexpr std::size_t component_count = component_arg_count<Args>();
    static_assert(component_count <= 64, "query callbacks can read at most 64 components");

    call_fields_impl<F, Args>(func, fields, count, shared_mask, std::make_index_sequence<N>{});
}

template <typename Args> inline std::uint64_t make_shared_mask(const ecs_iter_t *it) {
    constexpr std::size_t component_count = component_arg_count<Args>();
    static_assert(component_count <= 64, "query callbacks can read at most 64 components");

    std::uint64_t mask = 0;
    for (std::size_t i = 0; i < component_count; i++) {
        if (it->field_kinds[i] == EcsFieldShared) {
            mask |= 1ULL << i;
        }
    }
    return mask;
}

template <typename T> consteval ecs_term_access_t term_access() {
    static_assert(
        std::is_lvalue_reference_v<T>,
        "query callback arguments must be lvalue references"
    );

    if constexpr (std::is_const_v<std::remove_reference_t<T>>) {
        return EcsIn;
    } else {
        return EcsInOut;
    }
}

inline void append_term(
    ecs_query_desc_t &desc,
    uint16_t &term_index,
    ecs_component_t id,
    ecs_term_access_t access
) {
    // assert(term_index + 1 < query_term_capacity && "too many query terms");

    desc.terms[term_index] = {
        .id = id,
        .access = access,
    };
    term_index += 1;
}

template <typename... T>
inline void append_terms(
    ecs_world_t *world,
    ecs_query_desc_t &desc,
    uint16_t &term_index,
    ecs_term_access_t access
) {
    (append_term(desc, term_index, ecs::detail::ecs_cpp_component_id<T>(world), access), ...);
}

template <typename Args>
inline void
append_callback_terms(ecs_world_t *world, ecs_query_desc_t &desc, uint16_t &term_index) {
    for_each_type<Args>([&]<typename T>() {
        if constexpr (!is_res_v<T>) {
            append_term(
                desc,
                term_index,
                ecs::detail::ecs_cpp_component_id<std::remove_cvref_t<T>>(world),
                term_access<T>()
            );
        }
    });
}

template <typename F, typename Args>
inline void run_query(F &func, ecs_world_t *world, ecs_query_id_t qid) {
    auto resources = make_resources<Args>(world);
    ecs_iter_t it = ecs_query_iter(world, qid);

    while (ecs_iter_next(&it)) {
        auto fields =
            make_fields<Args>(&it, resources, std::make_index_sequence<std::tuple_size_v<Args>>{});
        call_fields<F, Args>(func, fields, it.count, make_shared_mask<Args>(&it));
    }
}

template <typename F, typename Args> inline void run_batch(F &func, ecs_iter_t *it) {
    auto resources = make_resources<Args>(it->world);
    auto fields =
        make_fields<Args>(it, resources, std::make_index_sequence<std::tuple_size_v<Args>>{});
    call_fields<F, Args>(func, fields, it->count, make_shared_mask<Args>(it));
}

template <typename F, typename Args> inline void run_once(F &func, ecs_world_t *world) {
    static_assert(component_arg_count<Args>() == 0);

    auto resources = make_resources<Args>(world);
    auto fields =
        make_fields<Args>(nullptr, resources, std::make_index_sequence<std::tuple_size_v<Args>>{});
    call_fields<F, Args>(func, fields, 1, 0);
}

template <typename F, typename Args>
inline void run_strict_query(F &func, ecs_world_t *world, ecs_query_id_t qid) {
    constexpr std::size_t component_count = component_arg_count<Args>();
    static_assert(component_count > 0, "query callbacks must read at least one component");

    run_query<F, Args>(func, world, qid);
}

} // namespace detail

class world;

class query {
  protected:
    ecs_query_desc_t desc{};
    uint16_t term_index = 0;
    ecs_world_t *_world = nullptr;

  public:
    explicit query(ecs_world_t *world) noexcept : _world(world) {}

    template <typename... T> query &&require() {
        detail::append_terms<T...>(_world, desc, term_index, EcsFilter);
        return std::move(*this);
    }

    template <typename... T> query &&exclude() {
        detail::append_terms<T...>(_world, desc, term_index, EcsNot);
        return std::move(*this);
    }

    query &&is_a(ecs_entity_t target) {
        desc.is_a = target;
        return std::move(*this);
    }

    ecs_query_id_t build() { return ecs_query_init(_world, &desc); }

    template <typename F> void each(F &&func) {
        using traits = function_traits<std::remove_reference_t<F>>;
        using args = typename traits::args_tuple;
        constexpr std::size_t component_count = detail::component_arg_count<args>();
        static_assert(component_count > 0, "query callbacks must read at least one component");

        detail::append_callback_terms<args>(_world, desc, term_index);

        ecs_query_id_t qid = this->build();

        detail::run_strict_query<F, args>(func, _world, qid);

        ecs_query_fini(_world, qid);
    }

    entity first() {
        ecs_query_id_t qid = this->build();
        ecs_iter_t it = ecs_query_iter(_world, qid);
        while (ecs_iter_next(&it)) {
            return entity(_world, it.entities[0]);
        }
        return entity::null();
    }
};

} // namespace ecs

#include <cstddef>
#include <cstdint>
#include <functional>
#include <tuple>
#include <type_traits>
#include <utility>

namespace ecs {

struct OnAdd {};
struct OnSet {};
struct OnRemove {};

namespace detail {

template <typename T> struct event_type {
    static inline ecs_event_t id = UINT16_MAX;
};

template <typename T> static ecs_event_t ecs_cpp_event_id(ecs_world_t *world) {
    ecs_event_t &eid = detail::event_type<T>::id;

    if (eid != UINT16_MAX) {
        return eid;
    }

    eid = ecs_event(world);

    return eid;
}

template <typename T> static void ecs_cpp_set_event_id(ecs_event_t eid) {
    detail::event_type<T>::id = eid;
}

template <typename T> decltype(auto) ecs_cpp_observer_arg(ecs_observer_event_t *event) {
    using raw = std::remove_cvref_t<T>;
    void *ptr = ecs_get_cid(event->world, event->entity, ecs_cpp_component_id<raw>(event->world));

    if constexpr (std::is_const_v<std::remove_reference_t<T>>) {
        return *static_cast<const raw *>(ptr);
    } else {
        return *static_cast<raw *>(ptr);
    }
}

template <typename Args, std::size_t I, typename Resources>
decltype(auto) ecs_cpp_observer_arg(ecs_observer_event_t *event, Resources &resources) {
    using arg = std::tuple_element_t<I, Args>;

    if constexpr (is_res_v<arg>) {
        (void)event;
        return std::get<I>(resources);
    } else {
        return ecs_cpp_observer_arg<arg>(event);
    }
}

template <typename Func, typename Args, std::size_t... Is>
void ecs_cpp_observer_callback_impl(ecs_observer_event_t *event, std::index_sequence<Is...>) {
    Func func{};
    auto resources = make_resources<Args>(event->world);
    std::invoke(func, ecs_cpp_observer_arg<Args, Is>(event, resources)...);
}

template <typename Func, typename Tuple>
void ecs_cpp_observer_callback(ecs_observer_event_t *event) {
    ecs_cpp_observer_callback_impl<Func, Tuple>(
        event,
        std::make_index_sequence<std::tuple_size_v<Tuple>>{}
    );
}

} // namespace detail

template <typename T> class observer : public query {

  public:
    observer(ecs_world_t *world) : query(world) {};

    template <typename F> ecs_observer_id_t each(F &&) {
        using callback = std::remove_cvref_t<F>;
        static_assert(
            std::is_empty_v<callback> && std::is_default_constructible_v<callback>,
            "observer callbacks must be stateless with the current C API"
        );

        using traits = function_traits<callback>;
        using args = typename traits::args_tuple;
        static_assert(
            detail::component_arg_count<args>() > 0,
            "observer callbacks must read at least one component"
        );

        ecs::detail::append_callback_terms<args>(_world, this->desc, term_index);

        ecs_observer_desc_t observer_desc = {
            .on = detail::ecs_cpp_event_id<T>(_world),
            .query = this->desc,
            .callback = detail::ecs_cpp_observer_callback<callback, args>,
        };

        return ecs_observer_init(_world, &observer_desc);
    }
};

} // namespace ecs

#pragma once

namespace ecs {

namespace detail {

template <typename Callback, typename Args> static void system_callback(ecs_iter_t *it) {
    Callback &callback = *reinterpret_cast<Callback *>(it->user_data);
    if constexpr (component_arg_count<Args>() == 0) {
        run_once<Callback, Args>(callback, it->world);
    } else {
        run_batch<Callback, Args>(callback, it);
    }
}

template <typename Callback> static void system_callback_dtor(uintptr_t user_data) {
    delete reinterpret_cast<Callback *>(user_data);
}

} // namespace detail

class system : protected query {
    const char *name;
    ecs_phase_t _phase = EcsOnUpdate;

  public:
    system(ecs_world_t *_world, const char *name) : query(_world), name(name) {}

    template <typename... T> system require() {
        query::require<T...>();
        return *this;
    }

    template <typename... T> system exclude() {
        query::exclude<T...>();
        return *this;
    }

    system phase(ecs_phase_t _phase) {
        this->_phase = _phase;
        return *this;
    }

    template <typename F> ecs_system_id_t each(F &&func) {
        using callback = std::remove_cvref_t<F>;

        using traits = function_traits<callback>;
        using args = typename traits::args_tuple;
        detail::append_callback_terms<args>(_world, desc, term_index);
        callback *state = new callback(std::forward<F>(func));

        ecs_system_desc_t system_desc = {
            .name = name,
            .query = this->desc,
            .callback = detail::system_callback<callback, args>,
            .user_data = reinterpret_cast<uintptr_t>(state),
            .user_data_dtor = detail::system_callback_dtor<callback>,
            .phase = _phase,
        };

        return ecs_system_init(_world, &system_desc);
    }
};

} // namespace ecs

#include <cstring>

namespace ecs {

enum class world_ownership : uint8_t {
    owned,
    borrowed,
};

class world {
    ecs_world_t *_world = nullptr;
    world_ownership _ownership = world_ownership::owned;

    template <typename T> static void import_module_callback(ecs_world_t *raw, const void *ptr) {
        ecs::world world = ecs::world::borrow(raw);
        T &module = *static_cast<T *>(const_cast<void *>(ptr));
        module.import(world);
    }

    template <typename T> [[nodiscard]] module_ref<T> import_module(T &module) const {
        static const std::string name = std::string(type_name<T>());

        ecs_module_desc_t desc = {
            .name = name.c_str(),
            .id = &detail::module_type<T>::id,
            .import = import_module_callback<T>,
            .desc = &module,
            .desc_size = sizeof(T),
            .disabled = false,
        };

        return module_ref<T>(_world, ecs_module_init(_world, &desc));
    }

  public:
    world() noexcept : _world(nullptr), _ownership(world_ownership::owned) {
        ecs_world_feat_desc_t desc{ .rest = true, .target_fps = 120 };
        _world = ecs_init_w_features(&desc);
        detail::ecs_cpp_set_component_id<Disabled>(ecs_id(Disabled));
        detail::ecs_cpp_set_component_id<Name>(ecs_id(Name));
        detail::ecs_cpp_set_component_id<ChildOf>(ecs_id(ChildOf));
        detail::ecs_cpp_set_event_id<OnAdd>(EcsOnAdd);
        detail::ecs_cpp_set_event_id<OnAdd>(EcsOnSet);
        detail::ecs_cpp_set_event_id<OnAdd>(EcsOnRemove);
    }
    explicit world(ecs_world_t *world) noexcept
        : _world(world), _ownership(world_ownership::owned) {}
    world(ecs_world_t *world, world_ownership ownership) noexcept
        : _world(world), _ownership(ownership) {}

    [[nodiscard]] static world borrow(ecs_world_t *world) noexcept {
        return ecs::world(world, world_ownership::borrowed);
    }

    world(const world &) = delete;
    world &operator=(const world &) = delete;

    world(world &&other) noexcept
        : _world(std::exchange(other._world, nullptr)),
          _ownership(std::exchange(other._ownership, world_ownership::owned)) {}

    world &operator=(world &&other) noexcept {
        if (this != &other) {
            reset();
            _world = std::exchange(other._world, nullptr);
            _ownership = std::exchange(other._ownership, world_ownership::owned);
        }

        return *this;
    }

    ~world() noexcept { reset(); }

    [[nodiscard]] ecs_world_t *c_ptr() const noexcept { return _world; }

    operator ecs_world_t *() const noexcept { return _world; }

    void reset(
        ecs_world_t *world = nullptr,
        world_ownership ownership = world_ownership::owned
    ) noexcept {
        if (_world != nullptr && _ownership == world_ownership::owned) {
            ecs_fini(_world);
        }

        _world = world;
        _ownership = ownership;
    }

    template <typename T> ecs_component_t component() const {
        return detail::ecs_cpp_component_id<T>(_world);
    }

    template <typename T> void set_resource(T &&value) const {
        using type = std::remove_cvref_t<T>;
        if constexpr (std::is_lvalue_reference_v<T>) {
            ecs_set_resource_rid(_world, ecs_cpp_resource_id<type>(_world), &value);
        } else {
            ecs_move_resource_rid(_world, ecs_cpp_resource_id<type>(_world), &value);
        }
    }

    template <typename T> [[nodiscard]] T &resource() const {
        using type = std::remove_cv_t<T>;
        return *static_cast<T *>(ecs_resource_rid(_world, ecs_cpp_resource_id<type>(_world)));
    }

    template <typename T> [[nodiscard]] T *try_resource() const {
        using type = std::remove_cv_t<T>;
        ecs_resource_t id = ecs_cpp_try_resource_id<type>(_world);
        return id ? static_cast<T *>(ecs_try_resource_rid(_world, id)) : nullptr;
    }

    template <typename T> [[nodiscard]] bool has_resource() const {
        using type = std::remove_cv_t<T>;
        ecs_resource_t id = ecs_cpp_try_resource_id<type>(_world);
        return id && ecs_has_resource_rid(_world, id);
    }

    template <typename T> void remove_resource() const {
        using type = std::remove_cv_t<T>;
        ecs_resource_t id = ecs_cpp_try_resource_id<type>(_world);
        if (id) {
            ecs_remove_resource_rid(_world, id);
        }
    }

    template <typename T>
        requires detail::module_importable<T>
    module_ref<T> import(T module) const {
        return import_module<T>(module);
    }

    template <typename T, typename... Args>
        requires detail::module_importable<T> && detail::module_list_initializable<T, Args...>
    module_ref<T> import(Args &&...args) const {
        T module{ std::forward<Args>(args)... };
        return import_module<T>(module);
    }

    template <typename T> [[nodiscard]] module_ref<T> module() const noexcept {
        return module_ref<T>(_world, ecs_module_find(_world, &detail::module_type<T>::id));
    }

    template <typename T> observer<T> observe() const { return observer<T>(_world); }

    template <typename T> [[nodiscard]] ecs_event_t event() const {
        return detail::ecs_cpp_event_id<T>(_world);
    }

    template <typename T> void trigger(ecs::entity entity, const void *data = nullptr) const {
        ecs_observer_trigger(_world, entity.id(), event<T>(), data);
    }

    [[nodiscard]] ecs::entity entity(const char *name = nullptr) const {
        auto e = ecs::entity(_world, ecs_new(_world));
        if (name) {
            e.set<Name>({ .value = strdup(name) });
        }
        return e;
    }
    [[nodiscard]] ecs::entity instantiate(ecs::entity e) { return this->entity().is_a(e); }
    [[nodiscard]] ecs::query query() const { return ecs::query(_world); }
    [[nodiscard]] ecs::system system(const char *name = "unamed") const {
        return ecs::system(_world, name);
    }

    bool progress() { return ecs_progress(_world); }
};

} // namespace ecs

#endif

#endif

#endif