forked from cuberite/cuberite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWorld.cpp
3615 lines (2511 loc) · 88.2 KB
/
World.cpp
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
#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),
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);
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, zombie, 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))
{