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
use crate::{
    components::{Name, Visible, SourcePath, VisibleChanges},
    geometry::{
        Geometry, Submesh, GeometryRef, AnimatedGeometry
    },
    transformation::RenderPlane,
};
use rin_material::{MaterialRef, MaterialMultiRef, ShadowMaterialRef};

#[cfg(feature="debug_geometry")]
use crate::geometry::DebugGeometryRef;

use crate::renderer::{
    components::{
        ProgramRef,
    },
    resources,
    material::{MaterialCache, ShadowMaterialCache},
    shadow,
    memory::*,
    allocator,
};
use super::{material::{MaterialOffsets, ShadowMaterialOffsets}, memory};

use rinecs::{Component, CreationSystem, Entities, EntitiesCreation, EntitiesThreadLocal, Entity, Has, NToOneComponent, OneToNComponent, Read, ReadNot, ReadOption, ReadRef, Ref, RefN, Resources, ResourcesCreation, ResourcesThreadLocal, World, Write, creation_system, storage::SliceView, system, system_thread_local};
use rinecs::SystemThreadLocal;
use rin_graphics::{self as graphics, PrimitiveTypeToGl, PrimitiveType, Node, node::DynamicTransformation};
use rin_gl::{self as gl, gl::types::*};
use glin::VertexFormat;
use std::marker::PhantomData;
use itertools::{Itertools, Either};
use rin_math::Mat4;
use std::mem;
use std::fmt::{self, Debug};
use std::rc::Rc;
use std::cell::RefCell;
use hashbrown::HashMap;
use super::resources::{GeometryIndex, ShadowGeometryIndex};
use super::renderer::RendererType;
use serde_derive::{Serialize, Deserialize};
use rinecs::streaming_iterator;

// Uses changes storage but never really changes, only used to detect additions / removals
// so geometry sort can use it as a run condition
#[derive(NToOneComponent, Clone, Copy, Eq, PartialEq, Debug, Ord, PartialOrd, Hash, Serialize, Deserialize)]
#[changes]
pub struct GpuGeometryRef(Entity);

// Uses changes storage but never really changes, only used to detect additions / removals
// so geometry sort can use it as a run condition
#[cfg(feature="debug_geometry")]
#[derive(NToOneComponent, Clone, Copy, Eq, PartialEq, Debug, Ord, PartialOrd, Hash, Serialize, Deserialize)]
#[changes]
pub struct GpuDebugGeometryRef(Entity);

// Used as a link between a cpu geometry and all it's
// gpu geometries to optimize when looking for changed geometries
#[derive(OneToNComponent, Clone, Copy, Eq, PartialEq, Debug, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct GeomToGpuGeomRef(pub Entity);

// Type to make some structures more understandable
type GpuGeometryReference = Entity;


#[derive(OneToNComponent)]
#[debug_as_string]
pub struct SubmeshBuffers{
    has_changed: bool,
    primitive_type: GLenum,
    vao_range: VaoRange,
    get_vao: Box<dyn Fn(
        &Rc<glin::CreationProxy>,
        &mut memory::AllocatorsIndex,
        Option<&MaterialOffsets>,
        &glin::SharedBuffer<(Mat4, Mat4)>) -> glin::Result<&'static mut glin::Vao>>,
    get_shadow_vao: Box<dyn Fn(
        &Rc<glin::CreationProxy>,
        &mut memory::AllocatorsIndex,
        &glin::SharedBuffer<Mat4>,
        Option<&glin::SharedBuffer<u32>>) -> glin::Result<&'static mut glin::Vao>>,
    #[cfg(not(any(feature="gles", feature="webgl")))]
    get_vao_range: Box<dyn Fn(
        &mut memory::AllocatorsIndex,
        &VaoRange) -> VaoRangeInfo>,
    #[cfg(any(feature="gles", feature="webgl"))]
    get_vao_range: Box<dyn Fn(
        &mut memory::AllocatorsIndex,
        &VaoRange,
        &mut glin::Vao,
        GLenum) -> glin::vao::Range<'static>>,
    get_command: Box<dyn Fn(
        &mut memory::AllocatorsIndex,
        &VaoRange,
        u32,
        u32) -> glin::DrawElementsIndirectCommand>,
}

impl Debug for SubmeshBuffers{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result{
        fmt.debug_struct("SubmeshBuffers")
            .field("has_changed", &self.has_changed)
            .finish()
    }
}

// Separate SubmeshBuffers into VaoRange and GetVao components
unsafe impl Send for SubmeshBuffers{}

impl SubmeshBuffers{
    pub fn new<T,B>(vao_range: VaoRange, primitive_type: PrimitiveType, unified_material_ubo: bool, allocator_handle: AllocatorHandle<T,B>) ->
        SubmeshBuffers
        where T: VertexFormat + Clone + 'static,
            B: 'static + Clone + BufferExt<u8> +
                glin::buffer::Cast<glin::IndexT> +
                glin::buffer::Cast<T>,
            <B as glin::buffer::Cast<glin::IndexT>>::CastTo: 'static +
                glin::BufferRangeMut<glin::IndexT> +
                Clone,
            <B as glin::buffer::Cast<T>>::CastTo: 'static
                + glin::BufferRangeMut<T>
                + glin::buffer::WithBackend
                + allocator::MapRange<T>
                + Clone,
            allocator::Allocator<B>: allocator::InternalCreation<B> +
                allocator::Creation<B> +
                allocator::Updater,
            Allocator<T,B>: AllocatorFlags,
    {
        let primitive_type = primitive_type.to_gl();
        let vao_id = vao_range.vao_id();

        let get_vao = if unified_material_ubo {
            let get_vao = move |
                gl: &Rc<glin::CreationProxy>,
                allocators: &mut memory::AllocatorsIndex,
                material_offsets: Option<&MaterialOffsets>,
                model_buffer: &glin::SharedBuffer<(Mat4, Mat4)>|
            {
                let material_offsets = material_offsets.map(|m| m.buffer());
                let allocator = &mut allocators[allocator_handle];
                unsafe{ mem::transmute(allocator.vao(gl, vao_id, model_buffer, material_offsets)) }
            };
            Box::new(get_vao) as Box<dyn Fn(
                &Rc<glin::CreationProxy>,
                &mut memory::AllocatorsIndex,
                Option<&MaterialOffsets>,
                &glin::SharedBuffer<(Mat4, Mat4)>) -> glin::Result<&'static mut glin::Vao>>
        }else{
            let get_vao = move |
                gl: &Rc<glin::CreationProxy>,
                allocators: &mut memory::AllocatorsIndex,
                material_offsets: Option<&MaterialOffsets>,
                model_buffer: &glin::SharedBuffer<(Mat4, Mat4)>|
            {
                let allocator = &mut allocators[allocator_handle];
                unsafe{ mem::transmute(allocator.vao(gl, vao_id, model_buffer, None)) }
            };
            Box::new(get_vao)
        };

        let get_shadow_vao = move |
            gl: &Rc<glin::CreationProxy>,
            allocators: &mut memory::AllocatorsIndex,
            model_buffer: &glin::SharedBuffer<Mat4>,
            material_offsets_buffer: Option<&glin::SharedBuffer<u32>>|
        {
            let allocator = &mut allocators[allocator_handle];
            unsafe{ mem::transmute(allocator.shadow_vao(gl, vao_id, model_buffer, material_offsets_buffer)) }
        };

        let get_command = move |
        allocators: &mut memory::AllocatorsIndex,
            range: &VaoRange,
            base_instance: u32,
            instance_count: u32|
        {
            let allocator = &mut allocators[allocator_handle];
            unsafe{ mem::transmute(allocator.command(range, base_instance, instance_count)) }
        };

        #[cfg(not(any(feature="gles", feature="webgl")))]
        let get_vao_range = move |allocators: &mut memory::AllocatorsIndex, range: &VaoRange|{
            let allocator = &mut allocators[allocator_handle];
            unsafe{ mem::transmute(allocator.vao_range(range)) }
        };

        #[cfg(any(feature="gles", feature="webgl"))]
        let get_vao_range = move |allocators: &mut memory::AllocatorsIndex, range: &VaoRange, vao: &mut glin::Vao, primitive_type: GLenum|{
            let allocator = &mut allocators[allocator_handle];
            unsafe{ mem::transmute(allocator.vao_range(range, vao, primitive_type)) }
        };

        SubmeshBuffers{
            vao_range,
            primitive_type,
            has_changed: true,
            get_vao,
            get_shadow_vao: Box::new(get_shadow_vao),
            get_command: Box::new(get_command),
            get_vao_range: Box::new(get_vao_range),
        }
    }

    #[cfg(not(any(feature="gles", feature="webgl")))]
    pub fn vao_base_instance<C: glin::CreationContext>(&self,
        gl: &C,
        allocators: &mut memory::AllocatorsIndex,
        material_offsets: Option<&MaterialOffsets>,
        model_buffer: &glin::SharedBuffer<(Mat4, Mat4)>,
        base_instance: u32) -> glin::Result<glin::vao::Range>
    {
        let vao = (self.get_vao)(gl.creation_proxy(), allocators, material_offsets, model_buffer)?;
        let vao_range = (self.get_vao_range)(allocators, &self.vao_range);
        if let Some(base_vertex) = vao_range.base_vertex{
            Ok(vao.range_base_vertex_base_instance(
                vao_range.range.clone(),
                base_vertex,
                base_instance,
                self.primitive_type))
        }else{
            Ok(vao.range_base_instance(
                vao_range.range.clone(),
                base_instance,
                self.primitive_type))
        }
    }

    #[cfg(not(any(feature="gles", feature="webgl")))]
    pub fn shadow_vao_base_instance<C: glin::CreationContext>(&self,
        gl: &C,
        allocators: &mut memory::AllocatorsIndex,
        model_buffer: &glin::SharedBuffer<Mat4>,
        material_offsets_buffer: Option<&glin::SharedBuffer<u32>>,
        base_instance: u32) -> glin::Result<glin::vao::Range>
    {
        let vao = (self.get_shadow_vao)(
            gl.creation_proxy(),
            allocators,
            model_buffer,
            material_offsets_buffer)?;
        let vao_range = (self.get_vao_range)(allocators, &self.vao_range);
        if let Some(base_vertex) = vao_range.base_vertex{
            Ok(vao.range_base_vertex_base_instance(
                vao_range.range.clone(),
                base_vertex,
                base_instance,
                self.primitive_type))
        }else{
            Ok(vao.range_base_instance(
                vao_range.range.clone(),
                base_instance,
                self.primitive_type))
        }
    }

    pub fn has_indices(&self) -> bool{
        self.vao_range.has_indices()
    }

    pub fn command(&self,
        allocators: &mut memory::AllocatorsIndex,
        base_instance: u32,
        instance_count: u32) -> glin::DrawElementsIndirectCommand
    {
        (self.get_command)(allocators, &self.vao_range, base_instance, instance_count)
    }

    pub fn full_vao<C: glin::CreationContext>(&self,
        gl: &C,
        allocators: &mut memory::AllocatorsIndex,
        material_offsets: Option<&MaterialOffsets>,
        model_buffer: &glin::SharedBuffer<(Mat4, Mat4)>) -> glin::Result<&mut glin::Vao>
    {
        (self.get_vao)(gl.creation_proxy(), allocators, material_offsets, model_buffer)
    }

    pub fn full_shadow_vao<C: glin::CreationContext>(&self,
        gl: &C,
        allocators: &mut memory::AllocatorsIndex,
        model_buffer: &glin::SharedBuffer<Mat4>,
        material_offsets_buffer: Option<&glin::SharedBuffer<u32>>) -> glin::Result<&mut glin::Vao>
    {
        (self.get_shadow_vao)(gl.creation_proxy(), allocators, model_buffer, material_offsets_buffer)
    }

    // TODO: is it worth to cache this and update it only on reallocation?
    // pub fn update_vao_range(&mut self, resources: &ResourcesThreadLocal){
    //     self.vao_range_info = (self.get_vao_range)(resources, &self.vao_range);
    // }

    #[cfg(not(any(feature="gles", feature="webgl")))]
    pub fn range_vao<'v>(&self, allocators: &mut memory::AllocatorsIndex, vao: &'v glin::Vao) -> glin::vao::Range<'v>{
        let vao_range = (self.get_vao_range)(allocators, &self.vao_range);
        if let Some(base_vertex) = vao_range.base_vertex{
            vao.range_base_vertex(vao_range.range.clone(), base_vertex, self.primitive_type)
        }else{
            vao.range(vao_range.range.clone(), self.primitive_type)
        }
    }

    #[cfg(any(feature="gles", feature="webgl"))]
    pub fn range_vao<'v>(&self, allocators: &mut memory::AllocatorsIndex, vao: &'v mut glin::Vao) -> glin::vao::Range<'v>{
        (self.get_vao_range)(allocators, &self.vao_range, vao, self.primitive_type())
    }

    pub fn vao_range(&self) -> &VaoRange{
        &self.vao_range
    }

    pub fn primitive_type(&self) -> GLenum{
        self.primitive_type
    }

    pub fn has_changed(&self) -> bool{
        self.has_changed
    }

    pub fn reset_has_changed(&mut self){
        self.has_changed = false;
    }
}

#[derive(Component, Debug)]
#[debug_as_string]
pub struct VertexBuffer(pub BufferRef);

#[derive(Component, Debug)]
#[debug_as_string]
pub struct IndicesBuffer(pub BufferRef);

#[derive(Component, Debug)]
#[debug_as_string]
pub struct DebugNormals(pub gl::SimpleVao<graphics::Vertex3D>);


#[derive(Component, Debug)]
#[debug_as_string]
pub struct ShadowGeometry(SubmeshBuffers);

#[system(name = "geometryref_changed_updater")]
#[needs(GeometryRef)]
#[writes(GeometryRef)]
#[cfg_attr(feature="debug_geometry", needs("DebugGeometryRef"))]
#[cfg_attr(feature="debug_geometry", writes("DebugGeometryRef"))]
pub fn geometryref_changed_updater(entities: Entities, _: Resources){
    entities.update_changed::<GeometryRef>();
    #[cfg(feature="debug_geometry")]
    entities.update_changed::<DebugGeometryRef>();
}

#[system(name = "geometry_changed_updater")]
#[needs(Geometry<V>)]
#[writes(Geometry<V>)]
pub fn geometry_changed_updater<V>(entities: Entities, _: Resources)
where V: Clone + Send + 'static
{
    entities.update_changed::<Geometry<V>>();
}

#[system(name = "update_visible_changed")]
#[needs(Visible)]
#[updates(VisibleChanges)]
#[writes(Visible)]
#[cfg_attr(feature="debug_geometry", needs(DebugGeometryRef))]
#[cfg_attr(feature="debug_geometry", writes(DebugGeometryRef))]
pub fn update_visible_changed(entities: Entities, _: Resources){
    entities.update_changed::<Visible>();
    #[cfg(feature="debug_geometry")]
    entities.update_changed::<DebugGeometryRef>();
}

#[system(name = "update_materialrefs_changed")]
#[needs(MaterialRef, MaterialMultiRef)]
#[writes(MaterialRef, MaterialMultiRef)]
pub fn update_materialrefs_changed(entities: Entities, _: Resources){
    entities.update_changed::<MaterialRef>();
    entities.update_changed::<MaterialMultiRef>();
}

pub struct GeometryUploader<T, B>{
    marker: PhantomData<T>,
    marker_buff: PhantomData<B>,
    #[cfg(not(any(feature = "webgl", feature = "gles")))]
    uses_command_buffers: bool,
    unified_material_ubo: bool,
    pub(super) allocator_handle: AllocatorHandle<T, B>,
}

impl<T: 'static + Clone + VertexFormat, B: 'static> GeometryUploader<T, B>{
    pub fn new(
        world: &mut World,
        vertex_bytes: usize,
        indices_allocator: Rc<RefCell<IndexAllocator<B>>>,
        renderer_ty: RendererType,
        unified_material_ubo: bool,) -> GeometryUploader<T, B>
    {
        let allocator = Allocator::<T,B>::new(vertex_bytes, indices_allocator);
        let allocator_handle = world
            .resource_mut::<memory::AllocatorsIndex>()
            .unwrap()
            .add_allocator(allocator);
        GeometryUploader{
            marker: PhantomData,
            marker_buff: PhantomData,
            #[cfg(not(any(feature = "webgl", feature = "gles")))]
            uses_command_buffers: renderer_ty == RendererType::MultiDrawIndirect,
            unified_material_ubo,
            allocator_handle,
        }
    }
}

#[cfg(feature="debug_geometry")]
type EntitiesVec = Vec<(Entity, bool)>;

#[cfg(not(feature="debug_geometry"))]
type EntitiesVec = Vec<Entity>;

#[creation_system(name = "geometry uploader")]
#[cfg_attr(feature="debug_geometry", cond(any(
    changed("crate::geometry::Geometry<V>"),
    changed("crate::geometry::GeometryRef"),
    changed("Visible"),
    changed("crate::geometry::DebugGeometryRef")
)))]
#[cfg_attr(not(feature="debug_geometry"), cond(any(
    changed("crate::geometry::Geometry<V>"),
    changed("crate::geometry::GeometryRef"),
    changed("Visible"),
)))]
#[after(geometry_changed_updater<V>, geometryref_changed_updater, update_visible_changed)]
#[creates(
    GpuGeometryRef,
    VertexBuffer,
    IndicesBuffer,
    GeomToGpuGeomRef,
    ShadowGeometry,
)]
impl<V, B> CreationSystem for GeometryUploader<V, B>
    where V: VertexFormat + Clone + Copy + Debug + Send + 'static,
        B: 'static + Clone + BufferExt<u8> +
            glin::buffer::Cast<glin::IndexT> +
            glin::buffer::Cast<V>,
        <B as glin::buffer::Cast<glin::IndexT>>::CastTo: 'static +
            glin::BufferRangeMut<glin::IndexT> +
            Clone,
        <B as glin::buffer::Cast<V>>::CastTo: 'static
            + glin::BufferRangeMut<V>
            + glin::buffer::WithBackend
            + allocator::MapRange<V>
            + Clone,
        allocator::Allocator<B>: allocator::InternalCreation<B> +
            allocator::Creation<B> +
            allocator::Updater,
        Allocator<V,B>: AllocatorFlags,
{
    fn run(&mut self, mut entities: EntitiesCreation, resources: ResourcesCreation) {
        log::trace!("Running geometry creation system");
        fn build_geometry<V,B>(
            entities: &EntitiesCreation,
            allocator: &mut Allocator<V,B>,
            allocator_handle: AllocatorHandle<V,B>,
            name: Name,
            geometryref: GeometryRef,
            entities_vec: EntitiesVec,
            glin: &gl::Renderer,
            dynamic: bool,
            unified_material_ubo: bool,
        ) -> AddGpuGeometry
        where V: gl::VertexFormat + Clone + Copy + 'static,
            B: 'static + Clone + BufferExt<u8> +
                glin::buffer::Cast<glin::IndexT> +
                glin::buffer::Cast<V>,
            <B as glin::buffer::Cast<glin::IndexT>>::CastTo: 'static +
                glin::BufferRangeMut<glin::IndexT> +
                Clone,
            <B as glin::buffer::Cast<V>>::CastTo: 'static
                + glin::BufferRangeMut<V>
                + glin::buffer::WithBackend
                + allocator::MapRange<V>
                + Clone,
            allocator::Allocator<B>: allocator::InternalCreation<B> +
                allocator::Creation<B> +
                allocator::Updater,
            Allocator<V,B>: AllocatorFlags,
        {
            let geom = entities.component_for::<Geometry<V>>(&geometryref).unwrap();
            let submeshes = entities.component_for::<Submesh>(&geometryref);
            let submeshes = submeshes.map(|s| *s);
            let source_path = entities.component_for::<SourcePath>(&geometryref);
            let bytes = geom.len() * mem::size_of::<V>() +
                        geom.indices().len() * mem::size_of::<glin::IndexT>();
            let size = allocator::human(bytes);
            log::trace!("Creating  gpu geometries for {:?}::{:?} {}", source_path, name, size);

            let has_submeshes = submeshes.is_some();
            let (vao_ranges, full_range, vertices, indices)
                = allocator.submesh_vaos(glin, &geom, submeshes, dynamic);
            if has_submeshes {
                log::trace!("Creating  {} gpu geometries for {:?}::{:?}, indices: {}, submeshes {}",
                    vao_ranges.len(), source_path, name, indices.is_some(), vao_ranges.len());
            }else{
                log::trace!("Creating 1 gpu geometries (no submeshes) for {:?}::{:?}", source_path, name);
            }

            let submesh_buffers = vao_ranges.into_iter().map(|vao_range|{
                // let vao_range_info = allocator.vao_range(&vao_range);
                SubmeshBuffers::new::<V,B>(
                    vao_range,
                    geom.primitive_type(),
                    unified_material_ubo,
                    allocator_handle
                )
            }).collect::<Vec<_>>();


            // let vao_range_info = allocator.vao_range(&full_range);
            let shadow_geom = ShadowGeometry(SubmeshBuffers::new::<V,B>(
                full_range.clone(),
                geom.primitive_type(),
                unified_material_ubo,
                allocator_handle
            ));

            AddGpuGeometry::New{
                entities_vec,
                geometryref,
                name,
                vertices,
                indices,
                submesh_buffers,
                shadow_geom,
            }
        }


        let glin = resources.get::<gl::Renderer<'static>>().unwrap();
        let mut allocators = resources.get_mut::<AllocatorsIndex>().unwrap();
        let mut allocator = allocators.get_mut::<V,B>(self.allocator_handle).unwrap();

        enum AddGpuGeometry{
            Reuse(EntitiesVec, GeometryRef, GpuGeometryReference),
            New{
                entities_vec: EntitiesVec,
                geometryref: GeometryRef,
                vertices: BufferRef,
                indices: Option<BufferRef>,
                submesh_buffers: Vec<SubmeshBuffers>,
                shadow_geom: ShadowGeometry,
                name: Name,
            }
        }

        let to_add_index = entities.iter_for::<(
            Entity,
            Read<Visible>,
            ReadNot<GeometryRef, GpuGeometryRef>,
            ReadRef<GeometryRef, Geometry<V>>,
            ReadOption<AnimatedGeometry<V>>
        )>().filter_map(|(entity, visible, geometryref, geom, animated_geom)|{
            // If geom is none it's a different vertex type
            // TODO: Use typed GeometryRef?
            if !visible.is_visible() || geom.is_empty() {
                None
            }else{
                Some((*geometryref, (entity, animated_geom.is_some(), false)))
            }
        });

        #[cfg(feature="debug_geometry")]
        let to_add_index = to_add_index.chain(entities.iter_for::<(
            Entity,
            ReadNot<DebugGeometryRef, GpuDebugGeometryRef>,
        )>().filter_map(|(entity, geometryref)|{
            // If geom is none it's a different vertex type
            // TODO: Use typed DebugGeometryRef?
            let geom = entities.component_for::<Geometry<V>>(geometryref.geometry());
            if !geometryref.is_visible() || geom.is_none() || geom.unwrap().is_empty() {
                None
            }else{
                Some((*geometryref.geometry(), (entity, false, true)))
            }
        }));

        let to_add_index = to_add_index.into_group_map();

        let to_add = to_add_index.into_iter().flat_map(|(geometryref, toadd)| {
            let (animated, nonanimated) : (Vec<_>, Vec<_>) = toadd.into_iter()
                .partition_map(|(entity, animated, _debug)| if animated{
                    Either::Left(entity)
                }else{
                    #[cfg(feature="debug_geometry")]
                    {
                        Either::Right((entity, _debug))
                    }

                    #[cfg(not(feature="debug_geometry"))]
                    {
                        Either::Right(entity)
                    }
                });

            let name = entities.component_for::<Name>(&geometryref);

            #[cfg(feature = "debug_geometry")]
            let non_animated = if !nonanimated.is_empty(){
                if let Some((gpugeom, _geom)) = entities.iter_for::<(Read<GpuGeometryRef>, Read<GeometryRef>)>()
                    .find(|(_, geom)| **geom == geometryref)
                {
                    log::trace!("Reusing gpu geometry");
                    Some(AddGpuGeometry::Reuse(nonanimated, geometryref, gpugeom.0))
                }else if let Some((gpugeom, _geom)) = entities.iter_for::<(Read<GpuDebugGeometryRef>, Read<DebugGeometryRef>)>()
                    .find(|(_, debug_geom)| *debug_geom.geometry() == geometryref)
                {
                    log::trace!("Reusing debug gpu geometry");
                    Some(AddGpuGeometry::Reuse(nonanimated, geometryref, gpugeom.0))
                }else{
                    log::trace!("Adding gpu geometry");
                    Some(build_geometry::<V,B>(
                        &entities,
                        &mut allocator,
                        self.allocator_handle,
                        name.as_ref()
                            .map(|n| Name(format!("{} gpu geometry", **n)))
                            .unwrap_or_else(|| Name("Gpu geometry".to_owned())),
                        geometryref,
                        nonanimated,
                        &glin,
                        false,
                        self.unified_material_ubo))
                }
            }else{
                None
            };

            #[cfg(not(feature = "debug_geometry"))]
            let non_animated = if !nonanimated.is_empty(){
                if let Some((gpugeom, _geom)) = entities.iter_for::<(Read<GpuGeometryRef>, Read<GeometryRef>)>()
                    .find(|(_, geom)| **geom == geometryref)
                {
                    log::trace!("Reusing gpu geometry");
                    Some(AddGpuGeometry::Reuse(nonanimated, geometryref, gpugeom.0))
                }else{
                    Some(build_geometry::<V,B>(
                        &entities,
                        &mut allocator,
                        self.allocator_handle,
                        name.as_ref()
                            .map(|n| Name(format!("{} gpu geometry", **n)))
                            .unwrap_or_else(|| Name("Gpu geometry".to_owned())),
                        geometryref,
                        nonanimated,
                        &glin,
                        false,
                        self.unified_material_ubo))
                }
            }else{
                None
            };

            let animated = animated.into_iter().map(|entity| {
                #[cfg(not(feature = "debug_geometry"))]
                let entities_vec = vec![entity];
                #[cfg(feature = "debug_geometry")]
                let entities_vec = vec![(entity, false)];

                build_geometry(
                    &entities,
                    &mut allocator,
                    self.allocator_handle,
                    name.as_ref()
                        .map(|name| Name(format!("{} animated gpu geometry for {}", **name, entity.guid())))
                        .unwrap_or_else(|| Name(format!("Animated gpu geometry for {}", entity.guid()))),
                    geometryref,
                    entities_vec,
                    &glin,
                    true,
                    self.unified_material_ubo)
            }).collect::<Vec<_>>();

            non_animated.into_iter().chain(animated)

        }).collect::<Vec<_>>();

        for gpuadd in to_add{
            match gpuadd{
                #[cfg(feature="debug_geometry")]
                AddGpuGeometry::Reuse(entities_vec, geometryref, gpugeom) => {
                    for (entity, debug) in entities_vec {
                        if debug {
                            entities.add_component_to(&entity, GpuDebugGeometryRef(gpugeom));
                        }else{
                            entities.add_component_to(&entity, GpuGeometryRef(gpugeom));
                        }
                    }
                    entities.add_component_to(&geometryref, GeomToGpuGeomRef(gpugeom));
                }

                #[cfg(not(feature="debug_geometry"))]
                AddGpuGeometry::Reuse(entities_vec, geometryref, gpugeom) => {
                    for entity in entities_vec {
                        entities.add_component_to(&entity, GpuGeometryRef(gpugeom));
                    }
                    entities.add_component_to(&geometryref, GeomToGpuGeomRef(gpugeom));
                }

                AddGpuGeometry::New{
                    entities_vec,
                    geometryref,
                    name,
                    vertices,
                    indices,
                    submesh_buffers,
                    shadow_geom} =>
                {
                    let gpugeom = entities.new_entity()
                        .add(name)
                        .add_slice(submesh_buffers)
                        .add(shadow_geom)
                        .add(VertexBuffer(vertices))
                        .build();
                    if let Some(indices) = indices {
                        entities.add_component_to_thread_local(&gpugeom, IndicesBuffer(indices));
                    }

                    #[cfg(feature="debug_geometry")]
                    for (entity, debug) in entities_vec {
                        if debug {
                            entities.add_component_to(&entity, GpuDebugGeometryRef(gpugeom));
                        }else{
                            entities.add_component_to(&entity, GpuGeometryRef(gpugeom));
                        }
                    }

                    #[cfg(not(feature="debug_geometry"))]
                    for entity in entities_vec {
                        entities.add_component_to(&entity, GpuGeometryRef(gpugeom));
                    }
                    entities.add_component_to(&geometryref, GeomToGpuGeomRef(gpugeom));
                }
            }
        }

        let gl = resources.get::<gl::Renderer>().unwrap();
        let mut command_buffers_dirty = false;
        let changed = entities.changed_iter_for_mut::<(
            Read<Geometry<V>>,
            RefN<GeomToGpuGeomRef, Write<VertexBuffer>>,
            RefN<GeomToGpuGeomRef, Write<IndicesBuffer>>)>();
        for (mesh, mut vertexbuffers, mut indicesbuffers) in changed {
            let iter = unsafe{ vertexbuffers.unsafe_iter_mut().zip(indicesbuffers.unsafe_iter_opt_mut()) };
            for (vertices, indices) in iter {
                // let name = entities.component_for_mut::<Name>(&geom);
                command_buffers_dirty |= allocator.vertex_buffer_range_len(&vertices) !=
                    mesh.len();
                allocator.update_vertex_buffer_range(&*gl, &vertices, mesh.vertices()).unwrap();
                if let Some(indices) = indices {
                    command_buffers_dirty |= allocator.index_buffer_range_len(&indices) !=
                        mesh.indices().len();
                    allocator.update_index_buffer_range(&*gl, &indices, mesh.indices()).unwrap();
                }else if !mesh.indices().is_empty(){
                    // println!("Creating index buffer");
                    // let indices = allocator.indices_static(&*gl, mesh.indices()).unwrap();
                    // add_indices.push((*gpugeom, IndicesBuffer(indices)))
                    unimplemented!("Trying to update mesh with indices that didn't have originally. Not supported yet")
                }
            }
        }

        // TODO: static and dynamic shadows might not need to be regenerated if the geometry that
        // chaged is only used by static or dynamic instances
        // Also neither might need to be updated if all geometries are invisible
        // Is it worth checking? probably regenerating the extra commands is not much slower
        #[cfg(not(any(feature = "webgl", feature = "gles")))]
        if self.uses_command_buffers && command_buffers_dirty {
            if let Some(mut commands) = resources.get_mut::<CommandBufferData>(){
                commands.dirty = command_buffers_dirty;
            }
            if let Some(mut shadow_commands) = resources.get_mut::<ShadowsCommandBufferData>(){
                shadow_commands.dirty = command_buffers_dirty;
            }
            if let Some(mut shadow_commands) = resources.get_mut::<StaticShadowsCommandBufferData>(){
                shadow_commands.dirty = command_buffers_dirty;
            }
            if let Some(mut shadow_commands) = resources.get_mut::<AllShadowsCommandBufferData>(){
                shadow_commands.dirty = command_buffers_dirty;
            }
        }

    }
}


#[derive(Ord, PartialOrd, PartialEq, Eq)]
#[repr(C)]
struct GeomKey<'a> {
    priority: i32,
    properties: &'a [glin::Property],
    programref: ProgramRef,
    textures_hash: u64,
    // camera_distance: u64,
    uniforms_hash: u64,
    materialref: MaterialRef,
    vao_id: VaoId,
    geometryref: Entity,
    submesh: usize,
}


// #[derive(Ord, PartialOrd, PartialEq, Eq)]
// #[repr(C)]
// struct DistanceSortGeomKey<'a> {
//     priority: i32,
//     properties: &'a [glin::Property],
//     programref: ProgramRef,
//     textures_hash: u64,
//     // camera_distance: u64,
//     // materialref: MaterialRef,
//     vao_id: VaoId,
// }

pub fn reset_geometry_indices(_: Entities, resources: Resources){
    resources.get_mut::<resources::OpaqueSortedGeometry>().unwrap().reset_has_changed();
    resources.get_mut::<resources::TranslucentSortedGeometry>().unwrap().reset_has_changed();
    #[cfg(feature = "debug_geometry")]
    resources.get_mut::<resources::DebugSortedGeometry>().unwrap().reset_has_changed();
}

#[system(name = "geometry sort")]
#[needs(
    MaterialRef,
    MaterialMultiRef,
    Visible,
    MaterialCache,
    GpuGeometryRef,
)]
#[cfg_attr(feature="debug_geometry", needs(DebugGeometryRef, GpuDebugGeometryRef))]
#[after(update_visible_changed, update_materialrefs_changed)]
#[updates(
    resources::TranslucentSortedGeometry,
    resources::OpaqueSortedGeometry
)]
#[cfg_attr(feature="debug_geometry", updates(resources::DebugSortedGeometry))]
#[cfg_attr(not(feature="debug_geometry"), cond(any(
    changed("MaterialRef"),
    changed("MaterialMultiRef"),
    changed("Visible"),
    changed("GpuGeometryRef"),
    resource("MaterialCache::<MaterialRef>::any_material_transparency_changed"),
    resource("MaterialCache::<MaterialRef>::any_texture_or_uniform_changed"),
)))]
#[cfg_attr(feature="debug_geometry", cond(any(
    changed("MaterialRef"),
    changed("MaterialMultiRef"),
    changed("Visible"),
    changed("GpuGeometryRef"),
    changed("DebugGeometryRef"),
    resource("MaterialCache::<MaterialRef>::any_material_transparency_changed"),
    resource("MaterialCache::<MaterialRef>::any_texture_or_uniform_changed"),
)))]
#[else_run("reset_geometry_indices")]
#[writes(Node, SubmeshBuffers)]
#[reads(RenderPlane)]
pub fn geometry_sort(entities: Entities, resources: Resources){
    let materials_cache = resources.get::<MaterialCache>().unwrap();
    let mut opaque_geometry = resources.get_mut::<resources::OpaqueSortedGeometry>().unwrap();
    let mut translucent_geometry = resources.get_mut::<resources::TranslucentSortedGeometry>()
        .unwrap();
    #[cfg(feature = "debug_geometry")]
    let mut debug_geometry = resources.get_mut::<resources::DebugSortedGeometry>().unwrap();

    opaque_geometry.clear();
    translucent_geometry.clear();
    #[cfg(feature = "debug_geometry")]
    debug_geometry.clear();

    let entities_models = entities.iter_for::<(
        Entity,
        // ReadOption<Name>,
        Read<Node>,
        Read<GpuGeometryRef>,
        ReadOption<RenderPlane>,
        ReadOption<MaterialRef>,
        ReadOption<MaterialMultiRef>,
        Ref<GpuGeometryRef, Read<SubmeshBuffers>>,
        Read<Visible>,)>()
        .filter_map(|(e, _, /*name,*/ gpu_geom, renderplane, materialref, multimat_ref, submesh_buffers, visible)| {
            if visible.is_visible() {
                Some((e, /*name,*/ gpu_geom.0, renderplane, materialref, multimat_ref, None, submesh_buffers))
            }else{
                None
            }
        });

    #[cfg(feature="debug_geometry")]
    let entities_models = entities_models.chain(entities.iter_for::<(
            Entity,
            // ReadOption<Name>,
            Read<Node>,
            Read<GpuDebugGeometryRef>,
            Read<DebugGeometryRef>,
            Ref<GpuDebugGeometryRef, Read<SubmeshBuffers>>,
        )>().filter_map(|(e, _, /*name,*/ gpu_geom, debug_geom, submesh_buffers)|{
            if debug_geom.is_visible() && materials_cache[*debug_geom.material()].visible {
                Some((e, /*name,*/ gpu_geom.0, None, None, None, Some(*debug_geom.material()), submesh_buffers))
            }else{
                None
            }
        }));

    let mut add_submesh_material = |
        entity: Entity,
        // name: Option<&Name>,
        geometryref: Entity,
        is_debug: bool,
        renderplane: Option<SliceView<RenderPlane>>,
        submesh_buffers: SliceView<SubmeshBuffers>,
        submesh: usize,
        materialref: &MaterialRef,

    |{
        let material = &materials_cache[*materialref];
        if !material.visible{
            return;
        }
        let vao_id = submesh_buffers[submesh].vao_range().vao_id();
        let geomkey = GeomKey{
            priority: material.priority,
            materialref: *materialref,
            programref: material.programref,
            properties: &material.properties,
            textures_hash: material.textures_hash,
            uniforms_hash: material.uniforms_hash,
            // camera_distance,
            geometryref,
            submesh,
            vao_id,
        };

        if !material.translucent && !is_debug {
            let insert_pos = opaque_geometry.binary_search_by_key(&geomkey, |geom| {
                let material = &materials_cache[geom.materialref];
                GeomKey{
                    priority: material.priority,
                    materialref: geom.materialref,
                    programref: material.programref,
                    properties: &material.properties,
                    textures_hash: material.textures_hash,
                    uniforms_hash: material.uniforms_hash,
                    // camera_distance: geom.camera_distance,
                    geometryref: geom.geometryref,
                    submesh: geom.submesh,
                    vao_id: geom.vao_id,
                }
            });

            match insert_pos {
                Ok(insert_pos) => opaque_geometry[insert_pos].entities.push(entity),

                Err(insert_pos) => opaque_geometry.insert(insert_pos,
                    resources::GeometryIndex{
                        entities: vec![entity],
                        // name: name.map(|n| n.0.as_str()).unwrap_or("").to_owned(),
                        geometryref,
                        materialref: *materialref,
                        submesh,
                        vao_id,
                        renderplane: renderplane.map(|_| entity),
                    }),
            }
        }else if !is_debug{
            let insert_pos = translucent_geometry.binary_search_by_key(&geomkey, |geom| {
                let material = &materials_cache[geom.materialref];
                GeomKey{
                    priority: material.priority,
                    materialref: geom.materialref,
                    programref: material.programref,
                    properties: &material.properties,
                    textures_hash: material.textures_hash,
                    uniforms_hash: material.uniforms_hash,
                    // camera_distance: geom.camera_distance,
                    geometryref: geom.geometryref,
                    submesh: geom.submesh,
                    vao_id: geom.vao_id,
                }
            });

            match insert_pos {
                Ok(insert_pos) => translucent_geometry[insert_pos].entities.push(entity),

                Err(insert_pos) => translucent_geometry.insert(insert_pos,
                    resources::GeometryIndex{
                        entities: vec![entity],
                        // name: name.map(|n| n.0.as_str()).unwrap_or("").to_owned(),
                        materialref: *materialref,
                        geometryref,
                        submesh,
                        vao_id,
                        renderplane: renderplane.map(|_| entity),
                    }),
            }
        }else{
            #[cfg(feature = "debug_geometry")]
            {
                let insert_pos = debug_geometry.binary_search_by_key(&geomkey, |geom| {
                    let material = &materials_cache[geom.materialref];
                    GeomKey{
                        priority: material.priority,
                        materialref: geom.materialref,
                        programref: material.programref,
                        properties: &material.properties,
                        textures_hash: material.textures_hash,
                        uniforms_hash: material.uniforms_hash,
                        // camera_distance: geom.camera_distance,
                        geometryref: geom.geometryref,
                        submesh: geom.submesh,
                        vao_id: geom.vao_id,
                    }
                });

                match insert_pos {
                    Ok(insert_pos) => debug_geometry[insert_pos].entities.push(entity),

                    Err(insert_pos) => debug_geometry.insert(insert_pos,
                        resources::GeometryIndex{
                            entities: vec![entity],
                            // name: name.map(|n| n.0.as_str()).unwrap_or("").to_owned(),
                            geometryref,
                            materialref: *materialref,
                            submesh,
                            vao_id,
                            renderplane: renderplane.map(|_| entity),
                        }),
                }
            }
        }
    };

    for (entity, /*name,*/ geometryref, renderplane, materials, multi_materials, one_material, submesh_buffers) in entities_models {
        if let Some(materials) = materials {
            for (submesh, materialref) in materials.iter().enumerate() {
                add_submesh_material(
                    entity,
                    // name,
                    geometryref,
                    false,
                    renderplane,
                    submesh_buffers,
                    submesh,
                    materialref)
            }
        }else if let Some(multi_materials) = multi_materials {
            for (submesh, material_multiref) in multi_materials.iter().enumerate() {
                for materialref in material_multiref.iter() {
                    add_submesh_material(
                        entity,
                        // name,
                        geometryref,
                        false,
                        renderplane,
                        submesh_buffers,
                        submesh,
                        materialref)
                }
            }
        }else if let Some(materialref) = one_material {
            let submesh = 0;
            add_submesh_material(
                entity,
                // name,
                geometryref,
                true,
                renderplane,
                submesh_buffers,
                submesh,
                &materialref)
        }
    }

    // TODO: Try to use a bounding box rather than the global position
    // and as a last step sort the batches by their bb distance to camera
    // use rin::graphics::NodeRef;
    // use rin::math::EuclideanSpace;
    // use crate::transformation::Camera;

    // let mut segments = vec![];
    // let mut prev_key = None;
    // let camera = resources.get::<Camera>().unwrap();
    // let camera_position = camera.global_position();
    // for (pos, geom) in opaque_geometry.iter().enumerate(){
    //     let material = &materials_cache[geom.materialref];
    //     let key = DistanceSortGeomKey{
    //         priority: material.priority,
    //         // materialref: geom.materialref,
    //         programref: material.programref,
    //         properties: &material.properties,
    //         textures_hash: material.textures_hash,
    //         vao_id: geom.vao_id,
    //     };
    //     if prev_key.as_ref().map(|prev_key| *prev_key != key).unwrap_or(true) {
    //         segments.push(pos);
    //         prev_key = Some(key);
    //     }
    // }

    // for geom in opaque_geometry.iter_mut(){
    //     geom.entities.sort_unstable_by_key(|entity|{
    //         let trafo = entities.component_for::<Transformation>(entity).unwrap();
    //         let camera_distance = trafo.global_position().distance_squared(&camera_position);
    //         (camera_distance * 10000.) as u64
    //     })
    // }

    // for segment in segments.windows(2){
    //     let start = segment[0];
    //     let end = segment[1];
    //     opaque_geometry[start .. end].sort_unstable_by_key(|geom|{
    //         let entity = &geom.entities[0];
    //         let trafo = entities.component_for::<Transformation>(entity).unwrap();
    //         let camera_distance = trafo.global_position().distance_squared(&camera_position);
    //         (camera_distance * 10000.) as u64
    //     })
    // }

    // segments.clear();
    // prev_key = None;
    // for (pos, geom) in translucent_geometry.iter().enumerate(){
    //     let material = &materials_cache[geom.materialref];
    //     let key = DistanceSortGeomKey{
    //         priority: material.priority,
    //         // materialref: geom.materialref,
    //         programref: material.programref,
    //         properties: &material.properties,
    //         textures_hash: material.textures_hash,
    //         vao_id: geom.vao_id,
    //     };
    //     if prev_key.as_ref().map(|prev_key| *prev_key != key).unwrap_or(true) {
    //         segments.push(pos);
    //         prev_key = Some(key);
    //     }
    // }

    // for geom in translucent_geometry.iter_mut(){
    //     geom.entities.sort_unstable_by_key(|entity|{
    //         let trafo = entities.component_for::<Transformation>(entity).unwrap();
    //         let camera_distance = trafo.global_position().distance_squared(&camera_position);
    //         (camera_distance * 10000.) as u64
    //     })
    // }

    // for segment in segments.windows(2){
    //     let start = segment[0];
    //     let end = segment[1];
    //     translucent_geometry[start .. end].sort_unstable_by_key(|geom|{
    //         let entity = &geom.entities[0];
    //         let trafo = entities.component_for::<Transformation>(entity).unwrap();
    //         let camera_distance = trafo.global_position().distance_squared(&camera_position);
    //         (camera_distance * 10000.) as u64
    //     })
    // }
}

#[derive(Default, Clone)]
pub struct Segment{
    pub start: usize,
    pub end: usize,
    pub vao_id: u32,
    pub primitive_type: u32,
    pub elements: bool,
}
type SubmeshIndex = usize;
type Posiiton = usize;

pub struct CommandBufferData{
    pub data: Vec<glin::DrawElementsIndirectCommand>,
    pub index: HashMap<(GpuGeometryReference, SubmeshIndex), Posiiton>,
    pub segments_per_renderplane: HashMap<Option<Entity>, Vec<Segment>>,
    pub translucent_starts: HashMap<Option<Entity>, Posiiton>,
    pub debug_starts: HashMap<Option<Entity>, Posiiton>,
    pub dirty: bool,
    pub changed: bool,
}

impl Default for CommandBufferData{
    fn default() -> CommandBufferData{
        CommandBufferData{
            data: Vec::default(),
            index: HashMap::default(),
            segments_per_renderplane: HashMap::default(),
            translucent_starts: HashMap::default(),
            debug_starts: HashMap::default(),
            dirty: true,
            changed: false,
        }
    }
}

#[system_thread_local(name = "command buffer data")]
#[needs(
    resources::OpaqueSortedGeometry,
    resources::TranslucentSortedGeometry,
    resources::ModelMatricesBuffer,
    MaterialCache,
    SubmeshBuffers,
)]
#[cfg_attr(feature="debug_geometry", needs(resources::DebugSortedGeometry))]
#[updates(CommandBufferData)]
#[reads(Visible, RenderPlane, gl::Renderer, MaterialOffsets)]
#[writes(AllocatorsIndex)]
pub fn update_command_buffer_data(entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
    let opaque_geometry = resources.get::<resources::OpaqueSortedGeometry>().unwrap();
    let translucent_geometry = resources.get::<resources::TranslucentSortedGeometry>().unwrap();
    #[cfg(feature = "debug_geometry")]
    let debug_geometry = resources.get::<resources::DebugSortedGeometry>().unwrap();
    let mut commands = resources.get_mut::<CommandBufferData>().unwrap();
    let materials_cache = resources.get::<MaterialCache>().unwrap();
    let willrun = commands.dirty
        || opaque_geometry.has_changed()
        || translucent_geometry.has_changed()
        || materials_cache.any_texture_or_uniform_changed();
    #[cfg(feature = "debug_geometry")]
    let willrun = willrun || debug_geometry.has_changed();
    if !willrun {
        return;
    }
    // trace!("Updating command buffers commands_dirty: {} opaque: {} traslucent: {}, texture or uniforms {}",
    //     commands.dirty,
    //     opaque_geometry.has_changed(),
    //     translucent_geometry.has_changed(),
    //     materials_cache.any_texture_or_uniform_changed());

    // Clear command buffers
    commands.data.clear();
    commands.index.clear();
    commands.segments_per_renderplane.entry(None).or_insert_with(|| vec![]).clear();
    commands.translucent_starts.clear();
    commands.debug_starts.clear();
    for (renderplane, _, _) in entities.iter_for::<(
        Entity,
        Read<Visible>,
        Read<RenderPlane>)>().filter(|(_,v,_)| v.is_visible())
    {
        commands.segments_per_renderplane.entry(Some(renderplane))
            .or_insert_with(|| vec![])
            .clear();
    }

    // Recreate command buffer for main camera
    let mut prev_vao_data = Segment::default();
    let mut prev_vao_id = None;
    let mut prev_program_ref = None;
    // let mut prev_materialref = None;
    let mut prev_uniforms = None;
    let mut prev_primitive_type = None;
    let mut prev_textures = None;
    let mut prev_properties = None;
    let mut segment_start = 0;
    let mut base_instance = 0;
    let mut translucent_start = None;
    let mut debug_start = None;
    let geometries = opaque_geometry.iter().chain(translucent_geometry.iter());
    #[cfg(feature = "debug_geometry")]
    let geometries = geometries.chain(debug_geometry.iter());
    let gl = resources.get::<gl::Renderer>().unwrap();
    let model_data_gpu = resources.get::<resources::ModelMatricesBuffer>().unwrap();
    let mut allocators = resources.get_mut::<AllocatorsIndex>().unwrap();
    let material_offsets = resources.get::<MaterialOffsets>();
    for (segment, geom_index) in geometries.enumerate() {
        let num_instances = geom_index.num_instances();
        if let Some(submeshes) = entities.component_for::<SubmeshBuffers>(&geom_index.geometryref){
            let submesh = &submeshes[geom_index.submesh];
            let material = &materials_cache[geom_index.materialref];

            if (prev_program_ref.is_some() && prev_program_ref != Some(material.programref))
                || (prev_vao_id.is_some() && prev_vao_id != Some(geom_index.vao_id))
                || (prev_primitive_type.is_some() && prev_primitive_type != Some(submesh.primitive_type()))
                || (prev_textures.is_some() && prev_textures != Some(material.textures_hash))
                || (prev_properties.is_some() && prev_properties != Some(&material.properties))
                || (prev_uniforms.is_some() && prev_uniforms != Some(material.uniforms_hash))
                // || (prev_materialref.is_some() && prev_materialref != Some(material.materialref)
                        // && !material.uniforms.is_empty())
                || segment == opaque_geometry.len() + translucent_geometry.len()
            {
                prev_vao_data.start = segment_start;
                prev_vao_data.end = segment;
                commands.segments_per_renderplane.get_mut(&None)
                    .unwrap()
                    .push(prev_vao_data.clone());

                segment_start = segment;
                if segment == opaque_geometry.len(){
                    translucent_start = Some(commands.segments_per_renderplane[&None].len())
                }
                if segment == opaque_geometry.len() + translucent_geometry.len() {
                    debug_start = Some(commands.segments_per_renderplane[&None].len())
                }
            }
            prev_vao_id = Some(geom_index.vao_id);
            prev_program_ref = Some(material.programref);
            // prev_materialref = Some(material.materialref);
            prev_primitive_type = Some(submesh.primitive_type());
            prev_textures = Some(material.textures_hash);
            prev_properties = Some(&material.properties);
            prev_uniforms = Some(material.uniforms_hash);
            prev_vao_data.vao_id = submesh
                .full_vao(&*gl, &mut allocators, material_offsets.as_deref(), &model_data_gpu)
                .unwrap()
                .id();
            prev_vao_data.primitive_type = submesh.primitive_type();
            prev_vao_data.elements = submesh.has_indices();

            let pos = commands.data.len();
            commands.index.insert((geom_index.geometryref, geom_index.submesh), pos);
            commands.data.push(submesh.command(&mut allocators, base_instance, num_instances as u32));
        }
        base_instance += num_instances as u32;
    }

    let last_segment = opaque_geometry.len() + translucent_geometry.len();
    #[cfg(feature="debug_geometry")]
    let last_segment = last_segment + debug_geometry.len();
    if last_segment > segment_start{
        prev_vao_data.start = segment_start;
        prev_vao_data.end = last_segment;
        commands.segments_per_renderplane.get_mut(&None)
            .unwrap()
            .push(prev_vao_data);
    }

    if let Some(translucent_start) = translucent_start{
        commands.translucent_starts.insert(None, translucent_start);
    }

    if let Some(debug_start) = debug_start{
        commands.debug_starts.insert(None, debug_start);
    }

    fn fill_renderplane_segments<'a, I: Iterator<Item = &'a GeometryIndex>>(
        geometries: I,
        renderplane: Entity,
        entities: &EntitiesThreadLocal,
        allocators: &mut memory::AllocatorsIndex,
        material_offsets: Option<&MaterialOffsets>,
        gl: &gl::Renderer,
        model_data_gpu: &resources::ModelMatricesBuffer,
        material_cache: &MaterialCache,
        commands: &mut CommandBufferData,
        opaque_len: usize,
        translucent_len: usize,
        debug_len: usize)
    {
        let mut prev_vao_data = Segment::default();
        let mut prev_vao_id = None;
        let mut prev_program_ref = None;
        let mut prev_primitive_type = None;
        let mut prev_textures = None;
        let mut prev_uniforms = None;
        let mut prev_properties = None;
        let mut segment_start = 0;
        let mut translucent_start = None;
        let mut debug_start = None;

        for (segment, geom_index) in geometries.enumerate() {
            if let Some(submeshes) = entities.component_for::<SubmeshBuffers>(&geom_index.geometryref){
                let submesh = &submeshes[geom_index.submesh];
                let material = &material_cache[geom_index.materialref];

                if geom_index.renderplane == Some(renderplane) {
                    if segment > segment_start {
                        prev_vao_data.start = segment_start;
                        prev_vao_data.end = segment;
                        commands.segments_per_renderplane.get_mut(&Some(renderplane))
                            .unwrap()
                            .push(prev_vao_data.clone());
                    }
                    segment_start = segment + 1;
                    continue;
                }

                if (segment_start != segment) && (prev_program_ref != Some(material.programref)
                    || prev_vao_id != Some(geom_index.vao_id)
                    || prev_primitive_type != Some(submesh.primitive_type())
                    || prev_textures != Some(material.textures_hash)
                    // || (prev_materialref.is_some() && prev_materialref != Some(material.materialref)
                            // && !material.uniforms.is_empty())
                    || (prev_uniforms.is_some() && prev_uniforms != Some(material.uniforms_hash))
                    || (prev_properties.is_some() && prev_properties != Some(&material.properties)))
                {
                    prev_vao_data.start = segment_start;
                    prev_vao_data.end = segment;
                    commands.segments_per_renderplane.get_mut(&Some(renderplane))
                        .unwrap()
                        .push(prev_vao_data.clone());

                    segment_start = segment;
                    if segment == opaque_len{
                        translucent_start = Some(commands.segments_per_renderplane[&Some(renderplane)].len())
                    }
                    if segment == opaque_len + translucent_len {
                        debug_start = Some(commands.segments_per_renderplane[&Some(renderplane)].len())
                    }
                }
                prev_vao_id = Some(geom_index.vao_id);
                prev_program_ref = Some(material.programref);
                prev_primitive_type = Some(submesh.primitive_type());
                prev_textures = Some(material.textures_hash);
                prev_uniforms = Some(material.uniforms_hash);
                prev_properties = Some(&material.properties);
                prev_vao_data.vao_id = submesh
                    .full_vao(gl, allocators, material_offsets, model_data_gpu)
                    .unwrap()
                    .id();
                prev_vao_data.primitive_type = submesh.primitive_type();
                prev_vao_data.elements = submesh.has_indices();
            }
        }

        let last_segment = opaque_len + translucent_len + debug_len;
        if last_segment > segment_start{
            prev_vao_data.start = segment_start;
            prev_vao_data.end = last_segment;
            commands.segments_per_renderplane.get_mut(&Some(renderplane))
                .unwrap()
                .push(prev_vao_data);
        }

        if let Some(translucent_start) = translucent_start{
            commands.translucent_starts.insert(Some(renderplane), translucent_start);
        }

        if let Some(debug_start) = debug_start{
            commands.debug_starts.insert(Some(renderplane), debug_start);
        }
    }


    // Recreate command buffer for each renderplane
    let opaque_len = opaque_geometry.len();
    let translucent_len = translucent_geometry.len();
    #[cfg(feature="debug_geometry")]
    let debug_len = debug_geometry.len();
    #[cfg(not(feature="debug_geometry"))]
    let debug_len = 0;

    for (renderplane_entity, _, renderplane) in entities.iter_for::<(
        Entity,
        Read<Visible>,
        Read<RenderPlane>)>().filter(|(_,v,_)| v.is_visible())
    {
        // TODO: right now we only check the first render plane in each entity
        // we would need to create an index per renderplane not per entity
        if renderplane[0].draw_translucent() && renderplane[0].draw_debug(){
            let geometries = opaque_geometry.iter().chain(translucent_geometry.iter());
            #[cfg(feature = "debug_geometry")]
            let geometries = geometries.chain(debug_geometry.iter());
            fill_renderplane_segments(
                geometries,
                renderplane_entity,
                &entities,
                &mut allocators,
                material_offsets.as_deref(),
                &gl,
                &model_data_gpu,
                &materials_cache,
                &mut commands,
                opaque_len,
                translucent_len,
                debug_len);
        }else if renderplane[0].draw_translucent(){
            let geometries = opaque_geometry.iter().chain(translucent_geometry.iter());
            fill_renderplane_segments(
                geometries,
                renderplane_entity,
                &entities,
                &mut allocators,
                material_offsets.as_deref(),
                &gl,
                &model_data_gpu,
                &materials_cache,
                &mut commands,
                opaque_len,
                translucent_len,
                debug_len);
        }else{
            let geometries = opaque_geometry.iter();
            fill_renderplane_segments(
                geometries,
                renderplane_entity,
                &entities,
                &mut allocators,
                material_offsets.as_deref(),
                &gl,
                &model_data_gpu,
                &materials_cache,
                &mut commands,
                opaque_len,
                translucent_len,
                debug_len);
        }
    }

    commands.changed = true;
    commands.dirty = false;
}

pub struct CommandBuffer(pub glin::Buffer<glin::DrawElementsIndirectCommand>);
#[system_thread_local(name = "upload command buffer")]
#[needs(CommandBufferData)]
#[updates(CommandBuffer)]
#[writes(CommandBufferData)]
#[gpu_stats]
pub fn upload_command_buffer(_: EntitiesThreadLocal, resources: ResourcesThreadLocal){
    let mut commands = resources.get_mut::<CommandBufferData>().unwrap();
    if commands.changed {
        let mut command_buffer = resources.get_mut::<CommandBuffer>().unwrap();
        if command_buffer.0.len() < commands.data.len(){
            command_buffer.0.load(&commands.data, gl::STREAM_DRAW);
        }else{
            command_buffer.0.update(&commands.data);
        }
        commands.changed = false;
    }
}



#[repr(C)]
#[derive(PartialOrd, PartialEq, Ord, Eq)]
struct ShadowGeomKey<'a>{
    priority: Option<i32>,
    properties: Option<&'a [glin::Property]>,
    programref: Option<ProgramRef>,
    textures_hash: Option<u64>,
    // camera_distance: u64,
    uniforms_hash: Option<u64>,
    materialref: Option<ShadowMaterialRef>,
    vao_id: VaoId,
    primitive_type: GLenum,
    geometryref: GpuGeometryRef,
    submesh: Option<usize>,
}

#[repr(C)]
#[derive(PartialOrd, PartialEq, Ord, Eq)]
struct ShadowDistanceSortGeomKey{
    vao_id: VaoId,
    primitive_type: GLenum,
}

#[derive(Default)]
pub struct ShadowsCommandBufferData{
    pub data: Vec<glin::DrawElementsIndirectCommand>,
    pub index: HashMap<GpuGeometryRef, usize>,
    pub segments: Vec<Segment>,
    pub changed: bool,
    pub dirty: bool,
}

impl ShadowsCommandBufferData{
    fn parts_mut(&mut self) -> (&mut Vec<glin::DrawElementsIndirectCommand>, &mut HashMap<GpuGeometryRef, usize>, &mut Vec<Segment>){
        (&mut self.data, &mut self.index, &mut self.segments)
    }
}

fn add_shadow_geometry(
    geometry_sorted: &mut Vec<ShadowGeometryIndex>,
    shadow_materials_cache: &ShadowMaterialCache,
    entity: Entity,
    geometryref: GpuGeometryRef,
    geom: &SubmeshBuffers,
    shadowmaterial: Option<(usize, ShadowMaterialRef)>)
{
    let material = shadowmaterial.map(|(_submesh, m)| &shadow_materials_cache[m]);
    let geomkey = ShadowGeomKey {
        priority: material.map(|m| m.priority),
        materialref: shadowmaterial.map(|(_, materialref)| materialref),
        programref: material.map(|m| m.programref),
        properties: material.map(|m| m.properties.as_slice()),
        textures_hash: material.map(|m| m.textures_hash),
        uniforms_hash: material.map(|m| m.uniforms_hash),
        vao_id: geom.vao_range().vao_id(),
        primitive_type: geom.primitive_type(),
        geometryref: geometryref,
        submesh: shadowmaterial.map(|(submesh,_)| submesh),
    };

    let insert_pos = geometry_sorted.binary_search_by_key(&geomkey, |geom| {
        let material = geom.materialref.map(|m| &shadow_materials_cache[m]);
        ShadowGeomKey{
            priority: material.map(|m| m.priority),
            materialref: shadowmaterial.map(|(_, materialref)| materialref),
            programref: material.map(|m| m.programref),
            properties: material.map(|m| m.properties.as_slice()),
            textures_hash: material.map(|m| m.textures_hash),
            uniforms_hash: material.map(|m| m.uniforms_hash),
            vao_id: geom.vao_id,
            primitive_type: geom.primitive_type,
            geometryref: geom.geometryref,
            submesh: geom.submesh,
        }
    });

    match insert_pos {
        Ok(insert_pos) => geometry_sorted[insert_pos].entities.push(entity),

        Err(insert_pos) => geometry_sorted.insert(insert_pos,
            resources::ShadowGeometryIndex{
                entities: vec![entity],
                geometryref: geometryref,
                vao_id: geom.vao_range().vao_id(),
                primitive_type: geom.primitive_type(),
                materialref: shadowmaterial.map(|(_, materialref)| materialref),
                submesh: shadowmaterial.map(|(submesh,_)| submesh),
            }),
    }
}

#[system(name = "geometry sort dynamic")]
#[needs(
    Visible,
    MaterialRef,
    MaterialMultiRef,
    ShadowMaterialRef,
    MaterialCache,
    ShadowMaterialCache,
    GpuGeometryRef,
)]
#[after(update_visible_changed, update_materialrefs_changed)]
#[updates(resources::DynamicShadowsSortedGeometry)]
#[cond(all(
    components(has("shadow::Map"), has("shadow::StaticMap")),
    any(
        changed("Visible"),
        changed("MaterialRef"),
        changed("MaterialMultiRef"),
        changed("ShadowMaterialRef"),
        resource("MaterialCache::<MaterialRef>::any_material_transparency_changed"),
        resource("ShadowMaterialCache::any_material_transparency_changed"),
        resource("ShadowMaterialCache::any_texture_or_uniform_changed"),
        resource("resources::DynamicShadowsSortedGeometry::is_empty")
    )
))]
#[reads(ShadowGeometry)]
pub fn dynamic_shadows_geometry_sort(entities: Entities, resources: Resources){
    let mut geometry_sorted = resources.get_mut::<resources::DynamicShadowsSortedGeometry>()
        .unwrap();
    let materials_cache = resources.get::<MaterialCache>().unwrap();
    let shadow_materials_cache = resources.get::<ShadowMaterialCache>().unwrap();

    let any_visible_changed =
        entities.changed_iter_for::<(Read<Visible>, Has<DynamicTransformation>)>()
            .next().is_some();
    let materialref_changed =
        entities.changed_iter_for::<(Read<MaterialRef>, Has<DynamicTransformation>)>()
            .next().is_some();
    let materialmultiref_changed =
        entities.changed_iter_for::<(Read<MaterialMultiRef>, Has<DynamicTransformation>)>()
            .next().is_some();

    if !geometry_sorted.is_empty()
        && !materials_cache.any_material_transparency_changed()
        && !shadow_materials_cache.any_material_transparency_changed()
        && !shadow_materials_cache.any_texture_or_uniform_changed()
        && !any_visible_changed
        && !materialref_changed
        && !materialmultiref_changed
    {
        return;
    }

    geometry_sorted.clear();

    let entities_models = entities.iter_for::<(
        Entity,
        Has<DynamicTransformation>,
        Read<GpuGeometryRef>,
        ReadRef<GpuGeometryRef, ShadowGeometry>,
        ReadOption<MaterialRef>,
        ReadOption<MaterialMultiRef>,
        ReadOption<ShadowMaterialRef>,
        Read<Visible>)>().filter(|(_,_,_,_, materials, multimaterials, shadowmaterials, visible)| {
            visible.is_visible() && if let Some(shadowmaterials) = shadowmaterials{
                shadowmaterials.iter()
                    .any(|m| shadow_materials_cache[*m].visible)
            }else if let Some(materials) = materials {
                materials.iter()
                    .any(|m| !materials_cache[*m].translucent && materials_cache[*m].visible)
            }else if let Some(multimaterials) = multimaterials {
                multimaterials.iter()
                    .any(|materials| materials.iter()
                        .any(|m| !materials_cache[*m].translucent && materials_cache[*m].visible))
            }else{
                false
            }
        });

    for (entity, _, geometryref, geom, _, _, shadowmaterials, _) in entities_models {
        if let Some(shadowmaterials) = shadowmaterials {
            for (submesh, shadowmaterial) in shadowmaterials.iter().enumerate() {
                add_shadow_geometry(
                    &mut geometry_sorted,
                    &shadow_materials_cache,
                    entity,
                    *geometryref,
                    geom,
                    Some((submesh, *shadowmaterial)))
            }
        }else{
            add_shadow_geometry(
                &mut geometry_sorted,
                &shadow_materials_cache,
                entity,
                *geometryref,
                geom,
                None)
        }
    }
}

#[system_thread_local(name = "shadows command buffer data")]
#[needs(
    resources::DynamicShadowsSortedGeometry,
    resources::DynamicModelMatricesBuffer,
    ShadowMaterialCache,
    ShadowGeometry,
    ShadowMaterialOffsets
)]
#[updates(ShadowsCommandBufferData)]
#[writes(AllocatorsIndex)]
#[reads(gl::Renderer)]
pub fn update_shadows_command_buffer_data(entities: EntitiesThreadLocal, resources: ResourcesThreadLocal) {
    let geometry_sorted = resources.get::<resources::DynamicShadowsSortedGeometry>()
        .unwrap();
    let mut commands = resources.get_mut::<ShadowsCommandBufferData>().unwrap();

    if !commands.dirty && !geometry_sorted.has_changed() {
        return
    }

    commands.data.clear();
    commands.segments.clear();
    commands.index.clear();
    let (data, index, segments) = commands.parts_mut();
    let mut iter = entities
        .iter_for_entities::<Read<ShadowGeometry>, _>(geometry_sorted.geometryrefs().map(|g| &**g))
        .zip(geometry_sorted.iter())
        .enumerate();
    if let Some((segment, (geom, geom_index))) = iter.next() {
        let mut allocators = resources.get_mut::<AllocatorsIndex>().unwrap();
        let gl = resources.get::<gl::Renderer>().unwrap();
        let shadow_materials_cache = resources.get::<ShadowMaterialCache>().unwrap();
        let model_data_gpu = resources.get::<resources::DynamicModelMatricesBuffer>().unwrap();
        let material_offsets = resources.get::<ShadowMaterialOffsets>();
        let material_offsets = material_offsets
            .as_ref()
            .and_then(|offsets| offsets.dynamic_buffer());
        let mut base_instance = 0;
        let num_instances = geom_index.num_instances() as u32;
        let material = geom_index.materialref
            .map(|m| &shadow_materials_cache[m]);
        let mut segment_start = segment;
        let mut prev_vao_id = geom_index.vao_id;
        let mut prev_primitive_type = geom.primitive_type();
        let mut prev_program_ref = material.map(|m| m.programref);
        let mut prev_materialref = geom_index.materialref;
        let mut prev_textures = material.map(|m| m.textures_hash);
        let mut prev_properties = material.map(|m| &m.properties);
        let mut prev_uniforms = material.map(|m| m.uniforms_hash);
        let mut prev_elements = geom.has_indices();
        let mut prev_vao_gl_id = geom
            .full_shadow_vao(&*gl, &mut allocators, &model_data_gpu, material_offsets)
            .unwrap()
            .id();
        let command = geom.command(&mut allocators, base_instance, num_instances);
        let pos = data.len();
        index.insert(geom_index.geometryref, pos);
        data.push(command);
        base_instance += num_instances;
        for (segment, (geom, geom_index)) in iter {
            let num_instances = geom_index.num_instances() as u32;
            let material = geom_index.materialref
                .map(|m| &shadow_materials_cache[m]);
            if prev_program_ref != material.map(|m| m.programref)
                || prev_vao_id != geom_index.vao_id
                || prev_primitive_type != geom.primitive_type()
                || prev_textures != material.map(|m| m.textures_hash)
                || prev_properties != material.map(|m| &m.properties)
                || prev_uniforms != material.map(|m| m.uniforms_hash)
                || prev_materialref != geom_index.materialref
                || segment == geometry_sorted.len()
            {
                segments.push(Segment {
                    start: segment_start,
                    end: segment,
                    vao_id: prev_vao_gl_id,
                    primitive_type: prev_primitive_type,
                    elements: prev_elements,
                });
                segment_start = segment;
                prev_vao_id = geom_index.vao_id;
                prev_primitive_type = geom.primitive_type();
                prev_program_ref = material.map(|m| m.programref);
                prev_materialref = geom_index.materialref;
                prev_textures = material.map(|m| m.textures_hash);
                prev_properties = material.map(|m| &m.properties);
                prev_uniforms = material.map(|m| m.uniforms_hash);
                prev_elements = geom.has_indices();
                prev_vao_gl_id = geom
                    .full_shadow_vao(&*gl, &mut allocators, &model_data_gpu, material_offsets)
                    .unwrap()
                    .id();
            }
            let command = geom.command(&mut allocators, base_instance, num_instances);
            let pos = data.len();
            index.insert(geom_index.geometryref, pos);
            data.push(command);
            base_instance += num_instances;
        }

        segments.push(Segment {
            start: segment_start,
            end: geometry_sorted.len(),
            vao_id: prev_vao_gl_id,
            primitive_type: prev_primitive_type,
            elements: prev_elements,
        });
    }
    commands.changed = true;
    commands.dirty = false;
}

pub struct ShadowsCommandBuffer(pub glin::Buffer<glin::DrawElementsIndirectCommand>);
#[system_thread_local(name = "upload shadows command buffer")]
#[needs(ShadowsCommandBufferData)]
#[updates(ShadowsCommandBuffer)]
#[writes(ShadowsCommandBufferData)]
#[gpu_stats]
pub fn upload_shadows_command_buffer(_: EntitiesThreadLocal, resources: ResourcesThreadLocal){
    let mut commands = resources.get_mut::<ShadowsCommandBufferData>().unwrap();
    if commands.changed {
        let mut command_buffer = resources.get_mut::<ShadowsCommandBuffer>().unwrap();
        if command_buffer.0.len() < commands.data.len(){
            command_buffer.0.load(&commands.data, gl::STREAM_DRAW);
        }else{
            command_buffer.0.update(&commands.data);
        }
        commands.changed = false;
    }
}

#[derive(Default)]
pub struct StaticShadowsCommandBufferData{
    pub data: Vec<glin::DrawElementsIndirectCommand>,
    pub segments: Vec<Segment>,
    pub dirty: bool,
}

impl StaticShadowsCommandBufferData{
    fn data_and_segments(&mut self) -> (&mut Vec<glin::DrawElementsIndirectCommand>, &mut Vec<Segment>){
        (&mut self.data, &mut self.segments)
    }
}

#[system(name = "geometry sort static")]
#[needs(
    Visible,
    MaterialRef,
    MaterialMultiRef,
    ShadowMaterialRef,
    MaterialCache,
    ShadowMaterialCache,
    GpuGeometryRef,
    ShadowGeometry,
)]
#[after(update_visible_changed, update_materialrefs_changed)]
#[updates(resources::StaticShadowsSortedGeometry)]
#[cond(all(
    components(has("shadow::StaticMap")),
    any(
        changed("Visible"),
        changed("MaterialRef"),
        changed("MaterialMultiRef"),
        changed("ShadowMaterialRef"),
        resource("MaterialCache::<MaterialRef>::any_material_transparency_changed"),
        resource("ShadowMaterialCache::any_material_transparency_changed"),
        resource("ShadowMaterialCache::any_texture_or_uniform_changed"),
        resource("resources::StaticShadowsSortedGeometry::is_empty")
    )
))]
#[writes(Node, AllocatorsIndex)]
pub fn static_shadows_geometry_sort(entities: Entities, resources: Resources){
    let mut geometry_sorted = resources.get_mut::<resources::StaticShadowsSortedGeometry>()
        .unwrap();
    let materials_cache = resources.get::<MaterialCache>().unwrap();
    let shadow_materials_cache = resources.get::<ShadowMaterialCache>().unwrap();

    let any_visible_changed =
        entities.changed_iter_for::<ReadNot<Visible, DynamicTransformation>>()
            .next()
            .is_some();
    let materialref_changed =
        entities.changed_iter_for::<ReadNot<MaterialRef, DynamicTransformation>>()
            .next()
            .is_some();
    let materialmultiref_changed =
        entities.changed_iter_for::<ReadNot<MaterialMultiRef, DynamicTransformation>>()
            .next()
            .is_some();

    if !geometry_sorted.is_empty()
        && !materials_cache.any_material_transparency_changed()
        && !shadow_materials_cache.any_material_transparency_changed()
        && !shadow_materials_cache.any_texture_or_uniform_changed()
        && !any_visible_changed
        && !materialref_changed
        && !materialmultiref_changed
    {
        return;
    }

    log::trace!("Sorting static shadows index");

    // Static geometry changed, recreate static shadow map indices
    geometry_sorted.clear();

    let entities_models = entities.iter_for::<(
        Entity,
        Read<Node>,
        ReadNot<GpuGeometryRef, DynamicTransformation>,
        ReadRef<GpuGeometryRef, ShadowGeometry>,
        ReadOption<MaterialRef>,
        ReadOption<MaterialMultiRef>,
        ReadOption<ShadowMaterialRef>,
        Read<Visible>)>().filter(|(_,_,_,_, materials, multimaterials, shadowmaterials, visible)| {
            visible.is_visible() && if let Some(shadowmaterials) = shadowmaterials{
                shadowmaterials.iter()
                    .any(|m| shadow_materials_cache[*m].visible)
            }else if let Some(materials) = materials {
                materials.iter()
                    .any(|m| !materials_cache[*m].translucent && materials_cache[*m].visible)
            }else if let Some(multimaterials) = multimaterials {
                multimaterials.iter()
                    .any(|materials| materials.iter()
                        .any(|m| !materials_cache[*m].translucent && materials_cache[*m].visible))
            }else{
                false
            }
        });

    for (entity, _, geometryref, geom, _, _, shadowmaterials, _) in entities_models {
        if let Some(shadowmaterials) = shadowmaterials {
            for (submesh, shadowmaterial) in shadowmaterials.iter().enumerate() {
                add_shadow_geometry(
                    &mut geometry_sorted,
                    &shadow_materials_cache,
                    entity,
                    *geometryref,
                    geom,
                    Some((submesh, *shadowmaterial)))
            }
        }else{
            add_shadow_geometry(
                &mut geometry_sorted,
                &shadow_materials_cache,
                entity,
                *geometryref,
                geom,
                None)
        }
    }
}

#[system_thread_local(name = "static shadows command buffer data")]
#[needs(
    resources::StaticShadowsSortedGeometry,
    resources::StaticModelMatricesBuffer,
    ShadowGeometry,
    ShadowMaterialCache,
    ShadowMaterialOffsets
)]
#[updates(StaticShadowsCommandBufferData)]
#[writes(AllocatorsIndex)]
#[reads(gl::Renderer)]
pub fn update_static_shadows_command_buffer_data(entities: EntitiesThreadLocal, resources: ResourcesThreadLocal) {
    let geometry_sorted = resources.get::<resources::StaticShadowsSortedGeometry>()
        .unwrap();
    let mut commands = resources.get_mut::<StaticShadowsCommandBufferData>().unwrap();

    if !commands.dirty && !geometry_sorted.has_changed() {
        return
    }

    commands.data.clear();
    commands.segments.clear();
    let (data, segments) = commands.data_and_segments();

    let mut iter = entities
        .iter_for_entities::<Read<ShadowGeometry>, _>(geometry_sorted.geometryrefs().map(|g| &**g))
        .zip(geometry_sorted.iter())
        .enumerate();

    if let Some((segment, (geom, geom_index))) = iter.next() {
        let gl = resources.get::<gl::Renderer>().unwrap();
        let shadow_materials_cache = resources.get::<ShadowMaterialCache>().unwrap();
        let model_data_gpu = resources.get::<resources::StaticModelMatricesBuffer>().unwrap();
        let mut allocators = resources.get_mut::<AllocatorsIndex>().unwrap();
        let material_offsets = resources.get::<ShadowMaterialOffsets>();
        let material_offsets = material_offsets
            .as_ref()
            .and_then(|offsets| offsets.static_buffer());

        let mut base_instance = 0;
        let num_instances = geom_index.num_instances() as u32;
        let material = geom_index.materialref
            .map(|m| &shadow_materials_cache[m]);
        let mut segment_start = segment;
        let mut prev_vao_id = geom_index.vao_id;
        let mut prev_primitive_type = geom.primitive_type();
        let mut prev_program_ref = material.map(|m| m.programref);
        let mut prev_materialref = geom_index.materialref;
        let mut prev_textures = material.map(|m| m.textures_hash);
        let mut prev_properties = material.map(|m| &m.properties);
        let mut prev_uniforms = material.map(|m| m.uniforms_hash);
        let mut prev_elements = geom.has_indices();
        let mut prev_vao_gl_id = geom
            .full_shadow_vao(&*gl, &mut allocators, &model_data_gpu, material_offsets)
            .unwrap()
            .id();
        let command = geom.command(&mut allocators, base_instance, num_instances);
        data.push(command);
        base_instance += num_instances;
        let new_commands = iter
            .map(|(segment, (geom, geom_index))| {
                let num_instances = geom_index.num_instances() as u32;
                let material = geom_index.materialref.map(|m| &shadow_materials_cache[m]);
                if prev_program_ref != material.map(|m| m.programref)
                    || prev_vao_id != geom_index.vao_id
                    || prev_primitive_type != geom.primitive_type()
                    || prev_textures != material.map(|m| m.textures_hash)
                    || prev_properties != material.map(|m| &m.properties)
                    || prev_uniforms != material.map(|m| m.uniforms_hash)
                    || prev_materialref != geom_index.materialref
                    || segment == geometry_sorted.len()
                {
                    segments.push(Segment {
                        start: segment_start,
                        end: segment,
                        vao_id: prev_vao_gl_id,
                        primitive_type: prev_primitive_type,
                        elements: prev_elements,
                    });
                    segment_start = segment;
                    prev_vao_id = geom_index.vao_id;
                    prev_primitive_type = geom.primitive_type();
                    prev_program_ref = material.map(|m| m.programref);
                    prev_materialref = geom_index.materialref;
                    prev_textures = material.map(|m| m.textures_hash);
                    prev_properties = material.map(|m| &m.properties);
                    prev_uniforms = material.map(|m| m.uniforms_hash);
                    prev_elements = geom.has_indices();
                    prev_vao_gl_id = geom
                        .full_shadow_vao(&*gl, &mut allocators, &model_data_gpu, material_offsets)
                        .unwrap()
                        .id();
                }
                let command = geom.command(&mut allocators, base_instance, num_instances);
                base_instance += num_instances;
                command
            });
        data.extend(new_commands);

        segments.push(Segment {
            start: segment_start,
            end: geometry_sorted.len(),
            vao_id: prev_vao_gl_id,
            primitive_type: prev_primitive_type,
            elements: prev_elements,
        });
    }
    commands.dirty = false;
}

pub struct StaticShadowsCommandBuffer(pub glin::Buffer<glin::DrawElementsIndirectCommand>);
#[system_thread_local(name = "upload static shadows command buffer")]
#[needs(StaticShadowsCommandBufferData)]
#[updates(StaticShadowsCommandBuffer)]
#[cond(resource("resources::StaticShadowsSortedGeometry::has_changed"))]
#[gpu_stats]
pub fn upload_static_shadows_command_buffer(_: EntitiesThreadLocal, resources: ResourcesThreadLocal){
    log::trace!("Regenerating static shadows command buffer");
    let commands = resources.get::<StaticShadowsCommandBufferData>().unwrap();
    let mut command_buffer = resources.get_mut::<StaticShadowsCommandBuffer>().unwrap();
    command_buffer.0.load(&commands.data, gl::STATIC_DRAW);
}

#[derive(Default)]
pub struct AllShadowsCommandBufferData{
    pub data: Vec<glin::DrawElementsIndirectCommand>,
    pub index_per_range_start: HashMap<GpuGeometryRef, usize>,
    pub segments: Vec<Segment>,
    pub changed: bool,
    pub dirty: bool,
}

impl AllShadowsCommandBufferData{
    fn parts_mut(&mut self) -> (&mut Vec<glin::DrawElementsIndirectCommand>, &mut HashMap<GpuGeometryRef, usize>, &mut Vec<Segment>){
        (&mut self.data, &mut self.index_per_range_start, &mut self.segments)
    }
}

#[system(name = "geometry sort all")]
#[needs(
    "Visible",
    "MaterialRef",
    "MaterialMultiRef",
    "ShadowMaterialRef",
    "MaterialCache",
    "ShadowMaterialCache",
    "GpuGeometryRef",
    "ShadowGeometry"
)]
#[after("update_visible_changed", "update_materialrefs_changed")]
#[updates("resources::AllShadowsSortedGeometry")]
#[cond(all(
    any(
        components(has_not("shadow::Map", "shadow::StaticMap")),
        has_resource("resources::DepthPrepass")
    ),
    any(
        changed("Visible"),
        changed("MaterialRef"),
        changed("ShadowMaterialRef"),
        changed("MaterialMultiRef"),
        resource("MaterialCache::<MaterialRef>::any_material_transparency_changed"),
        resource("ShadowMaterialCache::any_material_transparency_changed"),
        resource("resources::AllShadowsSortedGeometry::is_empty"),
    )
))]
#[reads("Node")]
pub fn all_shadows_geometry_sort(entities: Entities, resources: Resources){
    let materials_cache = resources.get::<MaterialCache>().unwrap();
    let shadow_materials_cache = resources.get::<ShadowMaterialCache>().unwrap();

    let mut geometry_sorted = resources.get_mut::<resources::AllShadowsSortedGeometry>().unwrap();
    geometry_sorted.clear();

    let entities_models = entities.iter_for::<(
        Entity,
        Read<Node>,
        Read<GpuGeometryRef>,
        ReadRef<GpuGeometryRef, ShadowGeometry>,
        ReadOption<MaterialRef>,
        ReadOption<MaterialMultiRef>,
        ReadOption<ShadowMaterialRef>,
        Read<Visible>)>().filter(|(_,_,_,_, materials, multimaterials, shadowmaterials, visible)| {
            visible.is_visible() && if let Some(shadowmaterials) = shadowmaterials{
                shadowmaterials.iter()
                    .any(|m| shadow_materials_cache[*m].visible)
            }else if let Some(materials) = materials {
                materials.iter()
                    .any(|m| !materials_cache[*m].translucent && materials_cache[*m].visible)
            }else if let Some(multimaterials) = multimaterials {
                multimaterials.iter()
                    .any(|materials| materials.iter()
                        .any(|m| !materials_cache[*m].translucent && materials_cache[*m].visible))
            }else{
                false
            }
        });

    for (entity, _, geometryref, geom,  _, _, shadowmaterials, _) in entities_models {
        if let Some(shadowmaterials) = shadowmaterials {
            for (submesh, shadowmaterial) in shadowmaterials.iter().enumerate() {
                add_shadow_geometry(
                    &mut geometry_sorted,
                    &shadow_materials_cache,
                    entity,
                    *geometryref,
                    geom,
                    Some((submesh, *shadowmaterial)))
            }
        }else{
            add_shadow_geometry(
                &mut geometry_sorted,
                &shadow_materials_cache,
                entity,
                *geometryref,
                geom,
                None)
        }
    }
}

#[system_thread_local(name = "all shadows command buffer data")]
#[needs(
    resources::AllShadowsSortedGeometry,
    resources::AllModelMatricesBuffer,
    ShadowMaterialCache,
    ShadowGeometry,
    ShadowMaterialOffsets
)]
#[updates(AllShadowsCommandBufferData)]
#[reads(gl::Renderer)]
#[writes(AllocatorsIndex)]
pub fn update_all_shadows_command_buffer_data(entities: EntitiesThreadLocal, resources: ResourcesThreadLocal) {
    let mut commands = resources.get_mut::<AllShadowsCommandBufferData>().unwrap();
    let geometry_sorted = resources.get::<resources::AllShadowsSortedGeometry>().unwrap();

    if !commands.dirty && !geometry_sorted.has_changed() {
        return
    }

    commands.data.clear();
    commands.index_per_range_start.clear();
    commands.segments.clear();
    let (data, index, segments) = commands.parts_mut();
    let mut iter = entities
        .iter_for_entities::<Read<ShadowGeometry>, _>(geometry_sorted.geometryrefs().map(|g| &**g))
        .zip(geometry_sorted.iter())
        .enumerate();
    if let Some((segment, (geom, geom_index))) = iter.next() {
        let mut allocators = resources.get_mut::<AllocatorsIndex>().unwrap();
        let gl = resources.get::<gl::Renderer>().unwrap();
        let shadow_materials_cache = resources.get::<ShadowMaterialCache>().unwrap();
        let model_data_gpu = resources.get::<resources::AllModelMatricesBuffer>().unwrap();
        let material_offsets = resources.get::<ShadowMaterialOffsets>();
        let material_offsets = material_offsets
            .as_ref()
            .and_then(|offsets| offsets.all_buffer());

        let mut base_instance = 0;
        let num_instances = geom_index.num_instances() as u32;
        let material = geom_index.materialref
            .map(|m| &shadow_materials_cache[m]);
        let mut segment_start = segment;
        let mut prev_vao_id = geom_index.vao_id;
        let mut prev_primitive_type = geom.primitive_type();
        let mut prev_program_ref = material.map(|m| m.programref);
        let mut prev_materialref = geom_index.materialref;
        let mut prev_textures = material.map(|m| m.textures_hash);
        let mut prev_properties = material.map(|m| &m.properties);
        let mut prev_uniforms = material.map(|m| m.uniforms_hash);
        let mut prev_elements = geom.has_indices();
        let mut prev_vao_gl_id = geom
            .full_shadow_vao(&*gl, &mut allocators, &model_data_gpu, material_offsets)
            .unwrap()
            .id();
        let command = geom.command(&mut allocators, base_instance, num_instances);
        let pos = data.len();
        index.insert(geom_index.geometryref, pos);
        data.push(command);
        base_instance += num_instances;

        for (segment, (geom, geom_index)) in iter {
            let num_instances = geom_index.num_instances() as u32;
            let material = geom_index.materialref
                .map(|m| &shadow_materials_cache[m]);
            if prev_program_ref != material.map(|m| m.programref)
                || prev_vao_id != geom_index.vao_id
                || prev_primitive_type != geom.primitive_type()
                || prev_textures != material.map(|m| m.textures_hash)
                || prev_properties != material.map(|m| &m.properties)
                || prev_uniforms != material.map(|m| m.uniforms_hash)
                || prev_materialref != geom_index.materialref
                || segment == geometry_sorted.len()
            {
                segments.push(Segment {
                    start: segment_start,
                    end: segment,
                    vao_id: prev_vao_gl_id,
                    primitive_type: prev_primitive_type,
                    elements: prev_elements,
                });
                segment_start = segment;
                prev_vao_id = geom_index.vao_id;
                prev_primitive_type = geom.primitive_type();
                prev_program_ref = material.map(|m| m.programref);
                prev_materialref = geom_index.materialref;
                prev_textures = material.map(|m| m.textures_hash);
                prev_properties = material.map(|m| &m.properties);
                prev_uniforms = material.map(|m| m.uniforms_hash);
                prev_elements = geom.has_indices();
                prev_vao_gl_id = geom
                    .full_shadow_vao(&*gl, &mut allocators, &model_data_gpu, material_offsets)
                    .unwrap()
                    .id();
            }
            let command = geom.command(&mut allocators, base_instance, num_instances);
            let pos = data.len();
            index.insert(geom_index.geometryref, pos);
            data.push(command);
            base_instance += num_instances;
        }

        segments.push(Segment {
            start: segment_start,
            end: geometry_sorted.len(),
            vao_id: prev_vao_gl_id,
            primitive_type: prev_primitive_type,
            elements: prev_elements,
        });
    }
    commands.changed = true;
    commands.dirty = false;
}

pub struct AllShadowsCommandBuffer(pub glin::Buffer<glin::DrawElementsIndirectCommand>);
#[system_thread_local(name = "upload all shadows command buffer")]
#[needs(AllShadowsCommandBufferData)]
#[updates(AllShadowsCommandBuffer)]
#[writes(AllShadowsCommandBufferData)]
#[gpu_stats]
pub fn upload_all_shadows_command_buffer(_: EntitiesThreadLocal, resources: ResourcesThreadLocal){
    let mut commands = resources.get_mut::<AllShadowsCommandBufferData>().unwrap();
    if commands.changed {
        let mut command_buffer = resources.get_mut::<AllShadowsCommandBuffer>().unwrap();
        if command_buffer.0.len() < commands.data.len(){
            command_buffer.0.load(&commands.data, gl::STREAM_DRAW);
        }else{
            command_buffer.0.update(&commands.data);
        }
        commands.changed = false;
    }
}


pub struct AnimatedGeometryGpuUpdater<V,B>{
    allocator_handle: AllocatorHandle<V, B>,
}

impl<V,B> AnimatedGeometryGpuUpdater<V,B>{
    pub fn new(allocator_handle: AllocatorHandle<V, B>) -> AnimatedGeometryGpuUpdater<V,B>{
        AnimatedGeometryGpuUpdater{
            allocator_handle
        }
    }
}

impl<V: 'static, B> AnimatedGeometryGpuUpdater<V, B>
    where V: Debug + Clone + VertexFormat + Send + 'static,
        B: 'static + Clone +
            BufferExt<u8> +
            glin::buffer::Cast<glin::IndexT> +
            glin::buffer::Cast<V>,
        <B as glin::buffer::Cast<glin::IndexT>>::CastTo: 'static +
            glin::BufferRangeMut<glin::IndexT> +
            Clone,
        <B as glin::buffer::Cast<V>>::CastTo: 'static +
            glin::BufferRangeMut<V> +
            Clone,
        allocator::Allocator<B>: allocator::InternalCreation<B> +
            allocator::Creation<B> +
            allocator::Updater,
        Allocator<V,B>: AllocatorFlags,
{
    fn update_thread_local(&mut self, entities: &mut EntitiesThreadLocal, resources: &ResourcesThreadLocal){
        // if let Some(mut allocator) = resources.get_mut::<Allocator<V, B>>() {
        let mut allocator_index = resources.get_mut::<memory::AllocatorsIndex>().unwrap();
        let allocator = allocator_index.get_mut(self.allocator_handle).unwrap();
        let gl = resources.get::<gl::Renderer>().unwrap();

        let iter = entities.iter_for_mut::<(
            Write<AnimatedGeometry<V>>,
            Ref<GpuGeometryRef, Read<VertexBuffer>>,
        )>();

        // TODO: By now there's a 1 to 1 correspondance between animated geometry and gpu geometry
        // but could be useful to be able to create animated instances so more than one model can
        // have the same animated geometry
        iter.filter(|(animated_geom, _,)| animated_geom.changed)
            .for_each(|(animated_geom, vertex_buffer)|
        {
            allocator.update_vertex_buffer_range(&*gl, &vertex_buffer, &animated_geom.geom).unwrap();
            animated_geom.changed = false;
        });
        // }
    }

    // fn update_send(&mut self, entities: &EntitiesThreadLocal, resources: &ResourcesThreadLocal){
    //     let mut allocator = resources.get_mut::<Allocator<V>>().unwrap();
    //     if let Some(persistent_map) = allocator.persistent_map(){
    //         #[cfg(feature="gl_multidraw_indirect")]
    //         let mut command_buffer_data = resources.get_mut::<CommandBufferData>().unwrap();
    //         #[cfg(feature="gl_multidraw_indirect")]
    //         let mut shadow_command_buffer_data = resources.get_mut::<ShadowsCommandBufferData>()
    //             .unwrap();
    //         #[cfg(feature="gl_multidraw_indirect")]
    //         let mut all_shadow_command_buffer_data = resources.get_mut::<AllShadowsCommandBufferData>()
    //             .unwrap();

    //         let any_has_only_dynamic_shadows = entities.iter_for::<(Read<shadow::Map>, ReadOption<shadow::StaticMap>)>()
    //             .any(|(_, ss)| ss.is_none());
    //         let depth_prepass = resources.get::<resources::DepthPrepass>().is_some();

    //         let offset_submesh = |submesh: &mut SubmeshBuffers, offset: usize|{
    //             if let Some(base_vertex) = submesh.original_vao_range.base_vertex {
    //                 let base_vertex = base_vertex + offset as i32;
    //                 submesh.vao_range.base_vertex = Some(base_vertex);
    //             }else{
    //                 let start = submesh.original_vao_range.range.start + offset;
    //                 let end = submesh.original_vao_range.range.end + offset;
    //                 submesh.vao_range.range = start .. end;
    //             }
    //         };

    //         #[cfg(feature="gl_multidraw_indirect")]
    //         let offset_command = |submesh: &SubmeshBuffers, command: &mut glin::DrawElementsIndirectCommand, offset: usize|{
    //             if let Some(base_vertex) = submesh.original_vao_range.base_vertex {
    //                 command.base_vertex = base_vertex as u32 + offset as u32;
    //             }else{
    //                 let range_start = submesh.original_vao_range.range.start;
    //                 command.first_index = (range_start + offset) as u32;
    //             }
    //         };

    //         let iter = entities.iter_for::<(
    //             Write<AnimatedGeometry<V>>,
    //             Read<GpuGeometryRef>,
    //         )>();

    //         // TODO: By now there's a 1 to 1 correspondance between animated geometry and gpu geometry
    //         // but could be useful to be able to create animated instances so more than one model can
    //         // have the same animated geometry
    //         iter.filter(|(animated_geom, _)| animated_geom.changed)
    //             .for_each(|(animated_geom, gpu_geometry_ref)| {
    //             if *self.update_debug_normals{
    //                 if let Some(mut debug_normals) = entities.component_for_mut::<DebugNormals>(gpu_geometry_ref){
    //                     let length = *self.debug_normals_length;
    //                     let normals_data: Vec<_> = animated_geom.geom.iter().flat_map(|v|{
    //                         vec![
    //                             graphics::vertex3d(v.position().xyz()),
    //                             graphics::vertex3d(v.position().xyz() + v.normal() * length),
    //                         ]
    //                     }).collect();
    //                     let mut mesh = graphics::Mesh::from_vertices(normals_data);
    //                     mesh.set_primitive_type(graphics::PrimitiveType::Lines);
    //                     debug_normals.update_vertices(&mesh);
    //                 }
    //             }

    //             let mut vertex_buffer = entities
    //                 .component_for_mut::<VertexBuffer>(&gpu_geometry_ref)
    //                 .unwrap();
    //             let mut submesh_buffers = entities
    //                 .component_for_mut::<SubmeshBuffers>(gpu_geometry_ref)
    //                 .unwrap();

    //             vertex_buffer.next_region();
    //             persistent_map.update(vertex_buffer.range(), &animated_geom.geom);

    //             let offset = vertex_buffer.offset::<V>();
    //             for (idx, submesh) in submesh_buffers.iter_mut().enumerate() {
    //                 offset_submesh(submesh, offset);

    //                 #[cfg(feature="gl_multidraw_indirect")]
    //                 {
    //                     let command_pos = command_buffer_data.index[&(*gpu_geometry_ref, idx)];
    //                     let command = &mut command_buffer_data.data[command_pos];
    //                     offset_command(submesh, command, offset);
    //                     command_buffer_data.changed = true;
    //                 }
    //             }

    //             if any_has_only_dynamic_shadows || depth_prepass {
    //                 if let Some(mut shadow_geom) = entities.component_for_mut::<AllShadowGeometry>(gpu_geometry_ref){
    //                     offset_submesh(&mut shadow_geom, offset);

    //                     #[cfg(feature="gl_multidraw_indirect")]
    //                     {
    //                         let command_pos = all_shadow_command_buffer_data.index_per_range_start[&gpu_geometry_ref];
    //                         let command = &mut all_shadow_command_buffer_data.data[command_pos];
    //                         offset_command(&mut shadow_geom, command, offset);
    //                         all_shadow_command_buffer_data.changed = true;
    //                     }
    //                 }
    //             }

    //             if let Some(mut shadow_geom) = entities.component_for_mut::<ShadowGeometry>(gpu_geometry_ref){
    //                 offset_submesh(&mut shadow_geom, offset);

    //                 #[cfg(feature="gl_multidraw_indirect")]
    //                 {
    //                     let command_pos = shadow_command_buffer_data.index[&gpu_geometry_ref];
    //                     let command = &mut shadow_command_buffer_data.data[command_pos];
    //                     offset_command(&mut shadow_geom, command, offset);
    //                     shadow_command_buffer_data.changed = true;
    //                 }
    //             }
    //         });
    //     }
    // }
}

// impl<V: 'static> System for AnimatedGeometryGpuUpdater<V>
//     where V: Vertex<Position = Vec4> + vertex::Normal + Debug + Clone + VertexFormat +
//              Serialize + Deserialize<'static> + 'static + Send
// {
//     fn run(&mut self, entities: Entities, resources: Resources){
//         let allocator = resources.get::<Allocator<V>>().unwrap();
//         self.update(&entities, &allocator)
//     }
// }

#[system_thread_local(name = "animated geometry uploader")]
#[updates(VertexBuffer)]
#[needs(AnimatedGeometry<V>)]
#[reads(GpuGeometryRef, gl::Renderer)]
#[writes(
    AnimatedGeometry<V>,
    // Allocator<V, glin::buffer::SharedBufferStorage<u8>>,
    memory::AllocatorsIndex,
)]
#[cond(components(has("AnimatedGeometry<V>")))]
#[gpu_stats]
impl<V: 'static, B> SystemThreadLocal for AnimatedGeometryGpuUpdater<V, B>
    where V: Debug + Clone + Send + VertexFormat + 'static,
        B: 'static +
            BufferExt<u8> +
            Clone +
            glin::buffer::Cast<glin::IndexT> +
            glin::buffer::Cast<V>,
        <B as glin::buffer::Cast<glin::IndexT>>::CastTo: 'static +
            glin::BufferRangeMut<glin::IndexT> +
            Clone,
        <B as glin::buffer::Cast<V>>::CastTo: 'static +
            glin::BufferRangeMut<V> +
            Clone,
        allocator::Allocator<B>: allocator::InternalCreation<B> +
            allocator::Creation<B> +
            allocator::Updater,
        Allocator<V,B>: AllocatorFlags,
{
    fn run(&mut self, mut entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
        // if dynamic_flags() & gl::MAP_PERSISTENT_BIT != 0 {
        //     // self.update_send(&entities, &resources);
        // }else{
            self.update_thread_local(&mut entities, &resources);
        // }
    }
}

// pub fn update_regions<V>(entities: EntitiesThreadLocal, resources: ResourcesThreadLocal)
// where V: 'static + Clone + VertexFormat
// {
//     let gl = resources.get::<gl::Renderer>().unwrap();
//     let mut allocator = resources.get_mut::<Allocator<V>>().unwrap();
//     let mut persistent_map = allocator.persistent_map();

//     let iter = entities.iter_for::<(
//         Read<Visible>,
//         Write<AnimatedGeometry<V>>,
//         ReadRef<GpuGeometryRef, VertexBuffer>,
//     )>();

//     // TODO: By now there's a 1 to 1 correspondance between animated geometry and gpu geometry
//     // but could be useful to be able to create animated instances so more than one model can
//     // have the same animated geometry
//     iter.filter(|(visible, animated_geom, _)| visible.is_visible() || animated_geom.changed)
//         .for_each(|(_, animated_geom, vertex_buffer)| {
//             if let Some(persistent_map) = persistent_map.as_mut() {
//                 let vertex_buffer = vertex_buffer.unwrap();
//                 persistent_map.done(&*gl, vertex_buffer.range());
//             }

//             animated_geom.changed = false;
//         });
// }


// pub fn update_vao_ranges(entities: EntitiesThreadLocal, resources: ResourcesThreadLocal) {
//     for submeshes in entities.iter_for::<Write<SubmeshBuffers>>(){
//         for submesh in submeshes{
//             submesh.update_vao_range(&resources);
//         }
//     }
// }