aboutsummaryrefslogtreecommitdiffhomepage
path: root/patches/server/0009-MC-Utils.patch
blob: c03d31609e9d83b457f2a66f325c3dde40774bca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Aikar <aikar@aikar.co>
Date: Mon, 28 Mar 2016 20:55:47 -0400
Subject: [PATCH] MC Utils

== AT ==
public net.minecraft.server.level.ServerChunkCache mainThread
public net.minecraft.server.level.ServerLevel chunkSource
public org.bukkit.craftbukkit.inventory.CraftItemStack handle
public net.minecraft.server.level.ChunkMap getVisibleChunkIfPresent(J)Lnet/minecraft/server/level/ChunkHolder;
public net.minecraft.server.level.ServerChunkCache mainThreadProcessor
public net.minecraft.server.level.ServerChunkCache$MainThreadExecutor

diff --git a/src/main/java/com/destroystokyo/paper/util/concurrent/WeakSeqLock.java b/src/main/java/com/destroystokyo/paper/util/concurrent/WeakSeqLock.java
new file mode 100644
index 0000000000000000000000000000000000000000..4029dc68cf35d63aa70c4a76c35bf65a7fc6358f
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/util/concurrent/WeakSeqLock.java
@@ -0,0 +1,68 @@
+package com.destroystokyo.paper.util.concurrent;
+
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * copied from https://github.com/Spottedleaf/ConcurrentUtil/blob/master/src/main/java/ca/spottedleaf/concurrentutil/lock/WeakSeqLock.java
+ * @author Spottedleaf
+ */
+public final class WeakSeqLock {
+    // TODO when the switch to J11 is made, nuke this class from orbit
+
+    protected final AtomicLong lock = new AtomicLong();
+
+    public WeakSeqLock() {
+        //VarHandle.storeStoreFence(); // warn: usages must be checked to ensure this behaviour isn't needed
+    }
+
+    public void acquireWrite() {
+        // must be release-type write
+        this.lock.lazySet(this.lock.get() + 1);
+    }
+
+    public boolean canRead(final long read) {
+        return (read & 1) == 0;
+    }
+
+    public boolean tryAcquireWrite() {
+        this.acquireWrite();
+        return true;
+    }
+
+    public void releaseWrite() {
+        // must be acquire-type write
+        final long lock = this.lock.get(); // volatile here acts as store-store
+        this.lock.lazySet(lock + 1);
+    }
+
+    public void abortWrite() {
+        // must be acquire-type write
+        final long lock = this.lock.get(); // volatile here acts as store-store
+        this.lock.lazySet(lock ^ 1);
+    }
+
+    public long acquireRead() {
+        int failures = 0;
+        long curr;
+
+        for (curr = this.lock.get(); !this.canRead(curr); curr = this.lock.get()) {
+            // without j11, our only backoff is the yield() call...
+
+            if (++failures > 5_000) { /* TODO determine a threshold */
+                Thread.yield();
+            }
+            /* Better waiting is beyond the scope of this lock; if it is needed the lock is being misused */
+        }
+
+        //VarHandle.loadLoadFence(); // volatile acts as the load-load barrier
+        return curr;
+    }
+
+    public boolean tryReleaseRead(final long read) {
+        return this.lock.get() == read; // volatile acts as the load-load barrier
+    }
+
+    public long getSequentialCounter() {
+        return this.lock.get();
+    }
+}
diff --git a/src/main/java/com/destroystokyo/paper/util/map/QueuedChangesMapLong2Int.java b/src/main/java/com/destroystokyo/paper/util/map/QueuedChangesMapLong2Int.java
new file mode 100644
index 0000000000000000000000000000000000000000..59868f37d14bbc0ece0836095cdad148778995e6
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/util/map/QueuedChangesMapLong2Int.java
@@ -0,0 +1,162 @@
+package com.destroystokyo.paper.util.map;
+
+import com.destroystokyo.paper.util.concurrent.WeakSeqLock;
+import it.unimi.dsi.fastutil.longs.Long2IntMap;
+import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
+import it.unimi.dsi.fastutil.longs.LongIterator;
+import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
+import it.unimi.dsi.fastutil.objects.ObjectIterator;
+
+/**
+ * @author Spottedleaf
+ */
+public class QueuedChangesMapLong2Int {
+
+    protected final Long2IntOpenHashMap updatingMap;
+    protected final Long2IntOpenHashMap visibleMap;
+    protected final Long2IntOpenHashMap queuedPuts;
+    protected final LongOpenHashSet queuedRemove;
+
+    protected int queuedDefaultReturnValue;
+
+    // we use a seqlock as writes are not common.
+    protected final WeakSeqLock updatingMapSeqLock = new WeakSeqLock();
+
+    public QueuedChangesMapLong2Int() {
+        this(16, 0.75f);
+    }
+
+    public QueuedChangesMapLong2Int(final int capacity, final float loadFactor) {
+        this.updatingMap = new Long2IntOpenHashMap(capacity, loadFactor);
+        this.visibleMap = new Long2IntOpenHashMap(capacity, loadFactor);
+        this.queuedPuts = new Long2IntOpenHashMap();
+        this.queuedRemove = new LongOpenHashSet();
+    }
+
+    public void queueDefaultReturnValue(final int dfl) {
+        this.queuedDefaultReturnValue = dfl;
+        this.updatingMap.defaultReturnValue(dfl);
+    }
+
+    public int queueUpdate(final long k, final int v) {
+        this.queuedRemove.remove(k);
+        this.queuedPuts.put(k, v);
+
+        return this.updatingMap.put(k, v);
+    }
+
+    public int queueRemove(final long k) {
+        this.queuedPuts.remove(k);
+        this.queuedRemove.add(k);
+
+        return this.updatingMap.remove(k);
+    }
+
+    public int getUpdating(final long k) {
+        return this.updatingMap.get(k);
+    }
+
+    public int getVisible(final long k) {
+        return this.visibleMap.get(k);
+    }
+
+    public int getVisibleAsync(final long k) {
+        long readlock;
+        int ret = 0;
+
+        do {
+            readlock = this.updatingMapSeqLock.acquireRead();
+            try {
+                ret = this.visibleMap.get(k);
+            } catch (final Throwable thr) {
+                if (thr instanceof ThreadDeath) {
+                    throw (ThreadDeath)thr;
+                }
+                // ignore...
+                continue;
+            }
+
+        } while (!this.updatingMapSeqLock.tryReleaseRead(readlock));
+
+        return ret;
+    }
+
+    public boolean performUpdates() {
+        this.updatingMapSeqLock.acquireWrite();
+        this.visibleMap.defaultReturnValue(this.queuedDefaultReturnValue);
+        this.updatingMapSeqLock.releaseWrite();
+
+        if (this.queuedPuts.isEmpty() && this.queuedRemove.isEmpty()) {
+            return false;
+        }
+
+        // update puts
+        final ObjectIterator<Long2IntMap.Entry> iterator0 = this.queuedPuts.long2IntEntrySet().fastIterator();
+        while (iterator0.hasNext()) {
+            final Long2IntMap.Entry entry = iterator0.next();
+            final long key = entry.getLongKey();
+            final int val = entry.getIntValue();
+
+            this.updatingMapSeqLock.acquireWrite();
+            try {
+                this.visibleMap.put(key, val);
+            } finally {
+                this.updatingMapSeqLock.releaseWrite();
+            }
+        }
+
+        this.queuedPuts.clear();
+
+        final LongIterator iterator1 = this.queuedRemove.iterator();
+        while (iterator1.hasNext()) {
+            final long key = iterator1.nextLong();
+
+            this.updatingMapSeqLock.acquireWrite();
+            try {
+                this.visibleMap.remove(key);
+            } finally {
+                this.updatingMapSeqLock.releaseWrite();
+            }
+        }
+
+        this.queuedRemove.clear();
+
+        return true;
+    }
+
+    public boolean performUpdatesLockMap() {
+        this.updatingMapSeqLock.acquireWrite();
+        try {
+            this.visibleMap.defaultReturnValue(this.queuedDefaultReturnValue);
+
+            if (this.queuedPuts.isEmpty() && this.queuedRemove.isEmpty()) {
+                return false;
+            }
+
+            // update puts
+            final ObjectIterator<Long2IntMap.Entry> iterator0 = this.queuedPuts.long2IntEntrySet().fastIterator();
+            while (iterator0.hasNext()) {
+                final Long2IntMap.Entry entry = iterator0.next();
+                final long key = entry.getLongKey();
+                final int val = entry.getIntValue();
+
+                this.visibleMap.put(key, val);
+            }
+
+            this.queuedPuts.clear();
+
+            final LongIterator iterator1 = this.queuedRemove.iterator();
+            while (iterator1.hasNext()) {
+                final long key = iterator1.nextLong();
+
+                this.visibleMap.remove(key);
+            }
+
+            this.queuedRemove.clear();
+
+            return true;
+        } finally {
+            this.updatingMapSeqLock.releaseWrite();
+        }
+    }
+}
diff --git a/src/main/java/com/destroystokyo/paper/util/map/QueuedChangesMapLong2Object.java b/src/main/java/com/destroystokyo/paper/util/map/QueuedChangesMapLong2Object.java
new file mode 100644
index 0000000000000000000000000000000000000000..7bab31a312463cc963d9621cdc543a281459bd32
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/util/map/QueuedChangesMapLong2Object.java
@@ -0,0 +1,202 @@
+package com.destroystokyo.paper.util.map;
+
+import com.destroystokyo.paper.util.concurrent.WeakSeqLock;
+import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap;
+import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
+import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * @author Spottedleaf
+ */
+public class QueuedChangesMapLong2Object<V> {
+
+    protected static final Object REMOVED = new Object();
+
+    protected final Long2ObjectLinkedOpenHashMap<V> updatingMap;
+    protected final Long2ObjectLinkedOpenHashMap<V> visibleMap;
+    protected final Long2ObjectLinkedOpenHashMap<Object> queuedChanges;
+
+    // we use a seqlock as writes are not common.
+    protected final WeakSeqLock updatingMapSeqLock = new WeakSeqLock();
+
+    public QueuedChangesMapLong2Object() {
+        this(16, 0.75f); // dfl for fastutil
+    }
+
+    public QueuedChangesMapLong2Object(final int capacity, final float loadFactor) {
+        this.updatingMap = new Long2ObjectLinkedOpenHashMap<>(capacity, loadFactor);
+        this.visibleMap = new Long2ObjectLinkedOpenHashMap<>(capacity, loadFactor);
+        this.queuedChanges = new Long2ObjectLinkedOpenHashMap<>();
+    }
+
+    public V queueUpdate(final long k, final V value) {
+        this.queuedChanges.put(k, value);
+        return this.updatingMap.put(k, value);
+    }
+
+    public V queueRemove(final long k) {
+        this.queuedChanges.put(k, REMOVED);
+        return this.updatingMap.remove(k);
+    }
+
+    public V getUpdating(final long k) {
+        return this.updatingMap.get(k);
+    }
+
+    public boolean updatingContainsKey(final long k) {
+        return this.updatingMap.containsKey(k);
+    }
+
+    public V getVisible(final long k) {
+        return this.visibleMap.get(k);
+    }
+
+    public boolean visibleContainsKey(final long k) {
+        return this.visibleMap.containsKey(k);
+    }
+
+    public V getVisibleAsync(final long k) {
+        long readlock;
+        V ret = null;
+
+        do {
+            readlock = this.updatingMapSeqLock.acquireRead();
+
+            try {
+                ret = this.visibleMap.get(k);
+            } catch (final Throwable thr) {
+                if (thr instanceof ThreadDeath) {
+                    throw (ThreadDeath)thr;
+                }
+                // ignore...
+                continue;
+            }
+
+        } while (!this.updatingMapSeqLock.tryReleaseRead(readlock));
+
+        return ret;
+    }
+
+    public boolean visibleContainsKeyAsync(final long k) {
+        long readlock;
+        boolean ret = false;
+
+        do {
+            readlock = this.updatingMapSeqLock.acquireRead();
+
+            try {
+                ret = this.visibleMap.containsKey(k);
+            } catch (final Throwable thr) {
+                if (thr instanceof ThreadDeath) {
+                    throw (ThreadDeath)thr;
+                }
+                // ignore...
+                continue;
+            }
+
+        } while (!this.updatingMapSeqLock.tryReleaseRead(readlock));
+
+        return ret;
+    }
+
+    public Long2ObjectLinkedOpenHashMap<V> getVisibleMap() {
+        return this.visibleMap;
+    }
+
+    public Long2ObjectLinkedOpenHashMap<V> getUpdatingMap() {
+        return this.updatingMap;
+    }
+
+    public int getVisibleSize() {
+        return this.visibleMap.size();
+    }
+
+    public int getVisibleSizeAsync() {
+        long readlock;
+        int ret;
+
+        do {
+            readlock = this.updatingMapSeqLock.acquireRead();
+            ret = this.visibleMap.size();
+        } while (!this.updatingMapSeqLock.tryReleaseRead(readlock));
+
+        return ret;
+    }
+
+    // unlike mojang's impl this cannot be used async since it's not a view of an immutable map
+    public Collection<V> getUpdatingValues() {
+        return this.updatingMap.values();
+    }
+
+    public List<V> getUpdatingValuesCopy() {
+        return new ArrayList<>(this.updatingMap.values());
+    }
+
+    // unlike mojang's impl this cannot be used async since it's not a view of an immutable map
+    public Collection<V> getVisibleValues() {
+        return this.visibleMap.values();
+    }
+
+    public List<V> getVisibleValuesCopy() {
+        return new ArrayList<>(this.visibleMap.values());
+    }
+
+    public boolean performUpdates() {
+        if (this.queuedChanges.isEmpty()) {
+            return false;
+        }
+
+        final ObjectBidirectionalIterator<Long2ObjectMap.Entry<Object>> iterator = this.queuedChanges.long2ObjectEntrySet().fastIterator();
+        while (iterator.hasNext()) {
+            final Long2ObjectMap.Entry<Object> entry = iterator.next();
+            final long key = entry.getLongKey();
+            final Object val = entry.getValue();
+
+            this.updatingMapSeqLock.acquireWrite();
+            try {
+                if (val == REMOVED) {
+                    this.visibleMap.remove(key);
+                } else {
+                    this.visibleMap.put(key, (V)val);
+                }
+            } finally {
+                this.updatingMapSeqLock.releaseWrite();
+            }
+        }
+
+        this.queuedChanges.clear();
+        return true;
+    }
+
+    public boolean performUpdatesLockMap() {
+        if (this.queuedChanges.isEmpty()) {
+            return false;
+        }
+
+        final ObjectBidirectionalIterator<Long2ObjectMap.Entry<Object>> iterator = this.queuedChanges.long2ObjectEntrySet().fastIterator();
+
+        try {
+            this.updatingMapSeqLock.acquireWrite();
+
+            while (iterator.hasNext()) {
+                final Long2ObjectMap.Entry<Object> entry = iterator.next();
+                final long key = entry.getLongKey();
+                final Object val = entry.getValue();
+
+                if (val == REMOVED) {
+                    this.visibleMap.remove(key);
+                } else {
+                    this.visibleMap.put(key, (V)val);
+                }
+            }
+        } finally {
+            this.updatingMapSeqLock.releaseWrite();
+        }
+
+        this.queuedChanges.clear();
+        return true;
+    }
+}
diff --git a/src/main/java/com/destroystokyo/paper/util/maplist/ChunkList.java b/src/main/java/com/destroystokyo/paper/util/maplist/ChunkList.java
new file mode 100644
index 0000000000000000000000000000000000000000..554f4d4e63c1431721989e6f502a32ccc53a8807
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/util/maplist/ChunkList.java
@@ -0,0 +1,128 @@
+package com.destroystokyo.paper.util.maplist;
+
+import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import net.minecraft.world.level.chunk.LevelChunk;
+
+// list with O(1) remove & contains
+/**
+ * @author Spottedleaf
+ */
+public final class ChunkList implements Iterable<LevelChunk> {
+
+    protected final Long2IntOpenHashMap chunkToIndex = new Long2IntOpenHashMap(2, 0.8f);
+    {
+        this.chunkToIndex.defaultReturnValue(Integer.MIN_VALUE);
+    }
+
+    protected static final LevelChunk[] EMPTY_LIST = new LevelChunk[0];
+
+    protected LevelChunk[] chunks = EMPTY_LIST;
+    protected int count;
+
+    public int size() {
+        return this.count;
+    }
+
+    public boolean contains(final LevelChunk chunk) {
+        return this.chunkToIndex.containsKey(chunk.coordinateKey);
+    }
+
+    public boolean remove(final LevelChunk chunk) {
+        final int index = this.chunkToIndex.remove(chunk.coordinateKey);
+        if (index == Integer.MIN_VALUE) {
+            return false;
+        }
+
+        // move the entity at the end to this index
+        final int endIndex = --this.count;
+        final LevelChunk end = this.chunks[endIndex];
+        if (index != endIndex) {
+            // not empty after this call
+            this.chunkToIndex.put(end.coordinateKey, index); // update index
+        }
+        this.chunks[index] = end;
+        this.chunks[endIndex] = null;
+
+        return true;
+    }
+
+    public boolean add(final LevelChunk chunk) {
+        final int count = this.count;
+        final int currIndex = this.chunkToIndex.putIfAbsent(chunk.coordinateKey, count);
+
+        if (currIndex != Integer.MIN_VALUE) {
+            return false; // already in this list
+        }
+
+        LevelChunk[] list = this.chunks;
+
+        if (list.length == count) {
+            // resize required
+            list = this.chunks = Arrays.copyOf(list, (int)Math.max(4L, count * 2L)); // overflow results in negative
+        }
+
+        list[count] = chunk;
+        this.count = count + 1;
+
+        return true;
+    }
+
+    public LevelChunk getChecked(final int index) {
+        if (index < 0 || index >= this.count) {
+            throw new IndexOutOfBoundsException("Index: " + index + " is out of bounds, size: " + this.count);
+        }
+        return this.chunks[index];
+    }
+
+    public LevelChunk getUnchecked(final int index) {
+        return this.chunks[index];
+    }
+
+    public LevelChunk[] getRawData() {
+        return this.chunks;
+    }
+
+    public void clear() {
+        this.chunkToIndex.clear();
+        Arrays.fill(this.chunks, 0, this.count, null);
+        this.count = 0;
+    }
+
+    @Override
+    public Iterator<LevelChunk> iterator() {
+        return new Iterator<LevelChunk>() {
+
+            LevelChunk lastRet;
+            int current;
+
+            @Override
+            public boolean hasNext() {
+                return this.current < ChunkList.this.count;
+            }
+
+            @Override
+            public LevelChunk next() {
+                if (this.current >= ChunkList.this.count) {
+                    throw new NoSuchElementException();
+                }
+                return this.lastRet = ChunkList.this.chunks[this.current++];
+            }
+
+            @Override
+            public void remove() {
+                final LevelChunk lastRet = this.lastRet;
+
+                if (lastRet == null) {
+                    throw new IllegalStateException();
+                }
+                this.lastRet = null;
+
+                ChunkList.this.remove(lastRet);
+                --this.current;
+            }
+        };
+    }
+}
diff --git a/src/main/java/com/destroystokyo/paper/util/maplist/EntityList.java b/src/main/java/com/destroystokyo/paper/util/maplist/EntityList.java
new file mode 100644
index 0000000000000000000000000000000000000000..0133ea6feb1ab88f021f66855669f58367e7420b
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/util/maplist/EntityList.java
@@ -0,0 +1,128 @@
+package com.destroystokyo.paper.util.maplist;
+
+import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
+import net.minecraft.world.entity.Entity;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+// list with O(1) remove & contains
+/**
+ * @author Spottedleaf
+ */
+public final class EntityList implements Iterable<Entity> {
+
+    protected final Int2IntOpenHashMap entityToIndex = new Int2IntOpenHashMap(2, 0.8f);
+    {
+        this.entityToIndex.defaultReturnValue(Integer.MIN_VALUE);
+    }
+
+    protected static final Entity[] EMPTY_LIST = new Entity[0];
+
+    protected Entity[] entities = EMPTY_LIST;
+    protected int count;
+
+    public int size() {
+        return this.count;
+    }
+
+    public boolean contains(final Entity entity) {
+        return this.entityToIndex.containsKey(entity.getId());
+    }
+
+    public boolean remove(final Entity entity) {
+        final int index = this.entityToIndex.remove(entity.getId());
+        if (index == Integer.MIN_VALUE) {
+            return false;
+        }
+
+        // move the entity at the end to this index
+        final int endIndex = --this.count;
+        final Entity end = this.entities[endIndex];
+        if (index != endIndex) {
+            // not empty after this call
+            this.entityToIndex.put(end.getId(), index); // update index
+        }
+        this.entities[index] = end;
+        this.entities[endIndex] = null;
+
+        return true;
+    }
+
+    public boolean add(final Entity entity) {
+        final int count = this.count;
+        final int currIndex = this.entityToIndex.putIfAbsent(entity.getId(), count);
+
+        if (currIndex != Integer.MIN_VALUE) {
+            return false; // already in this list
+        }
+
+        Entity[] list = this.entities;
+
+        if (list.length == count) {
+            // resize required
+            list = this.entities = Arrays.copyOf(list, (int)Math.max(4L, count * 2L)); // overflow results in negative
+        }
+
+        list[count] = entity;
+        this.count = count + 1;
+
+        return true;
+    }
+
+    public Entity getChecked(final int index) {
+        if (index < 0 || index >= this.count) {
+            throw new IndexOutOfBoundsException("Index: " + index + " is out of bounds, size: " + this.count);
+        }
+        return this.entities[index];
+    }
+
+    public Entity getUnchecked(final int index) {
+        return this.entities[index];
+    }
+
+    public Entity[] getRawData() {
+        return this.entities;
+    }
+
+    public void clear() {
+        this.entityToIndex.clear();
+        Arrays.fill(this.entities, 0, this.count, null);
+        this.count = 0;
+    }
+
+    @Override
+    public Iterator<Entity> iterator() {
+        return new Iterator<Entity>() {
+
+            Entity lastRet;
+            int current;
+
+            @Override
+            public boolean hasNext() {
+                return this.current < EntityList.this.count;
+            }
+
+            @Override
+            public Entity next() {
+                if (this.current >= EntityList.this.count) {
+                    throw new NoSuchElementException();
+                }
+                return this.lastRet = EntityList.this.entities[this.current++];
+            }
+
+            @Override
+            public void remove() {
+                final Entity lastRet = this.lastRet;
+
+                if (lastRet == null) {
+                    throw new IllegalStateException();
+                }
+                this.lastRet = null;
+
+                EntityList.this.remove(lastRet);
+                --this.current;
+            }
+        };
+    }
+}
diff --git a/src/main/java/com/destroystokyo/paper/util/maplist/IBlockDataList.java b/src/main/java/com/destroystokyo/paper/util/maplist/IBlockDataList.java
new file mode 100644
index 0000000000000000000000000000000000000000..277cfd9d1e8fff5d9b5e534b75c3c5162d58b0b7
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/util/maplist/IBlockDataList.java
@@ -0,0 +1,128 @@
+package com.destroystokyo.paper.util.maplist;
+
+import it.unimi.dsi.fastutil.longs.LongIterator;
+import it.unimi.dsi.fastutil.shorts.Short2LongOpenHashMap;
+import java.util.Arrays;
+import net.minecraft.world.level.block.Block;
+import net.minecraft.world.level.block.state.BlockState;
+import net.minecraft.world.level.chunk.GlobalPalette;
+
+/**
+ * @author Spottedleaf
+ */
+public final class IBlockDataList {
+
+    static final GlobalPalette<BlockState> GLOBAL_PALETTE = new GlobalPalette<>(Block.BLOCK_STATE_REGISTRY);
+
+    // map of location -> (index | (location << 16) | (palette id << 32))
+    private final Short2LongOpenHashMap map = new Short2LongOpenHashMap(2, 0.8f);
+    {
+        this.map.defaultReturnValue(Long.MAX_VALUE);
+    }
+
+    private static final long[] EMPTY_LIST = new long[0];
+
+    private long[] byIndex = EMPTY_LIST;
+    private int size;
+
+    public static int getLocationKey(final int x, final int y, final int z) {
+        return (x & 15) | (((z & 15) << 4)) | ((y & 255) << (4 + 4));
+    }
+
+    public static BlockState getBlockDataFromRaw(final long raw) {
+        return GLOBAL_PALETTE.valueFor((int)(raw >>> 32));
+    }
+
+    public static int getIndexFromRaw(final long raw) {
+        return (int)(raw & 0xFFFF);
+    }
+
+    public static int getLocationFromRaw(final long raw) {
+        return (int)((raw >>> 16) & 0xFFFF);
+    }
+
+    public static long getRawFromValues(final int index, final int location, final BlockState data) {
+        return (long)index | ((long)location << 16) | (((long)GLOBAL_PALETTE.idFor(data)) << 32);
+    }
+
+    public static long setIndexRawValues(final long value, final int index) {
+        return value & ~(0xFFFF) | (index);
+    }
+
+    public long add(final int x, final int y, final int z, final BlockState data) {
+        return this.add(getLocationKey(x, y, z), data);
+    }
+
+    public long add(final int location, final BlockState data) {
+        final long curr = this.map.get((short)location);
+
+        if (curr == Long.MAX_VALUE) {
+            final int index = this.size++;
+            final long raw = getRawFromValues(index, location, data);
+            this.map.put((short)location, raw);
+
+            if (index >= this.byIndex.length) {
+                this.byIndex = Arrays.copyOf(this.byIndex, (int)Math.max(4L, this.byIndex.length * 2L));
+            }
+
+            this.byIndex[index] = raw;
+            return raw;
+        } else {
+            final int index = getIndexFromRaw(curr);
+            final long raw = this.byIndex[index] = getRawFromValues(index, location, data);
+
+            this.map.put((short)location, raw);
+
+            return raw;
+        }
+    }
+
+    public long remove(final int x, final int y, final int z) {
+        return this.remove(getLocationKey(x, y, z));
+    }
+
+    public long remove(final int location) {
+        final long ret = this.map.remove((short)location);
+        final int index = getIndexFromRaw(ret);
+        if (ret == Long.MAX_VALUE) {
+            return ret;
+        }
+
+        // move the entry at the end to this index
+        final int endIndex = --this.size;
+        final long end = this.byIndex[endIndex];
+        if (index != endIndex) {
+            // not empty after this call
+            this.map.put((short)getLocationFromRaw(end), setIndexRawValues(end, index));
+        }
+        this.byIndex[index] = end;
+        this.byIndex[endIndex] = 0L;
+
+        return ret;
+    }
+
+    public int size() {
+        return this.size;
+    }
+
+    public long getRaw(final int index) {
+        return this.byIndex[index];
+    }
+
+    public int getLocation(final int index) {
+        return getLocationFromRaw(this.getRaw(index));
+    }
+
+    public BlockState getData(final int index) {
+        return getBlockDataFromRaw(this.getRaw(index));
+    }
+
+    public void clear() {
+        this.size = 0;
+        this.map.clear();
+    }
+
+    public LongIterator getRawIterator() {
+        return this.map.values().iterator();
+    }
+}
diff --git a/src/main/java/com/destroystokyo/paper/util/maplist/ReferenceList.java b/src/main/java/com/destroystokyo/paper/util/maplist/ReferenceList.java
new file mode 100644
index 0000000000000000000000000000000000000000..190c5f0b02a3d99054704ae1afbffb3498ddffe1
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/util/maplist/ReferenceList.java
@@ -0,0 +1,125 @@
+package com.destroystokyo.paper.util.maplist;
+
+import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+/**
+ * @author Spottedleaf
+ */
+public final class ReferenceList<E> implements Iterable<E> {
+
+    protected final Reference2IntOpenHashMap<E> referenceToIndex = new Reference2IntOpenHashMap<>(2, 0.8f);
+    {
+        this.referenceToIndex.defaultReturnValue(Integer.MIN_VALUE);
+    }
+
+    protected static final Object[] EMPTY_LIST = new Object[0];
+
+    protected Object[] references = EMPTY_LIST;
+    protected int count;
+
+    public int size() {
+        return this.count;
+    }
+
+    public boolean contains(final E obj) {
+        return this.referenceToIndex.containsKey(obj);
+    }
+
+    public boolean remove(final E obj) {
+        final int index = this.referenceToIndex.removeInt(obj);
+        if (index == Integer.MIN_VALUE) {
+            return false;
+        }
+
+        // move the object at the end to this index
+        final int endIndex = --this.count;
+        final E end = (E)this.references[endIndex];
+        if (index != endIndex) {
+            // not empty after this call
+            this.referenceToIndex.put(end, index); // update index
+        }
+        this.references[index] = end;
+        this.references[endIndex] = null;
+
+        return true;
+    }
+
+    public boolean add(final E obj) {
+        final int count = this.count;
+        final int currIndex = this.referenceToIndex.putIfAbsent(obj, count);
+
+        if (currIndex != Integer.MIN_VALUE) {
+            return false; // already in this list
+        }
+
+        Object[] list = this.references;
+
+        if (list.length == count) {
+            // resize required
+            list = this.references = Arrays.copyOf(list, (int)Math.max(4L, count * 2L)); // overflow results in negative
+        }
+
+        list[count] = obj;
+        this.count = count + 1;
+
+        return true;
+    }
+
+    public E getChecked(final int index) {
+        if (index < 0 || index >= this.count) {
+            throw new IndexOutOfBoundsException("Index: " + index + " is out of bounds, size: " + this.count);
+        }
+        return (E)this.references[index];
+    }
+
+    public E getUnchecked(final int index) {
+        return (E)this.references[index];
+    }
+
+    public Object[] getRawData() {
+        return this.references;
+    }
+
+    public void clear() {
+        this.referenceToIndex.clear();
+        Arrays.fill(this.references, 0, this.count, null);
+        this.count = 0;
+    }
+
+    @Override
+    public Iterator<E> iterator() {
+        return new Iterator<>() {
+            private E lastRet;
+            private int current;
+
+            @Override
+            public boolean hasNext() {
+                return this.current < ReferenceList.this.count;
+            }
+
+            @Override
+            public E next() {
+                if (this.current >= ReferenceList.this.count) {
+                    throw new NoSuchElementException();
+                }
+                return this.lastRet = (E)ReferenceList.this.references[this.current++];
+            }
+
+            @Override
+            public void remove() {
+                final E lastRet = this.lastRet;
+
+                if (lastRet == null) {
+                    throw new IllegalStateException();
+                }
+                this.lastRet = null;
+
+                ReferenceList.this.remove(lastRet);
+                --this.current;
+            }
+        };
+    }
+}
diff --git a/src/main/java/com/destroystokyo/paper/util/misc/AreaMap.java b/src/main/java/com/destroystokyo/paper/util/misc/AreaMap.java
new file mode 100644
index 0000000000000000000000000000000000000000..41b9405d6759d865e0d14dd4f95163e9690e967d
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/util/misc/AreaMap.java
@@ -0,0 +1,453 @@
+package com.destroystokyo.paper.util.misc;
+
+import io.papermc.paper.util.IntegerUtil;
+import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap;
+import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
+import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
+import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap;
+import io.papermc.paper.util.MCUtil;
+import net.minecraft.server.MinecraftServer;
+import net.minecraft.world.level.ChunkPos;
+import javax.annotation.Nullable;
+import java.util.Iterator;
+
+/** @author Spottedleaf */
+public abstract class AreaMap<E> {
+
+    /* Tested via https://gist.github.com/Spottedleaf/520419c6f41ef348fe9926ce674b7217 */
+
+    protected final Object2LongOpenHashMap<E> objectToLastCoordinate = new Object2LongOpenHashMap<>();
+    protected final Object2IntOpenHashMap<E> objectToViewDistance = new Object2IntOpenHashMap<>();
+
+    {
+        this.objectToViewDistance.defaultReturnValue(-1);
+        this.objectToLastCoordinate.defaultReturnValue(Long.MIN_VALUE);
+    }
+
+    // we use linked for better iteration.
+    // map of: coordinate to set of objects in coordinate
+    protected final Long2ObjectOpenHashMap<PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E>> areaMap = new Long2ObjectOpenHashMap<>(1024, 0.7f);
+    protected final PooledLinkedHashSets<E> pooledHashSets;
+
+    protected final ChangeCallback<E> addCallback;
+    protected final ChangeCallback<E> removeCallback;
+    protected final ChangeSourceCallback<E> changeSourceCallback;
+
+    public AreaMap() {
+        this(new PooledLinkedHashSets<>());
+    }
+
+    // let users define a "global" or "shared" pooled sets if they wish
+    public AreaMap(final PooledLinkedHashSets<E> pooledHashSets) {
+        this(pooledHashSets, null, null);
+    }
+
+    public AreaMap(final PooledLinkedHashSets<E> pooledHashSets, final ChangeCallback<E> addCallback, final ChangeCallback<E> removeCallback) {
+        this(pooledHashSets, addCallback, removeCallback, null);
+    }
+    public AreaMap(final PooledLinkedHashSets<E> pooledHashSets, final ChangeCallback<E> addCallback, final ChangeCallback<E> removeCallback, final ChangeSourceCallback<E> changeSourceCallback) {
+        this.pooledHashSets = pooledHashSets;
+        this.addCallback = addCallback;
+        this.removeCallback = removeCallback;
+        this.changeSourceCallback = changeSourceCallback;
+    }
+
+    @Nullable
+    public final PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E> getObjectsInRange(final long key) {
+        return this.areaMap.get(key);
+    }
+
+    @Nullable
+    public final PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E> getObjectsInRange(final ChunkPos chunkPos) {
+        return this.areaMap.get(MCUtil.getCoordinateKey(chunkPos));
+    }
+
+    @Nullable
+    public final PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E> getObjectsInRange(final int chunkX, final int chunkZ) {
+        return this.areaMap.get(MCUtil.getCoordinateKey(chunkX, chunkZ));
+    }
+
+    // Long.MIN_VALUE indicates the object is not mapped
+    public final long getLastCoordinate(final E object) {
+        return this.objectToLastCoordinate.getOrDefault(object, Long.MIN_VALUE);
+    }
+
+    // -1 indicates the object is not mapped
+    public final int getLastViewDistance(final E object) {
+        return this.objectToViewDistance.getOrDefault(object, -1);
+    }
+
+    // returns the total number of mapped chunks
+    public final int size() {
+        return this.areaMap.size();
+    }
+
+    public final void addOrUpdate(final E object, final int chunkX, final int chunkZ, final int viewDistance) {
+        final int oldViewDistance = this.objectToViewDistance.put(object, viewDistance);
+        final long newPos = MCUtil.getCoordinateKey(chunkX, chunkZ);
+        final long oldPos = this.objectToLastCoordinate.put(object, newPos);
+
+        if (oldViewDistance == -1) {
+            this.addObject(object, chunkX, chunkZ, Integer.MIN_VALUE, Integer.MIN_VALUE, viewDistance);
+            this.addObjectCallback(object, chunkX, chunkZ, viewDistance);
+        } else {
+            this.updateObject(object, oldPos, newPos, oldViewDistance, viewDistance);
+            this.updateObjectCallback(object, oldPos, newPos, oldViewDistance, viewDistance);
+        }
+        //this.validate(object, viewDistance);
+    }
+
+    public final boolean update(final E object, final int chunkX, final int chunkZ, final int viewDistance) {
+        final int oldViewDistance = this.objectToViewDistance.replace(object, viewDistance);
+        if (oldViewDistance == -1) {
+            return false;
+        } else {
+            final long newPos = MCUtil.getCoordinateKey(chunkX, chunkZ);
+            final long oldPos = this.objectToLastCoordinate.put(object, newPos);
+            this.updateObject(object, oldPos, newPos, oldViewDistance, viewDistance);
+            this.updateObjectCallback(object, oldPos, newPos, oldViewDistance, viewDistance);
+        }
+        //this.validate(object, viewDistance);
+        return true;
+    }
+
+    // called after the distance map updates
+    protected void updateObjectCallback(final E Object, final long oldPosition, final long newPosition, final int oldViewDistance, final int newViewDistance) {
+        if (newPosition != oldPosition && this.changeSourceCallback != null) {
+            this.changeSourceCallback.accept(Object, oldPosition, newPosition);
+        }
+    }
+
+    public final boolean add(final E object, final int chunkX, final int chunkZ, final int viewDistance) {
+        final int oldViewDistance = this.objectToViewDistance.putIfAbsent(object, viewDistance);
+        if (oldViewDistance != -1) {
+            return false;
+        }
+
+        final long newPos = MCUtil.getCoordinateKey(chunkX, chunkZ);
+        this.objectToLastCoordinate.put(object, newPos);
+        this.addObject(object, chunkX, chunkZ, Integer.MIN_VALUE, Integer.MIN_VALUE, viewDistance);
+        this.addObjectCallback(object, chunkX, chunkZ, viewDistance);
+
+        //this.validate(object, viewDistance);
+
+        return true;
+    }
+
+    // called after the distance map updates
+    protected void addObjectCallback(final E object, final int chunkX, final int chunkZ, final int viewDistance) {}
+
+    public final boolean remove(final E object) {
+        final long position = this.objectToLastCoordinate.removeLong(object);
+        final int viewDistance = this.objectToViewDistance.removeInt(object);
+
+        if (viewDistance == -1) {
+            return false;
+        }
+
+        final int currentX = MCUtil.getCoordinateX(position);
+        final int currentZ = MCUtil.getCoordinateZ(position);
+
+        this.removeObject(object, currentX, currentZ, currentX, currentZ, viewDistance);
+        this.removeObjectCallback(object, currentX, currentZ, viewDistance);
+        //this.validate(object, -1);
+        return true;
+    }
+
+    // called after the distance map updates
+    protected void removeObjectCallback(final E object, final int chunkX, final int chunkZ, final int viewDistance) {}
+
+    protected abstract PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E> getEmptySetFor(final E object);
+
+    // expensive op, only for debug
+    protected void validate(final E object, final int viewDistance) {
+        int entiesGot = 0;
+        int expectedEntries = (2 * viewDistance + 1);
+        expectedEntries *= expectedEntries;
+        if (viewDistance < 0) {
+            expectedEntries = 0;
+        }
+
+        final long currPosition = this.objectToLastCoordinate.getLong(object);
+
+        final int centerX = MCUtil.getCoordinateX(currPosition);
+        final int centerZ = MCUtil.getCoordinateZ(currPosition);
+
+        for (Iterator<Long2ObjectLinkedOpenHashMap.Entry<PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E>>> iterator = this.areaMap.long2ObjectEntrySet().fastIterator();
+             iterator.hasNext();) {
+
+            final Long2ObjectLinkedOpenHashMap.Entry<PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E>> entry = iterator.next();
+            final long key = entry.getLongKey();
+            final PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E> map = entry.getValue();
+
+            if (map.referenceCount == 0) {
+                throw new IllegalStateException("Invalid map");
+            }
+
+            if (map.contains(object)) {
+                ++entiesGot;
+
+                final int chunkX = MCUtil.getCoordinateX(key);
+                final int chunkZ = MCUtil.getCoordinateZ(key);
+
+                final int dist = Math.max(IntegerUtil.branchlessAbs(chunkX - centerX), IntegerUtil.branchlessAbs(chunkZ - centerZ));
+
+                if (dist > viewDistance) {
+                    throw new IllegalStateException("Expected view distance " + viewDistance + ", got " + dist);
+                }
+            }
+        }
+
+        if (entiesGot != expectedEntries) {
+            throw new IllegalStateException("Expected " + expectedEntries + ", got " + entiesGot);
+        }
+    }
+
+    private void addObjectTo(final E object, final int chunkX, final int chunkZ, final int currChunkX,
+                             final int currChunkZ, final int prevChunkX, final int prevChunkZ) {
+        final long key = MCUtil.getCoordinateKey(chunkX, chunkZ);
+
+        PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E> empty = this.getEmptySetFor(object);
+        PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E> current = this.areaMap.putIfAbsent(key, empty);
+
+        if (current != null) {
+            PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E> next = this.pooledHashSets.findMapWith(current, object);
+            if (next == current) {
+                throw new IllegalStateException("Expected different map: got " + next.toString());
+            }
+            this.areaMap.put(key, next);
+
+            current = next;
+            // fall through to callback
+        } else {
+            current = empty;
+        }
+
+        if (this.addCallback != null) {
+            try {
+                this.addCallback.accept(object, chunkX, chunkZ, currChunkX, currChunkZ, prevChunkX, prevChunkZ, current);
+            } catch (final Throwable ex) {
+                if (ex instanceof ThreadDeath) {
+                    throw (ThreadDeath)ex;
+                }
+                MinecraftServer.LOGGER.error("Add callback for map threw exception ", ex);
+            }
+        }
+    }
+
+    private void removeObjectFrom(final E object, final int chunkX, final int chunkZ, final int currChunkX,
+                                  final int currChunkZ, final int prevChunkX, final int prevChunkZ) {
+        final long key = MCUtil.getCoordinateKey(chunkX, chunkZ);
+
+        PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E> current = this.areaMap.get(key);
+
+        if (current == null) {
+            throw new IllegalStateException("Current map may not be null for " + object + ", (" + chunkX + "," + chunkZ + ")");
+        }
+
+        PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E> next = this.pooledHashSets.findMapWithout(current, object);
+
+        if (next == current) {
+            throw new IllegalStateException("Current map [" + next.toString() + "] should have contained " + object + ", (" + chunkX + "," + chunkZ + ")");
+        }
+
+        if (next != null) {
+            this.areaMap.put(key, next);
+        } else {
+            this.areaMap.remove(key);
+        }
+
+        if (this.removeCallback != null) {
+            try {
+                this.removeCallback.accept(object, chunkX, chunkZ, currChunkX, currChunkZ, prevChunkX, prevChunkZ, next);
+            } catch (final Throwable ex) {
+                if (ex instanceof ThreadDeath) {
+                    throw (ThreadDeath)ex;
+                }
+                MinecraftServer.LOGGER.error("Remove callback for map threw exception ", ex);
+            }
+        }
+    }
+
+    private void addObject(final E object, final int chunkX, final int chunkZ, final int prevChunkX, final int prevChunkZ, final int viewDistance) {
+        final int maxX = chunkX + viewDistance;
+        final int maxZ = chunkZ + viewDistance;
+        final int minX = chunkX - viewDistance;
+        final int minZ = chunkZ - viewDistance;
+        for (int x = minX; x <= maxX; ++x) {
+            for (int z = minZ; z <= maxZ; ++z) {
+                this.addObjectTo(object, x, z, chunkX, chunkZ, prevChunkX, prevChunkZ);
+            }
+        }
+    }
+
+    private void removeObject(final E object, final int chunkX, final int chunkZ, final int currentChunkX, final int currentChunkZ, final int viewDistance) {
+        final int maxX = chunkX + viewDistance;
+        final int maxZ = chunkZ + viewDistance;
+        final int minX = chunkX - viewDistance;
+        final int minZ = chunkZ - viewDistance;
+        for (int x = minX; x <= maxX; ++x) {
+            for (int z = minZ; z <= maxZ; ++z) {
+                this.removeObjectFrom(object, x, z, currentChunkX, currentChunkZ, chunkX, chunkZ);
+            }
+        }
+    }
+
+    /* math sign function except 0 returns 1 */
+    protected static int sign(int val) {
+        return 1 | (val >> (Integer.SIZE - 1));
+    }
+
+    private void updateObject(final E object, final long oldPosition, final long newPosition, final int oldViewDistance, final int newViewDistance) {
+        final int toX = MCUtil.getCoordinateX(newPosition);
+        final int toZ = MCUtil.getCoordinateZ(newPosition);
+        final int fromX = MCUtil.getCoordinateX(oldPosition);
+        final int fromZ = MCUtil.getCoordinateZ(oldPosition);
+
+        final int dx = toX - fromX;
+        final int dz = toZ - fromZ;
+
+        final int totalX = IntegerUtil.branchlessAbs(fromX - toX);
+        final int totalZ = IntegerUtil.branchlessAbs(fromZ - toZ);
+
+        if (Math.max(totalX, totalZ) > (2 * Math.max(newViewDistance, oldViewDistance))) {
+            // teleported?
+            this.removeObject(object, fromX, fromZ, fromX, fromZ, oldViewDistance);
+            this.addObject(object, toX, toZ, fromX, fromZ, newViewDistance);
+            return;
+        }
+
+        if (oldViewDistance != newViewDistance) {
+            // remove loop
+
+            final int oldMinX = fromX - oldViewDistance;
+            final int oldMinZ = fromZ - oldViewDistance;
+            final int oldMaxX = fromX + oldViewDistance;
+            final int oldMaxZ = fromZ + oldViewDistance;
+            for (int currX = oldMinX; currX <= oldMaxX; ++currX) {
+                for (int currZ = oldMinZ; currZ <= oldMaxZ; ++currZ) {
+
+                    // only remove if we're outside the new view distance...
+                    if (Math.max(IntegerUtil.branchlessAbs(currX - toX), IntegerUtil.branchlessAbs(currZ - toZ)) > newViewDistance) {
+                        this.removeObjectFrom(object, currX, currZ, toX, toZ, fromX, fromZ);
+                    }
+                }
+            }
+
+            // add loop
+
+            final int newMinX = toX - newViewDistance;
+            final int newMinZ = toZ - newViewDistance;
+            final int newMaxX = toX + newViewDistance;
+            final int newMaxZ = toZ + newViewDistance;
+            for (int currX = newMinX; currX <= newMaxX; ++currX) {
+                for (int currZ = newMinZ; currZ <= newMaxZ; ++currZ) {
+
+                    // only add if we're outside the old view distance...
+                    if (Math.max(IntegerUtil.branchlessAbs(currX - fromX), IntegerUtil.branchlessAbs(currZ - fromZ)) > oldViewDistance) {
+                        this.addObjectTo(object, currX, currZ, toX, toZ, fromX, fromZ);
+                    }
+                }
+            }
+
+            return;
+        }
+
+        // x axis is width
+        // z axis is height
+        // right refers to the x axis of where we moved
+        // top refers to the z axis of where we moved
+
+        // same view distance
+
+        // used for relative positioning
+        final int up = sign(dz); // 1 if dz >= 0, -1 otherwise
+        final int right = sign(dx); // 1 if dx >= 0, -1 otherwise
+
+        // The area excluded by overlapping the two view distance squares creates four rectangles:
+        // Two on the left, and two on the right. The ones on the left we consider the "removed" section
+        // and on the right the "added" section.
+        // https://i.imgur.com/MrnOBgI.png is a reference image. Note that the outside border is not actually
+        // exclusive to the regions they surround.
+
+        // 4 points of the rectangle
+        int maxX; // exclusive
+        int minX; // inclusive
+        int maxZ; // exclusive
+        int minZ; // inclusive
+
+        if (dx != 0) {
+            // handle right addition
+
+            maxX = toX + (oldViewDistance * right) + right; // exclusive
+            minX = fromX + (oldViewDistance * right) + right; // inclusive
+            maxZ = fromZ + (oldViewDistance * up) + up; // exclusive
+            minZ = toZ - (oldViewDistance * up); // inclusive
+
+            for (int currX = minX; currX != maxX; currX += right) {
+                for (int currZ = minZ; currZ != maxZ; currZ += up) {
+                    this.addObjectTo(object, currX, currZ, toX, toZ, fromX, fromZ);
+                }
+            }
+        }
+
+        if (dz != 0) {
+            // handle up addition
+
+            maxX = toX + (oldViewDistance * right) + right; // exclusive
+            minX = toX - (oldViewDistance * right); // inclusive
+            maxZ = toZ + (oldViewDistance * up) + up; // exclusive
+            minZ = fromZ + (oldViewDistance * up) + up; // inclusive
+
+            for (int currX = minX; currX != maxX; currX += right) {
+                for (int currZ = minZ; currZ != maxZ; currZ += up) {
+                    this.addObjectTo(object, currX, currZ, toX, toZ, fromX, fromZ);
+                }
+            }
+        }
+
+        if (dx != 0) {
+            // handle left removal
+
+            maxX = toX - (oldViewDistance * right); // exclusive
+            minX = fromX - (oldViewDistance * right); // inclusive
+            maxZ = fromZ + (oldViewDistance * up) + up; // exclusive
+            minZ = toZ - (oldViewDistance * up); // inclusive
+
+            for (int currX = minX; currX != maxX; currX += right) {
+                for (int currZ = minZ; currZ != maxZ; currZ += up) {
+                    this.removeObjectFrom(object, currX, currZ, toX, toZ, fromX, fromZ);
+                }
+            }
+        }
+
+        if (dz != 0) {
+            // handle down removal
+
+            maxX = fromX + (oldViewDistance * right) + right; // exclusive
+            minX = fromX - (oldViewDistance * right); // inclusive
+            maxZ = toZ - (oldViewDistance * up); // exclusive
+            minZ = fromZ - (oldViewDistance * up); // inclusive
+
+            for (int currX = minX; currX != maxX; currX += right) {
+                for (int currZ = minZ; currZ != maxZ; currZ += up) {
+                    this.removeObjectFrom(object, currX, currZ, toX, toZ, fromX, fromZ);
+                }
+            }
+        }
+    }
+
+    @FunctionalInterface
+    public static interface ChangeCallback<E> {
+
+        // if there is no previous position, then prevPos = Integer.MIN_VALUE
+        void accept(final E object, final int rangeX, final int rangeZ, final int currPosX, final int currPosZ, final int prevPosX, final int prevPosZ,
+                    final PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E> newState);
+
+    }
+
+    @FunctionalInterface
+    public static interface ChangeSourceCallback<E> {
+        void accept(final E object, final long prevPos, final long newPos);
+    }
+}
diff --git a/src/main/java/com/destroystokyo/paper/util/misc/DistanceTrackingAreaMap.java b/src/main/java/com/destroystokyo/paper/util/misc/DistanceTrackingAreaMap.java
new file mode 100644
index 0000000000000000000000000000000000000000..896c3ff7ddb07f1f6f05f90e1e3fe7fb615071d4
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/util/misc/DistanceTrackingAreaMap.java
@@ -0,0 +1,175 @@
+package com.destroystokyo.paper.util.misc;
+
+import io.papermc.paper.util.IntegerUtil;
+import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
+import io.papermc.paper.util.MCUtil;
+import net.minecraft.world.level.ChunkPos;
+
+/** @author Spottedleaf */
+public abstract class DistanceTrackingAreaMap<E> extends AreaMap<E> {
+
+    // use this map only if you need distance tracking, the tracking here is obviously going to hit harder.
+
+    protected final Long2IntOpenHashMap chunkToNearestDistance = new Long2IntOpenHashMap(1024, 0.7f);
+    {
+        this.chunkToNearestDistance.defaultReturnValue(-1);
+    }
+
+    protected final DistanceChangeCallback<E> distanceChangeCallback;
+
+    public DistanceTrackingAreaMap() {
+        this(new PooledLinkedHashSets<>());
+    }
+
+    // let users define a "global" or "shared" pooled sets if they wish
+    public DistanceTrackingAreaMap(final PooledLinkedHashSets<E> pooledHashSets) {
+        this(pooledHashSets, null, null, null);
+    }
+
+    public DistanceTrackingAreaMap(final PooledLinkedHashSets<E> pooledHashSets, final ChangeCallback<E> addCallback, final ChangeCallback<E> removeCallback,
+                                   final DistanceChangeCallback<E> distanceChangeCallback) {
+        super(pooledHashSets, addCallback, removeCallback);
+        this.distanceChangeCallback = distanceChangeCallback;
+    }
+
+    // ret -1 if there is nothing mapped
+    public final int getNearestObjectDistance(final long key) {
+        return this.chunkToNearestDistance.get(key);
+    }
+
+    // ret -1 if there is nothing mapped
+    public final int getNearestObjectDistance(final ChunkPos chunkPos) {
+        return this.chunkToNearestDistance.get(MCUtil.getCoordinateKey(chunkPos));
+    }
+
+    // ret -1 if there is nothing mapped
+    public final int getNearestObjectDistance(final int chunkX, final int chunkZ) {
+        return this.chunkToNearestDistance.get(MCUtil.getCoordinateKey(chunkX, chunkZ));
+    }
+
+    protected final void recalculateDistance(final int chunkX, final int chunkZ) {
+        final long key = MCUtil.getCoordinateKey(chunkX, chunkZ);
+        final PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E> state = this.areaMap.get(key);
+        if (state == null) {
+            final int oldDistance = this.chunkToNearestDistance.remove(key);
+            // nothing here.
+            if (oldDistance == -1) {
+                // nothing was here previously
+                return;
+            }
+            if (this.distanceChangeCallback != null) {
+                this.distanceChangeCallback.accept(chunkX, chunkZ, oldDistance, -1, null);
+            }
+            return;
+        }
+
+        int newDistance = Integer.MAX_VALUE;
+
+        final Object[] rawData = state.getBackingSet();
+        for (int i = 0, len = rawData.length; i < len; ++i) {
+            final Object raw = rawData[i];
+
+            if (raw == null) {
+                continue;
+            }
+
+            final E object = (E)raw;
+            final long location = this.objectToLastCoordinate.getLong(object);
+
+            final int distance = Math.max(IntegerUtil.branchlessAbs(chunkX - MCUtil.getCoordinateX(location)), IntegerUtil.branchlessAbs(chunkZ - MCUtil.getCoordinateZ(location)));
+
+            if (distance < newDistance) {
+                newDistance = distance;
+            }
+        }
+
+        final int oldDistance = this.chunkToNearestDistance.put(key, newDistance);
+
+        if (oldDistance != newDistance) {
+            if (this.distanceChangeCallback != null) {
+                this.distanceChangeCallback.accept(chunkX, chunkZ, oldDistance, newDistance, state);
+            }
+        }
+    }
+
+    @Override
+    protected void addObjectCallback(final E object, final int chunkX, final int chunkZ, final int viewDistance) {
+        final int maxX = chunkX + viewDistance;
+        final int maxZ = chunkZ + viewDistance;
+        final int minX = chunkX - viewDistance;
+        final int minZ = chunkZ - viewDistance;
+        for (int x = minX; x <= maxX; ++x) {
+            for (int z = minZ; z <= maxZ; ++z) {
+                this.recalculateDistance(x, z);
+            }
+        }
+    }
+
+    @Override
+    protected void removeObjectCallback(final E object, final int chunkX, final int chunkZ, final int viewDistance) {
+        final int maxX = chunkX + viewDistance;
+        final int maxZ = chunkZ + viewDistance;
+        final int minX = chunkX - viewDistance;
+        final int minZ = chunkZ - viewDistance;
+        for (int x = minX; x <= maxX; ++x) {
+            for (int z = minZ; z <= maxZ; ++z) {
+                this.recalculateDistance(x, z);
+            }
+        }
+    }
+
+    @Override
+    protected void updateObjectCallback(final E object, final long oldPosition, final long newPosition, final int oldViewDistance, final int newViewDistance) {
+        if (oldPosition == newPosition && newViewDistance == oldViewDistance) {
+            return;
+        }
+
+        final int toX = MCUtil.getCoordinateX(newPosition);
+        final int toZ = MCUtil.getCoordinateZ(newPosition);
+        final int fromX = MCUtil.getCoordinateX(oldPosition);
+        final int fromZ = MCUtil.getCoordinateZ(oldPosition);
+
+        final int totalX = IntegerUtil.branchlessAbs(fromX - toX);
+        final int totalZ = IntegerUtil.branchlessAbs(fromZ - toZ);
+
+        if (Math.max(totalX, totalZ) > (2 * Math.max(newViewDistance, oldViewDistance))) {
+            // teleported?
+            this.removeObjectCallback(object, fromX, fromZ, oldViewDistance);
+            this.addObjectCallback(object, toX, toZ, newViewDistance);
+            return;
+        }
+
+        final int minX = Math.min(fromX - oldViewDistance, toX - newViewDistance);
+        final int maxX = Math.max(fromX + oldViewDistance, toX + newViewDistance);
+        final int minZ = Math.min(fromZ - oldViewDistance, toZ - newViewDistance);
+        final int maxZ = Math.max(fromZ + oldViewDistance, toZ + newViewDistance);
+
+        for (int x = minX; x <= maxX; ++x) {
+            for (int z = minZ; z <= maxZ; ++z) {
+                final int distXOld = IntegerUtil.branchlessAbs(x - fromX);
+                final int distZOld = IntegerUtil.branchlessAbs(z - fromZ);
+
+                if (Math.max(distXOld, distZOld) <= oldViewDistance) {
+                    this.recalculateDistance(x, z);
+                    continue;
+                }
+
+                final int distXNew = IntegerUtil.branchlessAbs(x - toX);
+                final int distZNew = IntegerUtil.branchlessAbs(z - toZ);
+
+                if (Math.max(distXNew, distZNew) <= newViewDistance) {
+                    this.recalculateDistance(x, z);
+                    continue;
+                }
+            }
+        }
+    }
+
+    @FunctionalInterface
+    public static interface DistanceChangeCallback<E> {
+
+        void accept(final int posX, final int posZ, final int oldNearestDistance, final int newNearestDistance,
+                    final PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<E> state);
+
+    }
+}
diff --git a/src/main/java/com/destroystokyo/paper/util/misc/PlayerAreaMap.java b/src/main/java/com/destroystokyo/paper/util/misc/PlayerAreaMap.java
new file mode 100644
index 0000000000000000000000000000000000000000..46954db7ecd35ac4018fdf476df7c8020d7ce6c8
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/util/misc/PlayerAreaMap.java
@@ -0,0 +1,32 @@
+package com.destroystokyo.paper.util.misc;
+
+import net.minecraft.server.level.ServerPlayer;
+
+/**
+ * @author Spottedleaf
+ */
+public final class PlayerAreaMap extends AreaMap<ServerPlayer> {
+
+    public PlayerAreaMap() {
+        super();
+    }
+
+    public PlayerAreaMap(final PooledLinkedHashSets<ServerPlayer> pooledHashSets) {
+        super(pooledHashSets);
+    }
+
+    public PlayerAreaMap(final PooledLinkedHashSets<ServerPlayer> pooledHashSets, final ChangeCallback<ServerPlayer> addCallback,
+                         final ChangeCallback<ServerPlayer> removeCallback) {
+        this(pooledHashSets, addCallback, removeCallback, null);
+    }
+
+    public PlayerAreaMap(final PooledLinkedHashSets<ServerPlayer> pooledHashSets, final ChangeCallback<ServerPlayer> addCallback,
+                         final ChangeCallback<ServerPlayer> removeCallback, final ChangeSourceCallback<ServerPlayer> changeSourceCallback) {
+        super(pooledHashSets, addCallback, removeCallback, changeSourceCallback);
+    }
+
+    @Override
+    protected PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> getEmptySetFor(final ServerPlayer player) {
+        return player.cachedSingleHashSet;
+    }
+}
diff --git a/src/main/java/com/destroystokyo/paper/util/misc/PlayerDistanceTrackingAreaMap.java b/src/main/java/com/destroystokyo/paper/util/misc/PlayerDistanceTrackingAreaMap.java
new file mode 100644
index 0000000000000000000000000000000000000000..d05dcea15f7047b58736c7c0e07920a04d6c5abe
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/util/misc/PlayerDistanceTrackingAreaMap.java
@@ -0,0 +1,24 @@
+package com.destroystokyo.paper.util.misc;
+
+import net.minecraft.server.level.ServerPlayer;
+
+public class PlayerDistanceTrackingAreaMap extends DistanceTrackingAreaMap<ServerPlayer> {
+
+    public PlayerDistanceTrackingAreaMap() {
+        super();
+    }
+
+    public PlayerDistanceTrackingAreaMap(final PooledLinkedHashSets<ServerPlayer> pooledHashSets) {
+        super(pooledHashSets);
+    }
+
+    public PlayerDistanceTrackingAreaMap(final PooledLinkedHashSets<ServerPlayer> pooledHashSets, final ChangeCallback<ServerPlayer> addCallback,
+                                         final ChangeCallback<ServerPlayer> removeCallback, final DistanceChangeCallback<ServerPlayer> distanceChangeCallback) {
+        super(pooledHashSets, addCallback, removeCallback, distanceChangeCallback);
+    }
+
+    @Override
+    protected PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> getEmptySetFor(final ServerPlayer player) {
+        return player.cachedSingleHashSet;
+    }
+}
diff --git a/src/main/java/com/destroystokyo/paper/util/misc/PooledLinkedHashSets.java b/src/main/java/com/destroystokyo/paper/util/misc/PooledLinkedHashSets.java
new file mode 100644
index 0000000000000000000000000000000000000000..e51104e65a07b6ea7bbbcbb6afb066ef6401cc5b
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/util/misc/PooledLinkedHashSets.java
@@ -0,0 +1,287 @@
+package com.destroystokyo.paper.util.misc;
+
+import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
+import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
+import java.lang.ref.WeakReference;
+
+/** @author Spottedleaf */
+public class PooledLinkedHashSets<E> {
+
+    /* Tested via https://gist.github.com/Spottedleaf/a93bb7a8993d6ce142d3efc5932bf573 */
+
+    // we really want to avoid that equals() check as much as possible...
+    protected final Object2ObjectOpenHashMap<PooledObjectLinkedOpenHashSet<E>, PooledObjectLinkedOpenHashSet<E>> mapPool = new Object2ObjectOpenHashMap<>(128, 0.25f);
+
+    protected void decrementReferenceCount(final PooledObjectLinkedOpenHashSet<E> current) {
+        if (current.referenceCount == 0) {
+            throw new IllegalStateException("Cannot decrement reference count for " + current);
+        }
+        if (current.referenceCount == -1 || --current.referenceCount > 0) {
+            return;
+        }
+
+        this.mapPool.remove(current);
+        return;
+    }
+
+    public PooledObjectLinkedOpenHashSet<E> findMapWith(final PooledObjectLinkedOpenHashSet<E> current, final E object) {
+        final PooledObjectLinkedOpenHashSet<E> cached = current.getAddCache(object);
+
+        if (cached != null) {
+            decrementReferenceCount(current);
+
+            if (cached.referenceCount == 0) {
+                // bring the map back from the dead
+                PooledObjectLinkedOpenHashSet<E> contending = this.mapPool.putIfAbsent(cached, cached);
+                if (contending != null) {
+                    // a map already exists with the elements we want
+                    if (contending.referenceCount != -1) {
+                        ++contending.referenceCount;
+                    }
+                    current.updateAddCache(object, contending);
+                    return contending;
+                }
+
+                cached.referenceCount = 1;
+            } else if (cached.referenceCount != -1) {
+                ++cached.referenceCount;
+            }
+
+            return cached;
+        }
+
+        if (!current.add(object)) {
+            return current;
+        }
+
+        // we use get/put since we use a different key on put
+        PooledObjectLinkedOpenHashSet<E> ret = this.mapPool.get(current);
+
+        if (ret == null) {
+            ret = new PooledObjectLinkedOpenHashSet<>(current);
+            current.remove(object);
+            this.mapPool.put(ret, ret);
+            ret.referenceCount = 1;
+        } else {
+            if (ret.referenceCount != -1) {
+                ++ret.referenceCount;
+            }
+            current.remove(object);
+        }
+
+        current.updateAddCache(object, ret);
+
+        decrementReferenceCount(current);
+        return ret;
+    }
+
+    // rets null if current.size() == 1
+    public PooledObjectLinkedOpenHashSet<E> findMapWithout(final PooledObjectLinkedOpenHashSet<E> current, final E object) {
+        if (current.set.size() == 1) {
+            decrementReferenceCount(current);
+            return null;
+        }
+
+        final PooledObjectLinkedOpenHashSet<E> cached = current.getRemoveCache(object);
+
+        if (cached != null) {
+            decrementReferenceCount(current);
+
+            if (cached.referenceCount == 0) {
+                // bring the map back from the dead
+                PooledObjectLinkedOpenHashSet<E> contending = this.mapPool.putIfAbsent(cached, cached);
+                if (contending != null) {
+                    // a map already exists with the elements we want
+                    if (contending.referenceCount != -1) {
+                        ++contending.referenceCount;
+                    }
+                    current.updateRemoveCache(object, contending);
+                    return contending;
+                }
+
+                cached.referenceCount = 1;
+            } else if (cached.referenceCount != -1) {
+                ++cached.referenceCount;
+            }
+
+            return cached;
+        }
+
+        if (!current.remove(object)) {
+            return current;
+        }
+
+        // we use get/put since we use a different key on put
+        PooledObjectLinkedOpenHashSet<E> ret = this.mapPool.get(current);
+
+        if (ret == null) {
+            ret = new PooledObjectLinkedOpenHashSet<>(current);
+            current.add(object);
+            this.mapPool.put(ret, ret);
+            ret.referenceCount = 1;
+        } else {
+            if (ret.referenceCount != -1) {
+                ++ret.referenceCount;
+            }
+            current.add(object);
+        }
+
+        current.updateRemoveCache(object, ret);
+
+        decrementReferenceCount(current);
+        return ret;
+    }
+
+    static final class RawSetObjectLinkedOpenHashSet<E> extends ObjectOpenHashSet<E> {
+
+        public RawSetObjectLinkedOpenHashSet() {
+            super();
+        }
+
+        public RawSetObjectLinkedOpenHashSet(final int capacity) {
+            super(capacity);
+        }
+
+        public RawSetObjectLinkedOpenHashSet(final int capacity, final float loadFactor) {
+            super(capacity, loadFactor);
+        }
+
+        @Override
+        public RawSetObjectLinkedOpenHashSet<E> clone() {
+            return (RawSetObjectLinkedOpenHashSet<E>)super.clone();
+        }
+
+        public E[] getRawSet() {
+            return this.key;
+        }
+    }
+
+    public static final class PooledObjectLinkedOpenHashSet<E> {
+
+        private static final WeakReference NULL_REFERENCE = new WeakReference<>(null);
+
+        final RawSetObjectLinkedOpenHashSet<E> set;
+        int referenceCount; // -1 if special
+        int hash; // optimize hashcode
+
+        // add cache
+        WeakReference<E> lastAddObject = NULL_REFERENCE;
+        WeakReference<PooledObjectLinkedOpenHashSet<E>> lastAddMap = NULL_REFERENCE;
+
+        // remove cache
+        WeakReference<E> lastRemoveObject = NULL_REFERENCE;
+        WeakReference<PooledObjectLinkedOpenHashSet<E>> lastRemoveMap = NULL_REFERENCE;
+
+        public PooledObjectLinkedOpenHashSet(final PooledLinkedHashSets<E> pooledSets) {
+            this.set = new RawSetObjectLinkedOpenHashSet<>(2, 0.8f);
+        }
+
+        public PooledObjectLinkedOpenHashSet(final E single) {
+            this((PooledLinkedHashSets<E>)null);
+            this.referenceCount = -1;
+            this.add(single);
+        }
+
+        public PooledObjectLinkedOpenHashSet(final PooledObjectLinkedOpenHashSet<E> other) {
+            this.set = other.set.clone();
+            this.hash = other.hash;
+        }
+
+        // from https://github.com/Spottedleaf/ConcurrentUtil/blob/master/src/main/java/ca/spottedleaf/concurrentutil/util/IntegerUtil.java
+        // generated by https://github.com/skeeto/hash-prospector
+        private static int hash0(int x) {
+            x *= 0x36935555;
+            x ^= x >>> 16;
+            return x;
+        }
+
+        PooledObjectLinkedOpenHashSet<E> getAddCache(final E element) {
+            final E currentAdd = this.lastAddObject.get();
+
+            if (currentAdd == null || !(currentAdd == element || currentAdd.equals(element))) {
+                return null;
+            }
+
+            return this.lastAddMap.get();
+        }
+
+        PooledObjectLinkedOpenHashSet<E> getRemoveCache(final E element) {
+            final E currentRemove = this.lastRemoveObject.get();
+
+            if (currentRemove == null || !(currentRemove == element || currentRemove.equals(element))) {
+                return null;
+            }
+
+            return this.lastRemoveMap.get();
+        }
+
+        void updateAddCache(final E element, final PooledObjectLinkedOpenHashSet<E> map) {
+            this.lastAddObject = new WeakReference<>(element);
+            this.lastAddMap = new WeakReference<>(map);
+        }
+
+        void updateRemoveCache(final E element, final PooledObjectLinkedOpenHashSet<E> map) {
+            this.lastRemoveObject = new WeakReference<>(element);
+            this.lastRemoveMap = new WeakReference<>(map);
+        }
+
+        boolean add(final E element) {
+            boolean added =  this.set.add(element);
+
+            if (added) {
+                this.hash += hash0(element.hashCode());
+            }
+
+            return added;
+        }
+
+        boolean remove(Object element) {
+            boolean removed = this.set.remove(element);
+
+            if (removed) {
+                this.hash -= hash0(element.hashCode());
+            }
+
+            return removed;
+        }
+
+        public boolean contains(final Object element) {
+            return this.set.contains(element);
+        }
+
+        public E[] getBackingSet() {
+            return this.set.getRawSet();
+        }
+
+        public int size() {
+            return this.set.size();
+        }
+
+        @Override
+        public int hashCode() {
+            return this.hash;
+        }
+
+        @Override
+        public boolean equals(final Object other) {
+            if (!(other instanceof PooledObjectLinkedOpenHashSet)) {
+                return false;
+            }
+            if (this.referenceCount == 0) {
+                return other == this;
+            } else {
+                if (other == this) {
+                    // Unfortunately we are never equal to our own instance while in use!
+                    return false;
+                }
+                return this.hash == ((PooledObjectLinkedOpenHashSet)other).hash && this.set.equals(((PooledObjectLinkedOpenHashSet)other).set);
+            }
+        }
+
+        @Override
+        public String toString() {
+            return "PooledHashSet: size: " + this.set.size() + ", reference count: " + this.referenceCount + ", hash: " +
+                this.hashCode() + ", identity: " + System.identityHashCode(this) + " map: " + this.set.toString();
+        }
+    }
+}
diff --git a/src/main/java/com/destroystokyo/paper/util/pooled/PooledObjects.java b/src/main/java/com/destroystokyo/paper/util/pooled/PooledObjects.java
new file mode 100644
index 0000000000000000000000000000000000000000..a743703502cea333bd4231b6557de50e8eaf81eb
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/util/pooled/PooledObjects.java
@@ -0,0 +1,85 @@
+package com.destroystokyo.paper.util.pooled;
+
+import io.papermc.paper.util.MCUtil;
+import org.apache.commons.lang3.mutable.MutableInt;
+
+import java.util.ArrayDeque;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+
+public final class PooledObjects<E> {
+
+    /**
+     * Wrapper for an object that will be have a cleaner registered for it, and may be automatically returned to pool.
+     */
+    public class AutoReleased {
+        private final E object;
+        private final Runnable cleaner;
+
+        public AutoReleased(E object, Runnable cleaner) {
+            this.object = object;
+            this.cleaner = cleaner;
+        }
+
+        public final E getObject() {
+            return object;
+        }
+
+        public final Runnable getCleaner() {
+            return cleaner;
+        }
+    }
+
+    public static final PooledObjects<MutableInt> POOLED_MUTABLE_INTEGERS = new PooledObjects<>(MutableInt::new, 1024);
+
+    private final Supplier<E> creator;
+    private final Consumer<E> releaser;
+    private final int maxPoolSize;
+    private final ArrayDeque<E> queue;
+
+    public PooledObjects(final Supplier<E> creator, int maxPoolSize) {
+        this(creator, maxPoolSize, null);
+    }
+    public PooledObjects(final Supplier<E> creator, int maxPoolSize, Consumer<E> releaser) {
+        if (creator == null) {
+            throw new NullPointerException("Creator must not be null");
+        }
+        if (maxPoolSize <= 0) {
+            throw new IllegalArgumentException("Max pool size must be greater-than 0");
+        }
+
+        this.queue = new ArrayDeque<>(maxPoolSize);
+        this.maxPoolSize = maxPoolSize;
+        this.creator = creator;
+        this.releaser = releaser;
+    }
+
+    public AutoReleased acquireCleaner(Object holder) {
+        return acquireCleaner(holder, this::release);
+    }
+
+    public AutoReleased acquireCleaner(Object holder, Consumer<E> releaser) {
+        E resource = acquire();
+        Runnable cleaner = MCUtil.registerCleaner(holder, resource, releaser);
+        return new AutoReleased(resource, cleaner);
+    }
+
+    public final E acquire() {
+        E value;
+        synchronized (queue) {
+            value = this.queue.pollLast();
+        }
+        return value != null ? value : this.creator.get();
+    }
+
+    public final void release(final E value) {
+        if (this.releaser != null) {
+            this.releaser.accept(value);
+        }
+        synchronized (this.queue) {
+            if (queue.size() < this.maxPoolSize) {
+                this.queue.addLast(value);
+            }
+        }
+    }
+}
diff --git a/src/main/java/com/destroystokyo/paper/util/set/OptimizedSmallEnumSet.java b/src/main/java/com/destroystokyo/paper/util/set/OptimizedSmallEnumSet.java
new file mode 100644
index 0000000000000000000000000000000000000000..b3329c6fcd6758a781a51f5ba8f5052ac1c77b49
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/util/set/OptimizedSmallEnumSet.java
@@ -0,0 +1,71 @@
+package com.destroystokyo.paper.util.set;
+
+import java.util.Collection;
+
+/**
+ * @author Spottedleaf <Spottedleaf@users.noreply.github.com>
+ */
+public final class OptimizedSmallEnumSet<E extends Enum<E>> {
+
+    private final Class<E> enumClass;
+    private long backingSet;
+
+    public OptimizedSmallEnumSet(final Class<E> clazz) {
+        if (clazz == null) {
+            throw new IllegalArgumentException("Null class");
+        }
+        if (!clazz.isEnum()) {
+            throw new IllegalArgumentException("Class must be enum, not " + clazz.getCanonicalName());
+        }
+        this.enumClass = clazz;
+    }
+
+    public boolean addUnchecked(final E element) {
+        final int ordinal = element.ordinal();
+        final long key = 1L << ordinal;
+
+        final long prev = this.backingSet;
+        this.backingSet = prev | key;
+
+        return (prev & key) == 0;
+    }
+
+    public boolean removeUnchecked(final E element) {
+        final int ordinal = element.ordinal();
+        final long key = 1L << ordinal;
+
+        final long prev = this.backingSet;
+        this.backingSet = prev & ~key;
+
+        return (prev & key) != 0;
+    }
+
+    public void clear() {
+        this.backingSet = 0L;
+    }
+
+    public int size() {
+        return Long.bitCount(this.backingSet);
+    }
+
+    public void addAllUnchecked(final Collection<E> enums) {
+        for (final E element : enums) {
+            if (element == null) {
+                throw new NullPointerException("Null element");
+            }
+            this.backingSet |= (1L << element.ordinal());
+        }
+    }
+
+    public long getBackingSet() {
+        return this.backingSet;
+    }
+
+    public boolean hasCommonElements(final OptimizedSmallEnumSet<E> other) {
+        return (other.backingSet & this.backingSet) != 0;
+    }
+
+    public boolean hasElement(final E element) {
+        return (this.backingSet & (1L << element.ordinal())) != 0;
+    }
+}
diff --git a/src/main/java/com/mojang/logging/LogUtils.java b/src/main/java/com/mojang/logging/LogUtils.java
index 46cab7a8c7b87ab01b26074b04f5a02b3907cfc4..49019b4a9bc4e634d54a9b0acaf9229a5c896f85 100644
--- a/src/main/java/com/mojang/logging/LogUtils.java
+++ b/src/main/java/com/mojang/logging/LogUtils.java
@@ -61,4 +61,9 @@ public class LogUtils {
     public static Logger getLogger() {
         return LoggerFactory.getLogger(STACK_WALKER.getCallerClass());
     }
+    // Paper start
+    public static Logger getClassLogger() {
+        return LoggerFactory.getLogger(STACK_WALKER.getCallerClass().getSimpleName());
+    }
+    // Paper end
 }
diff --git a/src/main/java/io/papermc/paper/chunk/SingleThreadChunkRegionManager.java b/src/main/java/io/papermc/paper/chunk/SingleThreadChunkRegionManager.java
new file mode 100644
index 0000000000000000000000000000000000000000..a5f706d6f716b2a463ae58adcde69d9e665c7733
--- /dev/null
+++ b/src/main/java/io/papermc/paper/chunk/SingleThreadChunkRegionManager.java
@@ -0,0 +1,477 @@
+package io.papermc.paper.chunk;
+
+import io.papermc.paper.util.maplist.IteratorSafeOrderedReferenceSet;
+import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
+import it.unimi.dsi.fastutil.objects.ReferenceLinkedOpenHashSet;
+import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
+import io.papermc.paper.util.MCUtil;
+import net.minecraft.server.level.ServerLevel;
+import net.minecraft.world.level.ChunkPos;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.function.Supplier;
+
+public final class SingleThreadChunkRegionManager {
+
+    protected final int regionSectionMergeRadius;
+    protected final int regionSectionChunkSize;
+    public final int regionChunkShift; // log2(REGION_CHUNK_SIZE)
+
+    public final ServerLevel world;
+    public final String name;
+
+    protected final Long2ObjectOpenHashMap<RegionSection> regionsBySection = new Long2ObjectOpenHashMap<>();
+    protected final ReferenceLinkedOpenHashSet<Region> needsRecalculation = new ReferenceLinkedOpenHashSet<>();
+    protected final int minSectionRecalcCount;
+    protected final double maxDeadRegionPercent;
+    protected final Supplier<RegionData> regionDataSupplier;
+    protected final Supplier<RegionSectionData> regionSectionDataSupplier;
+
+    public SingleThreadChunkRegionManager(final ServerLevel world, final int minSectionRecalcCount,
+                                          final double maxDeadRegionPercent, final int sectionMergeRadius,
+                                          final int regionSectionChunkShift,
+                                          final String name, final Supplier<RegionData> regionDataSupplier,
+                                          final Supplier<RegionSectionData> regionSectionDataSupplier) {
+        this.regionSectionMergeRadius = sectionMergeRadius;
+        this.regionSectionChunkSize = 1 << regionSectionChunkShift;
+        this.regionChunkShift = regionSectionChunkShift;
+        this.world = world;
+        this.name = name;
+        this.minSectionRecalcCount = Math.max(2, minSectionRecalcCount);
+        this.maxDeadRegionPercent = maxDeadRegionPercent;
+        this.regionDataSupplier = regionDataSupplier;
+        this.regionSectionDataSupplier = regionSectionDataSupplier;
+    }
+
+    // tested via https://gist.github.com/Spottedleaf/aa7ade3451c37b4cac061fc77074db2f
+
+    /*
+    protected void check() {
+        ReferenceOpenHashSet<Region<T>> checked = new ReferenceOpenHashSet<>();
+
+        for (RegionSection<T> section : this.regionsBySection.values()) {
+            if (!checked.add(section.region)) {
+                section.region.check();
+            }
+        }
+        for (Region<T> region : this.needsRecalculation) {
+            region.check();
+        }
+    }
+    */
+
+    protected void addToRecalcQueue(final Region region) {
+        this.needsRecalculation.add(region);
+    }
+
+    protected void removeFromRecalcQueue(final Region region) {
+        this.needsRecalculation.remove(region);
+    }
+
+    public RegionSection getRegionSection(final int chunkX, final int chunkZ) {
+        return this.regionsBySection.get(MCUtil.getCoordinateKey(chunkX >> this.regionChunkShift, chunkZ >> this.regionChunkShift));
+    }
+
+    public Region getRegion(final int chunkX, final int chunkZ) {
+        final RegionSection section = this.regionsBySection.get(MCUtil.getCoordinateKey(chunkX >> regionChunkShift, chunkZ >> regionChunkShift));
+        return section != null ? section.region : null;
+    }
+
+    private final List<Region> toMerge = new ArrayList<>();
+
+    protected RegionSection getOrCreateAndMergeSection(final int sectionX, final int sectionZ, final RegionSection force) {
+        final long sectionKey = MCUtil.getCoordinateKey(sectionX, sectionZ);
+
+        if (force == null) {
+            RegionSection region = this.regionsBySection.get(sectionKey);
+            if (region != null) {
+                return region;
+            }
+        }
+
+        int mergeCandidateSectionSize = -1;
+        Region mergeIntoCandidate = null;
+
+        // find optimal candidate to merge into
+
+        final int minX = sectionX - this.regionSectionMergeRadius;
+        final int maxX = sectionX + this.regionSectionMergeRadius;
+        final int minZ = sectionZ - this.regionSectionMergeRadius;
+        final int maxZ = sectionZ + this.regionSectionMergeRadius;
+        for (int currX = minX; currX <= maxX; ++currX) {
+            for (int currZ = minZ; currZ <= maxZ; ++currZ) {
+                final RegionSection section = this.regionsBySection.get(MCUtil.getCoordinateKey(currX, currZ));
+                if (section == null) {
+                    continue;
+                }
+                final Region region = section.region;
+                if (region.dead) {
+                    throw new IllegalStateException("Dead region should not be in live region manager state: " + region);
+                }
+                final int sections = region.sections.size();
+
+                if (sections > mergeCandidateSectionSize) {
+                    mergeCandidateSectionSize = sections;
+                    mergeIntoCandidate = region;
+                }
+                this.toMerge.add(region);
+            }
+        }
+
+        // merge
+        if (mergeIntoCandidate != null) {
+            for (int i = 0; i < this.toMerge.size(); ++i) {
+                final Region region = this.toMerge.get(i);
+                if (region.dead || mergeIntoCandidate == region) {
+                    continue;
+                }
+                region.mergeInto(mergeIntoCandidate);
+            }
+            this.toMerge.clear();
+        } else {
+            mergeIntoCandidate = new Region(this);
+        }
+
+        final RegionSection section;
+        if (force == null) {
+            this.regionsBySection.put(sectionKey, section = new RegionSection(sectionKey, this));
+        } else {
+            final RegionSection existing = this.regionsBySection.putIfAbsent(sectionKey, force);
+            if (existing != null) {
+                throw new IllegalStateException("Attempting to override section '" + existing.toStringWithRegion() +
+                        ", with " + force.toStringWithRegion());
+            }
+
+            section = force;
+        }
+
+        mergeIntoCandidate.addRegionSection(section);
+        //mergeIntoCandidate.check();
+        //this.check();
+
+        return section;
+    }
+
+    public void addChunk(final int chunkX, final int chunkZ) {
+        this.getOrCreateAndMergeSection(chunkX >> this.regionChunkShift, chunkZ >> this.regionChunkShift, null).addChunk(chunkX, chunkZ);
+    }
+
+    public void removeChunk(final int chunkX, final int chunkZ) {
+        final RegionSection section = this.regionsBySection.get(
+                MCUtil.getCoordinateKey(chunkX >> this.regionChunkShift, chunkZ >> this.regionChunkShift)
+        );
+        if (section != null) {
+            section.removeChunk(chunkX, chunkZ);
+        } else {
+            throw new IllegalStateException("Cannot remove chunk at (" + chunkX + "," + chunkZ + ") from region state, section does not exist");
+        }
+    }
+
+    public void recalculateRegions() {
+        for (int i = 0, len = this.needsRecalculation.size(); i < len; ++i) {
+            final Region region = this.needsRecalculation.removeFirst();
+
+            this.recalculateRegion(region);
+            //this.check();
+        }
+    }
+
+    protected void recalculateRegion(final Region region) {
+        region.markedForRecalc = false;
+        //region.check();
+        // clear unused regions
+        for (final Iterator<RegionSection> iterator = region.deadSections.iterator(); iterator.hasNext();) {
+            final RegionSection deadSection = iterator.next();
+
+            if (deadSection.hasChunks()) {
+                throw new IllegalStateException("Dead section '" + deadSection.toStringWithRegion() + "' is marked dead but has chunks!");
+            }
+            if (!region.removeRegionSection(deadSection)) {
+                throw new IllegalStateException("Region " + region + " has inconsistent state, it should contain section " + deadSection);
+            }
+            if (!this.regionsBySection.remove(deadSection.regionCoordinate, deadSection)) {
+                throw new IllegalStateException("Cannot remove dead section '" +
+                        deadSection.toStringWithRegion() + "' from section state! State at section coordinate: " +
+                        this.regionsBySection.get(deadSection.regionCoordinate));
+            }
+        }
+        region.deadSections.clear();
+
+        // implicitly cover cases where size == 0
+        if (region.sections.size() < this.minSectionRecalcCount) {
+            //region.check();
+            return;
+        }
+
+        // run a test to see if we actually need to recalculate
+        // TODO
+
+        // destroy and rebuild the region
+        region.dead = true;
+
+        // destroy region state
+        for (final Iterator<RegionSection> iterator = region.sections.unsafeIterator(IteratorSafeOrderedReferenceSet.ITERATOR_FLAG_SEE_ADDITIONS); iterator.hasNext();) {
+            final RegionSection aliveSection = iterator.next();
+            if (!aliveSection.hasChunks()) {
+                throw new IllegalStateException("Alive section '" + aliveSection.toStringWithRegion() + "' has no chunks!");
+            }
+            if (!this.regionsBySection.remove(aliveSection.regionCoordinate, aliveSection)) {
+                throw new IllegalStateException("Cannot remove alive section '" +
+                        aliveSection.toStringWithRegion() + "' from section state! State at section coordinate: " +
+                        this.regionsBySection.get(aliveSection.regionCoordinate));
+            }
+        }
+
+        // rebuild regions
+        for (final Iterator<RegionSection> iterator = region.sections.unsafeIterator(IteratorSafeOrderedReferenceSet.ITERATOR_FLAG_SEE_ADDITIONS); iterator.hasNext();) {
+            final RegionSection aliveSection = iterator.next();
+            this.getOrCreateAndMergeSection(aliveSection.getSectionX(), aliveSection.getSectionZ(), aliveSection);
+        }
+    }
+
+    public static final class Region {
+        protected final IteratorSafeOrderedReferenceSet<RegionSection> sections = new IteratorSafeOrderedReferenceSet<>();
+        protected final ReferenceOpenHashSet<RegionSection> deadSections = new ReferenceOpenHashSet<>(16, 0.7f);
+        protected boolean dead;
+        protected boolean markedForRecalc;
+
+        public final SingleThreadChunkRegionManager regionManager;
+        public final RegionData regionData;
+
+        protected Region(final SingleThreadChunkRegionManager regionManager) {
+            this.regionManager = regionManager;
+            this.regionData = regionManager.regionDataSupplier.get();
+        }
+
+        public IteratorSafeOrderedReferenceSet.Iterator<RegionSection> getSections() {
+            return this.sections.iterator(IteratorSafeOrderedReferenceSet.ITERATOR_FLAG_SEE_ADDITIONS);
+        }
+
+        protected final double getDeadSectionPercent() {
+            return (double)this.deadSections.size() / (double)this.sections.size();
+        }
+
+        /*
+        protected void check() {
+            if (this.dead) {
+                throw new IllegalStateException("Dead region!");
+            }
+            for (final Iterator<RegionSection<T>> iterator = this.sections.unsafeIterator(IteratorSafeOrderedReferenceSet.ITERATOR_FLAG_SEE_ADDITIONS); iterator.hasNext();) {
+                final RegionSection<T> section = iterator.next();
+                if (section.region != this) {
+                    throw new IllegalStateException("Region section must point to us!");
+                }
+                if (this.regionManager.regionsBySection.get(section.regionCoordinate) != section) {
+                    throw new IllegalStateException("Region section must match the regionmanager state!");
+                }
+            }
+        }
+        */
+
+        // note: it is not true that the region at this point is not in any region. use the region field on the section
+        // to see if it is currently in another region.
+        protected final boolean addRegionSection(final RegionSection section) {
+            if (!this.sections.add(section)) {
+                return false;
+            }
+
+            section.sectionData.addToRegion(section, section.region, this);
+
+            section.region = this;
+            return true;
+        }
+
+        protected final boolean removeRegionSection(final RegionSection section) {
+            if (!this.sections.remove(section)) {
+                return false;
+            }
+
+            section.sectionData.removeFromRegion(section, this);
+
+            return true;
+        }
+
+        protected void mergeInto(final Region mergeTarget) {
+            if (this == mergeTarget) {
+                throw new IllegalStateException("Cannot merge a region onto itself");
+            }
+            if (this.dead) {
+                throw new IllegalStateException("Source region is dead! Source " + this + ", target " + mergeTarget);
+            } else if (mergeTarget.dead) {
+                throw new IllegalStateException("Target region is dead! Source " + this + ", target " + mergeTarget);
+            }
+            this.dead = true;
+            if (this.markedForRecalc) {
+                this.regionManager.removeFromRecalcQueue(this);
+            }
+
+            for (final Iterator<RegionSection> iterator = this.sections.unsafeIterator(IteratorSafeOrderedReferenceSet.ITERATOR_FLAG_SEE_ADDITIONS); iterator.hasNext();) {
+                final RegionSection section = iterator.next();
+
+                if (!mergeTarget.addRegionSection(section)) {
+                    throw new IllegalStateException("Target cannot contain source's sections! Source " + this + ", target " + mergeTarget);
+                }
+            }
+
+            for (final RegionSection deadSection : this.deadSections) {
+                if (!this.sections.contains(deadSection)) {
+                    throw new IllegalStateException("Source region does not even contain its own dead sections! Missing " + deadSection + " from region " + this);
+                }
+                mergeTarget.deadSections.add(deadSection);
+            }
+            //mergeTarget.check();
+        }
+
+        protected void markSectionAlive(final RegionSection section) {
+            this.deadSections.remove(section);
+            if (this.markedForRecalc && (this.sections.size() < this.regionManager.minSectionRecalcCount || this.getDeadSectionPercent() < this.regionManager.maxDeadRegionPercent)) {
+                this.regionManager.removeFromRecalcQueue(this);
+                this.markedForRecalc = false;
+            }
+        }
+
+        protected void markSectionDead(final RegionSection section) {
+            this.deadSections.add(section);
+            if (!this.markedForRecalc && (this.sections.size() >= this.regionManager.minSectionRecalcCount || this.sections.size() == this.deadSections.size()) && this.getDeadSectionPercent() >= this.regionManager.maxDeadRegionPercent) {
+                this.regionManager.addToRecalcQueue(this);
+                this.markedForRecalc = true;
+            }
+        }
+
+        @Override
+        public String toString() {
+            final StringBuilder ret = new StringBuilder(128);
+
+            ret.append("Region{");
+            ret.append("dead=").append(this.dead).append(',');
+            ret.append("markedForRecalc=").append(this.markedForRecalc).append(',');
+
+            ret.append("sectionCount=").append(this.sections.size()).append(',');
+            ret.append("sections=[");
+            for (final Iterator<RegionSection> iterator = this.sections.unsafeIterator(IteratorSafeOrderedReferenceSet.ITERATOR_FLAG_SEE_ADDITIONS); iterator.hasNext();) {
+                final RegionSection section = iterator.next();
+                ret.append(section);
+                if (iterator.hasNext()) {
+                    ret.append(',');
+                }
+            }
+            ret.append(']');
+
+            ret.append('}');
+            return ret.toString();
+        }
+    }
+
+    public static final class RegionSection {
+        protected final long regionCoordinate;
+        protected final long[] chunksBitset;
+        protected int chunkCount;
+        protected Region region;
+
+        public final SingleThreadChunkRegionManager regionManager;
+        public final RegionSectionData sectionData;
+
+        protected RegionSection(final long regionCoordinate, final SingleThreadChunkRegionManager regionManager) {
+            this.regionCoordinate = regionCoordinate;
+            this.regionManager = regionManager;
+            this.chunksBitset = new long[Math.max(1, regionManager.regionSectionChunkSize * regionManager.regionSectionChunkSize / Long.SIZE)];
+            this.sectionData = regionManager.regionSectionDataSupplier.get();
+        }
+
+        public int getSectionX() {
+            return MCUtil.getCoordinateX(this.regionCoordinate);
+        }
+
+        public int getSectionZ() {
+            return MCUtil.getCoordinateZ(this.regionCoordinate);
+        }
+
+        public Region getRegion() {
+            return this.region;
+        }
+
+        private int getChunkIndex(final int chunkX, final int chunkZ) {
+            return (chunkX & (this.regionManager.regionSectionChunkSize - 1)) | ((chunkZ & (this.regionManager.regionSectionChunkSize - 1)) << this.regionManager.regionChunkShift);
+        }
+
+        protected boolean hasChunks() {
+            return this.chunkCount != 0;
+        }
+
+        protected void addChunk(final int chunkX, final int chunkZ) {
+            final int index = this.getChunkIndex(chunkX, chunkZ);
+            final long bitset = this.chunksBitset[index >>> 6]; // index / Long.SIZE
+            final long after = this.chunksBitset[index >>> 6] = bitset | (1L << (index & (Long.SIZE - 1)));
+            if (after == bitset) {
+                throw new IllegalStateException("Cannot add a chunk to a section which already has the chunk! RegionSection: " + this + ", global chunk: " + new ChunkPos(chunkX, chunkZ).toString());
+            }
+            if (++this.chunkCount != 1) {
+                return;
+            }
+            this.region.markSectionAlive(this);
+        }
+
+        protected void removeChunk(final int chunkX, final int chunkZ) {
+            final int index = this.getChunkIndex(chunkX, chunkZ);
+            final long before = this.chunksBitset[index >>> 6]; // index / Long.SIZE
+            final long bitset = this.chunksBitset[index >>> 6] = before & ~(1L << (index & (Long.SIZE - 1)));
+            if (before == bitset) {
+                throw new IllegalStateException("Cannot remove a chunk from a section which does not have that chunk! RegionSection: " + this + ", global chunk: " + new ChunkPos(chunkX, chunkZ).toString());
+            }
+            if (--this.chunkCount != 0) {
+                return;
+            }
+            this.region.markSectionDead(this);
+        }
+
+        @Override
+        public String toString() {
+            return "RegionSection{" +
+                    "regionCoordinate=" + new ChunkPos(this.regionCoordinate).toString() + "," +
+                    "chunkCount=" + this.chunkCount + "," +
+                    "chunksBitset=" + toString(this.chunksBitset) + "," +
+                    "hash=" + this.hashCode() +
+                    "}";
+        }
+
+        public String toStringWithRegion() {
+            return "RegionSection{" +
+                    "regionCoordinate=" + new ChunkPos(this.regionCoordinate).toString() + "," +
+                    "chunkCount=" + this.chunkCount + "," +
+                    "chunksBitset=" + toString(this.chunksBitset) + "," +
+                    "hash=" + this.hashCode() + "," +
+                    "region=" + this.region +
+                    "}";
+        }
+
+        private static String toString(final long[] array) {
+            final StringBuilder ret = new StringBuilder();
+            for (final long value : array) {
+                // zero pad the hex string
+                final char[] zeros = new char[Long.SIZE / 4];
+                Arrays.fill(zeros, '0');
+                final String string = Long.toHexString(value);
+                System.arraycopy(string.toCharArray(), 0, zeros, zeros.length - string.length(), string.length());
+
+                ret.append(zeros);
+            }
+
+            return ret.toString();
+        }
+    }
+
+    public static interface RegionData {
+
+    }
+
+    public static interface RegionSectionData {
+
+        public void removeFromRegion(final RegionSection section, final Region from);
+
+        // removal from the old region is handled via removeFromRegion
+        public void addToRegion(final RegionSection section, final Region oldRegion, final Region newRegion);
+
+    }
+}
diff --git a/src/main/java/io/papermc/paper/chunk/system/ChunkSystem.java b/src/main/java/io/papermc/paper/chunk/system/ChunkSystem.java
new file mode 100644
index 0000000000000000000000000000000000000000..95eac2e12a16938d81ab512b00e90c5234b42834
--- /dev/null
+++ b/src/main/java/io/papermc/paper/chunk/system/ChunkSystem.java
@@ -0,0 +1,295 @@
+package io.papermc.paper.chunk.system;
+
+import ca.spottedleaf.concurrentutil.executor.standard.PrioritisedExecutor;
+import com.destroystokyo.paper.util.SneakyThrow;
+import com.mojang.datafixers.util.Either;
+import com.mojang.logging.LogUtils;
+import io.papermc.paper.util.CoordinateUtils;
+import net.minecraft.server.level.ChunkHolder;
+import net.minecraft.server.level.ChunkMap;
+import net.minecraft.server.level.FullChunkStatus;
+import net.minecraft.server.level.ServerLevel;
+import net.minecraft.server.level.ServerPlayer;
+import net.minecraft.server.level.TicketType;
+import net.minecraft.world.entity.Entity;
+import net.minecraft.world.level.ChunkPos;
+import net.minecraft.world.level.chunk.ChunkAccess;
+import net.minecraft.world.level.chunk.ChunkStatus;
+import net.minecraft.world.level.chunk.LevelChunk;
+import org.bukkit.Bukkit;
+import org.slf4j.Logger;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.function.Consumer;
+
+public final class ChunkSystem {
+
+    private static final Logger LOGGER = LogUtils.getLogger();
+
+    public static void scheduleChunkTask(final ServerLevel level, final int chunkX, final int chunkZ, final Runnable run) {
+        scheduleChunkTask(level, chunkX, chunkZ, run, PrioritisedExecutor.Priority.NORMAL);
+    }
+
+    public static void scheduleChunkTask(final ServerLevel level, final int chunkX, final int chunkZ, final Runnable run, final PrioritisedExecutor.Priority priority) {
+        level.chunkSource.mainThreadProcessor.execute(run);
+    }
+
+    public static void scheduleChunkLoad(final ServerLevel level, final int chunkX, final int chunkZ, final boolean gen,
+                                         final ChunkStatus toStatus, final boolean addTicket, final PrioritisedExecutor.Priority priority,
+                                         final Consumer<ChunkAccess> onComplete) {
+        if (gen) {
+            scheduleChunkLoad(level, chunkX, chunkZ, toStatus, addTicket, priority, onComplete);
+            return;
+        }
+        scheduleChunkLoad(level, chunkX, chunkZ, ChunkStatus.EMPTY, addTicket, priority, (final ChunkAccess chunk) -> {
+            if (chunk == null) {
+                onComplete.accept(null);
+            } else {
+                if (chunk.getStatus().isOrAfter(toStatus)) {
+                    scheduleChunkLoad(level, chunkX, chunkZ, toStatus, addTicket, priority, onComplete);
+                } else {
+                    onComplete.accept(null);
+                }
+            }
+        });
+    }
+
+    static final TicketType<Long> CHUNK_LOAD = TicketType.create("chunk_load", Long::compareTo);
+
+    private static long chunkLoadCounter = 0L;
+    public static void scheduleChunkLoad(final ServerLevel level, final int chunkX, final int chunkZ, final ChunkStatus toStatus,
+                                         final boolean addTicket, final PrioritisedExecutor.Priority priority, final Consumer<ChunkAccess> onComplete) {
+        if (!Bukkit.isPrimaryThread()) {
+            scheduleChunkTask(level, chunkX, chunkZ, () -> {
+                scheduleChunkLoad(level, chunkX, chunkZ, toStatus, addTicket, priority, onComplete);
+            }, priority);
+            return;
+        }
+
+        final int minLevel = 33 + ChunkStatus.getDistance(toStatus);
+        final Long chunkReference = addTicket ? Long.valueOf(++chunkLoadCounter) : null;
+        final ChunkPos chunkPos = new ChunkPos(chunkX, chunkZ);
+
+        if (addTicket) {
+            level.chunkSource.addTicketAtLevel(CHUNK_LOAD, chunkPos, minLevel, chunkReference);
+        }
+        level.chunkSource.runDistanceManagerUpdates();
+
+        final Consumer<ChunkAccess> loadCallback = (final ChunkAccess chunk) -> {
+            try {
+                if (onComplete != null) {
+                    onComplete.accept(chunk);
+                }
+            } catch (final ThreadDeath death) {
+                throw death;
+            } catch (final Throwable thr) {
+                LOGGER.error("Exception handling chunk load callback", thr);
+                SneakyThrow.sneaky(thr);
+            } finally {
+                if (addTicket) {
+                    level.chunkSource.addTicketAtLevel(TicketType.UNKNOWN, chunkPos, minLevel, chunkPos);
+                    level.chunkSource.removeTicketAtLevel(CHUNK_LOAD, chunkPos, minLevel, chunkReference);
+                }
+            }
+        };
+
+        final ChunkHolder holder = level.chunkSource.chunkMap.getUpdatingChunkIfPresent(CoordinateUtils.getChunkKey(chunkX, chunkZ));
+
+        if (holder == null || holder.getTicketLevel() > minLevel) {
+            loadCallback.accept(null);
+            return;
+        }
+
+        final CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>> loadFuture = holder.getOrScheduleFuture(toStatus, level.chunkSource.chunkMap);
+
+        if (loadFuture.isDone()) {
+            loadCallback.accept(loadFuture.join().left().orElse(null));
+            return;
+        }
+
+        loadFuture.whenCompleteAsync((final Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure> either, final Throwable thr) -> {
+            if (thr != null) {
+                loadCallback.accept(null);
+                return;
+            }
+            loadCallback.accept(either.left().orElse(null));
+        }, (final Runnable r) -> {
+            scheduleChunkTask(level, chunkX, chunkZ, r, PrioritisedExecutor.Priority.HIGHEST);
+        });
+    }
+
+    public static void scheduleTickingState(final ServerLevel level, final int chunkX, final int chunkZ,
+                                            final FullChunkStatus toStatus, final boolean addTicket,
+                                            final PrioritisedExecutor.Priority priority, final Consumer<LevelChunk> onComplete) {
+        if (toStatus == ChunkHolder.FullChunkStatus.INACCESSIBLE) {
+            throw new IllegalArgumentException("Cannot wait for INACCESSIBLE status");
+        }
+
+        if (!Bukkit.isPrimaryThread()) {
+            scheduleChunkTask(level, chunkX, chunkZ, () -> {
+                scheduleTickingState(level, chunkX, chunkZ, toStatus, addTicket, priority, onComplete);
+            }, priority);
+            return;
+        }
+
+        final int minLevel = 33 - (toStatus.ordinal() - 1);
+        final int radius = toStatus.ordinal() - 1;
+        final Long chunkReference = addTicket ? Long.valueOf(++chunkLoadCounter) : null;
+        final ChunkPos chunkPos = new ChunkPos(chunkX, chunkZ);
+
+        if (addTicket) {
+            level.chunkSource.addTicketAtLevel(CHUNK_LOAD, chunkPos, minLevel, chunkReference);
+        }
+        level.chunkSource.runDistanceManagerUpdates();
+
+        final Consumer<LevelChunk> loadCallback = (final LevelChunk chunk) -> {
+            try {
+                if (onComplete != null) {
+                    onComplete.accept(chunk);
+                }
+            } catch (final ThreadDeath death) {
+                throw death;
+            } catch (final Throwable thr) {
+                LOGGER.error("Exception handling chunk load callback", thr);
+                SneakyThrow.sneaky(thr);
+            } finally {
+                if (addTicket) {
+                    level.chunkSource.addTicketAtLevel(TicketType.UNKNOWN, chunkPos, minLevel, chunkPos);
+                    level.chunkSource.removeTicketAtLevel(CHUNK_LOAD, chunkPos, minLevel, chunkReference);
+                }
+            }
+        };
+
+        final ChunkHolder holder = level.chunkSource.chunkMap.getUpdatingChunkIfPresent(CoordinateUtils.getChunkKey(chunkX, chunkZ));
+
+        if (holder == null || holder.getTicketLevel() > minLevel) {
+            loadCallback.accept(null);
+            return;
+        }
+
+        final CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> tickingState;
+        switch (toStatus) {
+            case BORDER: {
+                tickingState = holder.getFullChunkFuture();
+                break;
+            }
+            case TICKING: {
+                tickingState = holder.getTickingChunkFuture();
+                break;
+            }
+            case ENTITY_TICKING: {
+                tickingState = holder.getEntityTickingChunkFuture();
+                break;
+            }
+            default: {
+                throw new IllegalStateException("Cannot reach here");
+            }
+        }
+
+        if (tickingState.isDone()) {
+            loadCallback.accept(tickingState.join().left().orElse(null));
+            return;
+        }
+
+        tickingState.whenCompleteAsync((final Either<LevelChunk, ChunkHolder.ChunkLoadingFailure> either, final Throwable thr) -> {
+            if (thr != null) {
+                loadCallback.accept(null);
+                return;
+            }
+            loadCallback.accept(either.left().orElse(null));
+        }, (final Runnable r) -> {
+            scheduleChunkTask(level, chunkX, chunkZ, r, PrioritisedExecutor.Priority.HIGHEST);
+        });
+    }
+
+    public static List<ChunkHolder> getVisibleChunkHolders(final ServerLevel level) {
+        return new ArrayList<>(level.chunkSource.chunkMap.visibleChunkMap.values());
+    }
+
+    public static List<ChunkHolder> getUpdatingChunkHolders(final ServerLevel level) {
+        return new ArrayList<>(level.chunkSource.chunkMap.updatingChunkMap.values());
+    }
+
+    public static int getVisibleChunkHolderCount(final ServerLevel level) {
+        return level.chunkSource.chunkMap.visibleChunkMap.size();
+    }
+
+    public static int getUpdatingChunkHolderCount(final ServerLevel level) {
+        return level.chunkSource.chunkMap.updatingChunkMap.size();
+    }
+
+    public static boolean hasAnyChunkHolders(final ServerLevel level) {
+        return getUpdatingChunkHolderCount(level) != 0;
+    }
+
+    public static void onEntityPreAdd(final ServerLevel level, final Entity entity) {
+
+    }
+
+    public static void onChunkHolderCreate(final ServerLevel level, final ChunkHolder holder) {
+        final ChunkMap chunkMap = level.chunkSource.chunkMap;
+        for (int index = 0, len = chunkMap.regionManagers.size(); index < len; ++index) {
+            chunkMap.regionManagers.get(index).addChunk(holder.pos.x, holder.pos.z);
+        }
+    }
+
+    public static void onChunkHolderDelete(final ServerLevel level, final ChunkHolder holder) {
+        final ChunkMap chunkMap = level.chunkSource.chunkMap;
+        for (int index = 0, len = chunkMap.regionManagers.size(); index < len; ++index) {
+            chunkMap.regionManagers.get(index).removeChunk(holder.pos.x, holder.pos.z);
+        }
+    }
+
+    public static void onChunkBorder(final LevelChunk chunk, final ChunkHolder holder) {
+        chunk.playerChunk = holder;
+    }
+
+    public static void onChunkNotBorder(final LevelChunk chunk, final ChunkHolder holder) {
+
+    }
+
+    public static void onChunkTicking(final LevelChunk chunk, final ChunkHolder holder) {
+        chunk.level.getChunkSource().tickingChunks.add(chunk);
+    }
+
+    public static void onChunkNotTicking(final LevelChunk chunk, final ChunkHolder holder) {
+        chunk.level.getChunkSource().tickingChunks.remove(chunk);
+    }
+
+    public static void onChunkEntityTicking(final LevelChunk chunk, final ChunkHolder holder) {
+        chunk.level.getChunkSource().entityTickingChunks.add(chunk);
+    }
+
+    public static void onChunkNotEntityTicking(final LevelChunk chunk, final ChunkHolder holder) {
+        chunk.level.getChunkSource().entityTickingChunks.remove(chunk);
+    }
+
+    public static ChunkHolder getUnloadingChunkHolder(final ServerLevel level, final int chunkX, final int chunkZ) {
+        return level.chunkSource.chunkMap.getUnloadingChunkHolder(chunkX, chunkZ);
+    }
+
+    public static int getSendViewDistance(final ServerPlayer player) {
+        return getLoadViewDistance(player);
+    }
+
+    public static int getLoadViewDistance(final ServerPlayer player) {
+        final ServerLevel level = player.getLevel();
+        if (level == null) {
+            return Bukkit.getViewDistance() + 1;
+        }
+        return level.chunkSource.chunkMap.getEffectiveViewDistance() + 1;
+    }
+
+    public static int getTickViewDistance(final ServerPlayer player) {
+        final ServerLevel level = player.getLevel();
+        if (level == null) {
+            return Bukkit.getSimulationDistance();
+        }
+        return level.chunkSource.chunkMap.distanceManager.getSimulationDistance();
+    }
+
+    private ChunkSystem() {
+        throw new RuntimeException();
+    }
+}
diff --git a/src/main/java/io/papermc/paper/util/CachedLists.java b/src/main/java/io/papermc/paper/util/CachedLists.java
new file mode 100644
index 0000000000000000000000000000000000000000..be668387f65a633c6ac497fca632a4767a1bf3a2
--- /dev/null
+++ b/src/main/java/io/papermc/paper/util/CachedLists.java
@@ -0,0 +1,8 @@
+package io.papermc.paper.util;
+
+public final class CachedLists {
+
+    public static void reset() {
+
+    }
+}
diff --git a/src/main/java/io/papermc/paper/util/CoordinateUtils.java b/src/main/java/io/papermc/paper/util/CoordinateUtils.java
new file mode 100644
index 0000000000000000000000000000000000000000..413e4b6da027876dbbe8eb78f2568a440f431547
--- /dev/null
+++ b/src/main/java/io/papermc/paper/util/CoordinateUtils.java
@@ -0,0 +1,128 @@
+package io.papermc.paper.util;
+
+import net.minecraft.core.BlockPos;
+import net.minecraft.core.SectionPos;
+import net.minecraft.util.Mth;
+import net.minecraft.world.entity.Entity;
+import net.minecraft.world.level.ChunkPos;
+
+public final class CoordinateUtils {
+
+    // dx, dz are relative to the target chunk
+    // dx, dz in [-radius, radius]
+    public static int getNeighbourMappedIndex(final int dx, final int dz, final int radius) {
+        return (dx + radius) + (2 * radius + 1)*(dz + radius);
+    }
+
+    // the chunk keys are compatible with vanilla
+
+    public static long getChunkKey(final BlockPos pos) {
+        return ((long)(pos.getZ() >> 4) << 32) | ((pos.getX() >> 4) & 0xFFFFFFFFL);
+    }
+
+    public static long getChunkKey(final Entity entity) {
+        return ((Mth.lfloor(entity.getZ()) >> 4) << 32) | ((Mth.lfloor(entity.getX()) >> 4) & 0xFFFFFFFFL);
+    }
+
+    public static long getChunkKey(final ChunkPos pos) {
+        return ((long)pos.z << 32) | (pos.x & 0xFFFFFFFFL);
+    }
+
+    public static long getChunkKey(final SectionPos pos) {
+        return ((long)pos.getZ() << 32) | (pos.getX() & 0xFFFFFFFFL);
+    }
+
+    public static long getChunkKey(final int x, final int z) {
+        return ((long)z << 32) | (x & 0xFFFFFFFFL);
+    }
+
+    public static int getChunkX(final long chunkKey) {
+        return (int)chunkKey;
+    }
+
+    public static int getChunkZ(final long chunkKey) {
+        return (int)(chunkKey >>> 32);
+    }
+
+    public static int getChunkCoordinate(final double blockCoordinate) {
+        return Mth.floor(blockCoordinate) >> 4;
+    }
+
+    // the section keys are compatible with vanilla's
+
+    static final int SECTION_X_BITS = 22;
+    static final long SECTION_X_MASK = (1L << SECTION_X_BITS) - 1;
+    static final int SECTION_Y_BITS = 20;
+    static final long SECTION_Y_MASK = (1L << SECTION_Y_BITS) - 1;
+    static final int SECTION_Z_BITS = 22;
+    static final long SECTION_Z_MASK = (1L << SECTION_Z_BITS) - 1;
+    // format is y,z,x (in order of LSB to MSB)
+    static final int SECTION_Y_SHIFT = 0;
+    static final int SECTION_Z_SHIFT = SECTION_Y_SHIFT + SECTION_Y_BITS;
+    static final int SECTION_X_SHIFT = SECTION_Z_SHIFT + SECTION_X_BITS;
+    static final int SECTION_TO_BLOCK_SHIFT = 4;
+
+    public static long getChunkSectionKey(final int x, final int y, final int z) {
+        return ((x & SECTION_X_MASK) << SECTION_X_SHIFT)
+                | ((y & SECTION_Y_MASK) << SECTION_Y_SHIFT)
+                | ((z & SECTION_Z_MASK) << SECTION_Z_SHIFT);
+    }
+
+    public static long getChunkSectionKey(final SectionPos pos) {
+        return ((pos.getX() & SECTION_X_MASK) << SECTION_X_SHIFT)
+                | ((pos.getY() & SECTION_Y_MASK) << SECTION_Y_SHIFT)
+                | ((pos.getZ() & SECTION_Z_MASK) << SECTION_Z_SHIFT);
+    }
+
+    public static long getChunkSectionKey(final ChunkPos pos, final int y) {
+        return ((pos.x & SECTION_X_MASK) << SECTION_X_SHIFT)
+                | ((y & SECTION_Y_MASK) << SECTION_Y_SHIFT)
+                | ((pos.z & SECTION_Z_MASK) << SECTION_Z_SHIFT);
+    }
+
+    public static long getChunkSectionKey(final BlockPos pos) {
+        return (((long)pos.getX() << (SECTION_X_SHIFT - SECTION_TO_BLOCK_SHIFT)) & (SECTION_X_MASK << SECTION_X_SHIFT)) |
+                ((pos.getY() >> SECTION_TO_BLOCK_SHIFT) & (SECTION_Y_MASK << SECTION_Y_SHIFT)) |
+                (((long)pos.getZ() << (SECTION_Z_SHIFT - SECTION_TO_BLOCK_SHIFT)) & (SECTION_Z_MASK << SECTION_Z_SHIFT));
+    }
+
+    public static long getChunkSectionKey(final Entity entity) {
+        return ((Mth.lfloor(entity.getX()) << (SECTION_X_SHIFT - SECTION_TO_BLOCK_SHIFT)) & (SECTION_X_MASK << SECTION_X_SHIFT)) |
+                ((Mth.lfloor(entity.getY()) >> SECTION_TO_BLOCK_SHIFT) & (SECTION_Y_MASK << SECTION_Y_SHIFT)) |
+                ((Mth.lfloor(entity.getZ()) << (SECTION_Z_SHIFT - SECTION_TO_BLOCK_SHIFT)) & (SECTION_Z_MASK << SECTION_Z_SHIFT));
+    }
+
+    public static int getChunkSectionX(final long key) {
+        return (int)(key << (Long.SIZE - (SECTION_X_SHIFT + SECTION_X_BITS)) >> (Long.SIZE - SECTION_X_BITS));
+    }
+
+    public static int getChunkSectionY(final long key) {
+        return (int)(key << (Long.SIZE - (SECTION_Y_SHIFT + SECTION_Y_BITS)) >> (Long.SIZE - SECTION_Y_BITS));
+    }
+
+    public static int getChunkSectionZ(final long key) {
+        return (int)(key << (Long.SIZE - (SECTION_Z_SHIFT + SECTION_Z_BITS)) >> (Long.SIZE - SECTION_Z_BITS));
+    }
+
+    // the block coordinates are not necessarily compatible with vanilla's
+
+    public static int getBlockCoordinate(final double blockCoordinate) {
+        return Mth.floor(blockCoordinate);
+    }
+
+    public static long getBlockKey(final int x, final int y, final int z) {
+        return ((long)x & 0x7FFFFFF) | (((long)z & 0x7FFFFFF) << 27) | ((long)y << 54);
+    }
+
+    public static long getBlockKey(final BlockPos pos) {
+        return ((long)pos.getX() & 0x7FFFFFF) | (((long)pos.getZ() & 0x7FFFFFF) << 27) | ((long)pos.getY() << 54);
+    }
+
+    public static long getBlockKey(final Entity entity) {
+        return ((long)entity.getX() & 0x7FFFFFF) | (((long)entity.getZ() & 0x7FFFFFF) << 27) | ((long)entity.getY() << 54);
+    }
+
+    private CoordinateUtils() {
+        throw new RuntimeException();
+    }
+}
diff --git a/src/main/java/io/papermc/paper/util/IntegerUtil.java b/src/main/java/io/papermc/paper/util/IntegerUtil.java
new file mode 100644
index 0000000000000000000000000000000000000000..16785bd5c0524f6bad0691ca7ecd4514608d2eab
--- /dev/null
+++ b/src/main/java/io/papermc/paper/util/IntegerUtil.java
@@ -0,0 +1,242 @@
+package io.papermc.paper.util;
+
+public final class IntegerUtil {
+
+    public static final int HIGH_BIT_U32 = Integer.MIN_VALUE;
+    public static final long HIGH_BIT_U64 = Long.MIN_VALUE;
+
+    public static int ceilLog2(final int value) {
+        return Integer.SIZE - Integer.numberOfLeadingZeros(value - 1); // see doc of numberOfLeadingZeros
+    }
+
+    public static long ceilLog2(final long value) {
+        return Long.SIZE - Long.numberOfLeadingZeros(value - 1); // see doc of numberOfLeadingZeros
+    }
+
+    public static int floorLog2(final int value) {
+        // xor is optimized subtract for 2^n -1
+        // note that (2^n -1) - k = (2^n -1) ^ k for k <= (2^n - 1)
+        return (Integer.SIZE - 1) ^ Integer.numberOfLeadingZeros(value); // see doc of numberOfLeadingZeros
+    }
+
+    public static int floorLog2(final long value) {
+        // xor is optimized subtract for 2^n -1
+        // note that (2^n -1) - k = (2^n -1) ^ k for k <= (2^n - 1)
+        return (Long.SIZE - 1) ^ Long.numberOfLeadingZeros(value); // see doc of numberOfLeadingZeros
+    }
+
+    public static int roundCeilLog2(final int value) {
+        // optimized variant of 1 << (32 - leading(val - 1))
+        // given
+        // 1 << n = HIGH_BIT_32 >>> (31 - n) for n [0, 32)
+        // 1 << (32 - leading(val - 1)) = HIGH_BIT_32 >>> (31 - (32 - leading(val - 1)))
+        // HIGH_BIT_32 >>> (31 - (32 - leading(val - 1)))
+        // HIGH_BIT_32 >>> (31 - 32 + leading(val - 1))
+        // HIGH_BIT_32 >>> (-1 + leading(val - 1))
+        return HIGH_BIT_U32 >>> (Integer.numberOfLeadingZeros(value - 1) - 1);
+    }
+
+    public static long roundCeilLog2(final long value) {
+        // see logic documented above
+        return HIGH_BIT_U64 >>> (Long.numberOfLeadingZeros(value - 1) - 1);
+    }
+
+    public static int roundFloorLog2(final int value) {
+        // optimized variant of 1 << (31 - leading(val))
+        // given
+        // 1 << n = HIGH_BIT_32 >>> (31 - n) for n [0, 32)
+        // 1 << (31 - leading(val)) = HIGH_BIT_32 >> (31 - (31 - leading(val)))
+        // HIGH_BIT_32 >> (31 - (31 - leading(val)))
+        // HIGH_BIT_32 >> (31 - 31 + leading(val))
+        return HIGH_BIT_U32 >>> Integer.numberOfLeadingZeros(value);
+    }
+
+    public static long roundFloorLog2(final long value) {
+        // see logic documented above
+        return HIGH_BIT_U64 >>> Long.numberOfLeadingZeros(value);
+    }
+
+    public static boolean isPowerOfTwo(final int n) {
+        // 2^n has one bit
+        // note: this rets true for 0 still
+        return IntegerUtil.getTrailingBit(n) == n;
+    }
+
+    public static boolean isPowerOfTwo(final long n) {
+        // 2^n has one bit
+        // note: this rets true for 0 still
+        return IntegerUtil.getTrailingBit(n) == n;
+    }
+
+    public static int getTrailingBit(final int n) {
+        return -n & n;
+    }
+
+    public static long getTrailingBit(final long n) {
+        return -n & n;
+    }
+
+    public static int trailingZeros(final int n) {
+        return Integer.numberOfTrailingZeros(n);
+    }
+
+    public static int trailingZeros(final long n) {
+        return Long.numberOfTrailingZeros(n);
+    }
+
+    // from hacker's delight (signed division magic value)
+    public static int getDivisorMultiple(final long numbers) {
+        return (int)(numbers >>> 32);
+    }
+
+    // from hacker's delight (signed division magic value)
+    public static int getDivisorShift(final long numbers) {
+        return (int)numbers;
+    }
+
+    // copied from hacker's delight (signed division magic value)
+    // http://www.hackersdelight.org/hdcodetxt/magic.c.txt
+    public static long getDivisorNumbers(final int d) {
+        final int ad = branchlessAbs(d);
+
+        if (ad < 2) {
+            throw new IllegalArgumentException("|number| must be in [2, 2^31 -1], not: " + d);
+        }
+
+        final int two31 = 0x80000000;
+        final long mask = 0xFFFFFFFFL; // mask for enforcing unsigned behaviour
+
+        /*
+         Signed usage:
+         int number;
+         long magic = getDivisorNumbers(div);
+         long mul = magic >>> 32;
+         int sign = number >> 31;
+         int result = (int)(((long)number * mul) >>> magic) - sign;
+         */
+        /*
+         Unsigned usage:
+         int number;
+         long magic = getDivisorNumbers(div);
+         long mul = magic >>> 32;
+         int result = (int)(((long)number * mul) >>> magic);
+         */
+
+        int p = 31;
+
+        // all these variables are UNSIGNED!
+        int t = two31 + (d >>> 31);
+        int anc = t - 1 - (int)((t & mask)%ad);
+        int q1 = (int)((two31 & mask)/(anc & mask));
+        int r1 = two31 - q1*anc;
+        int q2 = (int)((two31 & mask)/(ad & mask));
+        int r2 = two31 - q2*ad;
+        int delta;
+
+        do {
+            p = p + 1;
+            q1 = 2*q1;                        // Update q1 = 2**p/|nc|.
+            r1 = 2*r1;                        // Update r1 = rem(2**p, |nc|).
+            if ((r1 & mask) >= (anc & mask)) {// (Must be an unsigned comparison here)
+                q1 = q1 + 1;
+                r1 = r1 - anc;
+            }
+            q2 = 2*q2;                       // Update q2 = 2**p/|d|.
+            r2 = 2*r2;                       // Update r2 = rem(2**p, |d|).
+            if ((r2 & mask) >= (ad & mask)) {// (Must be an unsigned comparison here)
+                q2 = q2 + 1;
+                r2 = r2 - ad;
+            }
+            delta = ad - r2;
+        } while ((q1 & mask) < (delta & mask) || (q1 == delta && r1 == 0));
+
+        int magicNum = q2 + 1;
+        if (d < 0) {
+            magicNum = -magicNum;
+        }
+        int shift = p;
+        return ((long)magicNum << 32) | shift;
+    }
+
+    public static int branchlessAbs(final int val) {
+        // -n = -1 ^ n + 1
+        final int mask = val >> (Integer.SIZE - 1); // -1 if < 0, 0 if >= 0
+        return (mask ^ val) - mask; // if val < 0, then (0 ^ val) - 0 else (-1 ^ val) + 1
+    }
+
+    public static long branchlessAbs(final long val) {
+        // -n = -1 ^ n + 1
+        final long mask = val >> (Long.SIZE - 1); // -1 if < 0, 0 if >= 0
+        return (mask ^ val) - mask; // if val < 0, then (0 ^ val) - 0 else (-1 ^ val) + 1
+    }
+
+    //https://github.com/skeeto/hash-prospector for hash functions
+
+    //score = ~590.47984224483832
+    public static int hash0(int x) {
+        x *= 0x36935555;
+        x ^= x >>> 16;
+        return x;
+    }
+
+    //score = ~310.01596637036749
+    public static int hash1(int x) {
+        x ^= x >>> 15;
+        x *= 0x356aaaad;
+        x ^= x >>> 17;
+        return x;
+    }
+
+    public static int hash2(int x) {
+        x ^= x >>> 16;
+        x *= 0x7feb352d;
+        x ^= x >>> 15;
+        x *= 0x846ca68b;
+        x ^= x >>> 16;
+        return x;
+    }
+
+    public static int hash3(int x) {
+        x ^= x >>> 17;
+        x *= 0xed5ad4bb;
+        x ^= x >>> 11;
+        x *= 0xac4c1b51;
+        x ^= x >>> 15;
+        x *= 0x31848bab;
+        x ^= x >>> 14;
+        return x;
+    }
+
+    //score = ~365.79959673201887
+    public static long hash1(long x) {
+        x ^= x >>> 27;
+        x *= 0xb24924b71d2d354bL;
+        x ^= x >>> 28;
+        return x;
+    }
+
+    //h2 hash
+    public static long hash2(long x) {
+        x ^= x >>> 32;
+        x *= 0xd6e8feb86659fd93L;
+        x ^= x >>> 32;
+        x *= 0xd6e8feb86659fd93L;
+        x ^= x >>> 32;
+        return x;
+    }
+
+    public static long hash3(long x) {
+        x ^= x >>> 45;
+        x *= 0xc161abe5704b6c79L;
+        x ^= x >>> 41;
+        x *= 0xe3e5389aedbc90f7L;
+        x ^= x >>> 56;
+        x *= 0x1f9aba75a52db073L;
+        x ^= x >>> 53;
+        return x;
+    }
+
+    private IntegerUtil() {
+        throw new RuntimeException();
+    }
+}
diff --git a/src/main/java/io/papermc/paper/util/IntervalledCounter.java b/src/main/java/io/papermc/paper/util/IntervalledCounter.java
new file mode 100644
index 0000000000000000000000000000000000000000..cea9c098ade00ee87b8efc8164ab72f5279758f0
--- /dev/null
+++ b/src/main/java/io/papermc/paper/util/IntervalledCounter.java
@@ -0,0 +1,115 @@
+package io.papermc.paper.util;
+
+public final class IntervalledCounter {
+
+    protected long[] times;
+    protected long[] counts;
+    protected final long interval;
+    protected long minTime;
+    protected long sum;
+    protected int head; // inclusive
+    protected int tail; // exclusive
+
+    public IntervalledCounter(final long interval) {
+        this.times = new long[8];
+        this.counts = new long[8];
+        this.interval = interval;
+    }
+
+    public void updateCurrentTime() {
+        this.updateCurrentTime(System.nanoTime());
+    }
+
+    public void updateCurrentTime(final long currentTime) {
+        long sum = this.sum;
+        int head = this.head;
+        final int tail = this.tail;
+        final long minTime = currentTime - this.interval;
+
+        final int arrayLen = this.times.length;
+
+        // guard against overflow by using subtraction
+        while (head != tail && this.times[head] - minTime < 0) {
+            sum -= this.counts[head];
+            // there are two ways we can do this:
+            // 1. free the count when adding
+            // 2. free it now
+            // option #2
+            this.counts[head] = 0;
+            if (++head >= arrayLen) {
+                head = 0;
+            }
+        }
+
+        this.sum = sum;
+        this.head = head;
+        this.minTime = minTime;
+    }
+
+    public void addTime(final long currTime) {
+        this.addTime(currTime, 1L);
+    }
+
+    public void addTime(final long currTime, final long count) {
+        // guard against overflow by using subtraction
+        if (currTime - this.minTime < 0) {
+            return;
+        }
+        int nextTail = (this.tail + 1) % this.times.length;
+        if (nextTail == this.head) {
+            this.resize();
+            nextTail = (this.tail + 1) % this.times.length;
+        }
+
+        this.times[this.tail] = currTime;
+        this.counts[this.tail] += count;
+        this.sum += count;
+        this.tail = nextTail;
+    }
+
+    public void updateAndAdd(final int count) {
+        final long currTime = System.nanoTime();
+        this.updateCurrentTime(currTime);
+        this.addTime(currTime, count);
+    }
+
+    public void updateAndAdd(final int count, final long currTime) {
+        this.updateCurrentTime(currTime);
+        this.addTime(currTime, count);
+    }
+
+    private void resize() {
+        final long[] oldElements = this.times;
+        final long[] oldCounts = this.counts;
+        final long[] newElements = new long[this.times.length * 2];
+        final long[] newCounts = new long[this.times.length * 2];
+        this.times = newElements;
+        this.counts = newCounts;
+
+        final int head = this.head;
+        final int tail = this.tail;
+        final int size = tail >= head ? (tail - head) : (tail + (oldElements.length - head));
+        this.head = 0;
+        this.tail = size;
+
+        if (tail >= head) {
+            System.arraycopy(oldElements, head, newElements, 0, size);
+            System.arraycopy(oldCounts, head, newCounts, 0, size);
+        } else {
+            System.arraycopy(oldElements, head, newElements, 0, oldElements.length - head);
+            System.arraycopy(oldElements, 0, newElements, oldElements.length - head, tail);
+
+            System.arraycopy(oldCounts, head, newCounts, 0, oldCounts.length - head);
+            System.arraycopy(oldCounts, 0, newCounts, oldCounts.length - head, tail);
+        }
+    }
+
+    // returns in units per second
+    public double getRate() {
+        return this.size() / (this.interval * 1.0e-9);
+    }
+
+    public long size() {
+        return this.sum;
+    }
+}
diff --git a/src/main/java/io/papermc/paper/util/MCUtil.java b/src/main/java/io/papermc/paper/util/MCUtil.java
new file mode 100644
index 0000000000000000000000000000000000000000..9572294a50110f2452090da1f32e0a73edc3db05
--- /dev/null
+++ b/src/main/java/io/papermc/paper/util/MCUtil.java
@@ -0,0 +1,534 @@
+package io.papermc.paper.util;
+
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import io.papermc.paper.math.BlockPosition;
+import io.papermc.paper.math.FinePosition;
+import io.papermc.paper.math.Position;
+import it.unimi.dsi.fastutil.objects.ObjectRBTreeSet;
+import java.lang.ref.Cleaner;
+import net.minecraft.core.BlockPos;
+import net.minecraft.core.Direction;
+import net.minecraft.core.Vec3i;
+import net.minecraft.server.MinecraftServer;
+import net.minecraft.server.level.ServerLevel;
+import net.minecraft.world.entity.Entity;
+import net.minecraft.world.level.ChunkPos;
+import net.minecraft.world.level.ClipContext;
+import net.minecraft.world.level.Level;
+import net.minecraft.world.phys.Vec3;
+import org.apache.commons.lang.exception.ExceptionUtils;
+import org.bukkit.Location;
+import org.bukkit.block.BlockFace;
+import org.bukkit.craftbukkit.CraftWorld;
+import org.bukkit.craftbukkit.util.Waitable;
+import org.bukkit.util.Vector;
+import org.spigotmc.AsyncCatcher;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+
+public final class MCUtil {
+    public static final ThreadPoolExecutor asyncExecutor = new ThreadPoolExecutor(
+        0, 2, 60L, TimeUnit.SECONDS,
+        new LinkedBlockingQueue<>(),
+        new ThreadFactoryBuilder()
+            .setNameFormat("Paper Async Task Handler Thread - %1$d")
+            .setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(MinecraftServer.LOGGER))
+            .build()
+    );
+    public static final ThreadPoolExecutor cleanerExecutor = new ThreadPoolExecutor(
+        1, 1, 0L, TimeUnit.SECONDS,
+        new LinkedBlockingQueue<>(),
+        new ThreadFactoryBuilder()
+            .setNameFormat("Paper Object Cleaner")
+            .setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(MinecraftServer.LOGGER))
+            .build()
+    );
+
+    public static final long INVALID_CHUNK_KEY = getCoordinateKey(Integer.MAX_VALUE, Integer.MAX_VALUE);
+
+
+    public static Runnable once(Runnable run) {
+        AtomicBoolean ran = new AtomicBoolean(false);
+        return () -> {
+            if (ran.compareAndSet(false, true)) {
+                run.run();
+            }
+        };
+    }
+
+    public static <T> Runnable once(List<T> list, Consumer<T> cb) {
+        return once(() -> {
+            list.forEach(cb);
+        });
+    }
+
+    private static Runnable makeCleanerCallback(Runnable run) {
+        return once(() -> cleanerExecutor.execute(run));
+    }
+
+    /**
+     * DANGER WILL ROBINSON: Be sure you do not use a lambda that lives in the object being monitored, or leaky leaky!
+     * @param obj
+     * @param run
+     * @return
+     */
+    public static Runnable registerCleaner(Object obj, Runnable run) {
+        // Wrap callback in its own method above or the lambda will leak object
+        Runnable cleaner = makeCleanerCallback(run);
+        CleanerHolder.CLEANER.register(obj, cleaner);
+        return cleaner;
+    }
+
+    private static final class CleanerHolder {
+        private static final Cleaner CLEANER = Cleaner.create();
+    }
+
+    /**
+     * DANGER WILL ROBINSON: Be sure you do not use a lambda that lives in the object being monitored, or leaky leaky!
+     * @param obj
+     * @param list
+     * @param cleaner
+     * @param <T>
+     * @return
+     */
+    public static <T> Runnable registerListCleaner(Object obj, List<T> list, Consumer<T> cleaner) {
+        return registerCleaner(obj, () -> {
+            list.forEach(cleaner);
+            list.clear();
+        });
+    }
+
+    /**
+     * DANGER WILL ROBINSON: Be sure you do not use a lambda that lives in the object being monitored, or leaky leaky!
+     * @param obj
+     * @param resource
+     * @param cleaner
+     * @param <T>
+     * @return
+     */
+    public static <T> Runnable registerCleaner(Object obj, T resource, java.util.function.Consumer<T> cleaner) {
+        return registerCleaner(obj, () -> cleaner.accept(resource));
+    }
+
+    public static List<ChunkPos> getSpiralOutChunks(BlockPos blockposition, int radius) {
+        List<ChunkPos> list = com.google.common.collect.Lists.newArrayList();
+
+        list.add(new ChunkPos(blockposition.getX() >> 4, blockposition.getZ() >> 4));
+        for (int r = 1; r <= radius; r++) {
+            int x = -r;
+            int z = r;
+
+            // Iterates the edge of half of the box; then negates for other half.
+            while (x <= r && z > -r) {
+                list.add(new ChunkPos((blockposition.getX() + (x << 4)) >> 4, (blockposition.getZ() + (z << 4)) >> 4));
+                list.add(new ChunkPos((blockposition.getX() - (x << 4)) >> 4, (blockposition.getZ() - (z << 4)) >> 4));
+
+                if (x < r) {
+                    x++;
+                } else {
+                    z--;
+                }
+            }
+        }
+        return list;
+    }
+
+    public static int fastFloor(double x) {
+        int truncated = (int)x;
+        return x < (double)truncated ? truncated - 1 : truncated;
+    }
+
+    public static int fastFloor(float x) {
+        int truncated = (int)x;
+        return x < (double)truncated ? truncated - 1 : truncated;
+    }
+
+    public static float normalizeYaw(float f) {
+        float f1 = f % 360.0F;
+
+        if (f1 >= 180.0F) {
+            f1 -= 360.0F;
+        }
+
+        if (f1 < -180.0F) {
+            f1 += 360.0F;
+        }
+
+        return f1;
+    }
+
+    /**
+     * Quickly generate a stack trace for current location
+     *
+     * @return Stacktrace
+     */
+    public static String stack() {
+        return ExceptionUtils.getFullStackTrace(new Throwable());
+    }
+
+    /**
+     * Quickly generate a stack trace for current location with message
+     *
+     * @param str
+     * @return Stacktrace
+     */
+    public static String stack(String str) {
+        return ExceptionUtils.getFullStackTrace(new Throwable(str));
+    }
+
+    public static long getCoordinateKey(final BlockPos blockPos) {
+        return ((long)(blockPos.getZ() >> 4) << 32) | ((blockPos.getX() >> 4) & 0xFFFFFFFFL);
+    }
+
+    public static long getCoordinateKey(final Entity entity) {
+        return ((long)(MCUtil.fastFloor(entity.getZ()) >> 4) << 32) | ((MCUtil.fastFloor(entity.getX()) >> 4) & 0xFFFFFFFFL);
+    }
+
+    public static long getCoordinateKey(final ChunkPos pair) {
+        return ((long)pair.z << 32) | (pair.x & 0xFFFFFFFFL);
+    }
+
+    public static long getCoordinateKey(final int x, final int z) {
+        return ((long)z << 32) | (x & 0xFFFFFFFFL);
+    }
+
+    public static int getCoordinateX(final long key) {
+        return (int)key;
+    }
+
+    public static int getCoordinateZ(final long key) {
+        return (int)(key >>> 32);
+    }
+
+    public static int getChunkCoordinate(final double coordinate) {
+        return MCUtil.fastFloor(coordinate) >> 4;
+    }
+
+    public static int getBlockCoordinate(final double coordinate) {
+        return MCUtil.fastFloor(coordinate);
+    }
+
+    public static long getBlockKey(final int x, final int y, final int z) {
+        return ((long)x & 0x7FFFFFF) | (((long)z & 0x7FFFFFF) << 27) | ((long)y << 54);
+    }
+
+    public static long getBlockKey(final BlockPos pos) {
+        return ((long)pos.getX() & 0x7FFFFFF) | (((long)pos.getZ() & 0x7FFFFFF) << 27) | ((long)pos.getY() << 54);
+    }
+
+    public static long getBlockKey(final Entity entity) {
+        return getBlockKey(getBlockCoordinate(entity.getX()), getBlockCoordinate(entity.getY()), getBlockCoordinate(entity.getZ()));
+    }
+
+    // assumes the sets have the same comparator, and if this comparator is null then assume T is Comparable
+    public static <T> void mergeSortedSets(final java.util.function.Consumer<T> consumer, final java.util.Comparator<? super T> comparator, final java.util.SortedSet<T>...sets) {
+        final ObjectRBTreeSet<T> all = new ObjectRBTreeSet<>(comparator);
+        // note: this is done in log(n!) ~ nlogn time. It could be improved if it were to mimic what mergesort does.
+        for (java.util.SortedSet<T> set : sets) {
+            if (set != null) {
+                all.addAll(set);
+            }
+        }
+        all.forEach(consumer);
+    }
+
+    private MCUtil() {}
+
+    public static final java.util.concurrent.Executor MAIN_EXECUTOR = (run) -> {
+        if (!isMainThread()) {
+            MinecraftServer.getServer().execute(run);
+        } else {
+            run.run();
+        }
+    };
+
+    public static <T> CompletableFuture<T> ensureMain(CompletableFuture<T> future) {
+        return future.thenApplyAsync(r -> r, MAIN_EXECUTOR);
+    }
+
+    public static <T> void thenOnMain(CompletableFuture<T> future, Consumer<T> consumer) {
+        future.thenAcceptAsync(consumer, MAIN_EXECUTOR);
+    }
+    public static <T> void thenOnMain(CompletableFuture<T> future, BiConsumer<T, Throwable> consumer) {
+        future.whenCompleteAsync(consumer, MAIN_EXECUTOR);
+    }
+
+    public static boolean isMainThread() {
+        return MinecraftServer.getServer().isSameThread();
+    }
+
+    public static org.bukkit.scheduler.BukkitTask scheduleTask(int ticks, Runnable runnable) {
+        return scheduleTask(ticks, runnable, null);
+    }
+
+    public static org.bukkit.scheduler.BukkitTask scheduleTask(int ticks, Runnable runnable, String taskName) {
+        return MinecraftServer.getServer().server.getScheduler().scheduleInternalTask(runnable, ticks, taskName);
+    }
+
+    public static void processQueue() {
+        Runnable runnable;
+        Queue<Runnable> processQueue = getProcessQueue();
+        while ((runnable = processQueue.poll()) != null) {
+            try {
+                runnable.run();
+            } catch (Exception e) {
+                MinecraftServer.LOGGER.error("Error executing task", e);
+            }
+        }
+    }
+    public static <T> T processQueueWhileWaiting(CompletableFuture <T> future) {
+        try {
+            if (isMainThread()) {
+                while (!future.isDone()) {
+                    try {
+                        return future.get(1, TimeUnit.MILLISECONDS);
+                    } catch (TimeoutException ignored) {
+                        processQueue();
+                    }
+                }
+            }
+            return future.get();
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    public static void ensureMain(Runnable run) {
+        ensureMain(null, run);
+    }
+    /**
+     * Ensures the target code is running on the main thread
+     * @param reason
+     * @param run
+     * @return
+     */
+    public static void ensureMain(String reason, Runnable run) {
+        if (!isMainThread()) {
+            if (reason != null) {
+                MinecraftServer.LOGGER.warn("Asynchronous " + reason + "!", new IllegalStateException());
+            }
+            getProcessQueue().add(run);
+            return;
+        }
+        run.run();
+    }
+
+    private static Queue<Runnable> getProcessQueue() {
+        return MinecraftServer.getServer().processQueue;
+    }
+
+    public static <T> T ensureMain(Supplier<T> run) {
+        return ensureMain(null, run);
+    }
+    /**
+     * Ensures the target code is running on the main thread
+     * @param reason
+     * @param run
+     * @param <T>
+     * @return
+     */
+    public static <T> T ensureMain(String reason, Supplier<T> run) {
+        if (!isMainThread()) {
+            if (reason != null) {
+                MinecraftServer.LOGGER.warn("Asynchronous " + reason + "! Blocking thread until it returns ", new IllegalStateException());
+            }
+            Waitable<T> wait = new Waitable<T>() {
+                @Override
+                protected T evaluate() {
+                    return run.get();
+                }
+            };
+            getProcessQueue().add(wait);
+            try {
+                return wait.get();
+            } catch (InterruptedException | ExecutionException e) {
+                MinecraftServer.LOGGER.warn("Encountered exception", e);
+            }
+            return null;
+        }
+        return run.get();
+    }
+
+    /**
+     * Calculates distance between 2 entities
+     * @param e1
+     * @param e2
+     * @return
+     */
+    public static double distance(Entity e1, Entity e2) {
+        return Math.sqrt(distanceSq(e1, e2));
+    }
+
+
+    /**
+     * Calculates distance between 2 block positions
+     * @param e1
+     * @param e2
+     * @return
+     */
+    public static double distance(BlockPos e1, BlockPos e2) {
+        return Math.sqrt(distanceSq(e1, e2));
+    }
+
+    /**
+     * Gets the distance between 2 positions
+     * @param x1
+     * @param y1
+     * @param z1
+     * @param x2
+     * @param y2
+     * @param z2
+     * @return
+     */
+    public static double distance(double x1, double y1, double z1, double x2, double y2, double z2) {
+        return Math.sqrt(distanceSq(x1, y1, z1, x2, y2, z2));
+    }
+
+    /**
+     * Get's the distance squared between 2 entities
+     * @param e1
+     * @param e2
+     * @return
+     */
+    public static double distanceSq(Entity e1, Entity e2) {
+        return distanceSq(e1.getX(),e1.getY(),e1.getZ(), e2.getX(),e2.getY(),e2.getZ());
+    }
+
+    /**
+     * Gets the distance sqaured between 2 block positions
+     * @param pos1
+     * @param pos2
+     * @return
+     */
+    public static double distanceSq(BlockPos pos1, BlockPos pos2) {
+        return distanceSq(pos1.getX(), pos1.getY(), pos1.getZ(), pos2.getX(), pos2.getY(), pos2.getZ());
+    }
+
+    /**
+     * Gets the distance squared between 2 positions
+     * @param x1
+     * @param y1
+     * @param z1
+     * @param x2
+     * @param y2
+     * @param z2
+     * @return
+     */
+    public static double distanceSq(double x1, double y1, double z1, double x2, double y2, double z2) {
+        return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2);
+    }
+
+    /**
+     * Converts a NMS World/BlockPosition to Bukkit Location
+     * @param world
+     * @param x
+     * @param y
+     * @param z
+     * @return
+     */
+    public static Location toLocation(Level world, double x, double y, double z) {
+        return new Location(world.getWorld(), x, y, z);
+    }
+
+    /**
+     * Converts a NMS World/BlockPosition to Bukkit Location
+     * @param world
+     * @param pos
+     * @return
+     */
+    public static Location toLocation(Level world, BlockPos pos) {
+        return new Location(world.getWorld(), pos.getX(), pos.getY(), pos.getZ());
+    }
+
+    /**
+     * Converts an NMS entity's current location to a Bukkit Location
+     * @param entity
+     * @return
+     */
+    public static Location toLocation(Entity entity) {
+        return new Location(entity.getCommandSenderWorld().getWorld(), entity.getX(), entity.getY(), entity.getZ());
+    }
+
+    public static org.bukkit.block.Block toBukkitBlock(Level world, BlockPos pos) {
+        return world.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ());
+    }
+
+    public static BlockPos toBlockPosition(Location loc) {
+        return new BlockPos(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
+    }
+
+    public static BlockPos toBlockPos(Position pos) {
+        return new BlockPos(pos.blockX(), pos.blockY(), pos.blockZ());
+    }
+
+    public static BlockPos toBlockPosition(Vector vec) {
+        return new BlockPos(vec.getBlockX(), vec.getBlockY(), vec.getBlockZ());
+    }
+
+    public static FinePosition toPosition(Vec3 vector) {
+        return Position.fine(vector.x, vector.y, vector.z);
+    }
+
+    public static BlockPosition toPosition(Vec3i vector) {
+        return Position.block(vector.getX(), vector.getY(), vector.getZ());
+    }
+
+    public static boolean isEdgeOfChunk(BlockPos pos) {
+        final int modX = pos.getX() & 15;
+        final int modZ = pos.getZ() & 15;
+        return (modX == 0 || modX == 15 || modZ == 0 || modZ == 15);
+    }
+
+    /**
+     * Posts a task to be executed asynchronously
+     * @param run
+     */
+    public static void scheduleAsyncTask(Runnable run) {
+        asyncExecutor.execute(run);
+    }
+
+    @Nonnull
+    public static ServerLevel getNMSWorld(@Nonnull org.bukkit.World world) {
+        return ((CraftWorld) world).getHandle();
+    }
+
+    public static ServerLevel getNMSWorld(@Nonnull org.bukkit.entity.Entity entity) {
+        return getNMSWorld(entity.getWorld());
+    }
+
+    public static BlockFace toBukkitBlockFace(Direction enumDirection) {
+        switch (enumDirection) {
+            case DOWN:
+                return BlockFace.DOWN;
+            case UP:
+                return BlockFace.UP;
+            case NORTH:
+                return BlockFace.NORTH;
+            case SOUTH:
+                return BlockFace.SOUTH;
+            case WEST:
+                return BlockFace.WEST;
+            case EAST:
+                return BlockFace.EAST;
+            default:
+                return null;
+        }
+    }
+
+    public static int getTicketLevelFor(net.minecraft.world.level.chunk.ChunkStatus status) {
+        return net.minecraft.server.level.ChunkMap.MAX_VIEW_DISTANCE + net.minecraft.world.level.chunk.ChunkStatus.getDistance(status);
+    }
+}
diff --git a/src/main/java/io/papermc/paper/util/StackWalkerUtil.java b/src/main/java/io/papermc/paper/util/StackWalkerUtil.java
new file mode 100644
index 0000000000000000000000000000000000000000..f7114d5b8f2f93f62883e24da29afaf9f74ee1a6
--- /dev/null
+++ b/src/main/java/io/papermc/paper/util/StackWalkerUtil.java
@@ -0,0 +1,24 @@
+package io.papermc.paper.util;
+
+import org.bukkit.plugin.java.JavaPlugin;
+import org.bukkit.plugin.java.PluginClassLoader;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.Optional;
+
+public class StackWalkerUtil {
+
+    @Nullable
+    public static JavaPlugin getFirstPluginCaller() {
+        Optional<JavaPlugin> foundFrame = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
+            .walk(stream -> stream
+                .filter(frame -> frame.getDeclaringClass().getClassLoader() instanceof PluginClassLoader)
+                .map((frame) -> {
+                    PluginClassLoader classLoader = (PluginClassLoader) frame.getDeclaringClass().getClassLoader();
+                    return classLoader.getPlugin();
+                })
+                .findFirst());
+
+        return foundFrame.orElse(null);
+    }
+}
diff --git a/src/main/java/io/papermc/paper/util/WorldUtil.java b/src/main/java/io/papermc/paper/util/WorldUtil.java
new file mode 100644
index 0000000000000000000000000000000000000000..67bb91fcfb532a919954cd9d7733d09a6c3fec35
--- /dev/null
+++ b/src/main/java/io/papermc/paper/util/WorldUtil.java
@@ -0,0 +1,46 @@
+package io.papermc.paper.util;
+
+import net.minecraft.world.level.LevelHeightAccessor;
+
+public final class WorldUtil {
+
+    // min, max are inclusive
+
+    public static int getMaxSection(final LevelHeightAccessor world) {
+        return world.getMaxSection() - 1; // getMaxSection() is exclusive
+    }
+
+    public static int getMinSection(final LevelHeightAccessor world) {
+        return world.getMinSection();
+    }
+
+    public static int getMaxLightSection(final LevelHeightAccessor world) {
+        return getMaxSection(world) + 1;
+    }
+
+    public static int getMinLightSection(final LevelHeightAccessor world) {
+        return getMinSection(world) - 1;
+    }
+
+
+
+    public static int getTotalSections(final LevelHeightAccessor world) {
+        return getMaxSection(world) - getMinSection(world) + 1;
+    }
+
+    public static int getTotalLightSections(final LevelHeightAccessor world) {
+        return getMaxLightSection(world) - getMinLightSection(world) + 1;
+    }
+
+    public static int getMinBlockY(final LevelHeightAccessor world) {
+        return getMinSection(world) << 4;
+    }
+
+    public static int getMaxBlockY(final LevelHeightAccessor world) {
+        return (getMaxSection(world) << 4) | 15;
+    }
+
+    private WorldUtil() {
+        throw new RuntimeException();
+    }
+}
diff --git a/src/main/java/io/papermc/paper/util/maplist/IteratorSafeOrderedReferenceSet.java b/src/main/java/io/papermc/paper/util/maplist/IteratorSafeOrderedReferenceSet.java
new file mode 100644
index 0000000000000000000000000000000000000000..0fd814f1d65c111266a2b20f86561839a4cef755
--- /dev/null
+++ b/src/main/java/io/papermc/paper/util/maplist/IteratorSafeOrderedReferenceSet.java
@@ -0,0 +1,334 @@
+package io.papermc.paper.util.maplist;
+
+import it.unimi.dsi.fastutil.objects.Reference2IntLinkedOpenHashMap;
+import it.unimi.dsi.fastutil.objects.Reference2IntMap;
+import org.bukkit.Bukkit;
+import java.util.Arrays;
+import java.util.NoSuchElementException;
+
+public final class IteratorSafeOrderedReferenceSet<E> {
+
+    public static final int ITERATOR_FLAG_SEE_ADDITIONS = 1 << 0;
+
+    protected final Reference2IntLinkedOpenHashMap<E> indexMap;
+    protected int firstInvalidIndex = -1;
+
+    /* list impl */
+    protected E[] listElements;
+    protected int listSize;
+
+    protected final double maxFragFactor;
+
+    protected int iteratorCount;
+
+    private final boolean threadRestricted;
+
+    public IteratorSafeOrderedReferenceSet() {
+        this(16, 0.75f, 16, 0.2);
+    }
+
+    public IteratorSafeOrderedReferenceSet(final boolean threadRestricted) {
+        this(16, 0.75f, 16, 0.2, threadRestricted);
+    }
+
+    public IteratorSafeOrderedReferenceSet(final int setCapacity, final float setLoadFactor, final int arrayCapacity,
+                                           final double maxFragFactor) {
+        this(setCapacity, setLoadFactor, arrayCapacity, maxFragFactor, false);
+    }
+    public IteratorSafeOrderedReferenceSet(final int setCapacity, final float setLoadFactor, final int arrayCapacity,
+                                           final double maxFragFactor, final boolean threadRestricted) {
+        this.indexMap = new Reference2IntLinkedOpenHashMap<>(setCapacity, setLoadFactor);
+        this.indexMap.defaultReturnValue(-1);
+        this.maxFragFactor = maxFragFactor;
+        this.listElements = (E[])new Object[arrayCapacity];
+        this.threadRestricted = threadRestricted;
+    }
+
+    /*
+    public void check() {
+        int iterated = 0;
+        ReferenceOpenHashSet<E> check = new ReferenceOpenHashSet<>();
+        if (this.listElements != null) {
+            for (int i = 0; i < this.listSize; ++i) {
+                Object obj = this.listElements[i];
+                if (obj != null) {
+                    iterated++;
+                    if (!check.add((E)obj)) {
+                        throw new IllegalStateException("contains duplicate");
+                    }
+                    if (!this.contains((E)obj)) {
+                        throw new IllegalStateException("desync");
+                    }
+                }
+            }
+        }
+
+        if (iterated != this.size()) {
+            throw new IllegalStateException("Size is mismatched! Got " + iterated + ", expected " + this.size());
+        }
+
+        check.clear();
+        iterated = 0;
+        for (final java.util.Iterator<E> iterator = this.unsafeIterator(IteratorSafeOrderedReferenceSet.ITERATOR_FLAG_SEE_ADDITIONS); iterator.hasNext();) {
+            final E element = iterator.next();
+            iterated++;
+            if (!check.add(element)) {
+                throw new IllegalStateException("contains duplicate (iterator is wrong)");
+            }
+            if (!this.contains(element)) {
+                throw new IllegalStateException("desync (iterator is wrong)");
+            }
+        }
+
+        if (iterated != this.size()) {
+            throw new IllegalStateException("Size is mismatched! (iterator is wrong) Got " + iterated + ", expected " + this.size());
+        }
+    }
+    */
+
+    protected final boolean allowSafeIteration() {
+        return !this.threadRestricted || Bukkit.isPrimaryThread();
+    }
+
+    protected final double getFragFactor() {
+        return 1.0 - ((double)this.indexMap.size() / (double)this.listSize);
+    }
+
+    public int createRawIterator() {
+        if (this.allowSafeIteration()) {
+            ++this.iteratorCount;
+        }
+        if (this.indexMap.isEmpty()) {
+            return -1;
+        } else {
+            return this.firstInvalidIndex == 0 ? this.indexMap.getInt(this.indexMap.firstKey()) : 0;
+        }
+    }
+
+    public int advanceRawIterator(final int index) {
+        final E[] elements = this.listElements;
+        int ret = index + 1;
+        for (int len = this.listSize; ret < len; ++ret) {
+            if (elements[ret] != null) {
+                return ret;
+            }
+        }
+
+        return -1;
+    }
+
+    public void finishRawIterator() {
+        if (this.allowSafeIteration() && --this.iteratorCount == 0) {
+            if (this.getFragFactor() >= this.maxFragFactor) {
+                this.defrag();
+            }
+        }
+    }
+
+    public boolean remove(final E element) {
+        final int index = this.indexMap.removeInt(element);
+        if (index >= 0) {
+            if (this.firstInvalidIndex < 0 || index < this.firstInvalidIndex) {
+                this.firstInvalidIndex = index;
+            }
+            if (this.listElements[index] != element) {
+                throw new IllegalStateException();
+            }
+            this.listElements[index] = null;
+            if (this.allowSafeIteration() && this.iteratorCount == 0 && this.getFragFactor() >= this.maxFragFactor) {
+                this.defrag();
+            }
+            //this.check();
+            return true;
+        }
+        return false;
+    }
+
+    public boolean contains(final E element) {
+        return this.indexMap.containsKey(element);
+    }
+
+    public boolean add(final E element) {
+        final int listSize = this.listSize;
+
+        final int previous = this.indexMap.putIfAbsent(element, listSize);
+        if (previous != -1) {
+            return false;
+        }
+
+        if (listSize >= this.listElements.length) {
+            this.listElements = Arrays.copyOf(this.listElements, listSize * 2);
+        }
+        this.listElements[listSize] = element;
+        this.listSize = listSize + 1;
+
+        //this.check();
+        return true;
+    }
+
+    protected void defrag() {
+        if (this.firstInvalidIndex < 0) {
+            return; // nothing to do
+        }
+
+        if (this.indexMap.isEmpty()) {
+            Arrays.fill(this.listElements, 0, this.listSize, null);
+            this.listSize = 0;
+            this.firstInvalidIndex = -1;
+            //this.check();
+            return;
+        }
+
+        final E[] backingArray = this.listElements;
+
+        int lastValidIndex;
+        java.util.Iterator<Reference2IntMap.Entry<E>> iterator;
+
+        if (this.firstInvalidIndex == 0) {
+            iterator = this.indexMap.reference2IntEntrySet().fastIterator();
+            lastValidIndex = 0;
+        } else {
+            lastValidIndex = this.firstInvalidIndex;
+            final E key = backingArray[lastValidIndex - 1];
+            iterator = this.indexMap.reference2IntEntrySet().fastIterator(new Reference2IntMap.Entry<E>() {
+                @Override
+                public int getIntValue() {
+                    throw new UnsupportedOperationException();
+                }
+
+                @Override
+                public int setValue(int i) {
+                    throw new UnsupportedOperationException();
+                }
+
+                @Override
+                public E getKey() {
+                    return key;
+                }
+            });
+        }
+
+        while (iterator.hasNext()) {
+            final Reference2IntMap.Entry<E> entry = iterator.next();
+
+            final int newIndex = lastValidIndex++;
+            backingArray[newIndex] = entry.getKey();
+            entry.setValue(newIndex);
+        }
+
+        // cleanup end
+        Arrays.fill(backingArray, lastValidIndex, this.listSize, null);
+        this.listSize = lastValidIndex;
+        this.firstInvalidIndex = -1;
+        //this.check();
+    }
+
+    public E rawGet(final int index) {
+        return this.listElements[index];
+    }
+
+    public int size() {
+        // always returns the correct amount - listSize can be different
+        return this.indexMap.size();
+    }
+
+    public IteratorSafeOrderedReferenceSet.Iterator<E> iterator() {
+        return this.iterator(0);
+    }
+
+    public IteratorSafeOrderedReferenceSet.Iterator<E> iterator(final int flags) {
+        if (this.allowSafeIteration()) {
+            ++this.iteratorCount;
+        }
+        return new BaseIterator<>(this, true, (flags & ITERATOR_FLAG_SEE_ADDITIONS) != 0 ? Integer.MAX_VALUE : this.listSize);
+    }
+
+    public java.util.Iterator<E> unsafeIterator() {
+        return this.unsafeIterator(0);
+    }
+    public java.util.Iterator<E> unsafeIterator(final int flags) {
+        return new BaseIterator<>(this, false, (flags & ITERATOR_FLAG_SEE_ADDITIONS) != 0 ? Integer.MAX_VALUE : this.listSize);
+    }
+
+    public static interface Iterator<E> extends java.util.Iterator<E> {
+
+        public void finishedIterating();
+
+    }
+
+    protected static final class BaseIterator<E> implements IteratorSafeOrderedReferenceSet.Iterator<E> {
+
+        protected final IteratorSafeOrderedReferenceSet<E> set;
+        protected final boolean canFinish;
+        protected final int maxIndex;
+        protected int nextIndex;
+        protected E pendingValue;
+        protected boolean finished;
+        protected E lastReturned;
+
+        protected BaseIterator(final IteratorSafeOrderedReferenceSet<E> set, final boolean canFinish, final int maxIndex) {
+            this.set = set;
+            this.canFinish = canFinish;
+            this.maxIndex = maxIndex;
+        }
+
+        @Override
+        public boolean hasNext() {
+            if (this.finished) {
+                return false;
+            }
+            if (this.pendingValue != null) {
+                return true;
+            }
+
+            final E[] elements = this.set.listElements;
+            int index, len;
+            for (index = this.nextIndex, len = Math.min(this.maxIndex, this.set.listSize); index < len; ++index) {
+                final E element = elements[index];
+                if (element != null) {
+                    this.pendingValue = element;
+                    this.nextIndex = index + 1;
+                    return true;
+                }
+            }
+
+            this.nextIndex = index;
+            return false;
+        }
+
+        @Override
+        public E next() {
+            if (!this.hasNext()) {
+                throw new NoSuchElementException();
+            }
+            final E ret = this.pendingValue;
+
+            this.pendingValue = null;
+            this.lastReturned = ret;
+
+            return ret;
+        }
+
+        @Override
+        public void remove() {
+            final E lastReturned = this.lastReturned;
+            if (lastReturned == null) {
+                throw new IllegalStateException();
+            }
+            this.lastReturned = null;
+            this.set.remove(lastReturned);
+        }
+
+        @Override
+        public void finishedIterating() {
+            if (this.finished || !this.canFinish) {
+                throw new IllegalStateException();
+            }
+            this.lastReturned = null;
+            this.finished = true;
+            if (this.set.allowSafeIteration()) {
+                this.set.finishRawIterator();
+            }
+        }
+    }
+}
diff --git a/src/main/java/io/papermc/paper/util/misc/Delayed26WayDistancePropagator3D.java b/src/main/java/io/papermc/paper/util/misc/Delayed26WayDistancePropagator3D.java
new file mode 100644
index 0000000000000000000000000000000000000000..470402573bc31106d5a63e415b958fb7f9c36aa9
--- /dev/null
+++ b/src/main/java/io/papermc/paper/util/misc/Delayed26WayDistancePropagator3D.java
@@ -0,0 +1,297 @@
+package io.papermc.paper.util.misc;
+
+import io.papermc.paper.util.CoordinateUtils;
+import it.unimi.dsi.fastutil.longs.Long2ByteOpenHashMap;
+import it.unimi.dsi.fastutil.longs.LongIterator;
+import it.unimi.dsi.fastutil.longs.LongLinkedOpenHashSet;
+
+public final class Delayed26WayDistancePropagator3D {
+
+    // this map is considered "stale" unless updates are propagated.
+    protected final Delayed8WayDistancePropagator2D.LevelMap levels = new Delayed8WayDistancePropagator2D.LevelMap(8192*2, 0.6f);
+
+    // this map is never stale
+    protected final Long2ByteOpenHashMap sources = new Long2ByteOpenHashMap(4096, 0.6f);
+
+    // Generally updates to positions are made close to other updates, so we link to decrease cache misses when
+    // propagating updates
+    protected final LongLinkedOpenHashSet updatedSources = new LongLinkedOpenHashSet();
+
+    @FunctionalInterface
+    public static interface LevelChangeCallback {
+
+        /**
+         * This can be called for intermediate updates. So do not rely on newLevel being close to or
+         * the exact level that is expected after a full propagation has occured.
+         */
+        public void onLevelUpdate(final long coordinate, final byte oldLevel, final byte newLevel);
+
+    }
+
+    protected final LevelChangeCallback changeCallback;
+
+    public Delayed26WayDistancePropagator3D() {
+        this(null);
+    }
+
+    public Delayed26WayDistancePropagator3D(final LevelChangeCallback changeCallback) {
+        this.changeCallback = changeCallback;
+    }
+
+    public int getLevel(final long pos) {
+        return this.levels.get(pos);
+    }
+
+    public int getLevel(final int x, final int y, final int z) {
+        return this.levels.get(CoordinateUtils.getChunkSectionKey(x, y, z));
+    }
+
+    public void setSource(final int x, final int y, final int z, final int level) {
+        this.setSource(CoordinateUtils.getChunkSectionKey(x, y, z), level);
+    }
+
+    public void setSource(final long coordinate, final int level) {
+        if ((level & 63) != level || level == 0) {
+            throw new IllegalArgumentException("Level must be in (0, 63], not " + level);
+        }
+
+        final byte byteLevel = (byte)level;
+        final byte oldLevel = this.sources.put(coordinate, byteLevel);
+
+        if (oldLevel == byteLevel) {
+            return; // nothing to do
+        }
+
+        // queue to update later
+        this.updatedSources.add(coordinate);
+    }
+
+    public void removeSource(final int x, final int y, final int z) {
+        this.removeSource(CoordinateUtils.getChunkSectionKey(x, y, z));
+    }
+
+    public void removeSource(final long coordinate) {
+        if (this.sources.remove(coordinate) != 0) {
+            this.updatedSources.add(coordinate);
+        }
+    }
+
+    // queues used for BFS propagating levels
+    protected final Delayed8WayDistancePropagator2D.WorkQueue[] levelIncreaseWorkQueues = new Delayed8WayDistancePropagator2D.WorkQueue[64];
+    {
+        for (int i = 0; i < this.levelIncreaseWorkQueues.length; ++i) {
+            this.levelIncreaseWorkQueues[i] = new Delayed8WayDistancePropagator2D.WorkQueue();
+        }
+    }
+    protected final Delayed8WayDistancePropagator2D.WorkQueue[] levelRemoveWorkQueues = new Delayed8WayDistancePropagator2D.WorkQueue[64];
+    {
+        for (int i = 0; i < this.levelRemoveWorkQueues.length; ++i) {
+            this.levelRemoveWorkQueues[i] = new Delayed8WayDistancePropagator2D.WorkQueue();
+        }
+    }
+    protected long levelIncreaseWorkQueueBitset;
+    protected long levelRemoveWorkQueueBitset;
+
+    protected final void addToIncreaseWorkQueue(final long coordinate, final byte level) {
+        final Delayed8WayDistancePropagator2D.WorkQueue queue = this.levelIncreaseWorkQueues[level];
+        queue.queuedCoordinates.enqueue(coordinate);
+        queue.queuedLevels.enqueue(level);
+
+        this.levelIncreaseWorkQueueBitset |= (1L << level);
+    }
+
+    protected final void addToIncreaseWorkQueue(final long coordinate, final byte index, final byte level) {
+        final Delayed8WayDistancePropagator2D.WorkQueue queue = this.levelIncreaseWorkQueues[index];
+        queue.queuedCoordinates.enqueue(coordinate);
+        queue.queuedLevels.enqueue(level);
+
+        this.levelIncreaseWorkQueueBitset |= (1L << index);
+    }
+
+    protected final void addToRemoveWorkQueue(final long coordinate, final byte level) {
+        final Delayed8WayDistancePropagator2D.WorkQueue queue = this.levelRemoveWorkQueues[level];
+        queue.queuedCoordinates.enqueue(coordinate);
+        queue.queuedLevels.enqueue(level);
+
+        this.levelRemoveWorkQueueBitset |= (1L << level);
+    }
+
+    public boolean propagateUpdates() {
+        if (this.updatedSources.isEmpty()) {
+            return false;
+        }
+
+        boolean ret = false;
+
+        for (final LongIterator iterator = this.updatedSources.iterator(); iterator.hasNext();) {
+            final long coordinate = iterator.nextLong();
+
+            final byte currentLevel = this.levels.get(coordinate);
+            final byte updatedSource = this.sources.get(coordinate);
+
+            if (currentLevel == updatedSource) {
+                continue;
+            }
+            ret = true;
+
+            if (updatedSource > currentLevel) {
+                // level increase
+                this.addToIncreaseWorkQueue(coordinate, updatedSource);
+            } else {
+                // level decrease
+                this.addToRemoveWorkQueue(coordinate, currentLevel);
+                // if the current coordinate is a source, then the decrease propagation will detect that and queue
+                // the source propagation
+            }
+        }
+
+        this.updatedSources.clear();
+
+        // propagate source level increases first for performance reasons (in crowded areas hopefully the additions
+        // make the removes remove less)
+        this.propagateIncreases();
+
+        // now we propagate the decreases (which will then re-propagate clobbered sources)
+        this.propagateDecreases();
+
+        return ret;
+    }
+
+    protected void propagateIncreases() {
+        for (int queueIndex = 63 ^ Long.numberOfLeadingZeros(this.levelIncreaseWorkQueueBitset);
+             this.levelIncreaseWorkQueueBitset != 0L;
+             this.levelIncreaseWorkQueueBitset ^= (1L << queueIndex), queueIndex = 63 ^ Long.numberOfLeadingZeros(this.levelIncreaseWorkQueueBitset)) {
+
+            final Delayed8WayDistancePropagator2D.WorkQueue queue = this.levelIncreaseWorkQueues[queueIndex];
+            while (!queue.queuedLevels.isEmpty()) {
+                final long coordinate = queue.queuedCoordinates.removeFirstLong();
+                byte level = queue.queuedLevels.removeFirstByte();
+
+                final boolean neighbourCheck = level < 0;
+
+                final byte currentLevel;
+                if (neighbourCheck) {
+                    level = (byte)-level;
+                    currentLevel = this.levels.get(coordinate);
+                } else {
+                    currentLevel = this.levels.putIfGreater(coordinate, level);
+                }
+
+                if (neighbourCheck) {
+                    // used when propagating from decrease to indicate that this level needs to check its neighbours
+                    // this means the level at coordinate could be equal, but would still need neighbours checked
+
+                    if (currentLevel != level) {
+                        // something caused the level to change, which means something propagated to it (which means
+                        // us propagating here is redundant), or something removed the level (which means we
+                        // cannot propagate further)
+                        continue;
+                    }
+                } else if (currentLevel >= level) {
+                    // something higher/equal propagated
+                    continue;
+                }
+                if (this.changeCallback != null) {
+                    this.changeCallback.onLevelUpdate(coordinate, currentLevel, level);
+                }
+
+                if (level == 1) {
+                    // can't propagate 0 to neighbours
+                    continue;
+                }
+
+                // propagate to neighbours
+                final byte neighbourLevel = (byte)(level - 1);
+                final int x = CoordinateUtils.getChunkSectionX(coordinate);
+                final int y = CoordinateUtils.getChunkSectionY(coordinate);
+                final int z = CoordinateUtils.getChunkSectionZ(coordinate);
+
+                for (int dy = -1; dy <= 1; ++dy) {
+                    for (int dz = -1; dz <= 1; ++dz) {
+                        for (int dx = -1; dx <= 1; ++dx) {
+                            if ((dy | dz | dx) == 0) {
+                                // already propagated to coordinate
+                                continue;
+                            }
+
+                            // sure we can check the neighbour level in the map right now and avoid a propagation,
+                            // but then we would still have to recheck it when popping the value off of the queue!
+                            // so just avoid the double lookup
+                            final long neighbourCoordinate = CoordinateUtils.getChunkSectionKey(dx + x, dy + y, dz + z);
+                            this.addToIncreaseWorkQueue(neighbourCoordinate, neighbourLevel);
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    protected void propagateDecreases() {
+        for (int queueIndex = 63 ^ Long.numberOfLeadingZeros(this.levelRemoveWorkQueueBitset);
+             this.levelRemoveWorkQueueBitset != 0L;
+             this.levelRemoveWorkQueueBitset ^= (1L << queueIndex), queueIndex = 63 ^ Long.numberOfLeadingZeros(this.levelRemoveWorkQueueBitset)) {
+
+            final Delayed8WayDistancePropagator2D.WorkQueue queue = this.levelRemoveWorkQueues[queueIndex];
+            while (!queue.queuedLevels.isEmpty()) {
+                final long coordinate = queue.queuedCoordinates.removeFirstLong();
+                final byte level = queue.queuedLevels.removeFirstByte();
+
+                final byte currentLevel = this.levels.removeIfGreaterOrEqual(coordinate, level);
+                if (currentLevel == 0) {
+                    // something else removed
+                    continue;
+                }
+
+                if (currentLevel > level) {
+                    // something higher propagated here or we hit the propagation of another source
+                    // in the second case we need to re-propagate because we could have just clobbered another source's
+                    // propagation
+                    this.addToIncreaseWorkQueue(coordinate, currentLevel, (byte)-currentLevel); // indicate to the increase code that the level's neighbours need checking
+                    continue;
+                }
+
+                if (this.changeCallback != null) {
+                    this.changeCallback.onLevelUpdate(coordinate, currentLevel, (byte)0);
+                }
+
+                final byte source = this.sources.get(coordinate);
+                if (source != 0) {
+                    // must re-propagate source later
+                    this.addToIncreaseWorkQueue(coordinate, source);
+                }
+
+                if (level == 0) {
+                    // can't propagate -1 to neighbours
+                    // we have to check neighbours for removing 1 just in case the neighbour is 2
+                    continue;
+                }
+
+                // propagate to neighbours
+                final byte neighbourLevel = (byte)(level - 1);
+                final int x = CoordinateUtils.getChunkSectionX(coordinate);
+                final int y = CoordinateUtils.getChunkSectionY(coordinate);
+                final int z = CoordinateUtils.getChunkSectionZ(coordinate);
+
+                for (int dy = -1; dy <= 1; ++dy) {
+                    for (int dz = -1; dz <= 1; ++dz) {
+                        for (int dx = -1; dx <= 1; ++dx) {
+                            if ((dy | dz | dx) == 0) {
+                                // already propagated to coordinate
+                                continue;
+                            }
+
+                            // sure we can check the neighbour level in the map right now and avoid a propagation,
+                            // but then we would still have to recheck it when popping the value off of the queue!
+                            // so just avoid the double lookup
+                            final long neighbourCoordinate = CoordinateUtils.getChunkSectionKey(dx + x, dy + y, dz + z);
+                            this.addToRemoveWorkQueue(neighbourCoordinate, neighbourLevel);
+                        }
+                    }
+                }
+            }
+        }
+
+        // propagate sources we clobbered in the process
+        this.propagateIncreases();
+    }
+}
diff --git a/src/main/java/io/papermc/paper/util/misc/Delayed8WayDistancePropagator2D.java b/src/main/java/io/papermc/paper/util/misc/Delayed8WayDistancePropagator2D.java
new file mode 100644
index 0000000000000000000000000000000000000000..808d1449ac44ae86a650932365081fbaf178d141
--- /dev/null
+++ b/src/main/java/io/papermc/paper/util/misc/Delayed8WayDistancePropagator2D.java
@@ -0,0 +1,718 @@
+package io.papermc.paper.util.misc;
+
+import it.unimi.dsi.fastutil.HashCommon;
+import it.unimi.dsi.fastutil.bytes.ByteArrayFIFOQueue;
+import it.unimi.dsi.fastutil.longs.Long2ByteOpenHashMap;
+import it.unimi.dsi.fastutil.longs.LongArrayFIFOQueue;
+import it.unimi.dsi.fastutil.longs.LongIterator;
+import it.unimi.dsi.fastutil.longs.LongLinkedOpenHashSet;
+import io.papermc.paper.util.MCUtil;
+
+public final class Delayed8WayDistancePropagator2D {
+
+    // Test
+    /*
+    protected static void test(int x, int z, com.destroystokyo.paper.util.misc.DistanceTrackingAreaMap<Ticket> reference, Delayed8WayDistancePropagator2D test) {
+        int got = test.getLevel(x, z);
+
+        int expect = 0;
+        Object[] nearest = reference.getObjectsInRange(x, z) == null ? null : reference.getObjectsInRange(x, z).getBackingSet();
+        if (nearest != null) {
+            for (Object _obj : nearest) {
+                if (_obj instanceof Ticket) {
+                    Ticket ticket = (Ticket)_obj;
+                    long ticketCoord = reference.getLastCoordinate(ticket);
+                    int viewDistance = reference.getLastViewDistance(ticket);
+                    int distance = Math.max(com.destroystokyo.paper.util.math.IntegerUtil.branchlessAbs(MCUtil.getCoordinateX(ticketCoord) - x),
+                            com.destroystokyo.paper.util.math.IntegerUtil.branchlessAbs(MCUtil.getCoordinateZ(ticketCoord) - z));
+                    int level = viewDistance - distance;
+                    if (level > expect) {
+                        expect = level;
+                    }
+                }
+            }
+        }
+
+        if (expect != got) {
+            throw new IllegalStateException("Expected " + expect + " at pos (" + x + "," + z + ") but got " + got);
+        }
+    }
+
+    static class Ticket {
+
+        int x;
+        int z;
+
+        final com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<Ticket> empty
+                = new com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<>(this);
+
+    }
+
+    public static void main(final String[] args) {
+        com.destroystokyo.paper.util.misc.DistanceTrackingAreaMap<Ticket> reference = new com.destroystokyo.paper.util.misc.DistanceTrackingAreaMap<Ticket>() {
+            @Override
+            protected com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<Ticket> getEmptySetFor(Ticket object) {
+                return object.empty;
+            }
+        };
+        Delayed8WayDistancePropagator2D test = new Delayed8WayDistancePropagator2D();
+
+        final int maxDistance = 64;
+        // test origin
+        {
+            Ticket originTicket = new Ticket();
+            int originDistance = 31;
+            // test single source
+            reference.add(originTicket, 0, 0, originDistance);
+            test.setSource(0, 0, originDistance); test.propagateUpdates(); // set and propagate
+            for (int dx = -originDistance; dx <= originDistance; ++dx) {
+                for (int dz = -originDistance; dz <= originDistance; ++dz) {
+                    test(dx, dz, reference, test);
+                }
+            }
+            // test single source decrease
+            reference.update(originTicket, 0, 0, originDistance/2);
+            test.setSource(0, 0, originDistance/2); test.propagateUpdates(); // set and propagate
+            for (int dx = -originDistance; dx <= originDistance; ++dx) {
+                for (int dz = -originDistance; dz <= originDistance; ++dz) {
+                    test(dx, dz, reference, test);
+                }
+            }
+            // test source increase
+            originDistance = 2*originDistance;
+            reference.update(originTicket, 0, 0, originDistance);
+            test.setSource(0, 0, originDistance); test.propagateUpdates(); // set and propagate
+            for (int dx = -4*originDistance; dx <= 4*originDistance; ++dx) {
+                for (int dz = -4*originDistance; dz <= 4*originDistance; ++dz) {
+                    test(dx, dz, reference, test);
+                }
+            }
+
+            reference.remove(originTicket);
+            test.removeSource(0, 0); test.propagateUpdates();
+        }
+
+        // test multiple sources at origin
+        {
+            int originDistance = 31;
+            java.util.List<Ticket> list = new java.util.ArrayList<>();
+            for (int i = 0; i < 10; ++i) {
+                Ticket a = new Ticket();
+                list.add(a);
+                a.x = (i & 1) == 1 ? -i : i;
+                a.z = (i & 1) == 1 ? -i : i;
+            }
+            for (Ticket ticket : list) {
+                reference.add(ticket, ticket.x, ticket.z, originDistance);
+                test.setSource(ticket.x, ticket.z, originDistance);
+            }
+            test.propagateUpdates();
+
+            for (int dx = -8*originDistance; dx <= 8*originDistance; ++dx) {
+                for (int dz = -8*originDistance; dz <= 8*originDistance; ++dz) {
+                    test(dx, dz, reference, test);
+                }
+            }
+
+            // test ticket level decrease
+
+            for (Ticket ticket : list) {
+                reference.update(ticket, ticket.x, ticket.z, originDistance/2);
+                test.setSource(ticket.x, ticket.z, originDistance/2);
+            }
+            test.propagateUpdates();
+
+            for (int dx = -8*originDistance; dx <= 8*originDistance; ++dx) {
+                for (int dz = -8*originDistance; dz <= 8*originDistance; ++dz) {
+                    test(dx, dz, reference, test);
+                }
+            }
+
+            // test ticket level increase
+
+            for (Ticket ticket : list) {
+                reference.update(ticket, ticket.x, ticket.z, originDistance*2);
+                test.setSource(ticket.x, ticket.z, originDistance*2);
+            }
+            test.propagateUpdates();
+
+            for (int dx = -16*originDistance; dx <= 16*originDistance; ++dx) {
+                for (int dz = -16*originDistance; dz <= 16*originDistance; ++dz) {
+                    test(dx, dz, reference, test);
+                }
+            }
+
+            // test ticket remove
+            for (int i = 0, len = list.size(); i < len; ++i) {
+                if ((i & 3) != 0) {
+                    continue;
+                }
+                Ticket ticket = list.get(i);
+                reference.remove(ticket);
+                test.removeSource(ticket.x, ticket.z);
+            }
+            test.propagateUpdates();
+
+            for (int dx = -16*originDistance; dx <= 16*originDistance; ++dx) {
+                for (int dz = -16*originDistance; dz <= 16*originDistance; ++dz) {
+                    test(dx, dz, reference, test);
+                }
+            }
+        }
+
+        // now test at coordinate offsets
+        // test offset
+        {
+            Ticket originTicket = new Ticket();
+            int originDistance = 31;
+            int offX = 54432;
+            int offZ = -134567;
+            // test single source
+            reference.add(originTicket, offX, offZ, originDistance);
+            test.setSource(offX, offZ, originDistance); test.propagateUpdates(); // set and propagate
+            for (int dx = -originDistance; dx <= originDistance; ++dx) {
+                for (int dz = -originDistance; dz <= originDistance; ++dz) {
+                    test(dx + offX, dz + offZ, reference, test);
+                }
+            }
+            // test single source decrease
+            reference.update(originTicket, offX, offZ, originDistance/2);
+            test.setSource(offX, offZ, originDistance/2); test.propagateUpdates(); // set and propagate
+            for (int dx = -originDistance; dx <= originDistance; ++dx) {
+                for (int dz = -originDistance; dz <= originDistance; ++dz) {
+                    test(dx + offX, dz + offZ, reference, test);
+                }
+            }
+            // test source increase
+            originDistance = 2*originDistance;
+            reference.update(originTicket, offX, offZ, originDistance);
+            test.setSource(offX, offZ, originDistance); test.propagateUpdates(); // set and propagate
+            for (int dx = -4*originDistance; dx <= 4*originDistance; ++dx) {
+                for (int dz = -4*originDistance; dz <= 4*originDistance; ++dz) {
+                    test(dx + offX, dz + offZ, reference, test);
+                }
+            }
+
+            reference.remove(originTicket);
+            test.removeSource(offX, offZ); test.propagateUpdates();
+        }
+
+        // test multiple sources at origin
+        {
+            int originDistance = 31;
+            int offX = 54432;
+            int offZ = -134567;
+            java.util.List<Ticket> list = new java.util.ArrayList<>();
+            for (int i = 0; i < 10; ++i) {
+                Ticket a = new Ticket();
+                list.add(a);
+                a.x = offX + ((i & 1) == 1 ? -i : i);
+                a.z = offZ + ((i & 1) == 1 ? -i : i);
+            }
+            for (Ticket ticket : list) {
+                reference.add(ticket, ticket.x, ticket.z, originDistance);
+                test.setSource(ticket.x, ticket.z, originDistance);
+            }
+            test.propagateUpdates();
+
+            for (int dx = -8*originDistance; dx <= 8*originDistance; ++dx) {
+                for (int dz = -8*originDistance; dz <= 8*originDistance; ++dz) {
+                    test(dx, dz, reference, test);
+                }
+            }
+
+            // test ticket level decrease
+
+            for (Ticket ticket : list) {
+                reference.update(ticket, ticket.x, ticket.z, originDistance/2);
+                test.setSource(ticket.x, ticket.z, originDistance/2);
+            }
+            test.propagateUpdates();
+
+            for (int dx = -8*originDistance; dx <= 8*originDistance; ++dx) {
+                for (int dz = -8*originDistance; dz <= 8*originDistance; ++dz) {
+                    test(dx, dz, reference, test);
+                }
+            }
+
+            // test ticket level increase
+
+            for (Ticket ticket : list) {
+                reference.update(ticket, ticket.x, ticket.z, originDistance*2);
+                test.setSource(ticket.x, ticket.z, originDistance*2);
+            }
+            test.propagateUpdates();
+
+            for (int dx = -16*originDistance; dx <= 16*originDistance; ++dx) {
+                for (int dz = -16*originDistance; dz <= 16*originDistance; ++dz) {
+                    test(dx, dz, reference, test);
+                }
+            }
+
+            // test ticket remove
+            for (int i = 0, len = list.size(); i < len; ++i) {
+                if ((i & 3) != 0) {
+                    continue;
+                }
+                Ticket ticket = list.get(i);
+                reference.remove(ticket);
+                test.removeSource(ticket.x, ticket.z);
+            }
+            test.propagateUpdates();
+
+            for (int dx = -16*originDistance; dx <= 16*originDistance; ++dx) {
+                for (int dz = -16*originDistance; dz <= 16*originDistance; ++dz) {
+                    test(dx, dz, reference, test);
+                }
+            }
+        }
+    }
+     */
+
+    // this map is considered "stale" unless updates are propagated.
+    protected final LevelMap levels = new LevelMap(8192*2, 0.6f);
+
+    // this map is never stale
+    protected final Long2ByteOpenHashMap sources = new Long2ByteOpenHashMap(4096, 0.6f);
+
+    // Generally updates to positions are made close to other updates, so we link to decrease cache misses when
+    // propagating updates
+    protected final LongLinkedOpenHashSet updatedSources = new LongLinkedOpenHashSet();
+
+    @FunctionalInterface
+    public static interface LevelChangeCallback {
+
+        /**
+         * This can be called for intermediate updates. So do not rely on newLevel being close to or
+         * the exact level that is expected after a full propagation has occured.
+         */
+        public void onLevelUpdate(final long coordinate, final byte oldLevel, final byte newLevel);
+
+    }
+
+    protected final LevelChangeCallback changeCallback;
+
+    public Delayed8WayDistancePropagator2D() {
+        this(null);
+    }
+
+    public Delayed8WayDistancePropagator2D(final LevelChangeCallback changeCallback) {
+        this.changeCallback = changeCallback;
+    }
+
+    public int getLevel(final long pos) {
+        return this.levels.get(pos);
+    }
+
+    public int getLevel(final int x, final int z) {
+        return this.levels.get(MCUtil.getCoordinateKey(x, z));
+    }
+
+    public void setSource(final int x, final int z, final int level) {
+        this.setSource(MCUtil.getCoordinateKey(x, z), level);
+    }
+
+    public void setSource(final long coordinate, final int level) {
+        if ((level & 63) != level || level == 0) {
+            throw new IllegalArgumentException("Level must be in (0, 63], not " + level);
+        }
+
+        final byte byteLevel = (byte)level;
+        final byte oldLevel = this.sources.put(coordinate, byteLevel);
+
+        if (oldLevel == byteLevel) {
+            return; // nothing to do
+        }
+
+        // queue to update later
+        this.updatedSources.add(coordinate);
+    }
+
+    public void removeSource(final int x, final int z) {
+        this.removeSource(MCUtil.getCoordinateKey(x, z));
+    }
+
+    public void removeSource(final long coordinate) {
+        if (this.sources.remove(coordinate) != 0) {
+            this.updatedSources.add(coordinate);
+        }
+    }
+
+    // queues used for BFS propagating levels
+    protected final WorkQueue[] levelIncreaseWorkQueues = new WorkQueue[64];
+    {
+        for (int i = 0; i < this.levelIncreaseWorkQueues.length; ++i) {
+            this.levelIncreaseWorkQueues[i] = new WorkQueue();
+        }
+    }
+    protected final WorkQueue[] levelRemoveWorkQueues = new WorkQueue[64];
+    {
+        for (int i = 0; i < this.levelRemoveWorkQueues.length; ++i) {
+            this.levelRemoveWorkQueues[i] = new WorkQueue();
+        }
+    }
+    protected long levelIncreaseWorkQueueBitset;
+    protected long levelRemoveWorkQueueBitset;
+
+    protected final void addToIncreaseWorkQueue(final long coordinate, final byte level) {
+        final WorkQueue queue = this.levelIncreaseWorkQueues[level];
+        queue.queuedCoordinates.enqueue(coordinate);
+        queue.queuedLevels.enqueue(level);
+
+        this.levelIncreaseWorkQueueBitset |= (1L << level);
+    }
+
+    protected final void addToIncreaseWorkQueue(final long coordinate, final byte index, final byte level) {
+        final WorkQueue queue = this.levelIncreaseWorkQueues[index];
+        queue.queuedCoordinates.enqueue(coordinate);
+        queue.queuedLevels.enqueue(level);
+
+        this.levelIncreaseWorkQueueBitset |= (1L << index);
+    }
+
+    protected final void addToRemoveWorkQueue(final long coordinate, final byte level) {
+        final WorkQueue queue = this.levelRemoveWorkQueues[level];
+        queue.queuedCoordinates.enqueue(coordinate);
+        queue.queuedLevels.enqueue(level);
+
+        this.levelRemoveWorkQueueBitset |= (1L << level);
+    }
+
+    public boolean propagateUpdates() {
+        if (this.updatedSources.isEmpty()) {
+            return false;
+        }
+
+        boolean ret = false;
+
+        for (final LongIterator iterator = this.updatedSources.iterator(); iterator.hasNext();) {
+            final long coordinate = iterator.nextLong();
+
+            final byte currentLevel = this.levels.get(coordinate);
+            final byte updatedSource = this.sources.get(coordinate);
+
+            if (currentLevel == updatedSource) {
+                continue;
+            }
+            ret = true;
+
+            if (updatedSource > currentLevel) {
+                // level increase
+                this.addToIncreaseWorkQueue(coordinate, updatedSource);
+            } else {
+                // level decrease
+                this.addToRemoveWorkQueue(coordinate, currentLevel);
+                // if the current coordinate is a source, then the decrease propagation will detect that and queue
+                // the source propagation
+            }
+        }
+
+        this.updatedSources.clear();
+
+        // propagate source level increases first for performance reasons (in crowded areas hopefully the additions
+        // make the removes remove less)
+        this.propagateIncreases();
+
+        // now we propagate the decreases (which will then re-propagate clobbered sources)
+        this.propagateDecreases();
+
+        return ret;
+    }
+
+    protected void propagateIncreases() {
+        for (int queueIndex = 63 ^ Long.numberOfLeadingZeros(this.levelIncreaseWorkQueueBitset);
+             this.levelIncreaseWorkQueueBitset != 0L;
+             this.levelIncreaseWorkQueueBitset ^= (1L << queueIndex), queueIndex = 63 ^ Long.numberOfLeadingZeros(this.levelIncreaseWorkQueueBitset)) {
+
+            final WorkQueue queue = this.levelIncreaseWorkQueues[queueIndex];
+            while (!queue.queuedLevels.isEmpty()) {
+                final long coordinate = queue.queuedCoordinates.removeFirstLong();
+                byte level = queue.queuedLevels.removeFirstByte();
+
+                final boolean neighbourCheck = level < 0;
+
+                final byte currentLevel;
+                if (neighbourCheck) {
+                    level = (byte)-level;
+                    currentLevel = this.levels.get(coordinate);
+                } else {
+                    currentLevel = this.levels.putIfGreater(coordinate, level);
+                }
+
+                if (neighbourCheck) {
+                    // used when propagating from decrease to indicate that this level needs to check its neighbours
+                    // this means the level at coordinate could be equal, but would still need neighbours checked
+
+                    if (currentLevel != level) {
+                        // something caused the level to change, which means something propagated to it (which means
+                        // us propagating here is redundant), or something removed the level (which means we
+                        // cannot propagate further)
+                        continue;
+                    }
+                } else if (currentLevel >= level) {
+                    // something higher/equal propagated
+                    continue;
+                }
+                if (this.changeCallback != null) {
+                    this.changeCallback.onLevelUpdate(coordinate, currentLevel, level);
+                }
+
+                if (level == 1) {
+                    // can't propagate 0 to neighbours
+                    continue;
+                }
+
+                // propagate to neighbours
+                final byte neighbourLevel = (byte)(level - 1);
+                final int x = (int)coordinate;
+                final int z = (int)(coordinate >>> 32);
+
+                for (int dx = -1; dx <= 1; ++dx) {
+                    for (int dz = -1; dz <= 1; ++dz) {
+                        if ((dx | dz) == 0) {
+                            // already propagated to coordinate
+                            continue;
+                        }
+
+                        // sure we can check the neighbour level in the map right now and avoid a propagation,
+                        // but then we would still have to recheck it when popping the value off of the queue!
+                        // so just avoid the double lookup
+                        final long neighbourCoordinate = MCUtil.getCoordinateKey(x + dx, z + dz);
+                        this.addToIncreaseWorkQueue(neighbourCoordinate, neighbourLevel);
+                    }
+                }
+            }
+        }
+    }
+
+    protected void propagateDecreases() {
+        for (int queueIndex = 63 ^ Long.numberOfLeadingZeros(this.levelRemoveWorkQueueBitset);
+             this.levelRemoveWorkQueueBitset != 0L;
+             this.levelRemoveWorkQueueBitset ^= (1L << queueIndex), queueIndex = 63 ^ Long.numberOfLeadingZeros(this.levelRemoveWorkQueueBitset)) {
+
+            final WorkQueue queue = this.levelRemoveWorkQueues[queueIndex];
+            while (!queue.queuedLevels.isEmpty()) {
+                final long coordinate = queue.queuedCoordinates.removeFirstLong();
+                final byte level = queue.queuedLevels.removeFirstByte();
+
+                final byte currentLevel = this.levels.removeIfGreaterOrEqual(coordinate, level);
+                if (currentLevel == 0) {
+                    // something else removed
+                    continue;
+                }
+
+                if (currentLevel > level) {
+                    // something higher propagated here or we hit the propagation of another source
+                    // in the second case we need to re-propagate because we could have just clobbered another source's
+                    // propagation
+                    this.addToIncreaseWorkQueue(coordinate, currentLevel, (byte)-currentLevel); // indicate to the increase code that the level's neighbours need checking
+                    continue;
+                }
+
+                if (this.changeCallback != null) {
+                    this.changeCallback.onLevelUpdate(coordinate, currentLevel, (byte)0);
+                }
+
+                final byte source = this.sources.get(coordinate);
+                if (source != 0) {
+                    // must re-propagate source later
+                    this.addToIncreaseWorkQueue(coordinate, source);
+                }
+
+                if (level == 0) {
+                    // can't propagate -1 to neighbours
+                    // we have to check neighbours for removing 1 just in case the neighbour is 2
+                    continue;
+                }
+
+                // propagate to neighbours
+                final byte neighbourLevel = (byte)(level - 1);
+                final int x = (int)coordinate;
+                final int z = (int)(coordinate >>> 32);
+
+                for (int dx = -1; dx <= 1; ++dx) {
+                    for (int dz = -1; dz <= 1; ++dz) {
+                        if ((dx | dz) == 0) {
+                            // already propagated to coordinate
+                            continue;
+                        }
+
+                        // sure we can check the neighbour level in the map right now and avoid a propagation,
+                        // but then we would still have to recheck it when popping the value off of the queue!
+                        // so just avoid the double lookup
+                        final long neighbourCoordinate = MCUtil.getCoordinateKey(x + dx, z + dz);
+                        this.addToRemoveWorkQueue(neighbourCoordinate, neighbourLevel);
+                    }
+                }
+            }
+        }
+
+        // propagate sources we clobbered in the process
+        this.propagateIncreases();
+    }
+
+    protected static final class LevelMap extends Long2ByteOpenHashMap {
+        public LevelMap() {
+            super();
+        }
+
+        public LevelMap(final int expected, final float loadFactor) {
+            super(expected, loadFactor);
+        }
+
+        // copied from superclass
+        private int find(final long k) {
+            if (k == 0L) {
+                return this.containsNullKey ? this.n : -(this.n + 1);
+            } else {
+                final long[] key = this.key;
+                long curr;
+                int pos;
+                if ((curr = key[pos = (int)HashCommon.mix(k) & this.mask]) == 0L) {
+                    return -(pos + 1);
+                } else if (k == curr) {
+                    return pos;
+                } else {
+                    while((curr = key[pos = pos + 1 & this.mask]) != 0L) {
+                        if (k == curr) {
+                            return pos;
+                        }
+                    }
+
+                    return -(pos + 1);
+                }
+            }
+        }
+
+        // copied from superclass
+        private void insert(final int pos, final long k, final byte v) {
+            if (pos == this.n) {
+                this.containsNullKey = true;
+            }
+
+            this.key[pos] = k;
+            this.value[pos] = v;
+            if (this.size++ >= this.maxFill) {
+                this.rehash(HashCommon.arraySize(this.size + 1, this.f));
+            }
+        }
+
+        // copied from superclass
+        public byte putIfGreater(final long key, final byte value) {
+            final int pos = this.find(key);
+            if (pos < 0) {
+                if (this.defRetValue < value) {
+                    this.insert(-pos - 1, key, value);
+                }
+                return this.defRetValue;
+            } else {
+                final byte curr = this.value[pos];
+                if (value > curr) {
+                    this.value[pos] = value;
+                    return curr;
+                }
+                return curr;
+            }
+        }
+
+        // copied from superclass
+        private void removeEntry(final int pos) {
+            --this.size;
+            this.shiftKeys(pos);
+            if (this.n > this.minN && this.size < this.maxFill / 4 && this.n > 16) {
+                this.rehash(this.n / 2);
+            }
+        }
+
+        // copied from superclass
+        private void removeNullEntry() {
+            this.containsNullKey = false;
+            --this.size;
+            if (this.n > this.minN && this.size < this.maxFill / 4 && this.n > 16) {
+                this.rehash(this.n / 2);
+            }
+        }
+
+        // copied from superclass
+        public byte removeIfGreaterOrEqual(final long key, final byte value) {
+            if (key == 0L) {
+                if (!this.containsNullKey) {
+                    return this.defRetValue;
+                }
+                final byte current = this.value[this.n];
+                if (value >= current) {
+                    this.removeNullEntry();
+                    return current;
+                }
+                return current;
+            } else {
+                long[] keys = this.key;
+                byte[] values = this.value;
+                long curr;
+                int pos;
+                if ((curr = keys[pos = (int)HashCommon.mix(key) & this.mask]) == 0L) {
+                    return this.defRetValue;
+                } else if (key == curr) {
+                    final byte current = values[pos];
+                    if (value >= current) {
+                        this.removeEntry(pos);
+                        return current;
+                    }
+                    return current;
+                } else {
+                    while((curr = keys[pos = pos + 1 & this.mask]) != 0L) {
+                        if (key == curr) {
+                            final byte current = values[pos];
+                            if (value >= current) {
+                                this.removeEntry(pos);
+                                return current;
+                            }
+                            return current;
+                        }
+                    }
+
+                    return this.defRetValue;
+                }
+            }
+        }
+    }
+
+    protected static final class WorkQueue {
+
+        public final NoResizeLongArrayFIFODeque queuedCoordinates = new NoResizeLongArrayFIFODeque();
+        public final NoResizeByteArrayFIFODeque queuedLevels = new NoResizeByteArrayFIFODeque();
+
+    }
+
+    protected static final class NoResizeLongArrayFIFODeque extends LongArrayFIFOQueue {
+
+        /**
+         * Assumes non-empty. If empty, undefined behaviour.
+         */
+        public long removeFirstLong() {
+            // copied from superclass
+            long t = this.array[this.start];
+            if (++this.start == this.length) {
+                this.start = 0;
+            }
+
+            return t;
+        }
+    }
+
+    protected static final class NoResizeByteArrayFIFODeque extends ByteArrayFIFOQueue {
+
+        /**
+         * Assumes non-empty. If empty, undefined behaviour.
+         */
+        public byte removeFirstByte() {
+            // copied from superclass
+            byte t = this.array[this.start];
+            if (++this.start == this.length) {
+                this.start = 0;
+            }
+
+            return t;
+        }
+    }
+}
diff --git a/src/main/java/net/minecraft/Util.java b/src/main/java/net/minecraft/Util.java
index 092bfedfb32c38550d1cab1b696feac6df09131f..9870eccc1dc5c2201f12f8e2affe647f6b0375f8 100644
--- a/src/main/java/net/minecraft/Util.java
+++ b/src/main/java/net/minecraft/Util.java
@@ -118,7 +118,7 @@ public class Util {
     }
 
     public static long getNanos() {
-        return timeSource.getAsLong();
+        return System.nanoTime(); // Paper
     }
 
     public static long getEpochMillis() {
diff --git a/src/main/java/net/minecraft/core/BlockPos.java b/src/main/java/net/minecraft/core/BlockPos.java
index 2bb5e51f71cbf66819d198505aa4a5ecffd246c6..1834f3efb05fd70c8c1c67733bff514829ae1154 100644
--- a/src/main/java/net/minecraft/core/BlockPos.java
+++ b/src/main/java/net/minecraft/core/BlockPos.java
@@ -562,6 +562,7 @@ public class BlockPos extends Vec3i {
             }
         }
 
+        // Paper start - comment out useless overrides @Override - TODO figure out why this is suddenly important to keep
         @Override
         public BlockPos.MutableBlockPos setX(int i) {
             super.setX(i);
@@ -579,6 +580,7 @@ public class BlockPos extends Vec3i {
             super.setZ(i);
             return this;
         }
+        // Paper end
 
         @Override
         public BlockPos immutable() {
diff --git a/src/main/java/net/minecraft/nbt/CompoundTag.java b/src/main/java/net/minecraft/nbt/CompoundTag.java
index 666df22c8f847ef7152669540a3844566ef90d78..92095b494a0c4fb89b84f0b1c0376615d28e34ce 100644
--- a/src/main/java/net/minecraft/nbt/CompoundTag.java
+++ b/src/main/java/net/minecraft/nbt/CompoundTag.java
@@ -160,7 +160,7 @@ public class CompoundTag implements Tag {
             return "TAG_Compound";
         }
     };
-    private final Map<String, Tag> tags;
+    public final Map<String, Tag> tags; // Paper
 
     protected CompoundTag(Map<String, Tag> entries) {
         this.tags = entries;
@@ -236,6 +236,10 @@ public class CompoundTag implements Tag {
         this.tags.put(key, NbtUtils.createUUID(value));
     }
 
+
+    /**
+     * You must use {@link #hasUUID(String)} before or else it <b>will</b> throw an NPE.
+     */
     public UUID getUUID(String key) {
         return NbtUtils.loadUUID(this.get(key));
     }
diff --git a/src/main/java/net/minecraft/network/PacketEncoder.java b/src/main/java/net/minecraft/network/PacketEncoder.java
index 427959874b7f167184785a582163029ad4a66df2..344c5af75c4a66bb27f3f422937c6c427c15ed25 100644
--- a/src/main/java/net/minecraft/network/PacketEncoder.java
+++ b/src/main/java/net/minecraft/network/PacketEncoder.java
@@ -46,7 +46,7 @@ public class PacketEncoder extends MessageToByteEncoder<Packet<?>> {
 
                     JvmProfiler.INSTANCE.onPacketSent(codecData.protocol(), i, channelHandlerContext.channel().remoteAddress(), k);
                 } catch (Throwable var13) {
-                    LOGGER.error("Error receiving packet {}", i, var13);
+                    LOGGER.error("Packet encoding of packet ID {} threw (skippable? {})", i, packet.isSkippable(), var13); // Paper - Give proper error message
                     if (packet.isSkippable()) {
                         throw new SkipPacketException(var13);
                     }
diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java
index 124fad1031d6125bca233541e2d5f256da70ca44..2a7c614df7b9c9405a5dd23e6a888ede7fc86683 100644
--- a/src/main/java/net/minecraft/server/MinecraftServer.java
+++ b/src/main/java/net/minecraft/server/MinecraftServer.java
@@ -290,6 +290,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
     public final double[] recentTps = new double[ 3 ];
     // Spigot end
     public final io.papermc.paper.configuration.PaperConfigurations paperConfigurations;
+    public static long currentTickLong = 0L; // Paper
 
     public static <S extends MinecraftServer> S spin(Function<Thread, S> serverFactory) {
         AtomicReference<S> atomicreference = new AtomicReference();
@@ -910,6 +911,9 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
             MinecraftServer.LOGGER.error("Failed to unlock level {}", this.storageSource.getLevelId(), ioexception1);
         }
         // Spigot start
+        io.papermc.paper.util.MCUtil.asyncExecutor.shutdown(); // Paper
+        try { io.papermc.paper.util.MCUtil.asyncExecutor.awaitTermination(30, java.util.concurrent.TimeUnit.SECONDS); // Paper
+        } catch (java.lang.InterruptedException ignored) {} // Paper
         if (org.spigotmc.SpigotConfig.saveUserCacheOnStopOnly) {
             MinecraftServer.LOGGER.info("Saving usercache.json");
             this.getProfileCache().save();
@@ -974,6 +978,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
                     this.lastOverloadWarning = this.nextTickTime;
                 }
 
+                ++MinecraftServer.currentTickLong; // Paper
                 if ( tickCount++ % MinecraftServer.SAMPLE_INTERVAL == 0 )
                 {
                     double currentTps = 1E3 / ( curTime - tickSection ) * MinecraftServer.SAMPLE_INTERVAL;
@@ -1191,7 +1196,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
             MinecraftServer.LOGGER.debug("Autosave finished");
             SpigotTimings.worldSaveTimer.stopTiming(); // Spigot
         }
-
+        io.papermc.paper.util.CachedLists.reset(); // Paper
         this.profiler.push("tallying");
         long j = this.tickTimes[this.tickCount % 100] = Util.getNanos() - i;
 
@@ -1286,6 +1291,11 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
             try {
                 worldserver.timings.doTick.startTiming(); // Spigot
                 worldserver.tick(shouldKeepTicking);
+                // Paper start
+                for (final io.papermc.paper.chunk.SingleThreadChunkRegionManager regionManager : worldserver.getChunkSource().chunkMap.regionManagers) {
+                    regionManager.recalculateRegions();
+                }
+                // Paper end
                 worldserver.timings.doTick.stopTiming(); // Spigot
             } catch (Throwable throwable) {
                 // Spigot Start
diff --git a/src/main/java/net/minecraft/server/level/ChunkHolder.java b/src/main/java/net/minecraft/server/level/ChunkHolder.java
index 1641bdf8725df778ba91bf5cd22c1ebbb3745058..facfdbb87e89f4db33ce13233c2ba4366d35c15b 100644
--- a/src/main/java/net/minecraft/server/level/ChunkHolder.java
+++ b/src/main/java/net/minecraft/server/level/ChunkHolder.java
@@ -50,9 +50,9 @@ public class ChunkHolder {
     private static final List<ChunkStatus> CHUNK_STATUSES = ChunkStatus.getStatusList();
     private final AtomicReferenceArray<CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>>> futures;
     private final LevelHeightAccessor levelHeightAccessor;
-    private volatile CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> fullChunkFuture;
-    private volatile CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> tickingChunkFuture;
-    private volatile CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> entityTickingChunkFuture;
+    private volatile CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> fullChunkFuture; private int fullChunkCreateCount; private volatile boolean isFullChunkReady; // Paper - cache chunk ticking stage
+    private volatile CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> tickingChunkFuture; private volatile boolean isTickingReady; // Paper - cache chunk ticking stage
+    private volatile CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> entityTickingChunkFuture; private volatile boolean isEntityTickingReady; // Paper - cache chunk ticking stage
     private CompletableFuture<ChunkAccess> chunkToSave;
     @Nullable
     private final DebugBuffer<ChunkHolder.ChunkSaveDebug> chunkToSaveHistory;
@@ -71,6 +71,18 @@ public class ChunkHolder {
     private CompletableFuture<Void> pendingFullStateConfirmation;
     private CompletableFuture<?> sendSync;
 
+    private final ChunkMap chunkMap; // Paper
+
+    // Paper start
+    public void onChunkAdd() {
+
+    }
+
+    public void onChunkRemove() {
+
+    }
+    // Paper end
+
     public ChunkHolder(ChunkPos pos, int level, LevelHeightAccessor world, LevelLightEngine lightingProvider, ChunkHolder.LevelChangeListener levelUpdateListener, ChunkHolder.PlayerProvider playersWatchingChunkProvider) {
         this.futures = new AtomicReferenceArray(ChunkHolder.CHUNK_STATUSES.size());
         this.fullChunkFuture = ChunkHolder.UNLOADED_LEVEL_CHUNK_FUTURE;
@@ -92,8 +104,23 @@ public class ChunkHolder {
         this.queueLevel = this.oldTicketLevel;
         this.setTicketLevel(level);
         this.changedBlocksPerSection = new ShortSet[world.getSectionsCount()];
+        this.chunkMap = (ChunkMap)playersWatchingChunkProvider; // Paper
     }
 
+    // Paper start
+    public @Nullable ChunkAccess getAvailableChunkNow() {
+        // TODO can we just getStatusFuture(EMPTY)?
+        for (ChunkStatus curr = ChunkStatus.FULL, next = curr.getParent(); curr != next; curr = next, next = next.getParent()) {
+            CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>> future = this.getFutureIfPresentUnchecked(curr);
+            Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure> either = future.getNow(null);
+            if (either == null || either.left().isEmpty()) {
+                continue;
+            }
+            return either.left().get();
+        }
+        return null;
+    }
+    // Paper end
     // CraftBukkit start
     public LevelChunk getFullChunkNow() {
         // Note: We use the oldTicketLevel for isLoaded checks.
@@ -118,20 +145,20 @@ public class ChunkHolder {
         return ChunkLevel.generationStatus(this.ticketLevel).isOrAfter(leastStatus) ? this.getFutureIfPresentUnchecked(leastStatus) : ChunkHolder.UNLOADED_CHUNK_FUTURE;
     }
 
-    public CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> getTickingChunkFuture() {
+    public final CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> getTickingChunkFuture() { // Paper - final for inline
         return this.tickingChunkFuture;
     }
 
-    public CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> getEntityTickingChunkFuture() {
+    public final CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> getEntityTickingChunkFuture() { // Paper - final for inline
         return this.entityTickingChunkFuture;
     }
 
-    public CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> getFullChunkFuture() {
+    public final CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> getFullChunkFuture() { // Paper - final for inline
         return this.fullChunkFuture;
     }
 
     @Nullable
-    public LevelChunk getTickingChunk() {
+    public final LevelChunk getTickingChunk() { // Paper - final for inline
         CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> completablefuture = this.getTickingChunkFuture();
         Either<LevelChunk, ChunkHolder.ChunkLoadingFailure> either = (Either) completablefuture.getNow(null); // CraftBukkit - decompile error
 
@@ -148,7 +175,7 @@ public class ChunkHolder {
     }
 
     @Nullable
-    public LevelChunk getFullChunk() {
+    public final LevelChunk getFullChunk() { // Paper - final for inline
         CompletableFuture<Either<LevelChunk, ChunkHolder.ChunkLoadingFailure>> completablefuture = this.getFullChunkFuture();
         Either<LevelChunk, ChunkHolder.ChunkLoadingFailure> either = (Either) completablefuture.getNow(null); // CraftBukkit - decompile error
 
@@ -169,6 +196,21 @@ public class ChunkHolder {
         return null;
     }
 
+    // Paper start
+    public ChunkStatus getChunkHolderStatus() {
+        for (ChunkStatus curr = ChunkStatus.FULL, next = curr.getParent(); curr != next; curr = next, next = next.getParent()) {
+            CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>> future = this.getFutureIfPresentUnchecked(curr);
+            Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure> either = future.getNow(null);
+            if (either == null || !either.left().isPresent()) {
+                continue;
+            }
+            return curr;
+        }
+
+        return null;
+    }
+    // Paper end
+
     @Nullable
     public ChunkAccess getLastAvailable() {
         for (int i = ChunkHolder.CHUNK_STATUSES.size() - 1; i >= 0; --i) {
@@ -187,7 +229,7 @@ public class ChunkHolder {
         return null;
     }
 
-    public CompletableFuture<ChunkAccess> getChunkToSave() {
+    public final CompletableFuture<ChunkAccess> getChunkToSave() { // Paper - final for inline
         return this.chunkToSave;
     }
 
@@ -386,11 +428,11 @@ public class ChunkHolder {
         return ChunkLevel.fullStatus(this.ticketLevel);
     }
 
-    public ChunkPos getPos() {
+    public final ChunkPos getPos() { // Paper - final for inline
         return this.pos;
     }
 
-    public int getTicketLevel() {
+    public final int getTicketLevel() { // Paper - final for inline
         return this.ticketLevel;
     }
 
@@ -479,14 +521,31 @@ public class ChunkHolder {
 
         this.wasAccessibleSinceLastSave |= flag3;
         if (!flag2 && flag3) {
+            int expectCreateCount = ++this.fullChunkCreateCount; // Paper
             this.fullChunkFuture = chunkStorage.prepareAccessibleChunk(this);
             this.scheduleFullChunkPromotion(chunkStorage, this.fullChunkFuture, executor, FullChunkStatus.FULL);
+            // Paper start - cache ticking ready status
+            this.fullChunkFuture.thenAccept(either -> {
+                final Optional<LevelChunk> left = either.left();
+                if (left.isPresent() && ChunkHolder.this.fullChunkCreateCount == expectCreateCount) {
+                    LevelChunk fullChunk = either.left().get();
+                    ChunkHolder.this.isFullChunkReady = true;
+                    io.papermc.paper.chunk.system.ChunkSystem.onChunkBorder(fullChunk, this);
+                }
+            });
             this.updateChunkToSave(this.fullChunkFuture, "full");
         }
 
         if (flag2 && !flag3) {
+            // Paper start
+            if (this.isFullChunkReady) {
+                io.papermc.paper.chunk.system.ChunkSystem.onChunkNotBorder(this.fullChunkFuture.join().left().get(), this); // Paper
+            }
+            // Paper end
             this.fullChunkFuture.complete(ChunkHolder.UNLOADED_LEVEL_CHUNK);
             this.fullChunkFuture = ChunkHolder.UNLOADED_LEVEL_CHUNK_FUTURE;
+            ++this.fullChunkCreateCount; // Paper - cache ticking ready status
+            this.isFullChunkReady = false; // Paper - cache ticking ready status
         }
 
         boolean flag4 = fullchunkstatus.isOrAfter(FullChunkStatus.BLOCK_TICKING);
@@ -495,11 +554,25 @@ public class ChunkHolder {
         if (!flag4 && flag5) {
             this.tickingChunkFuture = chunkStorage.prepareTickingChunk(this);
             this.scheduleFullChunkPromotion(chunkStorage, this.tickingChunkFuture, executor, FullChunkStatus.BLOCK_TICKING);
+            // Paper start - cache ticking ready status
+            this.tickingChunkFuture.thenAccept(either -> {
+                either.ifLeft(chunk -> {
+                    // note: Here is a very good place to add callbacks to logic waiting on this.
+                    ChunkHolder.this.isTickingReady = true;
+                    io.papermc.paper.chunk.system.ChunkSystem.onChunkTicking(chunk, this);
+                });
+            });
+            // Paper end
             this.updateChunkToSave(this.tickingChunkFuture, "ticking");
         }
 
         if (flag4 && !flag5) {
-            this.tickingChunkFuture.complete(ChunkHolder.UNLOADED_LEVEL_CHUNK);
+            // Paper start
+            if (this.isTickingReady) {
+                io.papermc.paper.chunk.system.ChunkSystem.onChunkNotTicking(this.tickingChunkFuture.join().left().get(), this); // Paper
+            }
+            // Paper end
+            this.tickingChunkFuture.complete(ChunkHolder.UNLOADED_LEVEL_CHUNK); this.isTickingReady = false; // Paper - cache chunk ticking stage
             this.tickingChunkFuture = ChunkHolder.UNLOADED_LEVEL_CHUNK_FUTURE;
         }
 
@@ -513,11 +586,24 @@ public class ChunkHolder {
 
             this.entityTickingChunkFuture = chunkStorage.prepareEntityTickingChunk(this);
             this.scheduleFullChunkPromotion(chunkStorage, this.entityTickingChunkFuture, executor, FullChunkStatus.ENTITY_TICKING);
+            // Paper start - cache ticking ready status
+            this.entityTickingChunkFuture.thenAccept(either -> {
+                either.ifLeft(chunk -> {
+                    ChunkHolder.this.isEntityTickingReady = true;
+                    io.papermc.paper.chunk.system.ChunkSystem.onChunkEntityTicking(chunk, this);
+                });
+            });
+            // Paper end
             this.updateChunkToSave(this.entityTickingChunkFuture, "entity ticking");
         }
 
         if (flag6 && !flag7) {
-            this.entityTickingChunkFuture.complete(ChunkHolder.UNLOADED_LEVEL_CHUNK);
+            // Paper start
+            if (this.isEntityTickingReady) {
+                io.papermc.paper.chunk.system.ChunkSystem.onChunkNotEntityTicking(this.entityTickingChunkFuture.join().left().get(), this);
+            }
+            // Paper end
+            this.entityTickingChunkFuture.complete(ChunkHolder.UNLOADED_LEVEL_CHUNK); this.isEntityTickingReady = false; // Paper - cache chunk ticking stage
             this.entityTickingChunkFuture = ChunkHolder.UNLOADED_LEVEL_CHUNK_FUTURE;
         }
 
@@ -615,4 +701,18 @@ public class ChunkHolder {
             }
         };
     }
+
+    // Paper start
+    public final boolean isEntityTickingReady() {
+        return this.isEntityTickingReady;
+    }
+
+    public final boolean isTickingReady() {
+        return this.isTickingReady;
+    }
+
+    public final boolean isFullChunkReady() {
+        return this.isFullChunkReady;
+    }
+    // Paper end
 }
diff --git a/src/main/java/net/minecraft/server/level/ChunkMap.java b/src/main/java/net/minecraft/server/level/ChunkMap.java
index e9cf8686b59c232816b2fde92fc6616f77979a64..a7c18ca224c536b7b97d5889af321f23e637b420 100644
--- a/src/main/java/net/minecraft/server/level/ChunkMap.java
+++ b/src/main/java/net/minecraft/server/level/ChunkMap.java
@@ -167,6 +167,56 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
     };
     // CraftBukkit end
 
+    // Paper start - distance maps
+    private final com.destroystokyo.paper.util.misc.PooledLinkedHashSets<ServerPlayer> pooledLinkedPlayerHashSets = new com.destroystokyo.paper.util.misc.PooledLinkedHashSets<>();
+
+    void addPlayerToDistanceMaps(ServerPlayer player) {
+        int chunkX = io.papermc.paper.util.MCUtil.getChunkCoordinate(player.getX());
+        int chunkZ = io.papermc.paper.util.MCUtil.getChunkCoordinate(player.getZ());
+        // Note: players need to be explicitly added to distance maps before they can be updated
+    }
+
+    void removePlayerFromDistanceMaps(ServerPlayer player) {
+
+    }
+
+    void updateMaps(ServerPlayer player) {
+        int chunkX = io.papermc.paper.util.MCUtil.getChunkCoordinate(player.getX());
+        int chunkZ = io.papermc.paper.util.MCUtil.getChunkCoordinate(player.getZ());
+        // Note: players need to be explicitly added to distance maps before they can be updated
+    }
+    // Paper end
+    // Paper start
+    public final List<io.papermc.paper.chunk.SingleThreadChunkRegionManager> regionManagers = new java.util.ArrayList<>();
+    public final io.papermc.paper.chunk.SingleThreadChunkRegionManager dataRegionManager;
+
+    public static final class DataRegionData implements io.papermc.paper.chunk.SingleThreadChunkRegionManager.RegionData {
+    }
+
+    public static final class DataRegionSectionData implements io.papermc.paper.chunk.SingleThreadChunkRegionManager.RegionSectionData {
+
+        @Override
+        public void removeFromRegion(final io.papermc.paper.chunk.SingleThreadChunkRegionManager.RegionSection section,
+                                     final io.papermc.paper.chunk.SingleThreadChunkRegionManager.Region from) {
+            final DataRegionSectionData sectionData = (DataRegionSectionData)section.sectionData;
+            final DataRegionData fromData = (DataRegionData)from.regionData;
+        }
+
+        @Override
+        public void addToRegion(final io.papermc.paper.chunk.SingleThreadChunkRegionManager.RegionSection section,
+                                final io.papermc.paper.chunk.SingleThreadChunkRegionManager.Region oldRegion,
+                                final io.papermc.paper.chunk.SingleThreadChunkRegionManager.Region newRegion) {
+            final DataRegionSectionData sectionData = (DataRegionSectionData)section.sectionData;
+            final DataRegionData oldRegionData = oldRegion == null ? null : (DataRegionData)oldRegion.regionData;
+            final DataRegionData newRegionData = (DataRegionData)newRegion.regionData;
+        }
+    }
+
+    public final ChunkHolder getUnloadingChunkHolder(int chunkX, int chunkZ) {
+        return this.pendingUnloads.get(io.papermc.paper.util.CoordinateUtils.getChunkKey(chunkX, chunkZ));
+    }
+    // Paper end
+
     public ChunkMap(ServerLevel world, LevelStorageSource.LevelStorageAccess session, DataFixer dataFixer, StructureTemplateManager structureTemplateManager, Executor executor, BlockableEventLoop<Runnable> mainThreadExecutor, LightChunkGetter chunkProvider, ChunkGenerator chunkGenerator, ChunkProgressListener worldGenerationProgressListener, ChunkStatusUpdateListener chunkStatusChangeListener, Supplier<DimensionDataStorage> persistentStateManagerFactory, int viewDistance, boolean dsync) {
         super(session.getDimensionPath(world.dimension()).resolve("region"), dataFixer, dsync);
         this.visibleChunkMap = this.updatingChunkMap.clone();
@@ -220,6 +270,10 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
         this.overworldDataStorage = persistentStateManagerFactory;
         this.poiManager = new PoiManager(path.resolve("poi"), dataFixer, dsync, iregistrycustom, world);
         this.setServerViewDistance(viewDistance);
+        // Paper start
+        this.dataRegionManager = new io.papermc.paper.chunk.SingleThreadChunkRegionManager(this.level, 2, (1.0 / 3.0), 1, 6, "Data", DataRegionData::new, DataRegionSectionData::new);
+        this.regionManagers.add(this.dataRegionManager);
+        // Paper end
     }
 
     protected ChunkGenerator generator() {
@@ -321,6 +375,15 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
         }
     }
 
+    // Paper start
+    public final int getEffectiveViewDistance() {
+        // TODO this needs to be checked on update
+        // Mojang currently sets it to +1 of the configured view distance. So subtract one to get the one we really want.
+        //TODO check if +0 is correct now
+        return this.viewDistance;
+    }
+    // Paper end
+
     private CompletableFuture<Either<List<ChunkAccess>, ChunkHolder.ChunkLoadingFailure>> getChunkRangeFuture(ChunkHolder centerChunk, int margin, IntFunction<ChunkStatus> distanceToStatus) {
         if (margin == 0) {
             ChunkStatus chunkstatus = (ChunkStatus) distanceToStatus.apply(0);
@@ -417,9 +480,9 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
         };
 
         stringbuilder.append("Updating:").append(System.lineSeparator());
-        this.updatingChunkMap.values().forEach(consumer);
+        io.papermc.paper.chunk.system.ChunkSystem.getUpdatingChunkHolders(this.level).forEach(consumer); // Paper
         stringbuilder.append("Visible:").append(System.lineSeparator());
-        this.visibleChunkMap.values().forEach(consumer);
+        io.papermc.paper.chunk.system.ChunkSystem.getVisibleChunkHolders(this.level).forEach(consumer); // Paper
         CrashReport crashreport = CrashReport.forThrowable(exception, "Chunk loading");
         CrashReportCategory crashreportsystemdetails = crashreport.addCategory("Chunk loading");
 
@@ -461,8 +524,14 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
                     holder.setTicketLevel(level);
                 } else {
                     holder = new ChunkHolder(new ChunkPos(pos), level, this.level, this.lightEngine, this.queueSorter, this);
+                    // Paper start
+                    io.papermc.paper.chunk.system.ChunkSystem.onChunkHolderCreate(this.level, holder);
+                    // Paper end
                 }
 
+                // Paper start
+                holder.onChunkAdd();
+                // Paper end
                 this.updatingChunkMap.put(pos, holder);
                 this.modified = true;
             }
@@ -484,7 +553,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
 
     protected void saveAllChunks(boolean flush) {
         if (flush) {
-            List<ChunkHolder> list = this.visibleChunkMap.values().stream().filter(ChunkHolder::wasAccessibleSinceLastSave).peek(ChunkHolder::refreshAccessibility).toList();
+            List<ChunkHolder> list = io.papermc.paper.chunk.system.ChunkSystem.getVisibleChunkHolders(this.level).stream().filter(ChunkHolder::wasAccessibleSinceLastSave).peek(ChunkHolder::refreshAccessibility).toList(); // Paper
             MutableBoolean mutableboolean = new MutableBoolean();
 
             do {
@@ -513,7 +582,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
             });
             this.flushWorker();
         } else {
-            this.visibleChunkMap.values().forEach(this::saveChunkIfNeeded);
+            io.papermc.paper.chunk.system.ChunkSystem.getVisibleChunkHolders(this.level).forEach(this::saveChunkIfNeeded);
         }
 
     }
@@ -532,7 +601,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
     }
 
     public boolean hasWork() {
-        return this.lightEngine.hasLightWork() || !this.pendingUnloads.isEmpty() || !this.updatingChunkMap.isEmpty() || this.poiManager.hasWork() || !this.toDrop.isEmpty() || !this.unloadQueue.isEmpty() || this.queueSorter.hasWork() || this.distanceManager.hasTickets();
+        return this.lightEngine.hasLightWork() || !this.pendingUnloads.isEmpty() || io.papermc.paper.chunk.system.ChunkSystem.hasAnyChunkHolders(this.level) || this.poiManager.hasWork() || !this.toDrop.isEmpty() || !this.unloadQueue.isEmpty() || this.queueSorter.hasWork() || this.distanceManager.hasTickets(); // Paper
     }
 
     private void processUnloads(BooleanSupplier shouldKeepTicking) {
@@ -543,6 +612,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
             ChunkHolder playerchunk = (ChunkHolder) this.updatingChunkMap.remove(j);
 
             if (playerchunk != null) {
+                playerchunk.onChunkRemove(); // Paper
                 this.pendingUnloads.put(j, playerchunk);
                 this.modified = true;
                 ++i;
@@ -560,7 +630,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
         }
 
         int l = 0;
-        ObjectIterator objectiterator = this.visibleChunkMap.values().iterator();
+        Iterator objectiterator = io.papermc.paper.chunk.system.ChunkSystem.getVisibleChunkHolders(this.level).iterator(); // Paper
 
         while (l < 20 && shouldKeepTicking.getAsBoolean() && objectiterator.hasNext()) {
             if (this.saveChunkIfNeeded((ChunkHolder) objectiterator.next())) {
@@ -578,7 +648,11 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
             if (completablefuture1 != completablefuture) {
                 this.scheduleUnload(pos, holder);
             } else {
-                if (this.pendingUnloads.remove(pos, holder) && ichunkaccess != null) {
+                // Paper start
+                boolean removed;
+                if ((removed = this.pendingUnloads.remove(pos, holder)) && ichunkaccess != null) {
+                    io.papermc.paper.chunk.system.ChunkSystem.onChunkHolderDelete(this.level, holder);
+                    // Paper end
                     if (ichunkaccess instanceof LevelChunk) {
                         ((LevelChunk) ichunkaccess).setLoaded(false);
                     }
@@ -594,7 +668,9 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
                     this.lightEngine.tryScheduleUpdate();
                     this.progressListener.onStatusChange(ichunkaccess.getPos(), (ChunkStatus) null);
                     this.chunkSaveCooldowns.remove(ichunkaccess.getPos().toLong());
-                }
+                } else if (removed) { // Paper start
+                    io.papermc.paper.chunk.system.ChunkSystem.onChunkHolderDelete(this.level, holder);
+                } // Paper end
 
             }
         };
@@ -1037,7 +1113,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
     }
 
     public int size() {
-        return this.visibleChunkMap.size();
+        return io.papermc.paper.chunk.system.ChunkSystem.getVisibleChunkHolderCount(this.level); // Paper
     }
 
     public DistanceManager getDistanceManager() {
@@ -1045,19 +1121,19 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
     }
 
     protected Iterable<ChunkHolder> getChunks() {
-        return Iterables.unmodifiableIterable(this.visibleChunkMap.values());
+        return Iterables.unmodifiableIterable(io.papermc.paper.chunk.system.ChunkSystem.getVisibleChunkHolders(this.level)); // Paper
     }
 
     void dumpChunks(Writer writer) throws IOException {
         CsvOutput csvwriter = CsvOutput.builder().addColumn("x").addColumn("z").addColumn("level").addColumn("in_memory").addColumn("status").addColumn("full_status").addColumn("accessible_ready").addColumn("ticking_ready").addColumn("entity_ticking_ready").addColumn("ticket").addColumn("spawning").addColumn("block_entity_count").addColumn("ticking_ticket").addColumn("ticking_level").addColumn("block_ticks").addColumn("fluid_ticks").build(writer);
         TickingTracker tickingtracker = this.distanceManager.tickingTracker();
-        ObjectBidirectionalIterator objectbidirectionaliterator = this.visibleChunkMap.long2ObjectEntrySet().iterator();
+        Iterator<ChunkHolder> objectbidirectionaliterator = io.papermc.paper.chunk.system.ChunkSystem.getVisibleChunkHolders(this.level).iterator(); // Paper
 
         while (objectbidirectionaliterator.hasNext()) {
-            Entry<ChunkHolder> entry = (Entry) objectbidirectionaliterator.next();
-            long i = entry.getLongKey();
+            ChunkHolder playerchunk = objectbidirectionaliterator.next(); // Paper
+            long i = playerchunk.pos.toLong(); // Paper
             ChunkPos chunkcoordintpair = new ChunkPos(i);
-            ChunkHolder playerchunk = (ChunkHolder) entry.getValue();
+            // Paper
             Optional<ChunkAccess> optional = Optional.ofNullable(playerchunk.getLastAvailable());
             Optional<LevelChunk> optional1 = optional.flatMap((ichunkaccess) -> {
                 return ichunkaccess instanceof LevelChunk ? Optional.of((LevelChunk) ichunkaccess) : Optional.empty();
@@ -1182,6 +1258,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
 
             player.setChunkTrackingView(ChunkTrackingView.EMPTY);
             this.updateChunkTracking(player);
+            this.addPlayerToDistanceMaps(player); // Paper - distance maps
         } else {
             SectionPos sectionposition = player.getLastSectionPos();
 
@@ -1190,6 +1267,9 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
                 this.distanceManager.removePlayer(sectionposition, player);
             }
 
+            this.removePlayerFromDistanceMaps(player); // Paper - distance maps
+        }
+
             this.applyChunkTrackingView(player, ChunkTrackingView.EMPTY);
         }
 
@@ -1241,6 +1321,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
             this.updateChunkTracking(player);
         }
 
+        this.updateMaps(player); // Paper - distance maps
     }
 
     private void updateChunkTracking(ServerPlayer player) {
@@ -1493,7 +1574,7 @@ public class ChunkMap extends ChunkStorage implements ChunkHolder.PlayerProvider
     private class ChunkDistanceManager extends DistanceManager {
 
         protected ChunkDistanceManager(Executor workerExecutor, Executor mainThreadExecutor) {
-            super(workerExecutor, mainThreadExecutor);
+            super(workerExecutor, mainThreadExecutor, ChunkMap.this);
         }
 
         @Override
diff --git a/src/main/java/net/minecraft/server/level/DistanceManager.java b/src/main/java/net/minecraft/server/level/DistanceManager.java
index 1bfa33253a154c66dc8b7e476c777b74cda8999f..d8b83c8c89143d78620f812c491a1950e3218eb1 100644
--- a/src/main/java/net/minecraft/server/level/DistanceManager.java
+++ b/src/main/java/net/minecraft/server/level/DistanceManager.java
@@ -56,8 +56,9 @@ public abstract class DistanceManager {
     final Executor mainThreadExecutor;
     private long ticketTickCounter;
     private int simulationDistance = 10;
+    private final ChunkMap chunkMap; // Paper
 
-    protected DistanceManager(Executor workerExecutor, Executor mainThreadExecutor) {
+    protected DistanceManager(Executor workerExecutor, Executor mainThreadExecutor, ChunkMap chunkMap) {
         Objects.requireNonNull(mainThreadExecutor);
         ProcessorHandle<Runnable> mailbox = ProcessorHandle.of("player ticket throttler", mainThreadExecutor::execute);
         ChunkTaskPriorityQueueSorter chunktaskqueuesorter = new ChunkTaskPriorityQueueSorter(ImmutableList.of(mailbox), workerExecutor, 4);
@@ -66,6 +67,7 @@ public abstract class DistanceManager {
         this.ticketThrottlerInput = chunktaskqueuesorter.getProcessor(mailbox, true);
         this.ticketThrottlerReleaser = chunktaskqueuesorter.getReleaseProcessor(mailbox);
         this.mainThreadExecutor = mainThreadExecutor;
+        this.chunkMap = chunkMap; // Paper
     }
 
     protected void purgeStaleTickets() {
@@ -315,6 +317,12 @@ public abstract class DistanceManager {
         this.playerTicketManager.updateViewDistance(viewDistance);
     }
 
+    // Paper start
+    public int getSimulationDistance() {
+        return this.simulationDistance;
+    }
+    // Paper end
+
     public void updateSimulationDistance(int simulationDistance) {
         if (simulationDistance != this.simulationDistance) {
             this.simulationDistance = simulationDistance;
@@ -378,7 +386,7 @@ public abstract class DistanceManager {
     }
 
     public void removeTicketsOnClosing() {
-        ImmutableSet<TicketType<?>> immutableset = ImmutableSet.of(TicketType.UNKNOWN, TicketType.POST_TELEPORT, TicketType.LIGHT);
+        ImmutableSet<TicketType<?>> immutableset = ImmutableSet.of(TicketType.UNKNOWN, TicketType.POST_TELEPORT, TicketType.LIGHT, TicketType.FUTURE_AWAIT); // Paper - add additional tickets to preserve
         ObjectIterator objectiterator = this.tickets.long2ObjectEntrySet().fastIterator();
 
         while (objectiterator.hasNext()) {
diff --git a/src/main/java/net/minecraft/server/level/ServerChunkCache.java b/src/main/java/net/minecraft/server/level/ServerChunkCache.java
index 6c94ffc01377e3a066771509727e62521b2cea78..f402341b95c7752a2706edd502098696f786f4ef 100644
--- a/src/main/java/net/minecraft/server/level/ServerChunkCache.java
+++ b/src/main/java/net/minecraft/server/level/ServerChunkCache.java
@@ -51,6 +51,7 @@ import net.minecraft.world.level.storage.LevelStorageSource;
 
 public class ServerChunkCache extends ChunkSource {
 
+    public static final org.slf4j.Logger LOGGER = com.mojang.logging.LogUtils.getLogger(); // Paper
     private static final List<ChunkStatus> CHUNK_STATUSES = ChunkStatus.getStatusList();
     private final DistanceManager distanceManager;
     final ServerLevel level;
@@ -69,6 +70,231 @@ public class ServerChunkCache extends ChunkSource {
     @Nullable
     @VisibleForDebug
     private NaturalSpawner.SpawnState lastSpawnState;
+    // Paper start
+    final com.destroystokyo.paper.util.concurrent.WeakSeqLock loadedChunkMapSeqLock = new com.destroystokyo.paper.util.concurrent.WeakSeqLock();
+    final it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap<LevelChunk> loadedChunkMap = new it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap<>(8192, 0.5f);
+
+    private final LevelChunk[] lastLoadedChunks = new LevelChunk[4 * 4];
+
+    private static int getChunkCacheKey(int x, int z) {
+        return x & 3 | ((z & 3) << 2);
+    }
+
+    public void addLoadedChunk(LevelChunk chunk) {
+        this.loadedChunkMapSeqLock.acquireWrite();
+        try {
+            this.loadedChunkMap.put(chunk.coordinateKey, chunk);
+        } finally {
+            this.loadedChunkMapSeqLock.releaseWrite();
+        }
+
+        // rewrite cache if we have to
+        // we do this since we also cache null chunks
+        int cacheKey = getChunkCacheKey(chunk.locX, chunk.locZ);
+
+        this.lastLoadedChunks[cacheKey] = chunk;
+    }
+
+    public void removeLoadedChunk(LevelChunk chunk) {
+        this.loadedChunkMapSeqLock.acquireWrite();
+        try {
+            this.loadedChunkMap.remove(chunk.coordinateKey);
+        } finally {
+            this.loadedChunkMapSeqLock.releaseWrite();
+        }
+
+        // rewrite cache if we have to
+        // we do this since we also cache null chunks
+        int cacheKey = getChunkCacheKey(chunk.locX, chunk.locZ);
+
+        LevelChunk cachedChunk = this.lastLoadedChunks[cacheKey];
+        if (cachedChunk != null && cachedChunk.coordinateKey == chunk.coordinateKey) {
+            this.lastLoadedChunks[cacheKey] = null;
+        }
+    }
+
+    public final LevelChunk getChunkAtIfLoadedMainThread(int x, int z) {
+        int cacheKey = getChunkCacheKey(x, z);
+
+        LevelChunk cachedChunk = this.lastLoadedChunks[cacheKey];
+        if (cachedChunk != null && cachedChunk.locX == x & cachedChunk.locZ == z) {
+            return cachedChunk;
+        }
+
+        long chunkKey = ChunkPos.asLong(x, z);
+
+        cachedChunk = this.loadedChunkMap.get(chunkKey);
+        // Skipping a null check to avoid extra instructions to improve inline capability
+        this.lastLoadedChunks[cacheKey] = cachedChunk;
+        return cachedChunk;
+    }
+
+    public final LevelChunk getChunkAtIfLoadedMainThreadNoCache(int x, int z) {
+        return this.loadedChunkMap.get(ChunkPos.asLong(x, z));
+    }
+
+    public final LevelChunk getChunkAtMainThread(int x, int z) {
+        LevelChunk ret = this.getChunkAtIfLoadedMainThread(x, z);
+        if (ret != null) {
+            return ret;
+        }
+        return (LevelChunk)this.getChunk(x, z, ChunkStatus.FULL, true);
+    }
+
+    long chunkFutureAwaitCounter; // Paper - private -> package private
+
+    public void getEntityTickingChunkAsync(int x, int z, java.util.function.Consumer<LevelChunk> onLoad) {
+        io.papermc.paper.chunk.system.ChunkSystem.scheduleTickingState(
+            this.level, x, z, FullChunkStatus.ENTITY_TICKING, true,
+            ca.spottedleaf.concurrentutil.executor.standard.PrioritisedExecutor.Priority.NORMAL, onLoad
+        );
+    }
+
+    public void getTickingChunkAsync(int x, int z, java.util.function.Consumer<LevelChunk> onLoad) {
+        io.papermc.paper.chunk.system.ChunkSystem.scheduleTickingState(
+            this.level, x, z, FullChunkStatus.BLOCK_TICKING, true,
+            ca.spottedleaf.concurrentutil.executor.standard.PrioritisedExecutor.Priority.NORMAL, onLoad
+        );
+    }
+
+    public void getFullChunkAsync(int x, int z, java.util.function.Consumer<LevelChunk> onLoad) {
+        io.papermc.paper.chunk.system.ChunkSystem.scheduleTickingState(
+            this.level, x, z, FullChunkStatus.FULL, true,
+            ca.spottedleaf.concurrentutil.executor.standard.PrioritisedExecutor.Priority.NORMAL, onLoad
+        );
+    }
+
+    void chunkLoadAccept(int chunkX, int chunkZ, ChunkAccess chunk, java.util.function.Consumer<ChunkAccess> consumer) {
+        try {
+            consumer.accept(chunk);
+        } catch (Throwable throwable) {
+            if (throwable instanceof ThreadDeath) {
+                throw (ThreadDeath)throwable;
+            }
+            LOGGER.error("Load callback for chunk " + chunkX + "," + chunkZ + " in world '" + this.level.getWorld().getName() + "' threw an exception", throwable);
+        }
+    }
+
+    void getChunkAtAsynchronously(int chunkX, int chunkZ, int ticketLevel,
+                                  java.util.function.Consumer<ChunkAccess> consumer) {
+        if (ticketLevel <= 33) {
+            this.getFullChunkAsync(chunkX, chunkZ, (java.util.function.Consumer)consumer);
+            return;
+        }
+
+        io.papermc.paper.chunk.system.ChunkSystem.scheduleChunkLoad(
+            this.level, chunkX, chunkZ, ChunkHolder.getStatus(ticketLevel), true,
+            ca.spottedleaf.concurrentutil.executor.standard.PrioritisedExecutor.Priority.NORMAL, consumer
+        );
+    }
+
+
+    public final void getChunkAtAsynchronously(int chunkX, int chunkZ, ChunkStatus status, boolean gen, boolean allowSubTicketLevel, java.util.function.Consumer<ChunkAccess> onLoad) {
+        // try to fire sync
+        int chunkStatusTicketLevel = 33 + ChunkStatus.getDistance(status);
+        ChunkHolder playerChunk = this.chunkMap.getUpdatingChunkIfPresent(io.papermc.paper.util.CoordinateUtils.getChunkKey(chunkX, chunkZ));
+        if (playerChunk != null) {
+            ChunkStatus holderStatus = playerChunk.getChunkHolderStatus();
+            ChunkAccess immediate = playerChunk.getAvailableChunkNow();
+            if (immediate != null) {
+                if (allowSubTicketLevel ? immediate.getStatus().isOrAfter(status) : (playerChunk.getTicketLevel() <= chunkStatusTicketLevel && holderStatus != null && holderStatus.isOrAfter(status))) {
+                    this.chunkLoadAccept(chunkX, chunkZ, immediate, onLoad);
+                    return;
+                } else {
+                    if (gen || (!allowSubTicketLevel && immediate.getStatus().isOrAfter(status))) {
+                        this.getChunkAtAsynchronously(chunkX, chunkZ, chunkStatusTicketLevel, onLoad);
+                        return;
+                    } else {
+                        this.chunkLoadAccept(chunkX, chunkZ, null, onLoad);
+                        return;
+                    }
+                }
+            }
+        }
+
+        // need to fire async
+
+        if (gen && !allowSubTicketLevel) {
+            this.getChunkAtAsynchronously(chunkX, chunkZ, chunkStatusTicketLevel, onLoad);
+            return;
+        }
+
+        this.getChunkAtAsynchronously(chunkX, chunkZ, io.papermc.paper.util.MCUtil.getTicketLevelFor(ChunkStatus.EMPTY), (ChunkAccess chunk) -> {
+            if (chunk == null) {
+                throw new IllegalStateException("Chunk cannot be null");
+            }
+
+            if (!chunk.getStatus().isOrAfter(status)) {
+                if (gen) {
+                    this.getChunkAtAsynchronously(chunkX, chunkZ, chunkStatusTicketLevel, onLoad);
+                    return;
+                } else {
+                    ServerChunkCache.this.chunkLoadAccept(chunkX, chunkZ, null, onLoad);
+                    return;
+                }
+            } else {
+                if (allowSubTicketLevel) {
+                    ServerChunkCache.this.chunkLoadAccept(chunkX, chunkZ, chunk, onLoad);
+                    return;
+                } else {
+                    this.getChunkAtAsynchronously(chunkX, chunkZ, chunkStatusTicketLevel, onLoad);
+                    return;
+                }
+            }
+        });
+    }
+    // Paper end
+
+    // Paper start
+    @Nullable
+    public ChunkAccess getChunkAtImmediately(int x, int z) {
+        ChunkHolder holder = this.chunkMap.getVisibleChunkIfPresent(ChunkPos.asLong(x, z));
+        if (holder == null) {
+            return null;
+        }
+
+        return holder.getLastAvailable();
+    }
+
+    // this will try to avoid chunk neighbours for lighting
+    public final ChunkAccess getFullStatusChunkAt(int chunkX, int chunkZ) {
+        LevelChunk ifLoaded = this.getChunkAtIfLoadedImmediately(chunkX, chunkZ);
+        if (ifLoaded != null) {
+            return ifLoaded;
+        }
+
+        ChunkAccess empty = this.getChunk(chunkX, chunkZ, ChunkStatus.EMPTY, true);
+        if (empty != null && empty.getStatus().isOrAfter(ChunkStatus.FULL)) {
+            return empty;
+        }
+        return this.getChunk(chunkX, chunkZ, ChunkStatus.FULL, true);
+    }
+
+    public final ChunkAccess getFullStatusChunkAtIfLoaded(int chunkX, int chunkZ) {
+        LevelChunk ifLoaded = this.getChunkAtIfLoadedImmediately(chunkX, chunkZ);
+        if (ifLoaded != null) {
+            return ifLoaded;
+        }
+
+        ChunkAccess ret = this.getChunkAtImmediately(chunkX, chunkZ);
+        if (ret != null && ret.getStatus().isOrAfter(ChunkStatus.FULL)) {
+            return ret;
+        } else {
+            return null;
+        }
+    }
+
+    public <T> void addTicketAtLevel(TicketType<T> ticketType, ChunkPos chunkPos, int ticketLevel, T identifier) {
+        this.distanceManager.addTicket(ticketType, chunkPos, ticketLevel, identifier);
+    }
+
+    public <T> void removeTicketAtLevel(TicketType<T> ticketType, ChunkPos chunkPos, int ticketLevel, T identifier) {
+        this.distanceManager.removeTicket(ticketType, chunkPos, ticketLevel, identifier);
+    }
+
+    public final io.papermc.paper.util.maplist.IteratorSafeOrderedReferenceSet<LevelChunk> tickingChunks = new io.papermc.paper.util.maplist.IteratorSafeOrderedReferenceSet<>(4096, 0.75f, 4096, 0.15, true);
+    public final io.papermc.paper.util.maplist.IteratorSafeOrderedReferenceSet<LevelChunk> entityTickingChunks = new io.papermc.paper.util.maplist.IteratorSafeOrderedReferenceSet<>(4096, 0.75f, 4096, 0.15, true);
+    // Paper end
 
     public ServerChunkCache(ServerLevel world, LevelStorageSource.LevelStorageAccess session, DataFixer dataFixer, StructureTemplateManager structureTemplateManager, Executor workerExecutor, ChunkGenerator chunkGenerator, int viewDistance, int simulationDistance, boolean dsync, ChunkProgressListener worldGenerationProgressListener, ChunkStatusUpdateListener chunkStatusChangeListener, Supplier<DimensionDataStorage> persistentStateManagerFactory) {
         this.level = world;
@@ -121,6 +347,49 @@ public class ServerChunkCache extends ChunkSource {
         this.lastChunk[0] = chunk;
     }
 
+    // Paper start - "real" get chunk if loaded
+    // Note: Partially copied from the getChunkAt method below
+    @Nullable
+    public LevelChunk getChunkAtIfCachedImmediately(int x, int z) {
+        long k = ChunkPos.asLong(x, z);
+
+        // Note: Bypass cache since we need to check ticket level, and to make this MT-Safe
+
+        ChunkHolder playerChunk = this.getVisibleChunkIfPresent(k);
+        if (playerChunk == null) {
+            return null;
+        }
+
+        return playerChunk.getFullChunkNowUnchecked();
+    }
+
+    @Nullable
+    public LevelChunk getChunkAtIfLoadedImmediately(int x, int z) {
+        long k = ChunkPos.asLong(x, z);
+
+        if (Thread.currentThread() == this.mainThread) {
+            return this.getChunkAtIfLoadedMainThread(x, z);
+        }
+
+        LevelChunk ret = null;
+        long readlock;
+        do {
+            readlock = this.loadedChunkMapSeqLock.acquireRead();
+            try {
+                ret = this.loadedChunkMap.get(k);
+            } catch (Throwable thr) {
+                if (thr instanceof ThreadDeath) {
+                    throw (ThreadDeath)thr;
+                }
+                // re-try, this means a CME occurred...
+                continue;
+            }
+        } while (!this.loadedChunkMapSeqLock.tryReleaseRead(readlock));
+
+        return ret;
+    }
+    // Paper end
+
     @Nullable
     @Override
     public ChunkAccess getChunk(int x, int z, ChunkStatus leastStatus, boolean create) {
@@ -329,6 +598,12 @@ public class ServerChunkCache extends ChunkSource {
         }
     }
 
+    // Paper start
+    public boolean isPositionTicking(Entity entity) {
+        return this.isPositionTicking(ChunkPos.asLong(net.minecraft.util.Mth.floor(entity.getX()) >> 4, net.minecraft.util.Mth.floor(entity.getZ()) >> 4));
+    }
+    // Paper end
+
     public boolean isPositionTicking(long pos) {
         ChunkHolder playerchunk = this.getVisibleChunkIfPresent(pos);
 
diff --git a/src/main/java/net/minecraft/server/level/ServerLevel.java b/src/main/java/net/minecraft/server/level/ServerLevel.java
index 32565740c6b013d9ad644e7c62d6721bdbd15b10..e2eff46cae9771931b2e0dfee5e73fd4842e3ab5 100644
--- a/src/main/java/net/minecraft/server/level/ServerLevel.java
+++ b/src/main/java/net/minecraft/server/level/ServerLevel.java
@@ -176,6 +176,7 @@ import org.bukkit.event.weather.LightningStrikeEvent;
 import org.bukkit.event.world.GenericGameEvent;
 import org.bukkit.event.world.TimeSkipEvent;
 // CraftBukkit end
+import it.unimi.dsi.fastutil.ints.IntArrayList; // Paper
 
 public class ServerLevel extends Level implements WorldGenLevel {
 
@@ -228,6 +229,98 @@ public class ServerLevel extends Level implements WorldGenLevel {
         return convertable.dimensionType;
     }
 
+    // Paper start
+    public final boolean areChunksLoadedForMove(AABB axisalignedbb) {
+        // copied code from collision methods, so that we can guarantee that they wont load chunks (we don't override
+        // ICollisionAccess methods for VoxelShapes)
+        // be more strict too, add a block (dumb plugins in move events?)
+        int minBlockX = Mth.floor(axisalignedbb.minX - 1.0E-7D) - 3;
+        int maxBlockX = Mth.floor(axisalignedbb.maxX + 1.0E-7D) + 3;
+
+        int minBlockZ = Mth.floor(axisalignedbb.minZ - 1.0E-7D) - 3;
+        int maxBlockZ = Mth.floor(axisalignedbb.maxZ + 1.0E-7D) + 3;
+
+        int minChunkX = minBlockX >> 4;
+        int maxChunkX = maxBlockX >> 4;
+
+        int minChunkZ = minBlockZ >> 4;
+        int maxChunkZ = maxBlockZ >> 4;
+
+        ServerChunkCache chunkProvider = this.getChunkSource();
+
+        for (int cx = minChunkX; cx <= maxChunkX; ++cx) {
+            for (int cz = minChunkZ; cz <= maxChunkZ; ++cz) {
+                if (chunkProvider.getChunkAtIfLoadedImmediately(cx, cz) == null) {
+                    return false;
+                }
+            }
+        }
+
+        return true;
+    }
+
+    public final void loadChunksForMoveAsync(AABB axisalignedbb, ca.spottedleaf.concurrentutil.executor.standard.PrioritisedExecutor.Priority priority,
+                                             java.util.function.Consumer<List<net.minecraft.world.level.chunk.ChunkAccess>> onLoad) {
+        if (Thread.currentThread() != this.thread) {
+            this.getChunkSource().mainThreadProcessor.execute(() -> {
+                this.loadChunksForMoveAsync(axisalignedbb, priority, onLoad);
+            });
+            return;
+        }
+        List<net.minecraft.world.level.chunk.ChunkAccess> ret = new java.util.ArrayList<>();
+        IntArrayList ticketLevels = new IntArrayList();
+
+        int minBlockX = Mth.floor(axisalignedbb.minX - 1.0E-7D) - 3;
+        int maxBlockX = Mth.floor(axisalignedbb.maxX + 1.0E-7D) + 3;
+
+        int minBlockZ = Mth.floor(axisalignedbb.minZ - 1.0E-7D) - 3;
+        int maxBlockZ = Mth.floor(axisalignedbb.maxZ + 1.0E-7D) + 3;
+
+        int minChunkX = minBlockX >> 4;
+        int maxChunkX = maxBlockX >> 4;
+
+        int minChunkZ = minBlockZ >> 4;
+        int maxChunkZ = maxBlockZ >> 4;
+
+        ServerChunkCache chunkProvider = this.getChunkSource();
+
+        int requiredChunks = (maxChunkX - minChunkX + 1) * (maxChunkZ - minChunkZ + 1);
+        int[] loadedChunks = new int[1];
+
+        Long holderIdentifier = Long.valueOf(chunkProvider.chunkFutureAwaitCounter++);
+
+        java.util.function.Consumer<net.minecraft.world.level.chunk.ChunkAccess> consumer = (net.minecraft.world.level.chunk.ChunkAccess chunk) -> {
+            if (chunk != null) {
+                int ticketLevel = Math.max(33, chunkProvider.chunkMap.getUpdatingChunkIfPresent(chunk.getPos().toLong()).getTicketLevel());
+                ret.add(chunk);
+                ticketLevels.add(ticketLevel);
+                chunkProvider.addTicketAtLevel(TicketType.FUTURE_AWAIT, chunk.getPos(), ticketLevel, holderIdentifier);
+            }
+            if (++loadedChunks[0] == requiredChunks) {
+                try {
+                    onLoad.accept(java.util.Collections.unmodifiableList(ret));
+                } finally {
+                    for (int i = 0, len = ret.size(); i < len; ++i) {
+                        ChunkPos chunkPos = ret.get(i).getPos();
+                        int ticketLevel = ticketLevels.getInt(i);
+
+                        chunkProvider.addTicketAtLevel(TicketType.UNKNOWN, chunkPos, ticketLevel, chunkPos);
+                        chunkProvider.removeTicketAtLevel(TicketType.FUTURE_AWAIT, chunkPos, ticketLevel, holderIdentifier);
+                    }
+                }
+            }
+        };
+
+        for (int cx = minChunkX; cx <= maxChunkX; ++cx) {
+            for (int cz = minChunkZ; cz <= maxChunkZ; ++cz) {
+                io.papermc.paper.chunk.system.ChunkSystem.scheduleChunkLoad(
+                    this, cx, cz, net.minecraft.world.level.chunk.ChunkStatus.FULL, true, priority, consumer
+                );
+            }
+        }
+    }
+    // Paper end
+
     // Add env and gen to constructor, IWorldDataServer -> WorldDataServer
     public ServerLevel(MinecraftServer minecraftserver, Executor executor, LevelStorageSource.LevelStorageAccess convertable_conversionsession, PrimaryLevelData iworlddataserver, ResourceKey<Level> resourcekey, LevelStem worlddimension, ChunkProgressListener worldloadlistener, boolean flag, long i, List<CustomSpawner> list, boolean flag1, @Nullable RandomSequences randomsequences, org.bukkit.World.Environment env, org.bukkit.generator.ChunkGenerator gen, org.bukkit.generator.BiomeProvider biomeProvider) {
         // IRegistryCustom.Dimension iregistrycustom_dimension = minecraftserver.registryAccess(); // CraftBukkit - decompile error
diff --git a/src/main/java/net/minecraft/server/level/ServerPlayer.java b/src/main/java/net/minecraft/server/level/ServerPlayer.java
index fb5043e69ef59623c51b88176914f9f8becfc9ae..084339c7da80ce21ab8405e20b76af87dbbbe8ce 100644
--- a/src/main/java/net/minecraft/server/level/ServerPlayer.java
+++ b/src/main/java/net/minecraft/server/level/ServerPlayer.java
@@ -251,6 +251,8 @@ public class ServerPlayer extends Player {
     public boolean sentListPacket = false;
     public String kickLeaveMessage = null; // SPIGOT-3034: Forward leave message to PlayerQuitEvent
     // CraftBukkit end
+    public boolean isRealPlayer; // Paper
+    public final com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<ServerPlayer> cachedSingleHashSet; // Paper
 
     public ServerPlayer(MinecraftServer server, ServerLevel world, GameProfile profile, ClientInformation clientOptions) {
         super(world, world.getSharedSpawnPos(), world.getSharedSpawnAngle(), profile);
@@ -319,6 +321,8 @@ public class ServerPlayer extends Player {
         this.fudgeSpawnLocation(world);
         this.updateOptions(clientOptions);
 
+        this.cachedSingleHashSet = new com.destroystokyo.paper.util.misc.PooledLinkedHashSets.PooledObjectLinkedOpenHashSet<>(this); // Paper
+
         // CraftBukkit start
         this.displayName = this.getScoreboardName();
         this.bukkitPickUpLoot = true;
diff --git a/src/main/java/net/minecraft/server/level/TicketType.java b/src/main/java/net/minecraft/server/level/TicketType.java
index 3a4f026c73cdd22d30bdadabbcf24bef969b73e4..0d536d72ac918fbd403397ff369d10143ee9c204 100644
--- a/src/main/java/net/minecraft/server/level/TicketType.java
+++ b/src/main/java/net/minecraft/server/level/TicketType.java
@@ -7,6 +7,7 @@ import net.minecraft.util.Unit;
 import net.minecraft.world.level.ChunkPos;
 
 public class TicketType<T> {
+    public static final TicketType<Long> FUTURE_AWAIT = create("future_await", Long::compareTo); // Paper
 
     private final String name;
     private final Comparator<T> comparator;
diff --git a/src/main/java/net/minecraft/server/level/WorldGenRegion.java b/src/main/java/net/minecraft/server/level/WorldGenRegion.java
index a63d5ba706a5b8e430aedc045bdeb3a410bd0eef..e96a0ca47e4701ba187555bd92c968345bc85677 100644
--- a/src/main/java/net/minecraft/server/level/WorldGenRegion.java
+++ b/src/main/java/net/minecraft/server/level/WorldGenRegion.java
@@ -160,6 +160,26 @@ public class WorldGenRegion implements WorldGenLevel {
         return chunkX >= this.firstPos.x && chunkX <= this.lastPos.x && chunkZ >= this.firstPos.z && chunkZ <= this.lastPos.z;
     }
 
+    // Paper start - if loaded util
+    @Nullable
+    @Override
+    public ChunkAccess getChunkIfLoadedImmediately(int x, int z) {
+        return this.getChunk(x, z, ChunkStatus.FULL, false);
+    }
+
+    @Override
+    public final BlockState getBlockStateIfLoaded(BlockPos blockposition) {
+        ChunkAccess chunk = this.getChunkIfLoadedImmediately(blockposition.getX() >> 4, blockposition.getZ() >> 4);
+        return chunk == null ? null : chunk.getBlockState(blockposition);
+    }
+
+    @Override
+    public final FluidState getFluidIfLoaded(BlockPos blockposition) {
+        ChunkAccess chunk = this.getChunkIfLoadedImmediately(blockposition.getX() >> 4, blockposition.getZ() >> 4);
+        return chunk == null ? null : chunk.getFluidState(blockposition);
+    }
+    // Paper end
+
     @Override
     public BlockState getBlockState(BlockPos pos) {
         return this.getChunk(SectionPos.blockToSectionCoord(pos.getX()), SectionPos.blockToSectionCoord(pos.getZ())).getBlockState(pos);
diff --git a/src/main/java/net/minecraft/server/players/PlayerList.java b/src/main/java/net/minecraft/server/players/PlayerList.java
index 0fcac9b089e030b387d1b4c79c26e69ed9dcf4ed..10b263b2693a6b507c858b6550b5b98a53cea575 100644
--- a/src/main/java/net/minecraft/server/players/PlayerList.java
+++ b/src/main/java/net/minecraft/server/players/PlayerList.java
@@ -178,6 +178,7 @@ public abstract class PlayerList {
     }
 
     public void placeNewPlayer(Connection connection, ServerPlayer player, CommonListenerCookie clientData) {
+        player.isRealPlayer = true; // Paper
         GameProfile gameprofile = player.getGameProfile();
         GameProfileCache usercache = this.server.getProfileCache();
         String s;
diff --git a/src/main/java/net/minecraft/util/thread/BlockableEventLoop.java b/src/main/java/net/minecraft/util/thread/BlockableEventLoop.java
index 337e0a7b3c14e1b1a28744920e0dc0a69e0c5a87..f5829ae484d93b547a5437b85a9621346384a11b 100644
--- a/src/main/java/net/minecraft/util/thread/BlockableEventLoop.java
+++ b/src/main/java/net/minecraft/util/thread/BlockableEventLoop.java
@@ -78,6 +78,13 @@ public abstract class BlockableEventLoop<R extends Runnable> implements Profiler
         }
 
     }
+    // Paper start
+    public void scheduleOnMain(Runnable r0) {
+        // postToMainThread does not work the same as older versions of mc
+        // This method is actually used to create a TickTask, which can then be posted onto main
+        this.tell(this.wrapRunnable(r0));
+    }
+    // Paper end
 
     @Override
     public void tell(R runnable) {
diff --git a/src/main/java/net/minecraft/world/entity/Entity.java b/src/main/java/net/minecraft/world/entity/Entity.java
index 0863d7acce248895d57a4c0496881b542e4b79f1..6c5000ff3dbb7517d095e9fb2cdf555212b2c090 100644
--- a/src/main/java/net/minecraft/world/entity/Entity.java
+++ b/src/main/java/net/minecraft/world/entity/Entity.java
@@ -323,6 +323,11 @@ public abstract class Entity implements Nameable, EntityAccess, CommandSource {
         return this.level.hasChunk((int) Math.floor(this.getX()) >> 4, (int) Math.floor(this.getZ()) >> 4);
     }
     // CraftBukkit end
+    // Paper start
+    public final AABB getBoundingBoxAt(double x, double y, double z) {
+        return this.dimensions.makeBoundingBox(x, y, z);
+    }
+    // Paper end
 
     public Entity(EntityType<?> type, Level world) {
         this.id = Entity.ENTITY_COUNTER.incrementAndGet();
diff --git a/src/main/java/net/minecraft/world/entity/LivingEntity.java b/src/main/java/net/minecraft/world/entity/LivingEntity.java
index 96f94f11d5d98cddf98020fdbf5ec658d6d53f38..e24e61a35fe9cffce4a2174d46b88cf934f4b69f 100644
--- a/src/main/java/net/minecraft/world/entity/LivingEntity.java
+++ b/src/main/java/net/minecraft/world/entity/LivingEntity.java
@@ -258,6 +258,7 @@ public abstract class LivingEntity extends Entity implements Attackable {
     public boolean collides = true;
     public Set<UUID> collidableExemptions = new HashSet<>();
     public boolean bukkitPickUpLoot;
+    public org.bukkit.craftbukkit.entity.CraftLivingEntity getBukkitLivingEntity() { return (org.bukkit.craftbukkit.entity.CraftLivingEntity) super.getBukkitEntity(); } // Paper
 
     @Override
     public float getBukkitYaw() {
diff --git a/src/main/java/net/minecraft/world/entity/Mob.java b/src/main/java/net/minecraft/world/entity/Mob.java
index 6041f79ad8e2b61b438b19b5569ab02936a0be99..ec841a4d9a11f0d9047c202a31f944b340da33c8 100644
--- a/src/main/java/net/minecraft/world/entity/Mob.java
+++ b/src/main/java/net/minecraft/world/entity/Mob.java
@@ -276,6 +276,7 @@ public abstract class Mob extends LivingEntity implements Targeting {
         return this.target;
     }
 
+    public org.bukkit.craftbukkit.entity.CraftMob getBukkitMob() { return (org.bukkit.craftbukkit.entity.CraftMob) super.getBukkitEntity(); } // Paper
     public void setTarget(@Nullable LivingEntity target) {
         // CraftBukkit start - fire event
         this.setTarget(target, EntityTargetEvent.TargetReason.UNKNOWN, true);
diff --git a/src/main/java/net/minecraft/world/entity/PathfinderMob.java b/src/main/java/net/minecraft/world/entity/PathfinderMob.java
index 21fa43e0c3fabf74919f7e41d074ab1f7c061967..5e9cf929674888b3a143a0691dc6936b304467f1 100644
--- a/src/main/java/net/minecraft/world/entity/PathfinderMob.java
+++ b/src/main/java/net/minecraft/world/entity/PathfinderMob.java
@@ -20,6 +20,8 @@ public abstract class PathfinderMob extends Mob {
         super(type, world);
     }
 
+    public org.bukkit.craftbukkit.entity.CraftCreature getBukkitCreature() { return (org.bukkit.craftbukkit.entity.CraftCreature) super.getBukkitEntity(); } // Paper
+
     public float getWalkTargetValue(BlockPos pos) {
         return this.getWalkTargetValue(pos, this.level());
     }
diff --git a/src/main/java/net/minecraft/world/entity/monster/Monster.java b/src/main/java/net/minecraft/world/entity/monster/Monster.java
index a0b5895abc88d297045e05f25bb09527991d43f0..6e0bd0eab0b06a4ac3042496bbb91292544e9f3c 100644
--- a/src/main/java/net/minecraft/world/entity/monster/Monster.java
+++ b/src/main/java/net/minecraft/world/entity/monster/Monster.java
@@ -27,6 +27,7 @@ import net.minecraft.world.level.ServerLevelAccessor;
 import net.minecraft.world.level.dimension.DimensionType;
 
 public abstract class Monster extends PathfinderMob implements Enemy {
+    public org.bukkit.craftbukkit.entity.CraftMonster getBukkitMonster() { return (org.bukkit.craftbukkit.entity.CraftMonster) super.getBukkitEntity(); } // Paper
     protected Monster(EntityType<? extends Monster> type, Level world) {
         super(type, world);
         this.xpReward = 5;
diff --git a/src/main/java/net/minecraft/world/item/ItemStack.java b/src/main/java/net/minecraft/world/item/ItemStack.java
index 099daefa53b930a9a94ed91ef3fcd9e1607bfd09..1b2c0fda262ca6d5bd2ce22bc2e934803bd6f602 100644
--- a/src/main/java/net/minecraft/world/item/ItemStack.java
+++ b/src/main/java/net/minecraft/world/item/ItemStack.java
@@ -798,6 +798,25 @@ public final class ItemStack {
         return this.tag != null ? this.tag.getList("Enchantments", 10) : new ListTag();
     }
 
+    // Paper start - (this is just a good no conflict location)
+    public org.bukkit.inventory.ItemStack asBukkitMirror() {
+        return CraftItemStack.asCraftMirror(this);
+    }
+    public org.bukkit.inventory.ItemStack asBukkitCopy() {
+        return CraftItemStack.asCraftMirror(this.copy());
+    }
+    public static ItemStack fromBukkitCopy(org.bukkit.inventory.ItemStack itemstack) {
+        return CraftItemStack.asNMSCopy(itemstack);
+    }
+    private org.bukkit.craftbukkit.inventory.CraftItemStack bukkitStack;
+    public org.bukkit.inventory.ItemStack getBukkitStack() {
+        if (bukkitStack == null || bukkitStack.handle != this) {
+            bukkitStack = org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(this);
+        }
+        return bukkitStack;
+    }
+    // Paper end
+
     public void setTag(@Nullable CompoundTag nbt) {
         this.tag = nbt;
         if (this.getItem().canBeDepleted()) {
@@ -1187,6 +1206,7 @@ public final class ItemStack {
     // CraftBukkit start
     @Deprecated
     public void setItem(Item item) {
+        this.bukkitStack = null; // Paper
         this.item = item;
     }
     // CraftBukkit end
diff --git a/src/main/java/net/minecraft/world/level/BlockGetter.java b/src/main/java/net/minecraft/world/level/BlockGetter.java
index 1c71d2c1b16bdba1e14a8230787e4cb4ad530163..d6d8bbc98fc71997cb52521d59ebb59d727d3c22 100644
--- a/src/main/java/net/minecraft/world/level/BlockGetter.java
+++ b/src/main/java/net/minecraft/world/level/BlockGetter.java
@@ -9,6 +9,7 @@ import javax.annotation.Nullable;
 import net.minecraft.core.BlockPos;
 import net.minecraft.core.Direction;
 import net.minecraft.util.Mth;
+import net.minecraft.world.level.block.Block;
 import net.minecraft.world.level.block.entity.BlockEntity;
 import net.minecraft.world.level.block.entity.BlockEntityType;
 import net.minecraft.world.level.block.state.BlockState;
@@ -30,6 +31,15 @@ public interface BlockGetter extends LevelHeightAccessor {
     }
 
     BlockState getBlockState(BlockPos pos);
+    // Paper start - if loaded util
+    @Nullable BlockState getBlockStateIfLoaded(BlockPos blockposition);
+
+    default @Nullable Block getBlockIfLoaded(BlockPos blockposition) {
+        BlockState type = this.getBlockStateIfLoaded(blockposition);
+        return type == null ? null : type.getBlock();
+    }
+    @Nullable FluidState getFluidIfLoaded(BlockPos blockposition);
+    // Paper end
 
     FluidState getFluidState(BlockPos pos);
 
diff --git a/src/main/java/net/minecraft/world/level/ChunkPos.java b/src/main/java/net/minecraft/world/level/ChunkPos.java
index 43bb3f5a617f4a6d719b02023a71edcb12aa9d05..34457c8afb4575d2395148f0a2bde6a96ec5e797 100644
--- a/src/main/java/net/minecraft/world/level/ChunkPos.java
+++ b/src/main/java/net/minecraft/world/level/ChunkPos.java
@@ -20,6 +20,7 @@ public class ChunkPos {
     public static final int REGION_MAX_INDEX = 31;
     public final int x;
     public final int z;
+    public final long longKey; // Paper
     private static final int HASH_A = 1664525;
     private static final int HASH_C = 1013904223;
     private static final int HASH_Z_XOR = -559038737;
@@ -27,16 +28,19 @@ public class ChunkPos {
     public ChunkPos(int x, int z) {
         this.x = x;
         this.z = z;
+        this.longKey = asLong(this.x, this.z); // Paper
     }
 
     public ChunkPos(BlockPos pos) {
         this.x = SectionPos.blockToSectionCoord(pos.getX());
         this.z = SectionPos.blockToSectionCoord(pos.getZ());
+        this.longKey = asLong(this.x, this.z); // Paper
     }
 
     public ChunkPos(long pos) {
         this.x = (int)pos;
         this.z = (int)(pos >> 32);
+        this.longKey = asLong(this.x, this.z); // Paper
     }
 
     public static ChunkPos minFromRegion(int x, int z) {
@@ -48,10 +52,10 @@ public class ChunkPos {
     }
 
     public long toLong() {
-        return asLong(this.x, this.z);
+        return longKey; // Paper
     }
 
-    public static long asLong(int chunkX, int chunkZ) {
+        public static long asLong(int chunkX, int chunkZ) {
         return (long)chunkX & 4294967295L | ((long)chunkZ & 4294967295L) << 32;
     }
 
diff --git a/src/main/java/net/minecraft/world/level/EmptyBlockGetter.java b/src/main/java/net/minecraft/world/level/EmptyBlockGetter.java
index 3c707d6674b2594b09503b959a31c1f4ad3981e6..db61b6b0158a9bcc0e1d735e34fe3671f8c89e21 100644
--- a/src/main/java/net/minecraft/world/level/EmptyBlockGetter.java
+++ b/src/main/java/net/minecraft/world/level/EmptyBlockGetter.java
@@ -17,6 +17,18 @@ public enum EmptyBlockGetter implements BlockGetter {
         return null;
     }
 
+    // Paper start - If loaded util
+    @Override
+    public final FluidState getFluidIfLoaded(BlockPos blockposition) {
+        return Fluids.EMPTY.defaultFluidState();
+    }
+
+    @Override
+    public final BlockState getBlockStateIfLoaded(BlockPos blockposition) {
+        return Blocks.AIR.defaultBlockState();
+    }
+    // Paper end
+
     @Override
     public BlockState getBlockState(BlockPos pos) {
         return Blocks.AIR.defaultBlockState();
diff --git a/src/main/java/net/minecraft/world/level/Level.java b/src/main/java/net/minecraft/world/level/Level.java
index bacd4d875642cd93c3185f788745dd73a3cfde8a..003e2064f64115d1f5c48ac97e16100d4c10c5d7 100644
--- a/src/main/java/net/minecraft/world/level/Level.java
+++ b/src/main/java/net/minecraft/world/level/Level.java
@@ -90,6 +90,7 @@ import org.bukkit.craftbukkit.CraftServer;
 import org.bukkit.craftbukkit.CraftWorld;
 import org.bukkit.craftbukkit.SpigotTimings; // Spigot
 import org.bukkit.craftbukkit.block.CapturedBlockState;
+import org.bukkit.craftbukkit.block.CraftBlockState;
 import org.bukkit.craftbukkit.block.data.CraftBlockData;
 import org.bukkit.craftbukkit.util.CraftSpawnCategory;
 import org.bukkit.craftbukkit.util.CraftNamespacedKey;
@@ -292,18 +293,52 @@ public abstract class Level implements LevelAccessor, AutoCloseable {
         return y < -20000000 || y >= 20000000;
     }
 
-    public LevelChunk getChunkAt(BlockPos pos) {
+    public final LevelChunk getChunkAt(BlockPos pos) { // Paper - help inline
         return this.getChunk(SectionPos.blockToSectionCoord(pos.getX()), SectionPos.blockToSectionCoord(pos.getZ()));
     }
 
     @Override
-    public LevelChunk getChunk(int chunkX, int chunkZ) {
-        return (LevelChunk) this.getChunk(chunkX, chunkZ, ChunkStatus.FULL);
+    public final LevelChunk getChunk(int chunkX, int chunkZ) { // Paper - final to help inline
+        return (LevelChunk) this.getChunk(chunkX, chunkZ, ChunkStatus.FULL, true); // Paper - avoid a method jump
     }
 
+    // Paper start - if loaded
     @Nullable
     @Override
-    public ChunkAccess getChunk(int chunkX, int chunkZ, ChunkStatus leastStatus, boolean create) {
+    public final ChunkAccess getChunkIfLoadedImmediately(int x, int z) {
+        return ((ServerLevel)this).chunkSource.getChunkAtIfLoadedImmediately(x, z);
+    }
+
+    @Override
+    @Nullable
+    public final BlockState getBlockStateIfLoaded(BlockPos pos) {
+        // CraftBukkit start - tree generation
+        if (this.captureTreeGeneration) {
+            CraftBlockState previous = this.capturedBlockStates.get(pos);
+            if (previous != null) {
+                return previous.getHandle();
+            }
+        }
+        // CraftBukkit end
+        if (this.isOutsideBuildHeight(pos)) {
+            return Blocks.VOID_AIR.defaultBlockState();
+        } else {
+            ChunkAccess chunk = this.getChunkIfLoadedImmediately(pos.getX() >> 4, pos.getZ() >> 4);
+
+            return chunk == null ? null : chunk.getBlockState(pos);
+        }
+    }
+
+    @Override
+    public final FluidState getFluidIfLoaded(BlockPos blockposition) {
+        ChunkAccess chunk = this.getChunkIfLoadedImmediately(blockposition.getX() >> 4, blockposition.getZ() >> 4);
+
+        return chunk == null ? null : chunk.getFluidState(blockposition);
+    }
+
+    @Override
+    public final ChunkAccess getChunk(int chunkX, int chunkZ, ChunkStatus leastStatus, boolean create) { // Paper - final for inline
+        // Paper end
         ChunkAccess ichunkaccess = this.getChunkSource().getChunk(chunkX, chunkZ, leastStatus, create);
 
         if (ichunkaccess == null && create) {
@@ -314,7 +349,7 @@ public abstract class Level implements LevelAccessor, AutoCloseable {
     }
 
     @Override
-    public boolean setBlock(BlockPos pos, BlockState state, int flags) {
+    public final boolean setBlock(BlockPos pos, BlockState state, int flags) { // Paper - final for inline
         return this.setBlock(pos, state, flags, 512);
     }
 
@@ -552,7 +587,7 @@ public abstract class Level implements LevelAccessor, AutoCloseable {
         if (this.isOutsideBuildHeight(pos)) {
             return Blocks.VOID_AIR.defaultBlockState();
         } else {
-            LevelChunk chunk = this.getChunk(SectionPos.blockToSectionCoord(pos.getX()), SectionPos.blockToSectionCoord(pos.getZ()));
+            ChunkAccess chunk = this.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.FULL, true); // Paper - manually inline to reduce hops and avoid unnecessary null check to reduce total byte code size, this should never return null and if it does we will see it the next line but the real stack trace will matter in the chunk engine
 
             return chunk.getBlockState(pos);
         }
diff --git a/src/main/java/net/minecraft/world/level/LevelReader.java b/src/main/java/net/minecraft/world/level/LevelReader.java
index e6aabec35f4e27623d1fbbfb285cc78531137014..cc0d20e9f851268fe8403ac516f426ec1d008150 100644
--- a/src/main/java/net/minecraft/world/level/LevelReader.java
+++ b/src/main/java/net/minecraft/world/level/LevelReader.java
@@ -26,6 +26,9 @@ public interface LevelReader extends BlockAndTintGetter, CollisionGetter, Signal
     @Nullable
     ChunkAccess getChunk(int chunkX, int chunkZ, ChunkStatus leastStatus, boolean create);
 
+    @Nullable ChunkAccess getChunkIfLoadedImmediately(int x, int z); // Paper - ifLoaded api (we need this since current impl blocks if the chunk is loading)
+    @Nullable default ChunkAccess getChunkIfLoadedImmediately(BlockPos pos) { return this.getChunkIfLoadedImmediately(pos.getX() >> 4, pos.getZ() >> 4);}
+
     /** @deprecated */
     @Deprecated
     boolean hasChunk(int chunkX, int chunkZ);
diff --git a/src/main/java/net/minecraft/world/level/PathNavigationRegion.java b/src/main/java/net/minecraft/world/level/PathNavigationRegion.java
index 249b3ed33672a9a9529bd14de978722b62019314..0f1025495237aebe30132ace0832aa5718d6f9bb 100644
--- a/src/main/java/net/minecraft/world/level/PathNavigationRegion.java
+++ b/src/main/java/net/minecraft/world/level/PathNavigationRegion.java
@@ -9,6 +9,7 @@ import net.minecraft.core.Holder;
 import net.minecraft.core.SectionPos;
 import net.minecraft.core.registries.Registries;
 import net.minecraft.util.profiling.ProfilerFiller;
+import net.minecraft.server.level.ServerLevel;
 import net.minecraft.world.entity.Entity;
 import net.minecraft.world.level.biome.Biome;
 import net.minecraft.world.level.biome.Biomes;
@@ -70,7 +71,7 @@ public class PathNavigationRegion implements BlockGetter, CollisionGetter {
     private ChunkAccess getChunk(int chunkX, int chunkZ) {
         int i = chunkX - this.centerX;
         int j = chunkZ - this.centerZ;
-        if (i >= 0 && i < this.chunks.length && j >= 0 && j < this.chunks[i].length) {
+        if (i >= 0 && i < this.chunks.length && j >= 0 && j < this.chunks[i].length) { // Paper - if this changes, update getChunkIfLoaded below
             ChunkAccess chunkAccess = this.chunks[i][j];
             return (ChunkAccess)(chunkAccess != null ? chunkAccess : new EmptyLevelChunk(this.level, new ChunkPos(chunkX, chunkZ), this.plains.get()));
         } else {
@@ -78,6 +79,30 @@ public class PathNavigationRegion implements BlockGetter, CollisionGetter {
         }
     }
 
+    // Paper start - if loaded util
+    private @Nullable ChunkAccess getChunkIfLoaded(int x, int z) {
+        // Based on getChunk(int, int)
+        int xx = x - this.centerX;
+        int zz = z - this.centerZ;
+
+        if (xx >= 0 && xx < this.chunks.length && zz >= 0 && zz < this.chunks[xx].length) {
+            return this.chunks[xx][zz];
+        }
+        return null;
+    }
+    @Override
+    public final FluidState getFluidIfLoaded(BlockPos blockposition) {
+        ChunkAccess chunk = getChunkIfLoaded(blockposition.getX() >> 4, blockposition.getZ() >> 4);
+        return chunk == null ? null : chunk.getFluidState(blockposition);
+    }
+
+    @Override
+    public final BlockState getBlockStateIfLoaded(BlockPos blockposition) {
+        ChunkAccess chunk = getChunkIfLoaded(blockposition.getX() >> 4, blockposition.getZ() >> 4);
+        return chunk == null ? null : chunk.getBlockState(blockposition);
+    }
+    // Paper end
+
     @Override
     public WorldBorder getWorldBorder() {
         return this.level.getWorldBorder();
diff --git a/src/main/java/net/minecraft/world/level/block/state/BlockBehaviour.java b/src/main/java/net/minecraft/world/level/block/state/BlockBehaviour.java
index fefeccaf347da1be9342df09fafabb6fcc3be4ae..2b8e88a75e9a974e1ecafe0360a9d69b79326d11 100644
--- a/src/main/java/net/minecraft/world/level/block/state/BlockBehaviour.java
+++ b/src/main/java/net/minecraft/world/level/block/state/BlockBehaviour.java
@@ -754,8 +754,8 @@ public abstract class BlockBehaviour implements FeatureElement {
 
     public abstract static class BlockStateBase extends StateHolder<Block, BlockState> {
 
-        private final int lightEmission;
-        private final boolean useShapeForLightOcclusion;
+        private final int lightEmission; public final int getEmittedLight() { return this.lightEmission; } // Paper - OBFHELPER
+        private final boolean useShapeForLightOcclusion; public final boolean isTransparentOnSomeFaces() { return this.useShapeForLightOcclusion; } // Paper - OBFHELPER
         private final boolean isAir;
         private final boolean ignitedByLava;
         /** @deprecated */
@@ -768,7 +768,7 @@ public abstract class BlockBehaviour implements FeatureElement {
         private final MapColor mapColor;
         public final float destroySpeed;
         private final boolean requiresCorrectToolForDrops;
-        private final boolean canOcclude;
+        private final boolean canOcclude; public final boolean isOpaque() { return this.canOcclude; } // Paper - OBFHELPER
         private final BlockBehaviour.StatePredicate isRedstoneConductor;
         private final BlockBehaviour.StatePredicate isSuffocating;
         private final BlockBehaviour.StatePredicate isViewBlocking;
@@ -829,12 +829,20 @@ public abstract class BlockBehaviour implements FeatureElement {
             }
         }
 
+        // Paper start
+        protected boolean shapeExceedsCube = true;
+        public final boolean shapeExceedsCube() {
+            return this.shapeExceedsCube;
+        }
+        // Paper end
+
         public void initCache() {
             this.fluidState = ((Block) this.owner).getFluidState(this.asState());
             this.isRandomlyTicking = ((Block) this.owner).isRandomlyTicking(this.asState());
             if (!this.getBlock().hasDynamicShape()) {
                 this.cache = new BlockBehaviour.BlockStateBase.Cache(this.asState());
             }
+            this.shapeExceedsCube = this.cache == null || this.cache.largeCollisionShape; // Paper - moved from actual method to here
 
             this.legacySolid = this.calculateSolid();
         }
@@ -881,8 +889,8 @@ public abstract class BlockBehaviour implements FeatureElement {
             return this.getBlock().getOcclusionShape(this.asState(), world, pos);
         }
 
-        public boolean hasLargeCollisionShape() {
-            return this.cache == null || this.cache.largeCollisionShape;
+        public final boolean hasLargeCollisionShape() { // Paper
+            return this.shapeExceedsCube; // Paper - moved into shape cache init
         }
 
         public boolean useShapeForLightOcclusion() {
diff --git a/src/main/java/net/minecraft/world/level/chunk/ChunkAccess.java b/src/main/java/net/minecraft/world/level/chunk/ChunkAccess.java
index 532a0cae6db0d830e720a72e9021aa7a8ed0f106..e5e562f75e7d4b6a750f192842940c5e3af81e7d 100644
--- a/src/main/java/net/minecraft/world/level/chunk/ChunkAccess.java
+++ b/src/main/java/net/minecraft/world/level/chunk/ChunkAccess.java
@@ -62,7 +62,7 @@ public abstract class ChunkAccess implements BlockGetter, BiomeManager.NoiseBiom
     protected final ShortList[] postProcessing;
     protected volatile boolean unsaved;
     private volatile boolean isLightCorrect;
-    protected final ChunkPos chunkPos;
+    protected final ChunkPos chunkPos; public final long coordinateKey; public final int locX; public final int locZ; // Paper - cache coordinate key
     private long inhabitedTime;
     /** @deprecated */
     @Nullable
@@ -88,7 +88,8 @@ public abstract class ChunkAccess implements BlockGetter, BiomeManager.NoiseBiom
     // CraftBukkit end
 
     public ChunkAccess(ChunkPos pos, UpgradeData upgradeData, LevelHeightAccessor heightLimitView, Registry<Biome> biomeRegistry, long inhabitedTime, @Nullable LevelChunkSection[] sectionArray, @Nullable BlendingData blendingData) {
-        this.chunkPos = pos;
+        this.locX = pos.x; this.locZ = pos.z; // Paper - reduce need for field lookups
+        this.chunkPos = pos; this.coordinateKey = ChunkPos.asLong(locX, locZ); // Paper - cache long key
         this.upgradeData = upgradeData;
         this.levelHeightAccessor = heightLimitView;
         this.sections = new LevelChunkSection[heightLimitView.getSectionsCount()];
diff --git a/src/main/java/net/minecraft/world/level/chunk/LevelChunk.java b/src/main/java/net/minecraft/world/level/chunk/LevelChunk.java
index 4185b7528ac757a2d6ebca4da4d46e65b7a981d0..b32e1bba27c91e81b7382072c4d8230db695066c 100644
--- a/src/main/java/net/minecraft/world/level/chunk/LevelChunk.java
+++ b/src/main/java/net/minecraft/world/level/chunk/LevelChunk.java
@@ -114,6 +114,109 @@ public class LevelChunk extends ChunkAccess {
     public boolean needsDecoration;
     // CraftBukkit end
 
+    // Paper start
+    public @Nullable net.minecraft.server.level.ChunkHolder playerChunk;
+
+    static final int NEIGHBOUR_CACHE_RADIUS = 3;
+    public static int getNeighbourCacheRadius() {
+        return NEIGHBOUR_CACHE_RADIUS;
+    }
+
+    boolean loadedTicketLevel;
+    private long neighbourChunksLoadedBitset;
+    private final LevelChunk[] loadedNeighbourChunks = new LevelChunk[(NEIGHBOUR_CACHE_RADIUS * 2 + 1) * (NEIGHBOUR_CACHE_RADIUS * 2 + 1)];
+
+    private static int getNeighbourIndex(final int relativeX, final int relativeZ) {
+        // index = (relativeX + NEIGHBOUR_CACHE_RADIUS) + (relativeZ + NEIGHBOUR_CACHE_RADIUS) * (NEIGHBOUR_CACHE_RADIUS * 2 + 1)
+        // optimised variant of the above by moving some of the ops to compile time
+        return relativeX + (relativeZ * (NEIGHBOUR_CACHE_RADIUS * 2 + 1)) + (NEIGHBOUR_CACHE_RADIUS + NEIGHBOUR_CACHE_RADIUS * ((NEIGHBOUR_CACHE_RADIUS * 2 + 1)));
+    }
+
+    public final LevelChunk getRelativeNeighbourIfLoaded(final int relativeX, final int relativeZ) {
+        return this.loadedNeighbourChunks[getNeighbourIndex(relativeX, relativeZ)];
+    }
+
+    public final boolean isNeighbourLoaded(final int relativeX, final int relativeZ) {
+        return (this.neighbourChunksLoadedBitset & (1L << getNeighbourIndex(relativeX, relativeZ))) != 0;
+    }
+
+    public final void setNeighbourLoaded(final int relativeX, final int relativeZ, final LevelChunk chunk) {
+        if (chunk == null) {
+            throw new IllegalArgumentException("Chunk must be non-null, neighbour: (" + relativeX + "," + relativeZ + "), chunk: " + this.chunkPos);
+        }
+        final long before = this.neighbourChunksLoadedBitset;
+        final int index = getNeighbourIndex(relativeX, relativeZ);
+        this.loadedNeighbourChunks[index] = chunk;
+        this.neighbourChunksLoadedBitset |= (1L << index);
+        this.onNeighbourChange(before, this.neighbourChunksLoadedBitset);
+    }
+
+    public final void setNeighbourUnloaded(final int relativeX, final int relativeZ) {
+        final long before = this.neighbourChunksLoadedBitset;
+        final int index = getNeighbourIndex(relativeX, relativeZ);
+        this.loadedNeighbourChunks[index] = null;
+        this.neighbourChunksLoadedBitset &= ~(1L << index);
+        this.onNeighbourChange(before, this.neighbourChunksLoadedBitset);
+    }
+
+    public final void resetNeighbours() {
+        final long before = this.neighbourChunksLoadedBitset;
+        this.neighbourChunksLoadedBitset = 0L;
+        java.util.Arrays.fill(this.loadedNeighbourChunks, null);
+        this.onNeighbourChange(before, 0L);
+    }
+
+    protected void onNeighbourChange(final long bitsetBefore, final long bitsetAfter) {
+
+    }
+
+    public final boolean isAnyNeighborsLoaded() {
+        return neighbourChunksLoadedBitset != 0;
+    }
+    public final boolean areNeighboursLoaded(final int radius) {
+        return LevelChunk.areNeighboursLoaded(this.neighbourChunksLoadedBitset, radius);
+    }
+
+    public static boolean areNeighboursLoaded(final long bitset, final int radius) {
+        // index = relativeX + (relativeZ * (NEIGHBOUR_CACHE_RADIUS * 2 + 1)) + (NEIGHBOUR_CACHE_RADIUS + NEIGHBOUR_CACHE_RADIUS * ((NEIGHBOUR_CACHE_RADIUS * 2 + 1)))
+        switch (radius) {
+            case 0: {
+                return (bitset & (1L << getNeighbourIndex(0, 0))) != 0;
+            }
+            case 1: {
+                long mask = 0L;
+                for (int dx = -1; dx <= 1; ++dx) {
+                    for (int dz = -1; dz <= 1; ++dz) {
+                        mask |= (1L << getNeighbourIndex(dx, dz));
+                    }
+                }
+                return (bitset & mask) == mask;
+            }
+            case 2: {
+                long mask = 0L;
+                for (int dx = -2; dx <= 2; ++dx) {
+                    for (int dz = -2; dz <= 2; ++dz) {
+                        mask |= (1L << getNeighbourIndex(dx, dz));
+                    }
+                }
+                return (bitset & mask) == mask;
+            }
+            case 3: {
+                long mask = 0L;
+                for (int dx = -3; dx <= 3; ++dx) {
+                    for (int dz = -3; dz <= 3; ++dz) {
+                        mask |= (1L << getNeighbourIndex(dx, dz));
+                    }
+                }
+                return (bitset & mask) == mask;
+            }
+
+            default:
+                throw new IllegalArgumentException("Radius not recognized: " + radius);
+        }
+    }
+    // Paper end
+
     public LevelChunk(ServerLevel world, ProtoChunk protoChunk, @Nullable LevelChunk.PostLoadProcessor entityLoader) {
         this(world, protoChunk.getPos(), protoChunk.getUpgradeData(), protoChunk.unpackBlockTicks(), protoChunk.unpackFluidTicks(), protoChunk.getInhabitedTime(), protoChunk.getSections(), entityLoader, protoChunk.getBlendingData());
         Iterator iterator = protoChunk.getBlockEntities().values().iterator();
@@ -224,6 +327,18 @@ public class LevelChunk extends ChunkAccess {
         }
     }
 
+    // Paper start - If loaded util
+    @Override
+    public final FluidState getFluidIfLoaded(BlockPos blockposition) {
+        return this.getFluidState(blockposition);
+    }
+
+    @Override
+    public final BlockState getBlockStateIfLoaded(BlockPos blockposition) {
+        return this.getBlockState(blockposition);
+    }
+    // Paper end
+
     @Override
     public FluidState getFluidState(BlockPos pos) {
         return this.getFluidState(pos.getX(), pos.getY(), pos.getZ());
@@ -355,6 +470,7 @@ public class LevelChunk extends ChunkAccess {
         return this.getBlockEntity(pos, LevelChunk.EntityCreationType.CHECK);
     }
 
+    @Deprecated @Nullable public final BlockEntity getTileEntityImmediately(BlockPos pos) { return this.getBlockEntity(pos, EntityCreationType.IMMEDIATE); } // Paper - OBFHELPER
     @Nullable
     public BlockEntity getBlockEntity(BlockPos pos, LevelChunk.EntityCreationType creationType) {
         // CraftBukkit start
@@ -537,7 +653,25 @@ public class LevelChunk extends ChunkAccess {
 
     // CraftBukkit start
     public void loadCallback() {
+        // Paper start - neighbour cache
+        int chunkX = this.chunkPos.x;
+        int chunkZ = this.chunkPos.z;
+        net.minecraft.server.level.ServerChunkCache chunkProvider = this.level.getChunkSource();
+        for (int dx = -NEIGHBOUR_CACHE_RADIUS; dx <= NEIGHBOUR_CACHE_RADIUS; ++dx) {
+            for (int dz = -NEIGHBOUR_CACHE_RADIUS; dz <= NEIGHBOUR_CACHE_RADIUS; ++dz) {
+                LevelChunk neighbour = chunkProvider.getChunkAtIfLoadedMainThreadNoCache(chunkX + dx, chunkZ + dz);
+                if (neighbour != null) {
+                    neighbour.setNeighbourLoaded(-dx, -dz, this);
+                    // should be in cached already
+                    this.setNeighbourLoaded(dx, dz, neighbour);
+                }
+            }
+        }
+        this.setNeighbourLoaded(0, 0, this);
+        this.loadedTicketLevel = true;
+        // Paper end - neighbour cache
         org.bukkit.Server server = this.level.getCraftServer();
+        this.level.getChunkSource().addLoadedChunk(this); // Paper
         if (server != null) {
             /*
              * If it's a new world, the first few chunks are generated inside
@@ -578,6 +712,22 @@ public class LevelChunk extends ChunkAccess {
         server.getPluginManager().callEvent(unloadEvent);
         // note: saving can be prevented, but not forced if no saving is actually required
         this.mustNotSave = !unloadEvent.isSaveChunk();
+        this.level.getChunkSource().removeLoadedChunk(this); // Paper
+        // Paper start - neighbour cache
+        int chunkX = this.chunkPos.x;
+        int chunkZ = this.chunkPos.z;
+        net.minecraft.server.level.ServerChunkCache chunkProvider = this.level.getChunkSource();
+        for (int dx = -NEIGHBOUR_CACHE_RADIUS; dx <= NEIGHBOUR_CACHE_RADIUS; ++dx) {
+            for (int dz = -NEIGHBOUR_CACHE_RADIUS; dz <= NEIGHBOUR_CACHE_RADIUS; ++dz) {
+                LevelChunk neighbour = chunkProvider.getChunkAtIfLoadedMainThreadNoCache(chunkX + dx, chunkZ + dz);
+                if (neighbour != null) {
+                    neighbour.setNeighbourUnloaded(-dx, -dz);
+                }
+            }
+        }
+        this.loadedTicketLevel = false;
+        this.resetNeighbours();
+        // Paper end
     }
 
     @Override
diff --git a/src/main/java/net/minecraft/world/level/chunk/ProtoChunk.java b/src/main/java/net/minecraft/world/level/chunk/ProtoChunk.java
index 51a0ddcee9a9cb1040fda643a6442d2e2e15b8a0..38ec21faaa16df5485a81a581506700a5ab0a440 100644
--- a/src/main/java/net/minecraft/world/level/chunk/ProtoChunk.java
+++ b/src/main/java/net/minecraft/world/level/chunk/ProtoChunk.java
@@ -72,6 +72,18 @@ public class ProtoChunk extends ChunkAccess {
         return new ChunkAccess.TicksToSave(this.blockTicks, this.fluidTicks);
     }
 
+    // Paper start - If loaded util
+    @Override
+    public final FluidState getFluidIfLoaded(BlockPos blockposition) {
+        return this.getFluidState(blockposition);
+    }
+
+    @Override
+    public final BlockState getBlockStateIfLoaded(BlockPos blockposition) {
+        return this.getBlockState(blockposition);
+    }
+    // Paper end
+
     @Override
     public BlockState getBlockState(BlockPos pos) {
         int i = pos.getY();
diff --git a/src/main/java/net/minecraft/world/level/entity/PersistentEntitySectionManager.java b/src/main/java/net/minecraft/world/level/entity/PersistentEntitySectionManager.java
index 25156be63f91a1c41ef41154f675d04eb97459a8..47bab513feec217d875192afef61f3af95b93d24 100644
--- a/src/main/java/net/minecraft/world/level/entity/PersistentEntitySectionManager.java
+++ b/src/main/java/net/minecraft/world/level/entity/PersistentEntitySectionManager.java
@@ -90,6 +90,18 @@ public class PersistentEntitySectionManager<T extends EntityAccess> implements A
     }
 
     private boolean addEntity(T entity, boolean existing) {
+        // Paper start - chunk system hooks
+        if (existing) {
+            // I don't want to know why this is a generic type.
+            Entity entityCasted = (Entity)entity;
+            boolean wasRemoved = entityCasted.isRemoved();
+            io.papermc.paper.chunk.system.ChunkSystem.onEntityPreAdd((net.minecraft.server.level.ServerLevel) entityCasted.level(), entityCasted);
+            if (!wasRemoved && entityCasted.isRemoved()) {
+                // removed by callback
+                return false;
+            }
+        }
+        // Paper end - chunk system hooks
         if (!this.addEntityUuid(entity)) {
             return false;
         } else {
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftWorld.java b/src/main/java/org/bukkit/craftbukkit/CraftWorld.java
index 8adac67a9315186d1ef453eae827ea7f69856f7a..153143b06fc088f3142a8fa17f153d8a344169d8 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftWorld.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftWorld.java
@@ -242,8 +242,8 @@ public class CraftWorld extends CraftRegionAccessor implements World {
 
     @Override
     public Chunk[] getLoadedChunks() {
-        Long2ObjectLinkedOpenHashMap<ChunkHolder> chunks = this.world.getChunkSource().chunkMap.visibleChunkMap;
-        return chunks.values().stream().map(ChunkHolder::getFullChunkNow).filter(Objects::nonNull).map(CraftChunk::new).toArray(Chunk[]::new);
+        List<ChunkHolder> chunks = io.papermc.paper.chunk.system.ChunkSystem.getVisibleChunkHolders(this.world); // Paper
+        return chunks.stream().map(ChunkHolder::getFullChunkNow).filter(Objects::nonNull).map(CraftChunk::new).toArray(Chunk[]::new);
     }
 
     @Override
@@ -318,7 +318,7 @@ public class CraftWorld extends CraftRegionAccessor implements World {
 
     @Override
     public boolean refreshChunk(int x, int z) {
-        ChunkHolder playerChunk = this.world.getChunkSource().chunkMap.visibleChunkMap.get(ChunkPos.asLong(x, z));
+        ChunkHolder playerChunk = this.world.getChunkSource().chunkMap.getVisibleChunkIfPresent(ChunkPos.asLong(x, z));
         if (playerChunk == null) return false;
 
         playerChunk.getTickingChunkFuture().thenAccept(either -> {
@@ -1970,4 +1970,32 @@ public class CraftWorld extends CraftRegionAccessor implements World {
         return this.spigot;
     }
     // Spigot end
+    // Paper start
+    public java.util.concurrent.CompletableFuture<Chunk> getChunkAtAsync(int x, int z, boolean gen, boolean urgent) {
+        if (Bukkit.isPrimaryThread()) {
+            net.minecraft.world.level.chunk.LevelChunk immediate = this.world.getChunkSource().getChunkAtIfLoadedImmediately(x, z);
+            if (immediate != null) {
+                return java.util.concurrent.CompletableFuture.completedFuture(new CraftChunk(immediate));
+            }
+        }
+
+        ca.spottedleaf.concurrentutil.executor.standard.PrioritisedExecutor.Priority priority;
+        if (urgent) {
+            priority = ca.spottedleaf.concurrentutil.executor.standard.PrioritisedExecutor.Priority.HIGHER;
+        } else {
+            priority = ca.spottedleaf.concurrentutil.executor.standard.PrioritisedExecutor.Priority.NORMAL;
+        }
+
+        java.util.concurrent.CompletableFuture<Chunk> ret = new java.util.concurrent.CompletableFuture<>();
+
+        io.papermc.paper.chunk.system.ChunkSystem.scheduleChunkLoad(this.getHandle(), x, z, gen, ChunkStatus.FULL, true, priority, (c) -> {
+            net.minecraft.server.MinecraftServer.getServer().scheduleOnMain(() -> {
+                net.minecraft.world.level.chunk.LevelChunk chunk = (net.minecraft.world.level.chunk.LevelChunk)c;
+                ret.complete(chunk == null ? null : new CraftChunk(chunk));
+            });
+        });
+
+        return ret;
+    }
+    // Paper end
 }
diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java
index 32adc1cee4dfe49a9a0009ab39382083001e6cbe..74f431e806a4c5abb7ddd193c1b5f7ba7f321cac 100644
--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java
+++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java
@@ -1186,4 +1186,37 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity {
         return this.spigot;
     }
     // Spigot end
+
+    // Paper start
+    @Override
+    public java.util.concurrent.CompletableFuture<Boolean> teleportAsync(Location location, TeleportCause cause) {
+        Preconditions.checkArgument(location != null, "location");
+        location.checkFinite();
+        Location locationClone = location.clone(); // clone so we don't need to worry about mutations after this call.
+
+        net.minecraft.server.level.ServerLevel world = ((CraftWorld)locationClone.getWorld()).getHandle();
+        java.util.concurrent.CompletableFuture<Boolean> ret = new java.util.concurrent.CompletableFuture<>();
+
+        world.loadChunksForMoveAsync(getHandle().getBoundingBoxAt(locationClone.getX(), locationClone.getY(), locationClone.getZ()),
+            this instanceof CraftPlayer ? ca.spottedleaf.concurrentutil.executor.standard.PrioritisedExecutor.Priority.HIGHER : ca.spottedleaf.concurrentutil.executor.standard.PrioritisedExecutor.Priority.NORMAL, (list) -> {
+            net.minecraft.server.level.ServerChunkCache chunkProviderServer = world.getChunkSource();
+            for (net.minecraft.world.level.chunk.ChunkAccess chunk : list) {
+                chunkProviderServer.addTicketAtLevel(net.minecraft.server.level.TicketType.POST_TELEPORT, chunk.getPos(), 33, CraftEntity.this.getEntityId());
+            }
+            net.minecraft.server.MinecraftServer.getServer().scheduleOnMain(() -> {
+                try {
+                    ret.complete(CraftEntity.this.teleport(locationClone, cause) ? Boolean.TRUE : Boolean.FALSE);
+                } catch (Throwable throwable) {
+                    if (throwable instanceof ThreadDeath) {
+                        throw (ThreadDeath)throwable;
+                    }
+                    net.minecraft.server.MinecraftServer.LOGGER.error("Failed to teleport entity " + CraftEntity.this, throwable);
+                    ret.completeExceptionally(throwable);
+                }
+            });
+        });
+
+        return ret;
+    }
+    // Paper end
 }
diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java
index 34a54a99e7484b2934e1d174c1b55f0472ff3812..40aad6a209fbded448e3db21207a85d9f2875e71 100644
--- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java
@@ -23,6 +23,16 @@ import org.bukkit.material.MaterialData;
 @DelegateDeserialization(ItemStack.class)
 public final class CraftItemStack extends ItemStack {
 
+    // Paper start - MC Utils
+    public static net.minecraft.world.item.ItemStack unwrap(ItemStack bukkit) {
+        if (bukkit instanceof CraftItemStack craftItemStack) {
+            return craftItemStack.handle != null ? craftItemStack.handle : net.minecraft.world.item.ItemStack.EMPTY;
+        } else {
+            return asNMSCopy(bukkit);
+        }
+    }
+    // Paper end - MC Utils
+
     public static net.minecraft.world.item.ItemStack asNMSCopy(ItemStack original) {
         if (original instanceof CraftItemStack) {
             CraftItemStack stack = (CraftItemStack) original;
diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java
index 07249989e6f0f76f8408363d7f20e7335b7a8e06..4d94c3a19f98f78476ecc403f410d75a6ea57c2d 100644
--- a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java
+++ b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java
@@ -44,6 +44,7 @@ import org.bukkit.scheduler.BukkitWorker;
  */
 public class CraftScheduler implements BukkitScheduler {
 
+    static Plugin MINECRAFT = new MinecraftInternalPlugin();
     /**
      * The start ID for the counter.
      */
@@ -192,6 +193,11 @@ public class CraftScheduler implements BukkitScheduler {
         this.runTaskTimer(plugin, (Object) task, delay, period);
     }
 
+    public BukkitTask scheduleInternalTask(Runnable run, int delay, String taskName) {
+        final CraftTask task = new CraftTask(run, nextId(), taskName);
+        return handle(task, delay);
+    }
+
     public BukkitTask runTaskTimer(Plugin plugin, Object runnable, long delay, long period) {
         CraftScheduler.validate(plugin, runnable);
         if (delay < 0L) {
@@ -415,13 +421,20 @@ public class CraftScheduler implements BukkitScheduler {
                     task.run();
                     task.timings.stopTiming(); // Spigot
                 } catch (final Throwable throwable) {
-                    task.getOwner().getLogger().log(
+                    // Paper start
+                    String msg = String.format(
+                        "Task #%s for %s generated an exception",
+                        task.getTaskId(),
+                        task.getOwner().getDescription().getFullName());
+                    if (task.getOwner() == MINECRAFT) {
+                        net.minecraft.server.MinecraftServer.LOGGER.error(msg, throwable);
+                    } else {
+                        task.getOwner().getLogger().log(
                             Level.WARNING,
-                            String.format(
-                                "Task #%s for %s generated an exception",
-                                task.getTaskId(),
-                                task.getOwner().getDescription().getFullName()),
+                            msg,
                             throwable);
+                    }
+                    // Paper end
                 } finally {
                     this.currentTask = null;
                 }
diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftTask.java b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftTask.java
index 592a2a513ebf0002abf1255e11012ecc66adecf0..b89846e0f645c79afec018dae1d64a1bda043ed9 100644
--- a/src/main/java/org/bukkit/craftbukkit/scheduler/CraftTask.java
+++ b/src/main/java/org/bukkit/craftbukkit/scheduler/CraftTask.java
@@ -40,6 +40,21 @@ public class CraftTask implements BukkitTask, Runnable { // Spigot
     CraftTask(final Object task) {
         this(null, task, CraftTask.NO_REPEATING, CraftTask.NO_REPEATING);
     }
+    // Paper start
+    public String taskName = null;
+    boolean internal = false;
+    CraftTask(final Object task, int id, String taskName) {
+        this.rTask = (Runnable) task;
+        this.cTask = null;
+        this.plugin = CraftScheduler.MINECRAFT;
+        this.taskName = taskName;
+        this.internal = true;
+        this.id = id;
+        this.period = CraftTask.NO_REPEATING;
+        this.taskName = taskName;
+        this.timings = null; // Will be changed in later patch
+    }
+    // Paper end
 
     CraftTask(final Plugin plugin, final Object task, final int id, final long period) {
         this.plugin = plugin;
diff --git a/src/main/java/org/bukkit/craftbukkit/scheduler/MinecraftInternalPlugin.java b/src/main/java/org/bukkit/craftbukkit/scheduler/MinecraftInternalPlugin.java
new file mode 100644
index 0000000000000000000000000000000000000000..909b2c98e7a9117d2f737245e4661792ffafb744
--- /dev/null
+++ b/src/main/java/org/bukkit/craftbukkit/scheduler/MinecraftInternalPlugin.java
@@ -0,0 +1,140 @@
+package org.bukkit.craftbukkit.scheduler;
+
+
+import org.bukkit.Server;
+import org.bukkit.command.Command;
+import org.bukkit.command.CommandSender;
+import org.bukkit.configuration.file.FileConfiguration;
+import org.bukkit.generator.BiomeProvider;
+import org.bukkit.generator.ChunkGenerator;
+import org.bukkit.plugin.PluginBase;
+import org.bukkit.plugin.PluginDescriptionFile;
+import org.bukkit.plugin.PluginLoader;
+import org.bukkit.plugin.PluginLogger;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.io.File;
+import java.io.InputStream;
+import java.util.List;
+
+public class MinecraftInternalPlugin extends PluginBase {
+    private boolean enabled = true;
+
+    private final String pluginName;
+    private PluginDescriptionFile pdf;
+
+    public MinecraftInternalPlugin() {
+        this.pluginName = "Minecraft";
+        pdf = new PluginDescriptionFile(pluginName, "1.0", "nms");
+    }
+
+    public void setEnabled(boolean enabled) {
+        this.enabled = enabled;
+    }
+
+    @Override
+    public File getDataFolder() {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public PluginDescriptionFile getDescription() {
+        return pdf;
+    }
+
+    @Override
+    public FileConfiguration getConfig() {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public InputStream getResource(String filename) {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public void saveConfig() {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public void saveDefaultConfig() {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public void saveResource(String resourcePath, boolean replace) {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public void reloadConfig() {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public PluginLogger getLogger() {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public PluginLoader getPluginLoader() {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public Server getServer() {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public boolean isEnabled() {
+        return enabled;
+    }
+
+    @Override
+    public void onDisable() {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public void onLoad() {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public void onEnable() {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public boolean isNaggable() {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public void setNaggable(boolean canNag) {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public @Nullable BiomeProvider getDefaultBiomeProvider(@NotNull String worldName, @Nullable String id) {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+
+    @Override
+    public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
+        throw new UnsupportedOperationException("Not supported.");
+    }
+}
diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java b/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java
index d2942ef34c6d68d57caec9f1209c2dcdd277c36d..35d2a206d4a36292c16e29247c950c2a69af2879 100644
--- a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java
+++ b/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java
@@ -105,8 +105,17 @@ public final class CraftMagicNumbers implements UnsafeValues {
     private static final BiMap<net.minecraft.world.level.material.Fluid, Fluid> FLUIDTYPE_FLUID = HashBiMap.create();
     private static final Map<Material, Item> MATERIAL_ITEM = new HashMap<>();
     private static final Map<Material, Block> MATERIAL_BLOCK = new HashMap<>();
+    // Paper start
+    private static final Map<org.bukkit.entity.EntityType, net.minecraft.world.entity.EntityType<?>> ENTITY_TYPE_ENTITY_TYPES = new HashMap<>();
+    private static final Map<net.minecraft.world.entity.EntityType<?>, org.bukkit.entity.EntityType> ENTITY_TYPES_ENTITY_TYPE = new HashMap<>();
 
     static {
+        for (org.bukkit.entity.EntityType type : org.bukkit.entity.EntityType.values()) {
+            if (type == org.bukkit.entity.EntityType.UNKNOWN) continue;
+            ENTITY_TYPE_ENTITY_TYPES.put(type, BuiltInRegistries.ENTITY_TYPE.get(CraftNamespacedKey.toMinecraft(type.getKey())));
+            ENTITY_TYPES_ENTITY_TYPE.put(BuiltInRegistries.ENTITY_TYPE.get(CraftNamespacedKey.toMinecraft(type.getKey())), type);
+        }
+        // Paper end
         for (Block block : BuiltInRegistries.BLOCK) {
             BLOCK_MATERIAL.put(block, Material.getMaterial(BuiltInRegistries.BLOCK.getKey(block).getPath().toUpperCase(Locale.ROOT)));
         }
@@ -170,6 +179,14 @@ public final class CraftMagicNumbers implements UnsafeValues {
     public static ResourceLocation key(Material mat) {
         return CraftNamespacedKey.toMinecraft(mat.getKey());
     }
+    // Paper start
+    public static net.minecraft.world.entity.EntityType<?> getEntityTypes(org.bukkit.entity.EntityType type) {
+        return ENTITY_TYPE_ENTITY_TYPES.get(type);
+    }
+    public static org.bukkit.entity.EntityType getEntityType(net.minecraft.world.entity.EntityType<?> entityTypes) {
+        return ENTITY_TYPES_ENTITY_TYPE.get(entityTypes);
+    }
+    // Paper end
     // ========================================================================
 
     public static byte toLegacyData(BlockState data) {
diff --git a/src/main/java/org/bukkit/craftbukkit/util/DummyGeneratorAccess.java b/src/main/java/org/bukkit/craftbukkit/util/DummyGeneratorAccess.java
index d2026d218405a40a6949c5f491c04704811b72b5..629178347039893fb9de710810fe8112499bb91c 100644
--- a/src/main/java/org/bukkit/craftbukkit/util/DummyGeneratorAccess.java
+++ b/src/main/java/org/bukkit/craftbukkit/util/DummyGeneratorAccess.java
@@ -212,7 +212,23 @@ public class DummyGeneratorAccess implements WorldGenLevel {
     public FluidState getFluidState(BlockPos pos) {
         return Fluids.EMPTY.defaultFluidState(); // SPIGOT-6634
     }
+    // Paper start - if loaded util
+    @javax.annotation.Nullable
+    @Override
+    public ChunkAccess getChunkIfLoadedImmediately(int x, int z) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    @Override
+    public BlockState getBlockStateIfLoaded(BlockPos blockposition) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
 
+    @Override
+    public FluidState getFluidIfLoaded(BlockPos blockposition) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+    // Paper end
     @Override
     public WorldBorder getWorldBorder() {
         throw new UnsupportedOperationException("Not supported yet.");
diff --git a/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java b/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java
index aced43492a32d603690e75d0d9877667770fc6db..40d6bf127d288340e9c2500732d1e0963c186ebd 100644
--- a/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java
+++ b/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java
@@ -120,6 +120,32 @@ public class UnsafeList<E> extends AbstractList<E> implements List<E>, RandomAcc
         return this.indexOf(o) >= 0;
     }
 
+    // Paper start
+    protected transient int maxSize;
+    public void setSize(int size) {
+        if (this.maxSize < this.size) {
+            this.maxSize = this.size;
+        }
+        this.size = size;
+    }
+
+    public void completeReset() {
+        if (this.data != null) {
+            Arrays.fill(this.data, 0, Math.max(this.size, this.maxSize), null);
+        }
+        this.size = 0;
+        this.maxSize = 0;
+        if (this.iterPool != null) {
+            for (Iterator temp : this.iterPool) {
+                if (temp == null) {
+                    continue;
+                }
+                ((Itr)temp).valid = false;
+            }
+        }
+    }
+    // Paper end
+
     @Override
     public void clear() {
         // Create new array to reset memory usage to initial capacity
diff --git a/src/main/java/org/spigotmc/SpigotConfig.java b/src/main/java/org/spigotmc/SpigotConfig.java
index b599e098e6d2e6f78b89114e05cb03d716b7c5f4..83eabc34d952bbb13ec4b4bdcf34f647189c0b46 100644
--- a/src/main/java/org/spigotmc/SpigotConfig.java
+++ b/src/main/java/org/spigotmc/SpigotConfig.java
@@ -118,7 +118,11 @@ public class SpigotConfig
                 }
             }
         }
-
+        // Paper start
+        SpigotConfig.save();
+    }
+    public static void save() {
+        // Paper end
         try
         {
             SpigotConfig.config.save( CONFIG_FILE );