summaryrefslogtreecommitdiffstats
path: root/src/World.cpp
blob: d8655ce114118a2dbd76bb425403ea855d25841f (plain) (blame)
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

#include "Globals.h"  // NOTE: MSVC stupidness requires this to be the same across all modules

#include "World.h"
#include "ClientHandle.h"
#include "Server.h"
#include "Root.h"
#include "IniFile.h"
#include "Generating/ChunkDesc.h"
#include "Generating/ComposableGenerator.h"
#include "SetChunkData.h"
#include "DeadlockDetect.h"
#include "LineBlockTracer.h"
#include "UUID.h"
#include "BlockInServerPluginInterface.h"

// Serializers
#include "WorldStorage/ScoreboardSerializer.h"

// Entities (except mobs):
#include "Entities/ExpOrb.h"
#include "Entities/FallingBlock.h"
#include "Entities/Minecart.h"
#include "Entities/Pickup.h"
#include "Entities/Player.h"
#include "Entities/TNTEntity.h"

#include "BlockEntities/CommandBlockEntity.h"
#include "BlockEntities/BeaconEntity.h"

// Simulators:
#include "Simulator/FloodyFluidSimulator.h"
#include "Simulator/FluidSimulator.h"
#include "Simulator/FireSimulator.h"
#include "Simulator/NoopFluidSimulator.h"
#include "Simulator/NoopRedstoneSimulator.h"
#include "Simulator/IncrementalRedstoneSimulator/IncrementalRedstoneSimulator.h"
#include "Simulator/SandSimulator.h"
#include "Simulator/VanillaFluidSimulator.h"
#include "Simulator/VaporizeFluidSimulator.h"

// Mobs:
#include "Mobs/IncludeAllMonsters.h"
#include "MobCensus.h"
#include "MobSpawner.h"

#include "Generating/Trees.h"
#include "Bindings/PluginManager.h"
#include "Blocks/BlockHandler.h"

#ifndef _WIN32
	#include <stdlib.h>
#endif

#include "SpawnPrepare.h"
#include "FastRandom.h"
#include "OpaqueWorld.h"



const int TIME_SUNSET        = 12000;
const int TIME_NIGHT_START   = 13187;
const int TIME_NIGHT_END     = 22812;
const int TIME_SUNRISE       = 23999;
const int TIME_SPAWN_DIVISOR =   148;





namespace World
{
	// Implement conversion functions from OpaqueWorld.h
	cBroadcastInterface * GetBroadcastInterface(cWorld * a_World) { return a_World; }
	cForEachChunkProvider * GetFECProvider     (cWorld * a_World) { return a_World; }
	cWorldInterface * GetWorldInterface        (cWorld * a_World) { return a_World; }

	cChunkInterface GetChunkInterface(cWorld & a_World)
	{
		return { a_World.GetChunkMap() };
	}
}





////////////////////////////////////////////////////////////////////////////////
// cWorld::cLock:

cWorld::cLock::cLock(cWorld & a_World) :
	super(&(a_World.m_ChunkMap->GetCS()))
{
}





////////////////////////////////////////////////////////////////////////////////
// cWorld::cTickThread:

cWorld::cTickThread::cTickThread(cWorld & a_World) :
	super(Printf("WorldTickThread: %s", a_World.GetName().c_str())),
	m_World(a_World)
{
}





void cWorld::cTickThread::Execute(void)
{
	auto LastTime = std::chrono::steady_clock::now();
	auto TickTime = std::chrono::duration_cast<std::chrono::milliseconds>(cTickTime(1));

	while (!m_ShouldTerminate)
	{
		auto NowTime = std::chrono::steady_clock::now();
		auto WaitTime = std::chrono::duration_cast<std::chrono::milliseconds>(NowTime - LastTime);
		m_World.Tick(WaitTime, TickTime);
		TickTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - NowTime);

		if (TickTime < cTickTime(1))
		{
			// Stretch tick time until it's at least 1 tick
			std::this_thread::sleep_for(cTickTime(1) - TickTime);
		}

		LastTime = NowTime;
	}
}





////////////////////////////////////////////////////////////////////////////////
// cWorld:

cWorld::cWorld(
	const AString & a_WorldName, const AString & a_DataPath,
	cDeadlockDetect & a_DeadlockDetect, const AStringVector & a_WorldNames,
	eDimension a_Dimension, const AString & a_LinkedOverworldName
):
	m_WorldName(a_WorldName),
	m_DataPath(a_DataPath),
	m_LinkedOverworldName(a_LinkedOverworldName),
	m_IniFileName(m_DataPath + "/world.ini"),
	m_StorageSchema("Default"),
#ifdef __arm__
	m_StorageCompressionFactor(0),
#else
	m_StorageCompressionFactor(6),
#endif
	m_IsSavingEnabled(true),
	m_Dimension(a_Dimension),
	m_IsSpawnExplicitlySet(false),
	m_SpawnX(0),
	m_SpawnY(cChunkDef::Height),
	m_SpawnZ(0),
	m_BroadcastDeathMessages(true),
	m_BroadcastAchievementMessages(true),
	m_IsDaylightCycleEnabled(true),
	m_WorldAge(0),
	m_TimeOfDay(0),
	m_LastTimeUpdate(0),
	m_LastChunkCheck(0),
	m_LastSave(0),
	m_SkyDarkness(0),
	m_GameMode(gmSurvival),
	m_bEnabledPVP(false),
	m_IsDeepSnowEnabled(false),
	m_ShouldLavaSpawnFire(true),
	m_VillagersShouldHarvestCrops(true),
	m_SimulatorManager(),
	m_SandSimulator(),
	m_WaterSimulator(nullptr),
	m_LavaSimulator(nullptr),
	m_FireSimulator(),
	m_RedstoneSimulator(nullptr),
	m_MaxPlayers(10),
	m_ChunkMap(),
	m_bAnimals(true),
	m_Weather(eWeather_Sunny),
	m_WeatherInterval(24000),  // Guaranteed 1 game-day of sunshine at server start :)
	m_MaxSunnyTicks(180000),        // 150 real-world minutes -+
	m_MinSunnyTicks(12000),         // 10 real-world minutes   |
	m_MaxRainTicks(24000),          // 20 real-world minutes   +- all values adapted from Vanilla 1.7.2
	m_MinRainTicks(12000),          // 10 real-world minutes   |
	m_MaxThunderStormTicks(15600),  // 13 real-world minutes   |
	m_MinThunderStormTicks(3600),   // 3 real-world minutes   -+
	m_MaxCactusHeight(3),
	m_MaxSugarcaneHeight(4),
	/* TODO: Enable when functionality exists again
	m_IsBeetrootsBonemealable(true),
	m_IsCactusBonemealable(false),
	m_IsCarrotsBonemealable(true),
	m_IsCropsBonemealable(true),
	m_IsGrassBonemealable(true),
	m_IsMelonStemBonemealable(true),
	m_IsMelonBonemealable(true),
	m_IsPotatoesBonemealable(true),
	m_IsPumpkinStemBonemealable(true),
	m_IsPumpkinBonemealable(true),
	m_IsSaplingBonemealable(true),
	m_IsSugarcaneBonemealable(false),
	m_IsBigFlowerBonemealable(true),
	m_IsTallGrassBonemealable(true),
	*/
	m_bCommandBlocksEnabled(true),
	m_bUseChatPrefixes(false),
	m_TNTShrapnelLevel(slNone),
	m_MaxViewDistance(12),
	m_Scoreboard(this),
	m_MapManager(this),
	m_GeneratorCallbacks(*this),
	m_ChunkSender(*this),
	m_Lighting(*this),
	m_TickThread(*this)
{
	LOGD("cWorld::cWorld(\"%s\")", a_WorldName.c_str());

	cFile::CreateFolderRecursive(FILE_IO_PREFIX + m_DataPath);

	// Load the scoreboard
	cScoreboardSerializer Serializer(m_DataPath, &m_Scoreboard);
	Serializer.Load();

	// Track the CSs used by this world in the deadlock detector:
	a_DeadlockDetect.TrackCriticalSection(m_CSClients, Printf("World %s clients", m_WorldName.c_str()));
	a_DeadlockDetect.TrackCriticalSection(m_CSPlayers, Printf("World %s players", m_WorldName.c_str()));
	a_DeadlockDetect.TrackCriticalSection(m_CSTasks,   Printf("World %s tasks",   m_WorldName.c_str()));

	// Load world settings from the ini file
	cIniFile IniFile;
	if (!IniFile.ReadFile(m_IniFileName))
	{
		LOGWARNING("Cannot read world settings from \"%s\", defaults will be used.", m_IniFileName.c_str());

		// TODO: More descriptions for each key
		IniFile.AddHeaderComment(" This is the per-world configuration file, managing settings such as generators, simulators, and spawn points");
		IniFile.AddKeyComment(" LinkedWorlds", "This section governs portal world linkage; leave a value blank to disabled that associated method of teleportation");
	}

	// The presence of a configuration value overrides everything
	// If no configuration value is found, GetDimension() is written to file and the variable is written to again to ensure that cosmic rays haven't sneakily changed its value
	m_Dimension = StringToDimension(IniFile.GetValueSet("General", "Dimension", DimensionToString(GetDimension())));
	int UnusedDirtyChunksCap = IniFile.GetValueSetI("General", "UnusedChunkCap", 1000);
	if (UnusedDirtyChunksCap < 0)
	{
		UnusedDirtyChunksCap *= -1;
		IniFile.SetValueI("General", "UnusedChunkCap", UnusedDirtyChunksCap);
	}
	m_UnusedDirtyChunksCap = static_cast<size_t>(UnusedDirtyChunksCap);

	m_BroadcastDeathMessages = IniFile.GetValueSetB("Broadcasting", "BroadcastDeathMessages", true);
	m_BroadcastAchievementMessages = IniFile.GetValueSetB("Broadcasting", "BroadcastAchievementMessages", true);

	SetMaxViewDistance(IniFile.GetValueSetI("SpawnPosition", "MaxViewDistance", 12));

	// Try to find the "SpawnPosition" key and coord values in the world configuration, set the flag if found
	int KeyNum = IniFile.FindKey("SpawnPosition");
	m_IsSpawnExplicitlySet =
	(
		(KeyNum >= 0) &&
		(
			(IniFile.FindValue(KeyNum, "X") >= 0) &&
			(IniFile.FindValue(KeyNum, "Y") >= 0) &&
			(IniFile.FindValue(KeyNum, "Z") >= 0)
		)
	);

	if (m_IsSpawnExplicitlySet)
	{
		LOGD("Spawnpoint explicitly set!");
		m_SpawnX = IniFile.GetValueF("SpawnPosition", "X", m_SpawnX);
		m_SpawnY = IniFile.GetValueF("SpawnPosition", "Y", m_SpawnY);
		m_SpawnZ = IniFile.GetValueF("SpawnPosition", "Z", m_SpawnZ);
	}

	m_StorageSchema               = IniFile.GetValueSet ("Storage",       "Schema",                      m_StorageSchema);
	m_StorageCompressionFactor    = IniFile.GetValueSetI("Storage",       "CompressionFactor",           m_StorageCompressionFactor);
	m_MaxCactusHeight             = IniFile.GetValueSetI("Plants",        "MaxCactusHeight",             3);
	m_MaxSugarcaneHeight          = IniFile.GetValueSetI("Plants",        "MaxSugarcaneHeight",          3);
	/* TODO: Enable when functionality exists again
	m_IsBeetrootsBonemealable     = IniFile.GetValueSetB("Plants",        "IsBeetrootsBonemealable",     true);
	m_IsCactusBonemealable        = IniFile.GetValueSetB("Plants",        "IsCactusBonemealable",        false);
	m_IsCarrotsBonemealable       = IniFile.GetValueSetB("Plants",        "IsCarrotsBonemealable",       true);
	m_IsCropsBonemealable         = IniFile.GetValueSetB("Plants",        "IsCropsBonemealable",         true);
	m_IsGrassBonemealable         = IniFile.GetValueSetB("Plants",        "IsGrassBonemealable",         true);
	m_IsMelonStemBonemealable     = IniFile.GetValueSetB("Plants",        "IsMelonStemBonemealable",     true);
	m_IsMelonBonemealable         = IniFile.GetValueSetB("Plants",        "IsMelonBonemealable",         false);
	m_IsPotatoesBonemealable      = IniFile.GetValueSetB("Plants",        "IsPotatoesBonemealable",      true);
	m_IsPumpkinStemBonemealable   = IniFile.GetValueSetB("Plants",        "IsPumpkinStemBonemealable",   true);
	m_IsPumpkinBonemealable       = IniFile.GetValueSetB("Plants",        "IsPumpkinBonemealable",       false);
	m_IsSaplingBonemealable       = IniFile.GetValueSetB("Plants",        "IsSaplingBonemealable",       true);
	m_IsSugarcaneBonemealable     = IniFile.GetValueSetB("Plants",        "IsSugarcaneBonemealable",     false);
	m_IsBigFlowerBonemealable     = IniFile.GetValueSetB("Plants",        "IsBigFlowerBonemealable",     true);
	m_IsTallGrassBonemealable     = IniFile.GetValueSetB("Plants",        "IsTallGrassBonemealable",     true);
	*/
	m_IsDeepSnowEnabled           = IniFile.GetValueSetB("Physics",       "DeepSnow",                    true);
	m_ShouldLavaSpawnFire         = IniFile.GetValueSetB("Physics",       "ShouldLavaSpawnFire",         true);
	int TNTShrapnelLevel          = IniFile.GetValueSetI("Physics",       "TNTShrapnelLevel",            static_cast<int>(slAll));
	m_bCommandBlocksEnabled       = IniFile.GetValueSetB("Mechanics",     "CommandBlocksEnabled",        false);
	m_bEnabledPVP                 = IniFile.GetValueSetB("Mechanics",     "PVPEnabled",                  true);
	m_bUseChatPrefixes            = IniFile.GetValueSetB("Mechanics",     "UseChatPrefixes",             true);
	m_MinNetherPortalWidth        = IniFile.GetValueSetI("Mechanics",     "MinNetherPortalWidth",        2);
	m_MaxNetherPortalWidth        = IniFile.GetValueSetI("Mechanics",     "MaxNetherPortalWidth",        21);
	m_MinNetherPortalHeight       = IniFile.GetValueSetI("Mechanics",     "MinNetherPortalHeight",       3);
	m_MaxNetherPortalHeight       = IniFile.GetValueSetI("Mechanics",     "MaxNetherPortalHeight",       21);
	m_VillagersShouldHarvestCrops = IniFile.GetValueSetB("Monsters",      "VillagersShouldHarvestCrops", true);
	m_IsDaylightCycleEnabled      = IniFile.GetValueSetB("General",       "IsDaylightCycleEnabled",      true);
	int GameMode                  = IniFile.GetValueSetI("General",       "Gamemode",                    static_cast<int>(m_GameMode));
	int Weather                   = IniFile.GetValueSetI("General",       "Weather",                     static_cast<int>(m_Weather));

	m_WorldAge = std::chrono::milliseconds(IniFile.GetValueSetI("General", "WorldAgeMS", 0LL));

	// Load the weather frequency data:
	if (m_Dimension == dimOverworld)
	{
		m_MaxSunnyTicks        = IniFile.GetValueSetI("Weather", "MaxSunnyTicks",        m_MaxSunnyTicks);
		m_MinSunnyTicks        = IniFile.GetValueSetI("Weather", "MinSunnyTicks",        m_MinSunnyTicks);
		m_MaxRainTicks         = IniFile.GetValueSetI("Weather", "MaxRainTicks",         m_MaxRainTicks);
		m_MinRainTicks         = IniFile.GetValueSetI("Weather", "MinRainTicks",         m_MinRainTicks);
		m_MaxThunderStormTicks = IniFile.GetValueSetI("Weather", "MaxThunderStormTicks", m_MaxThunderStormTicks);
		m_MinThunderStormTicks = IniFile.GetValueSetI("Weather", "MinThunderStormTicks", m_MinThunderStormTicks);
		if (m_MaxSunnyTicks < m_MinSunnyTicks)
		{
			std::swap(m_MaxSunnyTicks, m_MinSunnyTicks);
		}
		if (m_MaxRainTicks < m_MinRainTicks)
		{
			std::swap(m_MaxRainTicks, m_MinRainTicks);
		}
		if (m_MaxThunderStormTicks < m_MinThunderStormTicks)
		{
			std::swap(m_MaxThunderStormTicks, m_MinThunderStormTicks);
		}
	}

	auto WorldExists = [&](const AString & a_CheckWorldName)
	{
		return (std::find(a_WorldNames.begin(), a_WorldNames.end(), a_CheckWorldName) != a_WorldNames.end());
	};

	if (a_Dimension == dimOverworld)
	{
		AString MyNetherName = GetName() + "_nether";
		AString MyEndName = GetName() + "_the_end";
		if (!WorldExists(MyNetherName))
		{
			MyNetherName.clear();
		}
		if (!WorldExists(MyEndName))
		{
			MyEndName = GetName() + "_end";
			if (!WorldExists(MyEndName))
			{
				MyEndName.clear();
			}
		}

		m_LinkedNetherWorldName = IniFile.GetValueSet("LinkedWorlds", "NetherWorldName", MyNetherName);
		m_LinkedEndWorldName    = IniFile.GetValueSet("LinkedWorlds", "EndWorldName",    MyEndName);
	}
	else
	{
		m_LinkedOverworldName = IniFile.GetValueSet("LinkedWorlds", "OverworldName", GetLinkedOverworldName());
	}

	// If we are linked to one or more worlds that do not exist, unlink them
	if (a_Dimension == dimOverworld)
	{
		if (!m_LinkedNetherWorldName.empty() && !WorldExists(m_LinkedNetherWorldName))
		{
			IniFile.SetValue("LinkedWorlds", "NetherWorldName", "");
			LOG("%s Is linked to a nonexisting nether world called \"%s\". The server has modified \"%s/world.ini\" and removed this invalid link.",
				GetName().c_str(), m_LinkedNetherWorldName.c_str(), GetName().c_str());
			m_LinkedNetherWorldName.clear();
		}
		if (!m_LinkedEndWorldName.empty() && !WorldExists(m_LinkedEndWorldName))
		{
			IniFile.SetValue("LinkedWorlds", "EndWorldName", "");
			LOG("%s Is linked to a nonexisting end world called \"%s\". The server has modified \"%s/world.ini\" and removed this invalid link.",
				GetName().c_str(), m_LinkedEndWorldName.c_str(), GetName().c_str());
			m_LinkedEndWorldName.clear();
		}
	}
	else
	{
		if (!m_LinkedOverworldName.empty() && !WorldExists(m_LinkedOverworldName))
		{
			IniFile.SetValue("LinkedWorlds", "OverworldName", "");
			LOG("%s Is linked to a nonexisting overworld called \"%s\". The server has modified \"%s/world.ini\" and removed this invalid link.",
				GetName().c_str(), m_LinkedOverworldName.c_str(), GetName().c_str());
			m_LinkedOverworldName.clear();
		}
	}



	// Adjust the enum-backed variables into their respective bounds:
	m_GameMode         = static_cast<eGameMode>     (Clamp<int>(GameMode,         gmSurvival, gmSpectator));
	m_TNTShrapnelLevel = static_cast<eShrapnelLevel>(Clamp<int>(TNTShrapnelLevel, slNone,     slAll));
	m_Weather          = static_cast<eWeather>      (Clamp<int>(Weather,          wSunny,     wStorm));

	cComposableGenerator::InitializeGeneratorDefaults(IniFile, m_Dimension);

	InitializeAndLoadMobSpawningValues(IniFile);
	SetTimeOfDay(IniFile.GetValueSetI("General", "TimeInTicks", GetTimeOfDay()));

	m_ChunkMap = cpp14::make_unique<cChunkMap>(this);
	m_ChunkMap->TrackInDeadlockDetect(a_DeadlockDetect, m_WorldName);

	// preallocate some memory for ticking blocks so we don't need to allocate that often
	m_BlockTickQueue.reserve(1000);
	m_BlockTickQueueCopy.reserve(1000);

	// Simulators:
	m_SimulatorManager  = cpp14::make_unique<cSimulatorManager>(*this);
	m_WaterSimulator    = InitializeFluidSimulator(IniFile, "Water", E_BLOCK_WATER, E_BLOCK_STATIONARY_WATER);
	m_LavaSimulator     = InitializeFluidSimulator(IniFile, "Lava",  E_BLOCK_LAVA,  E_BLOCK_STATIONARY_LAVA);
	m_SandSimulator     = cpp14::make_unique<cSandSimulator>(*this, IniFile);
	m_FireSimulator     = cpp14::make_unique<cFireSimulator>(*this, IniFile);
	m_RedstoneSimulator = InitializeRedstoneSimulator(IniFile);

	// Water, Lava and Redstone simulators get registered in their initialize function.
	m_SimulatorManager->RegisterSimulator(m_SandSimulator.get(), 1);
	m_SimulatorManager->RegisterSimulator(m_FireSimulator.get(), 1);

	m_Storage.Initialize(*this, m_StorageSchema, m_StorageCompressionFactor);
	m_Generator.Initialize(m_GeneratorCallbacks, m_GeneratorCallbacks, IniFile);

	m_MapManager.LoadMapData();

	// Save any changes that the defaults may have done to the ini file:
	if (!IniFile.WriteFile(m_IniFileName))
	{
		LOGWARNING("Could not write world config to %s", m_IniFileName.c_str());
	}

	// Init of the spawn monster time (as they are supposed to have different spawn rate)
	m_LastSpawnMonster.emplace(cMonster::mfHostile, cTickTimeLong(0));
	m_LastSpawnMonster.emplace(cMonster::mfPassive, cTickTimeLong(0));
	m_LastSpawnMonster.emplace(cMonster::mfAmbient, cTickTimeLong(0));
	m_LastSpawnMonster.emplace(cMonster::mfWater,   cTickTimeLong(0));
}





cWorld::~cWorld()
{
	delete m_WaterSimulator;     m_WaterSimulator    = nullptr;
	delete m_LavaSimulator;      m_LavaSimulator     = nullptr;
	delete m_RedstoneSimulator;  m_RedstoneSimulator = nullptr;

	m_Storage.WaitForFinish();

	if (IsSavingEnabled())
	{
		// Unload the scoreboard
		cScoreboardSerializer Serializer(m_DataPath, &m_Scoreboard);
		Serializer.Save();

		m_MapManager.SaveMapData();
	}

	// Explicitly destroy the chunkmap, so that it's guaranteed to be destroyed before the other internals
	// This fixes crashes on stopping the server, because chunk destructor deletes entities and those access the world.
	m_ChunkMap.reset();
}





void cWorld::CastThunderbolt(int a_BlockX, int a_BlockY, int a_BlockZ)
{
	LOG("CastThunderbolt(int, int, int) is deprecated, use CastThunderbolt(Vector3i) instead");
	CastThunderbolt({a_BlockX, a_BlockY, a_BlockZ});
}





void cWorld::CastThunderbolt(Vector3i a_Block)
{
	BroadcastThunderbolt(a_Block);
	BroadcastSoundEffect("entity.lightning.thunder", a_Block, 50, 1);
}





int cWorld::GetDefaultWeatherInterval(eWeather a_Weather)
{
	auto & Random = GetRandomProvider();
	switch (a_Weather)
	{
		case eWeather_Sunny:
		{
			return Random.RandInt(m_MinSunnyTicks, m_MaxSunnyTicks);
		}
		case eWeather_Rain:
		{
			return Random.RandInt(m_MinRainTicks, m_MaxRainTicks);
		}
		case eWeather_ThunderStorm:
		{
			return Random.RandInt(m_MinThunderStormTicks, m_MaxThunderStormTicks);
		}
	}
	UNREACHABLE("Unsupported weather");
}





void cWorld::SetWeather(eWeather a_NewWeather)
{
	// Do the plugins agree? Do they want a different weather?
	if (cRoot::Get()->GetPluginManager()->CallHookWeatherChanging(*this, a_NewWeather))
	{
		m_WeatherInterval = GetDefaultWeatherInterval(m_Weather);
		return;
	}

	// Set new period for the selected weather:
	m_WeatherInterval = GetDefaultWeatherInterval(a_NewWeather);

	// The weather can't be found:
	if (m_WeatherInterval < 0)
	{
		return;
	}

	m_Weather = a_NewWeather;
	BroadcastWeather(m_Weather);

	// Let the plugins know about the change:
	cPluginManager::Get()->CallHookWeatherChanged(*this);
}





void cWorld::ChangeWeather(void)
{
	// In the next tick the weather will be changed
	m_WeatherInterval = 0;
}





bool cWorld::IsWeatherWetAtXYZ(Vector3i a_Pos)
{
	if ((a_Pos.y < 0) || !IsWeatherWetAt(a_Pos.x, a_Pos.z))
	{
		return false;
	}

	if (a_Pos.y >= cChunkDef::Height)
	{
		return true;
	}

	for (int y = GetHeight(a_Pos.x, a_Pos.z); y >= a_Pos.y; y--)
	{
		auto BlockType = GetBlock({a_Pos.x, y, a_Pos.z});
		if (cBlockInfo::IsRainBlocker(BlockType))
		{
			return false;
		}
	}

	return true;
}





void cWorld::SetNextBlockTick(int a_BlockX, int a_BlockY, int a_BlockZ)
{
	return m_ChunkMap->SetNextBlockTick(a_BlockX, a_BlockY, a_BlockZ);
}





bool cWorld::SetSpawn(double a_X, double a_Y, double a_Z)
{
		cIniFile IniFile;

		IniFile.ReadFile(m_IniFileName);
		IniFile.SetValueF("SpawnPosition", "X", a_X);
		IniFile.SetValueF("SpawnPosition", "Y", a_Y);
		IniFile.SetValueF("SpawnPosition", "Z", a_Z);
		if (IniFile.WriteFile(m_IniFileName))
		{
			m_SpawnX = a_X;
			m_SpawnY = a_Y;
			m_SpawnZ = a_Z;
			FLOGD("Spawn set at {0}", Vector3d{m_SpawnX, m_SpawnY, m_SpawnZ});
			return true;
		}
		else
		{
			LOGWARNING("Couldn't write new spawn settings to \"%s\".", m_IniFileName.c_str());
		}
		return false;
}





void cWorld::InitializeSpawn(void)
{
	// For the debugging builds, don't make the server build too much world upon start:
	#if defined(_DEBUG) || defined(ANDROID)
		const int DefaultViewDist = 9;
	#else
		const int DefaultViewDist = 20;  // Always prepare an area 20 chunks across, no matter what the actual cClientHandle::VIEWDISTANCE is
	#endif  // _DEBUG

	if (!m_IsSpawnExplicitlySet)
	{
		// Spawn position wasn't already explicitly set, enumerate random solid-land coordinate and then write it to the world configuration:
		GenerateRandomSpawn(DefaultViewDist);
	}

	cIniFile IniFile;
	IniFile.ReadFile(m_IniFileName);
	int ViewDist = IniFile.GetValueSetI("SpawnPosition", "PregenerateDistance", DefaultViewDist);
	IniFile.WriteFile(m_IniFileName);

	int ChunkX = 0, ChunkZ = 0;
	cChunkDef::BlockToChunk(FloorC(m_SpawnX), FloorC(m_SpawnZ), ChunkX, ChunkZ);
	cSpawnPrepare::PrepareChunks(*this, ChunkX, ChunkZ, ViewDist);
}





void cWorld::Start()
{
	m_Lighting.Start();
	m_Storage.Start();
	m_Generator.Start();
	m_ChunkSender.Start();
	m_TickThread.Start();
}





void cWorld::GenerateRandomSpawn(int a_MaxSpawnRadius)
{
	LOGD("Generating random spawnpoint...");

	// Number of checks to make sure we have a valid biome
	// 100 checks will check across 400 chunks, we should have
	// a valid biome by then.
	static const int BiomeCheckCount = 100;

	// Make sure we are in a valid biome
	Vector3i BiomeOffset = Vector3i(0, 0, 0);
	for (int BiomeCheckIndex = 0; BiomeCheckIndex < BiomeCheckCount; ++BiomeCheckIndex)
	{
		EMCSBiome Biome = GetBiomeAt(BiomeOffset.x, BiomeOffset.z);
		if ((Biome == EMCSBiome::biOcean) || (Biome == EMCSBiome::biFrozenOcean))
		{
			BiomeOffset += Vector3d(cChunkDef::Width * 4, 0, 0);
			continue;
		}

		// Found a usable biome
		// Spawn chunks so we can find a nice spawn.
		int ChunkX = 0, ChunkZ = 0;
		cChunkDef::BlockToChunk(BiomeOffset.x, BiomeOffset.z, ChunkX, ChunkZ);
		cSpawnPrepare::PrepareChunks(*this, ChunkX, ChunkZ, a_MaxSpawnRadius);
		break;
	}

	// Check 0, 0 first.
	double SpawnY = 0.0;
	if (CanSpawnAt(BiomeOffset.x, SpawnY, BiomeOffset.z))
	{
		SetSpawn(BiomeOffset.x + 0.5, SpawnY, BiomeOffset.z + 0.5);

		FLOGINFO("World \"{0}\": Generated spawnpoint position at {1:.2f}", m_WorldName, Vector3d{m_SpawnX, m_SpawnY, m_SpawnZ});
		return;
	}

	// A search grid (searches clockwise around the origin)
	static const int HalfChunk = static_cast<int>(cChunkDef::Width / 2.0f);
	static const Vector3i ChunkOffset[] =
	{
		Vector3i(0, 0, HalfChunk),
		Vector3i(HalfChunk, 0, HalfChunk),
		Vector3i(HalfChunk, 0, 0),
		Vector3i(HalfChunk, 0, -HalfChunk),
		Vector3i(0, 0, -HalfChunk),
		Vector3i(-HalfChunk, 0, -HalfChunk),
		Vector3i(-HalfChunk, 0, 0),
		Vector3i(-HalfChunk, 0, HalfChunk),
	};

	static const int PerRadiSearchCount = ARRAYCOUNT(ChunkOffset);

	for (int RadiusOffset = 1; RadiusOffset < (a_MaxSpawnRadius * 2); ++RadiusOffset)
	{
		for (int SearchGridIndex = 0; SearchGridIndex < PerRadiSearchCount; ++SearchGridIndex)
		{
			const Vector3i PotentialSpawn = BiomeOffset + (ChunkOffset[SearchGridIndex] * RadiusOffset);

			if (CanSpawnAt(PotentialSpawn.x, SpawnY, PotentialSpawn.z))
			{
				SetSpawn(PotentialSpawn.x + 0.5, SpawnY, PotentialSpawn.z + 0.5);

				int ChunkX, ChunkZ;
				cChunkDef::BlockToChunk(static_cast<int>(m_SpawnX), static_cast<int>(m_SpawnZ), ChunkX, ChunkZ);
				cSpawnPrepare::PrepareChunks(*this, ChunkX, ChunkZ, a_MaxSpawnRadius);

				FLOGINFO("World \"{0}\":Generated spawnpoint position at {1:.2f}", m_WorldName, Vector3d{m_SpawnX, m_SpawnY, m_SpawnZ});
				return;
			}
		}
	}

	m_SpawnY = GetHeight(static_cast<int>(m_SpawnX), static_cast<int>(m_SpawnZ));
	FLOGWARNING("World \"{0}\": Did not find an acceptable spawnpoint. Generated a random spawnpoint position at {1:.2f}", m_WorldName, Vector3d{m_SpawnX, m_SpawnY, m_SpawnZ});
}





bool cWorld::CanSpawnAt(double a_X, double & a_Y, double a_Z)
{
	// All this blocks can only be found above ground.
	// Apart from netherrack (as the Nether is technically a massive cave)
	static const BLOCKTYPE ValidSpawnBlocks[] =
	{
		E_BLOCK_GRASS,
		E_BLOCK_SAND,
		E_BLOCK_SNOW,
		E_BLOCK_SNOW_BLOCK,
		E_BLOCK_NETHERRACK
	};

	static const int ValidSpawnBlocksCount = ARRAYCOUNT(ValidSpawnBlocks);

	// Increase this by two, because we need two more blocks for body and head
	static const int HighestSpawnPoint = GetHeight(static_cast<int>(a_X), static_cast<int>(a_Z)) + 2;
	static const int LowestSpawnPoint = static_cast<int>(HighestSpawnPoint / 2.0f);

	for (int PotentialY = HighestSpawnPoint; PotentialY > LowestSpawnPoint; --PotentialY)
	{
		BLOCKTYPE HeadBlock = GetBlock(static_cast<int>(a_X), PotentialY, static_cast<int>(a_Z));

		// Is this block safe for spawning
		if (HeadBlock != E_BLOCK_AIR)
		{
			continue;
		}

		BLOCKTYPE BodyBlock = GetBlock(static_cast<int>(a_X), PotentialY - 1, static_cast<int>(a_Z));

		// Is this block safe for spawning
		if (BodyBlock != E_BLOCK_AIR)
		{
			continue;
		}

		BLOCKTYPE FloorBlock = GetBlock(static_cast<int>(a_X), PotentialY - 2, static_cast<int>(a_Z));

		// Early out - Is the floor block air
		if (FloorBlock == E_BLOCK_AIR)
		{
			continue;
		}

		// Is the floor block ok
		bool ValidSpawnBlock = false;
		for (int BlockIndex = 0; BlockIndex < ValidSpawnBlocksCount; ++BlockIndex)
		{
			ValidSpawnBlock |= (ValidSpawnBlocks[BlockIndex] == FloorBlock);
		}

		if (!ValidSpawnBlock)
		{
			continue;
		}

		if (!CheckPlayerSpawnPoint(static_cast<int>(a_X), PotentialY - 1, static_cast<int>(a_Z)))
		{
			continue;
		}

		a_Y = PotentialY - 1.0;
		return true;
	}

	return false;
}





bool cWorld::CheckPlayerSpawnPoint(int a_PosX, int a_PosY, int a_PosZ)
{
	// Check height bounds
	if (!cChunkDef::IsValidHeight(a_PosY))
	{
		return false;
	}

	// Check that surrounding blocks are neither solid or liquid
	static const Vector3i SurroundingCoords[] =
	{
		Vector3i(0,  0,  1),
		Vector3i(1,  0,  1),
		Vector3i(1,  0,  0),
		Vector3i(1,  0, -1),
		Vector3i(0,  0, -1),
		Vector3i(-1, 0, -1),
		Vector3i(-1, 0,  0),
		Vector3i(-1, 0,  1),
	};

	static const int SurroundingCoordsCount = ARRAYCOUNT(SurroundingCoords);

	for (int CoordIndex = 0; CoordIndex < SurroundingCoordsCount; ++CoordIndex)
	{
		const int XPos = a_PosX + SurroundingCoords[CoordIndex].x;
		const int ZPos = a_PosZ + SurroundingCoords[CoordIndex].z;

		const BLOCKTYPE BlockType = GetBlock(XPos, a_PosY, ZPos);
		if (cBlockInfo::IsSolid(BlockType) || IsBlockLiquid(BlockType))
		{
			return false;
		}
	}

	return true;
}





eWeather cWorld::ChooseNewWeather()
{
	// Pick a new weather. Only reasonable transitions allowed:
	switch (m_Weather)
	{
		case eWeather_Sunny:
		case eWeather_ThunderStorm:
		{
			return eWeather_Rain;
		}
		case eWeather_Rain:
		{
			// 1 / 8 chance of turning into a thunderstorm
			return GetRandomProvider().RandBool(0.125) ? eWeather_ThunderStorm : eWeather_Sunny;
		}
	}
	UNREACHABLE("Unsupported weather");
}





void cWorld::InitializeAndLoadMobSpawningValues(cIniFile & a_IniFile)
{
	AString DefaultMonsters;
	switch (m_Dimension)
	{
		case dimOverworld: DefaultMonsters = "bat, cavespider, chicken, cow, creeper, guardian, horse, mooshroom, ocelot, pig, rabbit, sheep, silverfish, skeleton, slime, spider, squid, wolf, zombie"; break;  // TODO Re-add Enderman when bugs are fixed
		case dimNether:    DefaultMonsters = "blaze, ghast, magmacube, skeleton, zombiepigman"; break;
		case dimEnd:       DefaultMonsters = ""; break;  // TODO Re-add Enderman when bugs are fixed
		case dimNotSet:    ASSERT(!"Dimension not set"); break;
	}

	m_bAnimals = a_IniFile.GetValueSetB("Monsters", "AnimalsOn", true);
	AString AllMonsters = a_IniFile.GetValueSet("Monsters", "Types", DefaultMonsters);

	if (!m_bAnimals)
	{
		return;
	}

	AStringVector SplitList = StringSplitAndTrim(AllMonsters, ",");
	for (AStringVector::const_iterator itr = SplitList.begin(), end = SplitList.end(); itr != end; ++itr)
	{
		eMonsterType ToAdd = cMonster::StringToMobType(*itr);
		if (ToAdd != mtInvalidType)
		{
			m_AllowedMobs.insert(ToAdd);
			LOGD("Allowed mob: %s", itr->c_str());
		}
		else
		{
			LOG("World \"%s\": Unknown mob type: %s", m_WorldName.c_str(), itr->c_str());
		}
	}
}





void cWorld::Stop(cDeadlockDetect & a_DeadlockDetect)
{
	// Delete the clients that have been in this world:
	{
		cCSLock Lock(m_CSClients);
		for (auto itr = m_Clients.begin(); itr != m_Clients.end(); ++itr)
		{
			(*itr)->Destroy();
		}  // for itr - m_Clients[]
		m_Clients.clear();
	}

	// Write settings to file; these are all plugin changeable values - keep updated!
	cIniFile IniFile;
	IniFile.ReadFile(m_IniFileName);
		if (GetDimension() == dimOverworld)
		{
			IniFile.SetValue("LinkedWorlds", "NetherWorldName", m_LinkedNetherWorldName);
			IniFile.SetValue("LinkedWorlds", "EndWorldName",    m_LinkedEndWorldName);
		}
		else
		{
			IniFile.SetValue("LinkedWorlds", "OverworldName", m_LinkedOverworldName);
		}
		IniFile.SetValueI("Physics", "TNTShrapnelLevel", static_cast<int>(m_TNTShrapnelLevel));
		IniFile.SetValueB("Mechanics", "CommandBlocksEnabled", m_bCommandBlocksEnabled);
		IniFile.SetValueB("Mechanics", "UseChatPrefixes", m_bUseChatPrefixes);
		IniFile.SetValueB("General", "IsDaylightCycleEnabled", m_IsDaylightCycleEnabled);
		IniFile.SetValueI("General", "Weather", static_cast<int>(m_Weather));
		IniFile.SetValueI("General", "TimeInTicks", GetTimeOfDay());
		IniFile.SetValueI("General", "WorldAgeMS", static_cast<Int64>(m_WorldAge.count()));
	IniFile.WriteFile(m_IniFileName);

	m_TickThread.Stop();
	m_Lighting.Stop();
	m_Generator.Stop();
	m_ChunkSender.Stop();
	m_Storage.Stop();

	a_DeadlockDetect.UntrackCriticalSection(m_CSClients);
	a_DeadlockDetect.UntrackCriticalSection(m_CSPlayers);
	a_DeadlockDetect.UntrackCriticalSection(m_CSTasks);
	m_ChunkMap->UntrackInDeadlockDetect(a_DeadlockDetect);
}





void cWorld::Tick(std::chrono::milliseconds a_Dt, std::chrono::milliseconds a_LastTickDurationMSec)
{
	// Call the plugins
	cPluginManager::Get()->CallHookWorldTick(*this, a_Dt, a_LastTickDurationMSec);

	// Set any chunk data that has been queued for setting:
	cSetChunkDataPtrs SetChunkDataQueue;
	{
		cCSLock Lock(m_CSSetChunkDataQueue);
		std::swap(SetChunkDataQueue, m_SetChunkDataQueue);
	}
	for (cSetChunkDataPtrs::iterator itr = SetChunkDataQueue.begin(), end = SetChunkDataQueue.end(); itr != end; ++itr)
	{
		SetChunkData(**itr);
	}  // for itr - SetChunkDataQueue[]

	m_WorldAge += a_Dt;

	if (m_IsDaylightCycleEnabled)
	{
		// We need sub-tick precision here, that's why we store the time in milliseconds and calculate ticks off of it
		m_TimeOfDay += a_Dt;

		// Wrap time of day each 20 minutes (1200 seconds)
		if (m_TimeOfDay > std::chrono::minutes(20))
		{
			m_TimeOfDay -= std::chrono::minutes(20);
		}

		// Updates the sky darkness based on current time of day
		UpdateSkyDarkness();

		// Broadcast time update every 40 ticks (2 seconds)
		if (m_LastTimeUpdate < m_WorldAge - cTickTime(40))
		{
			BroadcastTimeUpdate();
			m_LastTimeUpdate = std::chrono::duration_cast<cTickTimeLong>(m_WorldAge);
		}
	}

	// Add entities waiting in the queue to be added:
	cEntityList EntitiesToAdd;
	{
		// Don't access chunkmap while holding lock
		cCSLock Lock(m_CSEntitiesToAdd);
		std::swap(EntitiesToAdd, m_EntitiesToAdd);
	}
	for (auto & Entity : EntitiesToAdd)
	{
		Entity->SetWorld(this);
		auto EntityPtr = Entity.get();
		m_ChunkMap->AddEntity(std::move(Entity));
		EntityPtr->OnAddToWorld(*this);
		ASSERT(!EntityPtr->IsTicking());
		EntityPtr->SetIsTicking(true);
	}
	EntitiesToAdd.clear();

	// Add players waiting in the queue to be added:
	AddQueuedPlayers();

	m_ChunkMap->Tick(a_Dt);
	TickMobs(a_Dt);
	m_MapManager.TickMaps();

	TickClients(static_cast<float>(a_Dt.count()));
	TickQueuedBlocks();
	TickQueuedTasks();

	GetSimulatorManager()->Simulate(static_cast<float>(a_Dt.count()));

	TickWeather(static_cast<float>(a_Dt.count()));

	if (m_WorldAge - m_LastChunkCheck > std::chrono::seconds(10))
	{
		// Unload every 10 seconds
		UnloadUnusedChunks();

		if (m_WorldAge - m_LastSave > std::chrono::minutes(5))
		{
			// Save every 5 minutes
			SaveAllChunks();
		}
		else if (GetNumUnusedDirtyChunks() > m_UnusedDirtyChunksCap)
		{
			// Save if we have too many dirty unused chunks
			SaveAllChunks();
		}
	}
}





void cWorld::TickWeather(float a_Dt)
{
	UNUSED(a_Dt);
	// There are no weather changes anywhere but in the Overworld:
	if (GetDimension() != dimOverworld)
	{
		return;
	}

	if (m_WeatherInterval > 0)
	{
		// Not yet, wait for the weather period to end
		m_WeatherInterval--;
	}
	else
	{
		// Change weather:
		SetWeather(ChooseNewWeather());
	}

	if (m_Weather == eWeather_ThunderStorm)
	{
		// 0.5% chance per tick of thunderbolt
		if (GetRandomProvider().RandBool(0.005))
		{
			CastThunderbolt({0, 0, 0});  // TODO: find random positions near players to cast thunderbolts.
		}
	}
}





void cWorld::TickMobs(std::chrono::milliseconds a_Dt)
{
	// _X 2013_10_22: This is a quick fix for #283 - the world needs to be locked while ticking mobs
	cWorld::cLock Lock(*this);

	// before every Mob action, we have to count them depending on the distance to players, on their family ...
	cMobCensus MobCensus;
	m_ChunkMap->CollectMobCensus(MobCensus);
	if (m_bAnimals)
	{
		// Spawning is enabled, spawn now:
		static const cMonster::eFamily AllFamilies[] =
		{
			cMonster::mfHostile,
			cMonster::mfPassive,
			cMonster::mfAmbient,
			cMonster::mfWater,
		} ;
		for (size_t i = 0; i < ARRAYCOUNT(AllFamilies); i++)
		{
			cMonster::eFamily Family = AllFamilies[i];
			cTickTime SpawnDelay = cTickTime(cMonster::GetSpawnDelay(Family));
			if (
				(m_LastSpawnMonster[Family] > m_WorldAge - SpawnDelay) ||  // Not reached the needed ticks before the next round
				MobCensus.IsCapped(Family)
			)
			{
				continue;
			}
			m_LastSpawnMonster[Family] = std::chrono::duration_cast<cTickTimeLong>(m_WorldAge);
			cMobSpawner Spawner(Family, m_AllowedMobs);
			if (Spawner.CanSpawnAnything())
			{
				m_ChunkMap->SpawnMobs(Spawner);
				// do the spawn
				for (auto & Mob : Spawner.getSpawned())
				{
					SpawnMobFinalize(std::move(Mob));
				}
			}
		}  // for i - AllFamilies[]
	}  // if (Spawning enabled)

	ForEachEntity([=](cEntity & a_Entity)
		{
			if (!a_Entity.IsMob())
			{
				return false;
			}
			if (!a_Entity.IsTicking())
			{
				return false;
			}

			auto & Monster = static_cast<cMonster &>(a_Entity);
			ASSERT(Monster.GetParentChunk() != nullptr);  // A ticking entity must have a valid parent chunk

			// Tick close mobs
			if (Monster.GetParentChunk()->HasAnyClients())
			{
				Monster.Tick(a_Dt, *(a_Entity.GetParentChunk()));
			}
			// Destroy far hostile mobs except if last target was a player
			else if ((Monster.GetMobFamily() == cMonster::eFamily::mfHostile) && !Monster.WasLastTargetAPlayer())
			{
				if (Monster.GetMobType() != eMonsterType::mtWolf)
				{
					Monster.Destroy();
				}
				else
				{
					auto & Wolf = static_cast<cWolf &>(Monster);
					if (!Wolf.IsAngry() && !Wolf.IsTame())
					{
						Monster.Destroy();
					}
				}
			}
			return false;
		}
	);
}





void cWorld::TickQueuedTasks(void)
{
	// Move the tasks to be executed to a seperate vector to avoid deadlocks on accessing m_Tasks
	decltype(m_Tasks) Tasks;
	{
		cCSLock Lock(m_CSTasks);
		if (m_Tasks.empty())
		{
			return;
		}

		// Partition everything to be executed by returning false to move to end of list if time reached
		auto MoveBeginIterator = std::partition(m_Tasks.begin(), m_Tasks.end(), [this](const decltype(m_Tasks)::value_type & a_Task)
			{
				if (a_Task.first < std::chrono::duration_cast<cTickTimeLong>(m_WorldAge).count())
				{
					return false;
				}
				return true;
			}
		);

		// Cut all the due tasks from m_Tasks into Tasks:
		Tasks.insert(
			Tasks.end(),
			std::make_move_iterator(MoveBeginIterator),
			std::make_move_iterator(m_Tasks.end())
		);
		m_Tasks.erase(MoveBeginIterator, m_Tasks.end());
	}

	// Execute each task:
	for (const auto & Task : Tasks)
	{
		Task.second(*this);
	}  // for itr - m_Tasks[]
}





void cWorld::TickClients(float a_Dt)
{
	cClientHandlePtrs RemoveClients;
	{
		cCSLock Lock(m_CSClients);

		// Remove clients scheduled for removal:
		for (auto itr = m_ClientsToRemove.begin(), end = m_ClientsToRemove.end(); itr != end; ++itr)
		{
			for (auto itrC = m_Clients.begin(), endC = m_Clients.end(); itrC != endC; ++itrC)
			{
				if (itrC->get() == *itr)
				{
					m_Clients.erase(itrC);
					break;
				}
			}
		}  // for itr - m_ClientsToRemove[]
		m_ClientsToRemove.clear();

		// Add clients scheduled for adding:
		for (auto itr = m_ClientsToAdd.begin(), end = m_ClientsToAdd.end(); itr != end; ++itr)
		{
			ASSERT(std::find(m_Clients.begin(), m_Clients.end(), *itr) == m_Clients.end());
			m_Clients.push_back(*itr);
		}  // for itr - m_ClientsToRemove[]
		m_ClientsToAdd.clear();

		// Tick the clients, take out those that have been destroyed into RemoveClients
		for (auto itr = m_Clients.begin(); itr != m_Clients.end();)
		{
			if ((*itr)->IsDestroyed())
			{
				// Remove the client later, when CS is not held, to avoid deadlock
				RemoveClients.push_back(*itr);
				itr = m_Clients.erase(itr);
				continue;
			}
			(*itr)->Tick(a_Dt);
			++itr;
		}  // for itr - m_Clients[]
	}

	// Delete the clients queued for removal:
	RemoveClients.clear();
}





void cWorld::UpdateSkyDarkness(void)
{
	int TempTime = std::chrono::duration_cast<cTickTime>(m_TimeOfDay).count();
	if (TempTime <= TIME_SUNSET)
	{
		m_SkyDarkness = 0;
	}
	else if (TempTime <= TIME_NIGHT_START)
	{
		m_SkyDarkness = static_cast<NIBBLETYPE>((TIME_NIGHT_START - TempTime) / TIME_SPAWN_DIVISOR);
	}
	else if (TempTime <= TIME_NIGHT_END)
	{
		m_SkyDarkness = 8;
	}
	else
	{
		m_SkyDarkness = static_cast<NIBBLETYPE>((TIME_SUNRISE - TempTime) / TIME_SPAWN_DIVISOR);
	}
}





void cWorld::WakeUpSimulators(Vector3i a_Block)
{
	return m_ChunkMap->WakeUpSimulators(a_Block);
}





void cWorld::WakeUpSimulatorsInArea(int a_MinBlockX, int a_MaxBlockX, int a_MinBlockY, int a_MaxBlockY, int a_MinBlockZ, int a_MaxBlockZ)
{
	LOGWARNING("cWorld::WakeUpSimulatorsInArea(int, int, int) is deprecated, use cWorld::WakeUpSimulatorsInArea(Vector3i) instead.");
	WakeUpSimulatorsInArea(cCuboid({a_MinBlockX, a_MinBlockY, a_MinBlockZ}, {a_MaxBlockX, a_MaxBlockY, a_MaxBlockZ}));
}





void cWorld::WakeUpSimulatorsInArea(const cCuboid & a_Area)
{
	m_SimulatorManager->WakeUpArea(a_Area);
}





bool cWorld::ForEachBlockEntityInChunk(int a_ChunkX, int a_ChunkZ, cBlockEntityCallback a_Callback)
{
	return m_ChunkMap->ForEachBlockEntityInChunk(a_ChunkX, a_ChunkZ, a_Callback);
}





bool cWorld::ForEachBrewingstandInChunk(int a_ChunkX, int a_ChunkZ, cBrewingstandCallback a_Callback)
{
	return m_ChunkMap->ForEachBrewingstandInChunk(a_ChunkX, a_ChunkZ, a_Callback);
}





bool cWorld::ForEachChestInChunk(int a_ChunkX, int a_ChunkZ, cChestCallback a_Callback)
{
	return m_ChunkMap->ForEachChestInChunk(a_ChunkX, a_ChunkZ, a_Callback);
}





bool cWorld::ForEachDispenserInChunk(int a_ChunkX, int a_ChunkZ, cDispenserCallback a_Callback)
{
	return m_ChunkMap->ForEachDispenserInChunk(a_ChunkX, a_ChunkZ, a_Callback);
}





bool cWorld::ForEachDropperInChunk(int a_ChunkX, int a_ChunkZ, cDropperCallback a_Callback)
{
	return m_ChunkMap->ForEachDropperInChunk(a_ChunkX, a_ChunkZ, a_Callback);
}





bool cWorld::ForEachDropSpenserInChunk(int a_ChunkX, int a_ChunkZ, cDropSpenserCallback a_Callback)
{
	return m_ChunkMap->ForEachDropSpenserInChunk(a_ChunkX, a_ChunkZ, a_Callback);
}





bool cWorld::ForEachFurnaceInChunk(int a_ChunkX, int a_ChunkZ, cFurnaceCallback a_Callback)
{
	return m_ChunkMap->ForEachFurnaceInChunk(a_ChunkX, a_ChunkZ, a_Callback);
}





void cWorld::DoExplosionAt(double a_ExplosionSize, double a_BlockX, double a_BlockY, double a_BlockZ, bool a_CanCauseFire, eExplosionSource a_Source, void * a_SourceData)
{
	if (cPluginManager::Get()->CallHookExploding(*this, a_ExplosionSize, a_CanCauseFire, a_BlockX, a_BlockY, a_BlockZ, a_Source, a_SourceData) || (a_ExplosionSize <= 0))
	{
		return;
	}

	// TODO: Implement block hardiness
	cVector3iArray BlocksAffected;
	m_ChunkMap->DoExplosionAt(a_ExplosionSize, a_BlockX, a_BlockY, a_BlockZ, BlocksAffected);

	auto & Random = GetRandomProvider();
	auto SoundPitchMultiplier = 1.0f + (Random.RandReal(1.0f) - Random.RandReal(1.0f)) * 0.2f;

	BroadcastSoundEffect("entity.generic.explode", Vector3d(a_BlockX, a_BlockY, a_BlockZ), 4.0f, SoundPitchMultiplier * 0.7f);

	{
		cCSLock Lock(m_CSPlayers);
		for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
		{
			cClientHandle * ch = (*itr)->GetClientHandle();
			if (ch == nullptr)
			{
				continue;
			}

			ch->SendExplosion(a_BlockX, a_BlockY, a_BlockZ, static_cast<float>(a_ExplosionSize), BlocksAffected, (*itr)->GetSpeed());
		}
	}

	auto Position = Vector3d(a_BlockX, a_BlockY - 0.5f, a_BlockZ);
	auto ParticleFormula = a_ExplosionSize * 0.33f;
	auto Spread = ParticleFormula * 0.5f;
	auto ParticleCount = std::min((ParticleFormula * 125), 600.0);

	BroadcastParticleEffect("largesmoke", Position, Vector3f{}, static_cast<float>(Spread), static_cast<int>(ParticleCount));

	Spread = ParticleFormula * 0.35f;
	ParticleCount = std::min((ParticleFormula * 550), 1800.0);

	BroadcastParticleEffect("explode", Position, Vector3f{}, static_cast<float>(Spread), static_cast<int>(ParticleCount));

	cPluginManager::Get()->CallHookExploded(*this, a_ExplosionSize, a_CanCauseFire, a_BlockX, a_BlockY, a_BlockZ, a_Source, a_SourceData);
}





bool cWorld::DoWithBlockEntityAt(int a_BlockX, int a_BlockY, int a_BlockZ, cBlockEntityCallback a_Callback)
{
	return m_ChunkMap->DoWithBlockEntityAt(a_BlockX, a_BlockY, a_BlockZ, a_Callback);
}





bool cWorld::DoWithBeaconAt(int a_BlockX, int a_BlockY, int a_BlockZ, cBeaconCallback a_Callback)
{
	return m_ChunkMap->DoWithBeaconAt(a_BlockX, a_BlockY, a_BlockZ, a_Callback);
}





bool cWorld::DoWithBedAt(int a_BlockX, int a_BlockY, int a_BlockZ, cBedCallback a_Callback)
{
	return m_ChunkMap->DoWithBedAt(a_BlockX, a_BlockY, a_BlockZ, a_Callback);
}





bool cWorld::DoWithBrewingstandAt(int a_BlockX, int a_BlockY, int a_BlockZ, cBrewingstandCallback a_Callback)
{
	return m_ChunkMap->DoWithBrewingstandAt(a_BlockX, a_BlockY, a_BlockZ, a_Callback);
}





bool cWorld::DoWithChestAt(int a_BlockX, int a_BlockY, int a_BlockZ, cChestCallback a_Callback)
{
	return m_ChunkMap->DoWithChestAt(a_BlockX, a_BlockY, a_BlockZ, a_Callback);
}





bool cWorld::DoWithDispenserAt(int a_BlockX, int a_BlockY, int a_BlockZ, cDispenserCallback a_Callback)
{
	return m_ChunkMap->DoWithDispenserAt(a_BlockX, a_BlockY, a_BlockZ, a_Callback);
}





bool cWorld::DoWithDropperAt(int a_BlockX, int a_BlockY, int a_BlockZ, cDropperCallback a_Callback)
{
	return m_ChunkMap->DoWithDropperAt(a_BlockX, a_BlockY, a_BlockZ, a_Callback);
}





bool cWorld::DoWithDropSpenserAt(int a_BlockX, int a_BlockY, int a_BlockZ, cDropSpenserCallback a_Callback)
{
	return m_ChunkMap->DoWithDropSpenserAt(a_BlockX, a_BlockY, a_BlockZ, a_Callback);
}





bool cWorld::DoWithFurnaceAt(int a_BlockX, int a_BlockY, int a_BlockZ, cFurnaceCallback a_Callback)
{
	return m_ChunkMap->DoWithFurnaceAt(a_BlockX, a_BlockY, a_BlockZ, a_Callback);
}





bool cWorld::DoWithNoteBlockAt(int a_BlockX, int a_BlockY, int a_BlockZ, cNoteBlockCallback a_Callback)
{
	return m_ChunkMap->DoWithNoteBlockAt(a_BlockX, a_BlockY, a_BlockZ, a_Callback);
}





bool cWorld::DoWithCommandBlockAt(int a_BlockX, int a_BlockY, int a_BlockZ, cCommandBlockCallback a_Callback)
{
	return m_ChunkMap->DoWithCommandBlockAt(a_BlockX, a_BlockY, a_BlockZ, a_Callback);
}





bool cWorld::DoWithMobHeadAt(int a_BlockX, int a_BlockY, int a_BlockZ, cMobHeadCallback a_Callback)
{
	return m_ChunkMap->DoWithMobHeadAt(a_BlockX, a_BlockY, a_BlockZ, a_Callback);
}





bool cWorld::DoWithFlowerPotAt(int a_BlockX, int a_BlockY, int a_BlockZ, cFlowerPotCallback a_Callback)
{
	return m_ChunkMap->DoWithFlowerPotAt(a_BlockX, a_BlockY, a_BlockZ, a_Callback);
}





bool cWorld::GetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4)
{
	return m_ChunkMap->GetSignLines(a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4);
}





bool cWorld::DoWithChunk(int a_ChunkX, int a_ChunkZ, cChunkCallback a_Callback)
{
	return m_ChunkMap->DoWithChunk(a_ChunkX, a_ChunkZ, a_Callback);
}





bool cWorld::DoWithChunkAt(Vector3i a_BlockPos, cChunkCallback a_Callback)
{
	return m_ChunkMap->DoWithChunkAt(a_BlockPos, a_Callback);
}





bool cWorld::GrowTree(int a_X, int a_Y, int a_Z)
{
	if (GetBlock(a_X, a_Y, a_Z) == E_BLOCK_SAPLING)
	{
		// There is a sapling here, grow a tree according to its type:
		return GrowTreeFromSapling(a_X, a_Y, a_Z, GetBlockMeta(a_X, a_Y, a_Z));
	}
	else
	{
		// There is nothing here, grow a tree based on the current biome here:
		return GrowTreeByBiome(a_X, a_Y, a_Z);
	}
}





bool cWorld::GrowTreeFromSapling(int a_X, int a_Y, int a_Z, NIBBLETYPE a_SaplingMeta)
{
	cNoise Noise(m_Generator.GetSeed());
	sSetBlockVector Logs, Other;
	auto WorldAge = static_cast<int>(std::chrono::duration_cast<cTickTimeLong>(m_WorldAge).count() & 0xffffffff);
	switch (a_SaplingMeta & 0x07)
	{
		case E_META_SAPLING_APPLE:    GetAppleTreeImage  ({ a_X, a_Y, a_Z }, Noise, WorldAge, Logs, Other); break;
		case E_META_SAPLING_BIRCH:    GetBirchTreeImage  ({ a_X, a_Y, a_Z }, Noise, WorldAge, Logs, Other); break;
		case E_META_SAPLING_CONIFER:  GetConiferTreeImage({ a_X, a_Y, a_Z }, Noise, WorldAge, Logs, Other); break;
		case E_META_SAPLING_ACACIA:   GetAcaciaTreeImage ({ a_X, a_Y, a_Z }, Noise, WorldAge, Logs, Other); break;
		case E_META_SAPLING_JUNGLE:
		{
			bool IsLarge = GetLargeTreeAdjustment(a_X, a_Y, a_Z, a_SaplingMeta);
			GetJungleTreeImage({ a_X, a_Y, a_Z }, Noise, WorldAge, Logs, Other, IsLarge);
			break;
		}
		case E_META_SAPLING_DARK_OAK:
		{
			if (!GetLargeTreeAdjustment(a_X, a_Y, a_Z, a_SaplingMeta))
			{
				return false;
			}

			GetDarkoakTreeImage({ a_X, a_Y, a_Z }, Noise, WorldAge, Logs, Other);
			break;
		}
	}
	Other.insert(Other.begin(), Logs.begin(), Logs.end());
	Logs.clear();
	return GrowTreeImage(Other);
}





bool cWorld::GetLargeTreeAdjustment(int & a_X, int & a_Y, int & a_Z, NIBBLETYPE a_Meta)
{
	bool IsLarge = true;
	a_Meta = a_Meta & 0x07;

	// Check to see if we are the northwest corner
	for (int x = 0; x  < 2; ++x)
	{
		for (int z = 0; z < 2; ++z)
		{
			NIBBLETYPE meta;
			BLOCKTYPE type;
			GetBlockTypeMeta(a_X + x, a_Y, a_Z + z, type, meta);
			IsLarge = IsLarge && (type == E_BLOCK_SAPLING) && ((a_Meta & meta) == a_Meta);
		}
	}

	if (IsLarge)
	{
		return true;
	}

	IsLarge = true;
	// Check to see if we are the southwest corner
	for (int x = 0; x  < 2; ++x)
	{
		for (int z = 0; z > -2; --z)
		{
			NIBBLETYPE meta;
			BLOCKTYPE type;
			GetBlockTypeMeta(a_X + x, a_Y, a_Z + z, type, meta);
			IsLarge = IsLarge && (type == E_BLOCK_SAPLING) && ((a_Meta & meta) == a_Meta);
		}
	}

	if (IsLarge)
	{
		--a_Z;
		return true;
	}

	IsLarge = true;
	// Check to see if we are the southeast corner
	for (int x = 0; x > -2; --x)
	{
		for (int z = 0; z > -2; --z)
		{
			NIBBLETYPE meta;
			BLOCKTYPE type;
			GetBlockTypeMeta(a_X + x, a_Y, a_Z + z, type, meta);
			IsLarge = IsLarge && (type == E_BLOCK_SAPLING) && ((a_Meta & meta) == a_Meta);
		}
	}

	if (IsLarge)
	{
		--a_Z;
		--a_X;
		return true;
	}

	IsLarge = true;
	// Check to see if we are the northeast corner
	for (int x = 0; x > -2; --x)
	{
		for (int z = 0; z < 2; ++z)
		{
			NIBBLETYPE meta;
			BLOCKTYPE type;
			GetBlockTypeMeta(a_X + x, a_Y, a_Z + z, type, meta);
			IsLarge = IsLarge && (type == E_BLOCK_SAPLING) && ((a_Meta & meta) == a_Meta);
		}
	}

	if (IsLarge)
	{
		--a_X;
	}

	return IsLarge;
}





bool cWorld::GrowTreeByBiome(int a_X, int a_Y, int a_Z)
{
	cNoise Noise(m_Generator.GetSeed());
	sSetBlockVector Logs, Other;
	GetTreeImageByBiome({ a_X, a_Y, a_Z }, Noise, static_cast<int>(std::chrono::duration_cast<cTickTimeLong>(m_WorldAge).count() & 0xffffffff), GetBiomeAt(a_X, a_Z), Logs, Other);
	Other.insert(Other.begin(), Logs.begin(), Logs.end());
	Logs.clear();
	return GrowTreeImage(Other);
}





bool cWorld::GrowTreeImage(const sSetBlockVector & a_Blocks)
{
	// Check that the tree has place to grow

	// Make a copy of the log blocks:
	sSetBlockVector b2;
	for (sSetBlockVector::const_iterator itr = a_Blocks.begin(); itr != a_Blocks.end(); ++itr)
	{
		if (itr->m_BlockType == E_BLOCK_LOG)
		{
			b2.push_back(*itr);
		}
	}  // for itr - a_Blocks[]

	// Query blocktypes and metas at those log blocks:
	if (!GetBlocks(b2, false))
	{
		return false;
	}

	// Check that at each log's coord there's an block allowed to be overwritten:
	for (sSetBlockVector::const_iterator itr = b2.begin(); itr != b2.end(); ++itr)
	{
		switch (itr->m_BlockType)
		{
			CASE_TREE_ALLOWED_BLOCKS:
			{
				break;
			}
			default:
			{
				return false;
			}
		}
	}  // for itr - b2[]

	// All ok, replace blocks with the tree image:
	m_ChunkMap->ReplaceTreeBlocks(a_Blocks);
	return true;
}





int cWorld::GrowPlantAt(Vector3i a_BlockPos, int a_NumStages)
{
	return m_ChunkMap->GrowPlantAt(a_BlockPos, a_NumStages);
}





bool cWorld::GrowRipePlant(Vector3i a_BlockPos)
{
	return (GrowPlantAt(a_BlockPos, 16) > 0);
}





int cWorld::GrowCactus(int a_BlockX, int a_BlockY, int a_BlockZ, int a_NumBlocksToGrow)
{
	LOGWARNING("cWorld::GrowCactus is obsolete, use cWorld::GrowPlantAt instead");
	return m_ChunkMap->GrowPlantAt({a_BlockX, a_BlockY, a_BlockZ});
}





bool cWorld::GrowMelonPumpkin(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType)
{
	LOGWARNING("cWorld::GrowMelonPumpkin is obsolete, use cWorld::GrowPlantAt instead");
	return (m_ChunkMap->GrowPlantAt({a_BlockX, a_BlockY, a_BlockZ}, 16) > 0);  // 8 stages for the stem, 8 attempts for the produce
}





int cWorld::GrowSugarcane(int a_BlockX, int a_BlockY, int a_BlockZ, int a_NumBlocksToGrow)
{
	LOGWARNING("cWorld::GrowSugarcane is obsolete, use cWorld::GrowPlantAt instead");
	return m_ChunkMap->GrowPlantAt({a_BlockX, a_BlockY, a_BlockZ}, a_NumBlocksToGrow);
}





EMCSBiome cWorld::GetBiomeAt (int a_BlockX, int a_BlockZ)
{
	return m_ChunkMap->GetBiomeAt(a_BlockX, a_BlockZ);
}





bool cWorld::SetBiomeAt(int a_BlockX, int a_BlockZ, EMCSBiome a_Biome)
{
	return m_ChunkMap->SetBiomeAt(a_BlockX, a_BlockZ, a_Biome);
}





bool cWorld::SetAreaBiome(int a_MinX, int a_MaxX, int a_MinZ, int a_MaxZ, EMCSBiome a_Biome)
{
	return m_ChunkMap->SetAreaBiome(a_MinX, a_MaxX, a_MinZ, a_MaxZ, a_Biome);
}





bool cWorld::SetAreaBiome(const cCuboid & a_Area, EMCSBiome a_Biome)
{
	return SetAreaBiome(
		std::min(a_Area.p1.x, a_Area.p2.x), std::max(a_Area.p1.x, a_Area.p2.x),
		std::min(a_Area.p1.z, a_Area.p2.z), std::max(a_Area.p1.z, a_Area.p2.z),
		a_Biome
	);
}





void cWorld::SetMaxViewDistance(int a_MaxViewDistance)
{
	m_MaxViewDistance = Clamp(a_MaxViewDistance, cClientHandle::MIN_VIEW_DISTANCE, cClientHandle::MAX_VIEW_DISTANCE);
}





void cWorld::SetBlock(Vector3i a_BlockPos, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta)
{
	m_ChunkMap->SetBlock(a_BlockPos, a_BlockType, a_BlockMeta);
}





void cWorld::SetBlockMeta(Vector3i a_BlockPos, NIBBLETYPE a_MetaData, bool a_ShouldMarkDirty, bool a_ShouldInformClients)
{
	m_ChunkMap->SetBlockMeta(a_BlockPos, a_MetaData, a_ShouldMarkDirty, a_ShouldInformClients);
}





NIBBLETYPE cWorld::GetBlockSkyLight(Vector3i a_BlockPos)
{
	return m_ChunkMap->GetBlockSkyLight(a_BlockPos);
}





NIBBLETYPE cWorld::GetBlockBlockLight(Vector3i a_BlockPos)
{
	return m_ChunkMap->GetBlockBlockLight(a_BlockPos);
}





bool cWorld::GetBlockTypeMeta(Vector3i a_BlockPos, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta)
{
	return m_ChunkMap->GetBlockTypeMeta(a_BlockPos, a_BlockType, a_BlockMeta);
}





bool cWorld::GetBlockInfo(Vector3i a_BlockPos, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_Meta, NIBBLETYPE & a_SkyLight, NIBBLETYPE & a_BlockLight)
{
	return m_ChunkMap->GetBlockInfo(a_BlockPos, a_BlockType, a_Meta, a_SkyLight, a_BlockLight);
}





bool cWorld::WriteBlockArea(cBlockArea & a_Area, int a_MinBlockX, int a_MinBlockY, int a_MinBlockZ, int a_DataTypes)
{
	return m_ChunkMap->WriteBlockArea(a_Area, a_MinBlockX, a_MinBlockY, a_MinBlockZ, a_DataTypes);
}





void cWorld::SpawnItemPickups(const cItems & a_Pickups, Vector3i a_BlockPos, double a_FlyAwaySpeed, bool a_IsPlayerCreated)
{
	auto & random = GetRandomProvider();
	auto microX = random.RandReal<double>(0, 1);
	auto microZ = random.RandReal<double>(0, 1);
	return SpawnItemPickups(a_Pickups, Vector3d(microX, 0, microZ) + a_BlockPos, a_FlyAwaySpeed, a_IsPlayerCreated);
}





void cWorld::SpawnItemPickups(const cItems & a_Pickups, Vector3d a_Pos, double a_FlyAwaySpeed, bool a_IsPlayerCreated)
{
	auto & Random = GetRandomProvider();
	a_FlyAwaySpeed /= 100;  // Pre-divide, so that we don't have to divide each time inside the loop
	for (cItems::const_iterator itr = a_Pickups.begin(); itr != a_Pickups.end(); ++itr)
	{
		if (!IsValidItem(itr->m_ItemType) || (itr->m_ItemType == E_BLOCK_AIR))
		{
			// Don't spawn pickup if item isn't even valid; should prevent client crashing too
			continue;
		}

		float SpeedX = static_cast<float>(a_FlyAwaySpeed * Random.RandInt(-10, 10));
		float SpeedY = static_cast<float>(a_FlyAwaySpeed * Random.RandInt(40, 50));
		float SpeedZ = static_cast<float>(a_FlyAwaySpeed * Random.RandInt(-10, 10));

		auto Pickup = cpp14::make_unique<cPickup>(a_Pos, *itr, a_IsPlayerCreated, Vector3f{SpeedX, SpeedY, SpeedZ});
		auto PickupPtr = Pickup.get();
		PickupPtr->Initialize(std::move(Pickup), *this);
	}
}





void cWorld::SpawnItemPickups(const cItems & a_Pickups, Vector3d a_Pos, Vector3d a_Speed, bool a_IsPlayerCreated)
{
	for (cItems::const_iterator itr = a_Pickups.begin(); itr != a_Pickups.end(); ++itr)
	{
		if (!IsValidItem(itr->m_ItemType) || (itr->m_ItemType == E_BLOCK_AIR))
		{
			continue;
		}

		auto pickup = cpp14::make_unique<cPickup>(a_Pos, *itr, a_IsPlayerCreated, a_Speed);
		auto pickupPtr = pickup.get();
		pickupPtr->Initialize(std::move(pickup), *this);
	}
}





UInt32 cWorld::SpawnItemPickup(Vector3d a_Pos, const cItem & a_Item, Vector3f a_Speed, int a_LifetimeTicks, bool a_CanCombine)
{
	auto pickup = cpp14::make_unique<cPickup>(a_Pos, a_Item, false, a_Speed, a_LifetimeTicks, a_CanCombine);
	auto pickupPtr = pickup.get();
	if (!pickupPtr->Initialize(std::move(pickup), *this))
	{
		return cEntity::INVALID_ID;
	}
	return pickupPtr->GetUniqueID();
}





UInt32 cWorld::SpawnFallingBlock(Vector3i a_Pos, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta)
{
	auto fallingBlock = cpp14::make_unique<cFallingBlock>(a_Pos, a_BlockType, a_BlockMeta);
	auto fallingBlockPtr = fallingBlock.get();
	auto ID = fallingBlock->GetUniqueID();
	if (!fallingBlockPtr->Initialize(std::move(fallingBlock), *this))
	{
		return cEntity::INVALID_ID;
	}
	return ID;
}





UInt32 cWorld::SpawnExperienceOrb(Vector3d a_Pos, int a_Reward)
{
	if (a_Reward < 1)
	{
		LOGWARNING("%s: Attempting to create an experience orb with non-positive reward!", __FUNCTION__);
		return cEntity::INVALID_ID;
	}

	auto expOrb = cpp14::make_unique<cExpOrb>(a_Pos, a_Reward);
	auto expOrbPtr = expOrb.get();
	if (!expOrbPtr->Initialize(std::move(expOrb), *this))
	{
		return cEntity::INVALID_ID;
	}
	return expOrbPtr->GetUniqueID();
}





std::vector<UInt32> cWorld::SpawnSplitExperienceOrbs(Vector3d a_Pos, int a_Reward)
{
	std::vector<UInt32> OrbsID;

	if (a_Reward < 1)
	{
		LOGWARNING("%s: Attempting to create an experience orb with non-positive reward!", __FUNCTION__);
		return OrbsID;
	}

	std::vector<int> Rewards = cExpOrb::Split(a_Reward);

	// Check generate number to decide speed limit (distribute range)
	float SpeedLimit = static_cast<float>((Rewards.size() / 2) + 5);
	if (SpeedLimit > 10)
	{
		SpeedLimit = 10;
	}

	auto & Random = GetRandomProvider();
	for (auto Reward : Rewards)
	{
		auto ExpOrb = cpp14::make_unique<cExpOrb>(a_Pos, Reward);
		auto ExpOrbPtr = ExpOrb.get();
		double SpeedX = Random.RandReal(-SpeedLimit, SpeedLimit);
		double SpeedY = Random.RandReal(0.5);
		double SpeedZ = Random.RandReal(-SpeedLimit, SpeedLimit);
		ExpOrbPtr->SetSpeed(SpeedX, SpeedY, SpeedZ);

		UInt32 Id = ExpOrbPtr->GetUniqueID();
		if (ExpOrbPtr->Initialize(std::move(ExpOrb), *this))
		{
			OrbsID.push_back(Id);
		}
	}

	return OrbsID;
}





UInt32 cWorld::SpawnMinecart(Vector3d a_Pos, int a_MinecartType, const cItem & a_Content, int a_BlockHeight)
{
	std::unique_ptr<cMinecart> Minecart;
	switch (a_MinecartType)
	{
		case E_ITEM_MINECART:             Minecart = cpp14::make_unique<cRideableMinecart>   (a_Pos, a_Content, a_BlockHeight); break;
		case E_ITEM_CHEST_MINECART:       Minecart = cpp14::make_unique<cMinecartWithChest>  (a_Pos); break;
		case E_ITEM_FURNACE_MINECART:     Minecart = cpp14::make_unique<cMinecartWithFurnace>(a_Pos); break;
		case E_ITEM_MINECART_WITH_TNT:    Minecart = cpp14::make_unique<cMinecartWithTNT>    (a_Pos); break;
		case E_ITEM_MINECART_WITH_HOPPER: Minecart = cpp14::make_unique<cMinecartWithHopper> (a_Pos); break;
		default:
		{
			return cEntity::INVALID_ID;
		}
	}  // switch (a_MinecartType)

	auto MinecartPtr = Minecart.get();
	if (!MinecartPtr->Initialize(std::move(Minecart), *this))
	{
		return cEntity::INVALID_ID;
	}
	return MinecartPtr->GetUniqueID();
}





UInt32 cWorld::SpawnBoat(Vector3d a_Pos, cBoat::eMaterial a_Material)
{
	auto Boat = cpp14::make_unique<cBoat>(a_Pos, a_Material);
	auto BoatPtr = Boat.get();
	if (!BoatPtr->Initialize(std::move(Boat), *this))
	{
		return cEntity::INVALID_ID;
	}
	return BoatPtr->GetUniqueID();
}





UInt32 cWorld::SpawnPrimedTNT(Vector3d a_Pos, int a_FuseTicks, double a_InitialVelocityCoeff, bool a_ShouldPlayFuseSound)
{
	auto TNT = cpp14::make_unique<cTNTEntity>(a_Pos, a_FuseTicks);
	auto TNTPtr = TNT.get();
	if (!TNTPtr->Initialize(std::move(TNT), *this))
	{
		return cEntity::INVALID_ID;
	}

	if (a_ShouldPlayFuseSound)
	{
		BroadcastSoundEffect("entity.tnt.primed", a_Pos, 1.0f, 1.0f);
	}

	auto & Random = GetRandomProvider();
	TNTPtr->SetSpeed(
		a_InitialVelocityCoeff * Random.RandReal(-0.5f, 0.5f),
		a_InitialVelocityCoeff * 2,
		a_InitialVelocityCoeff * Random.RandReal(-0.5f, 0.5f)
	);
	return TNTPtr->GetUniqueID();
}





void cWorld::SetBlocks(const sSetBlockVector & a_Blocks)
{
	m_ChunkMap->SetBlocks(a_Blocks);
}





void cWorld::ReplaceBlocks(const sSetBlockVector & a_Blocks, BLOCKTYPE a_FilterBlockType)
{
	m_ChunkMap->ReplaceBlocks(a_Blocks, a_FilterBlockType);
}





bool cWorld::GetBlocks(sSetBlockVector & a_Blocks, bool a_ContinueOnFailure)
{
	return m_ChunkMap->GetBlocks(a_Blocks, a_ContinueOnFailure);
}





bool cWorld::DigBlock(Vector3i a_BlockPos)
{
	BLOCKTYPE blockType;
	NIBBLETYPE blockMeta;
	GetBlockTypeMeta(a_BlockPos, blockType, blockMeta);
	cChunkInterface chunkInterface(GetChunkMap());
	auto blockHandler = cBlockInfo::GetHandler(blockType);
	blockHandler->OnBreaking(chunkInterface, *this, a_BlockPos);
	if (!m_ChunkMap->DigBlock(a_BlockPos))
	{
		return false;
	}
	blockHandler->OnBroken(chunkInterface, *this, a_BlockPos, blockType, blockMeta);
	return true;
}





bool cWorld::DropBlockAsPickups(Vector3i a_BlockPos, const cEntity * a_Digger, const cItem * a_Tool)
{
	auto pickups = PickupsFromBlock(a_BlockPos, a_Digger, a_Tool);
	if (!DigBlock(a_BlockPos))
	{
		return false;
	}
	SpawnItemPickups(pickups, Vector3d(0.5, 0.5, 0.5) + a_BlockPos, 10);
	return true;
}





cItems cWorld::PickupsFromBlock(Vector3i a_BlockPos, const cEntity * a_Digger, const cItem * a_Tool)
{
	return m_ChunkMap->PickupsFromBlock(a_BlockPos, a_Digger, a_Tool);
}





void cWorld::SendBlockTo(int a_X, int a_Y, int a_Z, cPlayer & a_Player)
{
	m_ChunkMap->SendBlockTo(a_X, a_Y, a_Z, a_Player);
}





int cWorld::GetHeight(int a_X, int a_Z)
{
	return m_ChunkMap->GetHeight(a_X, a_Z);
}





bool cWorld::TryGetHeight(int a_BlockX, int a_BlockZ, int & a_Height)
{
	return m_ChunkMap->TryGetHeight(a_BlockX, a_BlockZ, a_Height);
}





void cWorld::SendBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cClientHandle & a_Client)
{
	m_ChunkMap->SendBlockEntity(a_BlockX, a_BlockY, a_BlockZ, a_Client);
}





void cWorld::MarkChunkDirty(int a_ChunkX, int a_ChunkZ)
{
	m_ChunkMap->MarkChunkDirty(a_ChunkX, a_ChunkZ);
}





void cWorld::MarkChunkSaving(int a_ChunkX, int a_ChunkZ)
{
	m_ChunkMap->MarkChunkSaving(a_ChunkX, a_ChunkZ);
}





void cWorld::MarkChunkSaved (int a_ChunkX, int a_ChunkZ)
{
	m_ChunkMap->MarkChunkSaved (a_ChunkX, a_ChunkZ);
}





void cWorld::QueueSetChunkData(cSetChunkDataPtr a_SetChunkData)
{
	// Validate biomes, if needed:
	if (!a_SetChunkData->AreBiomesValid())
	{
		// The biomes are not assigned, get them from the generator:
		m_Generator.GenerateBiomes({a_SetChunkData->GetChunkX(), a_SetChunkData->GetChunkZ()}, a_SetChunkData->GetBiomes());
		a_SetChunkData->MarkBiomesValid();
	}

	// Validate heightmap, if needed:
	if (!a_SetChunkData->IsHeightMapValid())
	{
		a_SetChunkData->CalculateHeightMap();
	}

	// Store a copy of the data in the queue:
	// TODO: If the queue is too large, wait for it to get processed. Not likely, though.
	cCSLock Lock(m_CSSetChunkDataQueue);
	m_SetChunkDataQueue.emplace_back(std::move(a_SetChunkData));
}





void cWorld::SetChunkData(cSetChunkData & a_SetChunkData)
{
	ASSERT(a_SetChunkData.AreBiomesValid());
	ASSERT(a_SetChunkData.IsHeightMapValid());

	m_ChunkMap->SetChunkData(a_SetChunkData);

	// Initialize the entities (outside the m_ChunkMap's CS, to fix FS #347):
	for (auto & Entity : a_SetChunkData.GetEntities())
	{
		auto EntityPtr = Entity.get();
		EntityPtr->Initialize(std::move(Entity), *this);
	}

	// If a client is requesting this chunk, send it to them:
	int ChunkX = a_SetChunkData.GetChunkX();
	int ChunkZ = a_SetChunkData.GetChunkZ();
	cChunkSender & ChunkSender = m_ChunkSender;
	DoWithChunk(
		ChunkX, ChunkZ,
		[&ChunkSender] (cChunk & a_Chunk) -> bool
		{
			if (a_Chunk.HasAnyClients())
			{
				ChunkSender.QueueSendChunkTo(
					a_Chunk.GetPosX(),
					a_Chunk.GetPosZ(),
					cChunkSender::E_CHUNK_PRIORITY_MEDIUM,
					a_Chunk.GetAllClients()
				);
			}
			return true;
		}
	);

	// Save the chunk right after generating, so that we don't have to generate it again on next run
	// If saving is disabled, then the chunk was marked dirty so it will get
	// saved if saving is later enabled.
	if (a_SetChunkData.ShouldMarkDirty() && IsSavingEnabled())
	{
		m_Storage.QueueSaveChunk(ChunkX, ChunkZ);
	}
}





void cWorld::ChunkLighted(
	int a_ChunkX, int a_ChunkZ,
	const cChunkDef::BlockNibbles & a_BlockLight,
	const cChunkDef::BlockNibbles & a_SkyLight
)
{
	m_ChunkMap->ChunkLighted(a_ChunkX, a_ChunkZ, a_BlockLight, a_SkyLight);
}





bool cWorld::GetChunkData(cChunkCoords a_Coords, cChunkDataCallback & a_Callback) const
{
	return m_ChunkMap->GetChunkData(a_Coords, a_Callback);
}





bool cWorld::GetChunkBlockTypes(int a_ChunkX, int a_ChunkZ, BLOCKTYPE * a_BlockTypes)
{
	return m_ChunkMap->GetChunkBlockTypes(a_ChunkX, a_ChunkZ, a_BlockTypes);
}





bool cWorld::IsChunkQueued(int a_ChunkX, int a_ChunkZ) const
{
	return m_ChunkMap->IsChunkQueued(a_ChunkX, a_ChunkZ);
}





bool cWorld::IsChunkValid(int a_ChunkX, int a_ChunkZ) const
{
	return m_ChunkMap->IsChunkValid(a_ChunkX, a_ChunkZ);
}





bool cWorld::HasChunkAnyClients(int a_ChunkX, int a_ChunkZ) const
{
	return m_ChunkMap->HasChunkAnyClients(a_ChunkX, a_ChunkZ);
}





void cWorld::UnloadUnusedChunks(void)
{
	m_LastChunkCheck = std::chrono::duration_cast<cTickTimeLong>(m_WorldAge);
	m_ChunkMap->UnloadUnusedChunks();
}





void cWorld::QueueUnloadUnusedChunks(void)
{
	QueueTask([](cWorld & a_World) { a_World.UnloadUnusedChunks(); });
}





void cWorld::CollectPickupsByPlayer(cPlayer & a_Player)
{
	m_ChunkMap->CollectPickupsByPlayer(a_Player);
}





void cWorld::AddPlayer(std::unique_ptr<cPlayer> a_Player, cWorld * a_OldWorld)
{
	cCSLock Lock(m_CSPlayersToAdd);
	m_PlayersToAdd.emplace_back(std::move(a_Player), a_OldWorld);
}





std::unique_ptr<cPlayer> cWorld::RemovePlayer(cPlayer & a_Player)
{
	// Check the chunkmap
	std::unique_ptr<cPlayer> PlayerPtr(static_cast<cPlayer *>(m_ChunkMap->RemoveEntity(a_Player).release()));

	if (PlayerPtr != nullptr)
	{
		// Player found in the world, tell it it's being removed
		PlayerPtr->OnRemoveFromWorld(*this);
	}
	else  // Check the awaiting players list
	{
		cCSLock Lock(m_CSPlayersToAdd);
		auto itr = std::find_if(m_PlayersToAdd.begin(), m_PlayersToAdd.end(),
			[&](const decltype(m_PlayersToAdd)::value_type & value)
			{
				return (value.first.get() == &a_Player);
			}
		);

		if (itr != m_PlayersToAdd.end())
		{
			PlayerPtr = std::move(itr->first);
			m_PlayersToAdd.erase(itr);
		}
	}

	// Remove from the player list
	{
		cCSLock Lock(m_CSPlayers);
		LOGD("Removing player %s from world \"%s\"", a_Player.GetName().c_str(), m_WorldName.c_str());
		m_Players.remove(&a_Player);
	}

	// Remove the player's client from the list of clients to be ticked:
	cClientHandle * Client = a_Player.GetClientHandle();
	if (Client != nullptr)
	{
		Client->RemoveFromWorld();
		m_ChunkMap->RemoveClientFromChunks(Client);
		cCSLock Lock(m_CSClients);
		m_ClientsToRemove.push_back(Client);
	}

	return PlayerPtr;
}





#ifdef _DEBUG
bool cWorld::IsPlayerReferencedInWorldOrChunk(cPlayer & a_Player)
{
	if (m_ChunkMap->RemoveEntity(a_Player) != nullptr)
	{
		return true;
	}

	{
		cCSLock Lock(m_CSPlayersToAdd);
		if (std::find_if(
			m_PlayersToAdd.begin(), m_PlayersToAdd.end(),
			[&a_Player](const cAwaitingPlayerList::value_type & Item) { return Item.first.get() == &a_Player; }) != m_PlayersToAdd.end()
		)
		{
			return true;
		}
	}

	{
		cCSLock Lock(m_CSPlayers);
		if (std::find(m_Players.begin(), m_Players.end(), &a_Player) != m_Players.end())
		{
			return true;
		}
	}

	{
		cCSLock Lock(m_CSEntitiesToAdd);
		if (std::find(m_ClientsToAdd.begin(), m_ClientsToAdd.end(), a_Player.GetClientHandlePtr()) != m_ClientsToAdd.end())
		{
			return true;
		}
	}

	{
		cCSLock Lock(m_CSClients);
		if (std::find(m_Clients.begin(), m_Clients.end(), a_Player.GetClientHandlePtr()) != m_Clients.end())
		{
			return true;
		}
	}

	// Assume OK if in ClientsToRemove or PlayersToRemove
	return false;
}
#endif





bool cWorld::ForEachPlayer(cPlayerListCallback a_Callback)
{
	// Calls the callback for each player in the list
	cCSLock Lock(m_CSPlayers);
	for (auto & Player : m_Players)
	{
		if (Player->IsTicking() && a_Callback(*Player))
		{
			return false;
		}
	}  // for itr - m_Players[]
	return true;
}





bool cWorld::DoWithPlayer(const AString & a_PlayerName, cPlayerListCallback a_Callback)
{
	// Calls the callback for the specified player in the list
	cCSLock Lock(m_CSPlayers);
	for (auto & Player : m_Players)
	{
		if (Player->IsTicking() && (NoCaseCompare(Player->GetName(), a_PlayerName) == 0))
		{
			a_Callback(*Player);
			return true;
		}
	}  // for itr - m_Players[]
	return false;
}





bool cWorld::FindAndDoWithPlayer(const AString & a_PlayerNameHint, cPlayerListCallback a_Callback)
{
	cPlayer * BestMatch = nullptr;
	size_t BestRating = 0;
	size_t NameLength = a_PlayerNameHint.length();

	cCSLock Lock(m_CSPlayers);
	for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
	{
		if (!(*itr)->IsTicking())
		{
			continue;
		}
		size_t Rating = RateCompareString (a_PlayerNameHint, (*itr)->GetName());
		if (Rating >= BestRating)
		{
			BestMatch = *itr;
			BestRating = Rating;
		}
		if (Rating == NameLength)  // Perfect match
		{
			break;
		}
	}  // for itr - m_Players[]

	if (BestMatch != nullptr)
	{
		return a_Callback(*BestMatch);
	}
	return false;
}





bool cWorld::DoWithPlayerByUUID(const cUUID & a_PlayerUUID, cPlayerListCallback a_Callback)
{
	cCSLock Lock(m_CSPlayers);
	for (auto & Player : m_Players)
	{
		if (Player->IsTicking() && (Player->GetUUID() == a_PlayerUUID))
		{
			return a_Callback(*Player);
		}
	}
	return false;
}





bool cWorld::DoWithNearestPlayer(Vector3d a_Pos, double a_RangeLimit, cPlayerListCallback a_Callback, bool a_CheckLineOfSight, bool a_IgnoreSpectator)
{
	double ClosestDistance = a_RangeLimit;
	cPlayer * ClosestPlayer = nullptr;

	cCSLock Lock(m_CSPlayers);
	for (cPlayerList::const_iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
	{
		if (!(*itr)->IsTicking())
		{
			continue;
		}

		if (a_IgnoreSpectator && (*itr)->IsGameModeSpectator())
		{
			continue;
		}

		Vector3f Pos = (*itr)->GetPosition();
		double Distance = (Pos - a_Pos).Length();

		// If the player is too far, skip them:
		if (Distance > ClosestDistance)
		{
			continue;
		}

		// Check LineOfSight, if requested:
		if (
			a_CheckLineOfSight &&
			!cLineBlockTracer::LineOfSightTrace(*this, a_Pos, Pos, cLineBlockTracer::losAirWater)
		)
		{
			continue;
		}

		ClosestDistance = Distance;
		ClosestPlayer = *itr;
	}

	if (ClosestPlayer)
	{
		return a_Callback(*ClosestPlayer);
	}
	else
	{
		return false;
	}
}





void cWorld::SendPlayerList(cPlayer * a_DestPlayer)
{
	// Sends the playerlist to a_DestPlayer
	cCSLock Lock(m_CSPlayers);
	for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
	{
		cClientHandle * ch = (*itr)->GetClientHandle();
		if ((ch != nullptr) && !ch->IsDestroyed())
		{
			a_DestPlayer->GetClientHandle()->SendPlayerListAddPlayer(*(*itr));
		}
	}
}





bool cWorld::ForEachEntity(cEntityCallback a_Callback)
{
	return m_ChunkMap->ForEachEntity(a_Callback);
}





bool cWorld::ForEachEntityInChunk(int a_ChunkX, int a_ChunkZ, cEntityCallback a_Callback)
{
	return m_ChunkMap->ForEachEntityInChunk(a_ChunkX, a_ChunkZ, a_Callback);
}





bool cWorld::ForEachEntityInBox(const cBoundingBox & a_Box, cEntityCallback a_Callback)
{
	return m_ChunkMap->ForEachEntityInBox(a_Box, a_Callback);
}





bool cWorld::DoWithEntityByID(UInt32 a_UniqueID, cEntityCallback a_Callback)
{
	// First check the entities-to-add:
	{
		cCSLock Lock(m_CSEntitiesToAdd);
		for (const auto & ent: m_EntitiesToAdd)
		{
			if (ent->GetUniqueID() == a_UniqueID)
			{
				a_Callback(*ent);
				return true;
			}
		}  // for ent - m_EntitiesToAdd[]
	}

	// Then check the chunkmap:
	return m_ChunkMap->DoWithEntityByID(a_UniqueID, a_Callback);
}





void cWorld::CompareChunkClients(int a_ChunkX1, int a_ChunkZ1, int a_ChunkX2, int a_ChunkZ2, cClientDiffCallback & a_Callback)
{
	m_ChunkMap->CompareChunkClients(a_ChunkX1, a_ChunkZ1, a_ChunkX2, a_ChunkZ2, a_Callback);
}





bool cWorld::AddChunkClient(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client)
{
	return m_ChunkMap->AddChunkClient(a_ChunkX, a_ChunkZ, a_Client);
}





void cWorld::RemoveChunkClient(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client)
{
	m_ChunkMap->RemoveChunkClient(a_ChunkX, a_ChunkZ, a_Client);
}





void cWorld::RemoveClientFromChunks(cClientHandle * a_Client)
{
	m_ChunkMap->RemoveClientFromChunks(a_Client);
}





void cWorld::SendChunkTo(int a_ChunkX, int a_ChunkZ, cChunkSender::eChunkPriority a_Priority, cClientHandle * a_Client)
{
	m_ChunkSender.QueueSendChunkTo(a_ChunkX, a_ChunkZ, a_Priority, a_Client);
}





void cWorld::ForceSendChunkTo(int a_ChunkX, int a_ChunkZ, cChunkSender::eChunkPriority a_Priority, cClientHandle * a_Client)
{
	a_Client->AddWantedChunk(a_ChunkX, a_ChunkZ);
	m_ChunkSender.QueueSendChunkTo(a_ChunkX, a_ChunkZ, a_Priority, a_Client);
}





void cWorld::RemoveClientFromChunkSender(cClientHandle * a_Client)
{
	m_ChunkSender.RemoveClient(a_Client);
}





void cWorld::TouchChunk(int a_ChunkX, int a_ChunkZ)
{
	m_ChunkMap->TouchChunk(a_ChunkX, a_ChunkZ);
}





void cWorld::PrepareChunk(int a_ChunkX, int a_ChunkZ, std::unique_ptr<cChunkCoordCallback> a_CallAfter)
{
	m_ChunkMap->PrepareChunk(a_ChunkX, a_ChunkZ, std::move(a_CallAfter));
}





void cWorld::ChunkLoadFailed(int a_ChunkX, int a_ChunkZ)
{
	m_ChunkMap->ChunkLoadFailed(a_ChunkX, a_ChunkZ);
}





bool cWorld::SetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player)
{
	AString Line1(a_Line1);
	AString Line2(a_Line2);
	AString Line3(a_Line3);
	AString Line4(a_Line4);

	if (cRoot::Get()->GetPluginManager()->CallHookUpdatingSign(*this, a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4, a_Player))
	{
		return false;
	}

	if (m_ChunkMap->SetSignLines(a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4))
	{
		cRoot::Get()->GetPluginManager()->CallHookUpdatedSign(*this, a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4, a_Player);
		return true;
	}

	return false;
}





bool cWorld::SetCommandBlockCommand(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Command)
{
	return DoWithCommandBlockAt(a_BlockX, a_BlockY, a_BlockZ, [&](cCommandBlockEntity & a_CommandBlock)
		{
			a_CommandBlock.SetCommand(a_Command);
			return false;
		}
	);
}





bool cWorld::IsTrapdoorOpen(int a_BlockX, int a_BlockY, int a_BlockZ)
{
	BLOCKTYPE Block;
	NIBBLETYPE Meta;
	GetBlockTypeMeta(a_BlockX, a_BlockY, a_BlockZ, Block, Meta);
	if ((Block != E_BLOCK_TRAPDOOR) && (Block != E_BLOCK_IRON_TRAPDOOR))
	{
		return false;
	}

	return (Meta & 0x4) > 0;
}





bool cWorld::SetTrapdoorOpen(int a_BlockX, int a_BlockY, int a_BlockZ, bool a_Open)
{
	BLOCKTYPE Block;
	NIBBLETYPE Meta;
	GetBlockTypeMeta(a_BlockX, a_BlockY, a_BlockZ, Block, Meta);
	if ((Block != E_BLOCK_TRAPDOOR) && (Block != E_BLOCK_IRON_TRAPDOOR))
	{
		return false;
	}

	bool IsOpen = (Meta & 0x4) != 0;
	if (a_Open != IsOpen)
	{
		SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, Meta ^ 0x4);
		BroadcastSoundParticleEffect(EffectID::SFX_RANDOM_WOODEN_TRAPDOOR_OPEN, {a_BlockX, a_BlockY, a_BlockZ}, 0);
		return true;
	}
	return false;
}





void cWorld::RegenerateChunk(int a_ChunkX, int a_ChunkZ)
{
	m_ChunkMap->MarkChunkRegenerating(a_ChunkX, a_ChunkZ);

	m_Generator.QueueGenerateChunk({a_ChunkX, a_ChunkZ}, true);
}





void cWorld::GenerateChunk(int a_ChunkX, int a_ChunkZ)
{
	m_ChunkMap->GenerateChunk(a_ChunkX, a_ChunkZ);
}





void cWorld::QueueLightChunk(int a_ChunkX, int a_ChunkZ, std::unique_ptr<cChunkCoordCallback> a_Callback)
{
	m_Lighting.QueueChunk(a_ChunkX, a_ChunkZ, std::move(a_Callback));
}





bool cWorld::IsChunkLighted(int a_ChunkX, int a_ChunkZ)
{
	return m_ChunkMap->IsChunkLighted(a_ChunkX, a_ChunkZ);
}





bool cWorld::ForEachChunkInRect(int a_MinChunkX, int a_MaxChunkX, int a_MinChunkZ, int a_MaxChunkZ, cChunkDataCallback & a_Callback)
{
	return m_ChunkMap->ForEachChunkInRect(a_MinChunkX, a_MaxChunkX, a_MinChunkZ, a_MaxChunkZ, a_Callback);
}





bool cWorld::ForEachLoadedChunk(cFunctionRef<bool(int, int)> a_Callback)
{
	return m_ChunkMap->ForEachLoadedChunk(a_Callback);
}





void cWorld::SaveAllChunks(void)
{
	if (IsSavingEnabled())
	{
		m_LastSave = std::chrono::duration_cast<cTickTimeLong>(m_WorldAge);
		m_ChunkMap->SaveAllChunks();
	}
}





void cWorld::QueueSaveAllChunks(void)
{
	QueueTask([](cWorld & a_World) { a_World.SaveAllChunks(); });
}





void cWorld::QueueTask(std::function<void(cWorld &)> a_Task)
{
	cCSLock Lock(m_CSTasks);
	m_Tasks.emplace_back(0, a_Task);
}





void cWorld::ScheduleTask(int a_DelayTicks, std::function<void (cWorld &)> a_Task)
{
	Int64 TargetTick = a_DelayTicks + std::chrono::duration_cast<cTickTimeLong>(m_WorldAge).count();

	// Insert the task into the list of scheduled tasks
	{
		cCSLock Lock(m_CSTasks);
		m_Tasks.emplace_back(TargetTick, a_Task);
	}
}





void cWorld::AddEntity(OwnedEntity a_Entity)
{
	a_Entity->SetWorld(this);
	cCSLock Lock(m_CSEntitiesToAdd);
	m_EntitiesToAdd.emplace_back(std::move(a_Entity));
}





bool cWorld::HasEntity(UInt32 a_UniqueID)
{
	// Check if the entity is in the queue to be added to the world:
	{
		cCSLock Lock(m_CSEntitiesToAdd);
		for (cEntityList::const_iterator itr = m_EntitiesToAdd.begin(), end = m_EntitiesToAdd.end(); itr != end; ++itr)
		{
			if ((*itr)->GetUniqueID() == a_UniqueID)
			{
				return true;
			}
		}  // for itr - m_EntitiesToAdd[]
	}

	// Check if the entity is in the chunkmap:
	if (m_ChunkMap.get() == nullptr)
	{
		// Chunkmap has already been destroyed, there are no entities anymore.
		return false;
	}
	return m_ChunkMap->HasEntity(a_UniqueID);
}





OwnedEntity cWorld::RemoveEntity(cEntity & a_Entity)
{
	// Check if the entity is in the chunkmap:
	auto Entity = m_ChunkMap->RemoveEntity(a_Entity);
	if (Entity != nullptr)
	{
		Entity->OnRemoveFromWorld(*this);
		return Entity;
	}

	// Check if the entity is in the queue to be added to the world:
	cCSLock Lock(m_CSEntitiesToAdd);
	auto itr = std::find_if(m_EntitiesToAdd.begin(), m_EntitiesToAdd.end(),
		[&a_Entity](const OwnedEntity & a_OwnedEntity)
		{
			return (a_OwnedEntity.get() == &a_Entity);
		}
	);

	if (itr != m_EntitiesToAdd.end())
	{
		Entity = std::move(*itr);
		m_EntitiesToAdd.erase(itr);
	}
	return Entity;
}





size_t cWorld::GetNumChunks(void) const
{
	return m_ChunkMap->GetNumChunks();
}





size_t cWorld::GetNumUnusedDirtyChunks(void) const
{
	return m_ChunkMap->GetNumUnusedDirtyChunks();
}





void cWorld::GetChunkStats(int & a_NumValid, int & a_NumDirty, int & a_NumInLightingQueue)
{
	m_ChunkMap->GetChunkStats(a_NumValid, a_NumDirty);
	a_NumInLightingQueue = static_cast<int>(m_Lighting.GetQueueLength());
}





void cWorld::TickQueuedBlocks(void)
{
	if (m_BlockTickQueue.empty())
	{
		return;
	}
	m_BlockTickQueueCopy.clear();
	m_BlockTickQueue.swap(m_BlockTickQueueCopy);

	for (std::vector<BlockTickQueueItem *>::iterator itr = m_BlockTickQueueCopy.begin(); itr != m_BlockTickQueueCopy.end(); ++itr)
	{
		BlockTickQueueItem * Block = (*itr);
		Block->TicksToWait -= 1;
		if (Block->TicksToWait <= 0)
		{
			// TODO: Handle the case when the chunk is already unloaded
			m_ChunkMap->TickBlock(Block->X, Block->Y, Block->Z);
			delete Block;  // We don't have to remove it from the vector, this will happen automatically on the next tick
		}
		else
		{
			m_BlockTickQueue.push_back(Block);  // Keep the block in the queue
		}
	}  // for itr - m_BlockTickQueueCopy[]
}





void cWorld::QueueBlockForTick(int a_BlockX, int a_BlockY, int a_BlockZ, int a_TicksToWait)
{
	BlockTickQueueItem * Block = new BlockTickQueueItem;
	Block->X = a_BlockX;
	Block->Y = a_BlockY;
	Block->Z = a_BlockZ;
	Block->TicksToWait = a_TicksToWait;

	m_BlockTickQueue.push_back(Block);
}





bool cWorld::IsBlockDirectlyWatered(int a_BlockX, int a_BlockY, int a_BlockZ)
{
	return (
		IsBlockWater(GetBlock(a_BlockX - 1, a_BlockY, a_BlockZ)) ||
		IsBlockWater(GetBlock(a_BlockX + 1, a_BlockY, a_BlockZ)) ||
		IsBlockWater(GetBlock(a_BlockX,     a_BlockY, a_BlockZ - 1)) ||
		IsBlockWater(GetBlock(a_BlockX,     a_BlockY, a_BlockZ + 1))
	);
}





UInt32 cWorld::SpawnMob(double a_PosX, double a_PosY, double a_PosZ, eMonsterType a_MonsterType, bool a_Baby)
{
	auto Monster = cMonster::NewMonsterFromType(a_MonsterType);
	if (Monster == nullptr)
	{
		return cEntity::INVALID_ID;
	}
	Monster->SetPosition(a_PosX, a_PosY, a_PosZ);

	if (a_Baby)
	{
		Monster->SetAge(-1);
	}

	return SpawnMobFinalize(std::move(Monster));
}





UInt32 cWorld::SpawnMobFinalize(std::unique_ptr<cMonster> a_Monster)
{
	ASSERT(a_Monster != nullptr);

	// Give the mob  full health.
	a_Monster->SetHealth(a_Monster->GetMaxHealth());

	// A plugin doesn't agree with the spawn. bail out.
	if (cPluginManager::Get()->CallHookSpawningMonster(*this, *a_Monster))
	{
		return cEntity::INVALID_ID;
	}

	auto & Monster = *a_Monster;

	// Initialize the monster into the current world.
	if (!Monster.Initialize(std::move(a_Monster), *this))
	{
		return cEntity::INVALID_ID;
	}

	cPluginManager::Get()->CallHookSpawnedMonster(*this, Monster);

	return Monster.GetUniqueID();
}





UInt32 cWorld::CreateProjectile(Vector3d a_Pos, cProjectileEntity::eKind a_Kind, cEntity * a_Creator, const cItem * a_Item, const Vector3d * a_Speed)
{
	auto Projectile = cProjectileEntity::Create(a_Kind, a_Creator, a_Pos, a_Item, a_Speed);
	if (Projectile == nullptr)
	{
		return cEntity::INVALID_ID;
	}

	auto ProjectilePtr = Projectile.get();
	if (!ProjectilePtr->Initialize(std::move(Projectile), *this))
	{
		return cEntity::INVALID_ID;
	}

	return ProjectilePtr->GetUniqueID();
}





UInt32 cWorld::CreateProjectile(double a_PosX, double a_PosY, double a_PosZ, cProjectileEntity::eKind a_Kind, cEntity * a_Creator, const cItem * a_Item, const Vector3d * a_Speed)
{
	return CreateProjectile({a_PosX, a_PosY, a_PosZ}, a_Kind, a_Creator, a_Item, a_Speed);
}





int cWorld::GetTickRandomNumber(int a_Range)
{
	return GetRandomProvider().RandInt(a_Range);
}





void cWorld::TabCompleteUserName(const AString & a_Text, AStringVector & a_Results)
{
	typedef std::pair<AString::size_type, AString> pair_t;
	size_t LastSpace = a_Text.find_last_of(" ");  // Find the position of the last space
	AString LastWord = a_Text.substr(LastSpace + 1, a_Text.length());  // Find the last word

	if (LastWord.empty())
	{
		return;
	}

	std::vector<pair_t> UsernamesByWeight;

	cCSLock Lock(m_CSPlayers);
	for (cPlayerList::iterator itr = m_Players.begin(), end = m_Players.end(); itr != end; ++itr)
	{
		AString PlayerName ((*itr)->GetName());
		if ((*itr)->HasCustomName())
		{
			PlayerName = (*itr)->GetCustomName();
		}

		AString::size_type Found = StrToLower(PlayerName).find(StrToLower(LastWord));  // Try to find last word in playername
		if (Found == AString::npos)
		{
			continue;  // No match
		}

		UsernamesByWeight.push_back(std::make_pair(Found, PlayerName));  // Match! Store it with the position of the match as a weight
	}
	Lock.Unlock();

	std::sort(UsernamesByWeight.begin(), UsernamesByWeight.end());  // Sort lexicographically (by the first value, then second), so higher weights (usernames with match closer to start) come first (#1274)

	/* TODO: Uncomment once migrated to C++11
	std::transform(
		UsernamesByWeight.begin(),
		UsernamesByWeight.end(),
		std::back_inserter(a_Results),
		[](const pair_t & p) { return p.first; }
	);
	*/

	a_Results.reserve(UsernamesByWeight.size());
	for (std::vector<pair_t>::const_iterator itr = UsernamesByWeight.begin(); itr != UsernamesByWeight.end(); ++itr)
	{
		a_Results.push_back(itr->second);
	}
}





void cWorld::SetChunkAlwaysTicked(int a_ChunkX, int a_ChunkZ, bool a_AlwaysTicked)
{
	m_ChunkMap->SetChunkAlwaysTicked(a_ChunkX, a_ChunkZ, a_AlwaysTicked);
}





cRedstoneSimulator * cWorld::InitializeRedstoneSimulator(cIniFile & a_IniFile)
{
	AString SimulatorName = a_IniFile.GetValueSet("Physics", "RedstoneSimulator", "Incremental");

	if (SimulatorName.empty())
	{
		LOGWARNING("[Physics] RedstoneSimulator not present or empty in %s, using the default of \"Incremental\".", GetIniFileName().c_str());
		SimulatorName = "Incremental";
	}

	cRedstoneSimulator * res = nullptr;

	if (NoCaseCompare(SimulatorName, "Incremental") == 0)
	{
		res = new cIncrementalRedstoneSimulator(*this);
	}
	else if (NoCaseCompare(SimulatorName, "noop") == 0)
	{
		res = new cRedstoneNoopSimulator(*this);
	}
	else
	{
		LOGWARNING("[Physics] Unknown RedstoneSimulator \"%s\" in %s, using the default of \"Incremental\".", SimulatorName.c_str(), GetIniFileName().c_str());
		res = new cIncrementalRedstoneSimulator(*this);
	}

	m_SimulatorManager->RegisterSimulator(res, 2 /* Two game ticks is a redstone tick */);

	return res;
}





cFluidSimulator * cWorld::InitializeFluidSimulator(cIniFile & a_IniFile, const char * a_FluidName, BLOCKTYPE a_SimulateBlock, BLOCKTYPE a_StationaryBlock)
{
	AString SimulatorNameKey;
	Printf(SimulatorNameKey, "%sSimulator", a_FluidName);
	AString SimulatorSectionName;
	Printf(SimulatorSectionName, "%sSimulator", a_FluidName);

	bool IsWater = (strcmp(a_FluidName, "Water") == 0);  // Used for defaults
	AString DefaultSimulatorName = ((GetDimension() == dimNether) && IsWater) ? "Vaporise" : "Vanilla";
	AString SimulatorName = a_IniFile.GetValueSet("Physics", SimulatorNameKey, DefaultSimulatorName);
	if (SimulatorName.empty())
	{
		LOGWARNING("[Physics] %s not present or empty in %s, using the default of \"%s\".", SimulatorNameKey.c_str(), GetIniFileName().c_str(), DefaultSimulatorName.c_str());
		SimulatorName = DefaultSimulatorName;
	}
	cFluidSimulator * res = nullptr;
	int Rate = 1;
	if (
		(NoCaseCompare(SimulatorName, "vaporize") == 0) ||
		(NoCaseCompare(SimulatorName, "vaporise") == 0)
	)
	{
		res = new cVaporizeFluidSimulator(*this, a_SimulateBlock, a_StationaryBlock);
	}
	else if (
		(NoCaseCompare(SimulatorName, "noop") == 0) ||
		(NoCaseCompare(SimulatorName, "nop") == 0) ||
		(NoCaseCompare(SimulatorName, "null") == 0) ||
		(NoCaseCompare(SimulatorName, "nil") == 0)
	)
	{
		res = new cNoopFluidSimulator(*this, a_SimulateBlock, a_StationaryBlock);
	}
	else
	{
		int Falloff               = a_IniFile.GetValueSetI(SimulatorSectionName, "Falloff",               IsWater ? 1 : 2);
		int TickDelay             = a_IniFile.GetValueSetI(SimulatorSectionName, "TickDelay",             IsWater ? 5 : 30);
		int NumNeighborsForSource = a_IniFile.GetValueSetI(SimulatorSectionName, "NumNeighborsForSource", IsWater ? 2 : -1);

		if ((Falloff > 15) || (Falloff < 0))
		{
			LOGWARNING("Falloff for %s simulator is out of range, assuming default of %d", a_FluidName, IsWater ? 1 : 2);
			Falloff = IsWater ? 1 : 2;
		}

		if (NoCaseCompare(SimulatorName, "floody") == 0)
		{
			res = new cFloodyFluidSimulator(*this, a_SimulateBlock, a_StationaryBlock, static_cast<NIBBLETYPE>(Falloff), TickDelay, NumNeighborsForSource);
		}
		else if (NoCaseCompare(SimulatorName, "vanilla") == 0)
		{
			res = new cVanillaFluidSimulator(*this, a_SimulateBlock, a_StationaryBlock, static_cast<NIBBLETYPE>(Falloff), TickDelay, NumNeighborsForSource);
		}
		else
		{
			// The simulator name doesn't match anything we have, issue a warning:
			LOGWARNING("%s [Physics]:%s specifies an unknown simulator, using the default \"Vanilla\".", GetIniFileName().c_str(), SimulatorNameKey.c_str());
			res = new cVanillaFluidSimulator(*this, a_SimulateBlock, a_StationaryBlock, static_cast<NIBBLETYPE>(Falloff), TickDelay, NumNeighborsForSource);
		}
	}

	m_SimulatorManager->RegisterSimulator(res, Rate);

	return res;
}





void cWorld::AddQueuedPlayers(void)
{
	ASSERT(m_TickThread.IsCurrentThread());

	// Grab the list of players to add, it has to be locked to access it:
	cAwaitingPlayerList PlayersToAdd;
	{
		cCSLock Lock(m_CSPlayersToAdd);
		std::swap(PlayersToAdd, m_PlayersToAdd);
	}

	// Temporary (#3115-will-fix): store pointers to player objects after ownership transferral
	std::vector<std::pair<cPlayer *, cWorld *>> AddedPlayerPtrs;
	AddedPlayerPtrs.reserve(PlayersToAdd.size());

	// Add all the players in the grabbed list:
	{
		cCSLock Lock(m_CSPlayers);
		for (auto & AwaitingPlayer : PlayersToAdd)
		{
			auto & Player = AwaitingPlayer.first;
			ASSERT(std::find(m_Players.begin(), m_Players.end(), Player.get()) == m_Players.end());  // Is it already in the list? HOW?
			LOGD("Adding player %s to world \"%s\".", Player->GetName().c_str(), m_WorldName.c_str());

			m_Players.push_back(Player.get());
			Player->SetWorld(this);

			// Add to chunkmap, if not already there (Spawn vs MoveToWorld):
			auto PlayerPtr = Player.get();
			m_ChunkMap->AddEntityIfNotPresent(std::move(Player));
			PlayerPtr->OnAddToWorld(*this);
			ASSERT(!PlayerPtr->IsTicking());
			PlayerPtr->SetIsTicking(true);
			AddedPlayerPtrs.emplace_back(PlayerPtr, AwaitingPlayer.second);
		}  // for itr - PlayersToAdd[]
	}  // Lock(m_CSPlayers)

	// Add all the players' clienthandles:
	{
		cCSLock Lock(m_CSClients);
		for (auto & AwaitingPlayer : AddedPlayerPtrs)
		{
			auto & Player = AwaitingPlayer.first;
			cClientHandlePtr Client = Player->GetClientHandlePtr();
			if (Client != nullptr)
			{
				m_Clients.push_back(Client);
			}
		}  // for itr - PlayersToAdd[]
	}  // Lock(m_CSClients)

	// Stream chunks to all eligible clients:
	for (auto & AwaitingPlayer : AddedPlayerPtrs)
	{
		auto & Player = AwaitingPlayer.first;
		cClientHandle * Client = Player->GetClientHandle();
		if (Client != nullptr)
		{
			Client->SendPlayerMoveLook();
			Client->SendHealth();
			Client->SendWholeInventory(*Player->GetWindow());
		}
	}  // for itr - PlayersToAdd[]

	// Call EntityChangedWorld callback on all eligible clients
	for (auto & AwaitingPlayer : AddedPlayerPtrs)
	{
		if (AwaitingPlayer.second != nullptr)
		{
			cRoot::Get()->GetPluginManager()->CallHookEntityChangedWorld(*(static_cast <cEntity *>(AwaitingPlayer.first)), *AwaitingPlayer.second);
		}
	}
}





////////////////////////////////////////////////////////////////////////////////
// cWorld::cChunkGeneratorCallbacks:

cWorld::cChunkGeneratorCallbacks::cChunkGeneratorCallbacks(cWorld & a_World) :
	m_World(&a_World)
{
}





void cWorld::cChunkGeneratorCallbacks::OnChunkGenerated(cChunkDesc & a_ChunkDesc)
{
	cChunkDef::BlockNibbles BlockMetas;
	a_ChunkDesc.CompressBlockMetas(BlockMetas);

	auto SetChunkData = cpp14::make_unique<cSetChunkData>(
		a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(),
		a_ChunkDesc.GetBlockTypes(), BlockMetas,
		nullptr, nullptr,  // We don't have lighting, chunk will be lighted when needed
		&a_ChunkDesc.GetHeightMap(), &a_ChunkDesc.GetBiomeMap(),
		std::move(a_ChunkDesc.GetEntities()), std::move(a_ChunkDesc.GetBlockEntities()),
		true
	);
	SetChunkData->RemoveInvalidBlockEntities();
	m_World->QueueSetChunkData(std::move(SetChunkData));
}





bool cWorld::cChunkGeneratorCallbacks::IsChunkValid(cChunkCoords a_Coords)
{
	return m_World->IsChunkValid(a_Coords.m_ChunkX, a_Coords.m_ChunkZ);
}





bool cWorld::cChunkGeneratorCallbacks::IsChunkQueued(cChunkCoords a_Coords)
{
	return m_World->IsChunkQueued(a_Coords.m_ChunkX, a_Coords.m_ChunkZ);
}





bool cWorld::cChunkGeneratorCallbacks::HasChunkAnyClients(cChunkCoords a_Coords)
{
	return m_World->HasChunkAnyClients(a_Coords.m_ChunkX, a_Coords.m_ChunkZ);
}





void cWorld::cChunkGeneratorCallbacks::CallHookChunkGenerating(cChunkDesc & a_ChunkDesc)
{
	cPluginManager::Get()->CallHookChunkGenerating(
		*m_World, a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(), &a_ChunkDesc
	);
}





void cWorld::cChunkGeneratorCallbacks::CallHookChunkGenerated (cChunkDesc & a_ChunkDesc)
{
	cPluginManager::Get()->CallHookChunkGenerated(
		*m_World, a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(), &a_ChunkDesc
	);
}