-
-
Notifications
You must be signed in to change notification settings - Fork 632
/
World.cpp
2714 lines (1825 loc) · 63.4 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 "BlockID.h"
#include "World.h"
#include "ChunkDef.h"
#include "ClientHandle.h"
#include "Server.h"
#include "Item.h"
#include "Root.h"
#include "../iniFile/iniFile.h"
#include "ChunkMap.h"
#include "OSSupport/Timer.h"
// Entities (except mobs):
#include "Entities/Pickup.h"
#include "Entities/Player.h"
#include "Entities/TNTEntity.h"
// Simulators:
#include "Simulator/SimulatorManager.h"
#include "Simulator/FloodyFluidSimulator.h"
#include "Simulator/FluidSimulator.h"
#include "Simulator/FireSimulator.h"
#include "Simulator/NoopFluidSimulator.h"
#include "Simulator/SandSimulator.h"
#include "Simulator/RedstoneSimulator.h"
#include "Simulator/VaporizeFluidSimulator.h"
// Mobs:
#include "Mobs/IncludeAllMonsters.h"
#include "MobCensus.h"
#include "MobSpawner.h"
#include "MersenneTwister.h"
#include "Generating/Trees.h"
#include "PluginManager.h"
#include "Blocks/BlockHandler.h"
#include "Vector3d.h"
#include "Tracer.h"
#include "tolua++.h"
// DEBUG: Test out the cLineBlockTracer class by tracing a few lines:
#include "LineBlockTracer.h"
#ifndef _WIN32
#include <stdlib.h>
#endif
/// Up to this many m_SpreadQueue elements are handled each world tick
const int MAX_LIGHTING_SPREAD_PER_TICK = 10;
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;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cWorldLoadProgress:
/// A simple thread that displays the progress of world loading / saving in cWorld::InitializeSpawn()
class cWorldLoadProgress :
public cIsThread
{
public:
cWorldLoadProgress(cWorld * a_World) :
cIsThread("cWorldLoadProgress"),
m_World(a_World)
{
Start();
}
void Stop(void)
{
m_ShouldTerminate = true;
Wait();
}
protected:
cWorld * m_World;
virtual void Execute(void) override
{
for (;;)
{
LOG("%d chunks to load, %d chunks to generate",
m_World->GetStorage().GetLoadQueueLength(),
m_World->GetGenerator().GetQueueLength()
);
// Wait for 2 sec, but be "reasonably wakeable" when the thread is to finish
for (int i = 0; i < 20; i++)
{
cSleep::MilliSleep(100);
if (m_ShouldTerminate)
{
return;
}
}
} // for (-ever)
}
} ;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cWorldLightingProgress:
/// A simple thread that displays the progress of world lighting in cWorld::InitializeSpawn()
class cWorldLightingProgress :
public cIsThread
{
public:
cWorldLightingProgress(cLightingThread * a_Lighting) :
cIsThread("cWorldLightingProgress"),
m_Lighting(a_Lighting)
{
Start();
}
void Stop(void)
{
m_ShouldTerminate = true;
Wait();
}
protected:
cLightingThread * m_Lighting;
virtual void Execute(void) override
{
for (;;)
{
LOG("%d chunks remaining to light", m_Lighting->GetQueueLength()
);
// Wait for 2 sec, but be "reasonably wakeable" when the thread is to finish
for (int i = 0; i < 20; i++)
{
cSleep::MilliSleep(100);
if (m_ShouldTerminate)
{
return;
}
}
} // for (-ever)
}
} ;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 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)
{
cTimer Timer;
long long msPerTick = 50;
long long LastTime = Timer.GetNowTime();
while (!m_ShouldTerminate)
{
long long NowTime = Timer.GetNowTime();
float DeltaTime = (float)(NowTime - LastTime);
m_World.Tick(DeltaTime);
long long TickTime = Timer.GetNowTime() - NowTime;
if (TickTime < msPerTick)
{
// Stretch tick time until it's at least msPerTick
cSleep::MilliSleep((unsigned int)(msPerTick - TickTime));
}
LastTime = NowTime;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cWorld:
cWorld::cWorld(const AString & a_WorldName) :
m_WorldName(a_WorldName),
m_IniFileName(m_WorldName + "/world.ini"),
m_StorageSchema("Default"),
m_WorldAgeSecs(0),
m_TimeOfDaySecs(0),
m_WorldAge(0),
m_TimeOfDay(0),
m_LastTimeUpdate(0),
m_RSList(0),
m_Weather(eWeather_Sunny),
m_WeatherInterval(24000), // Guaranteed 1 day of sunshine at server start :)
m_TickThread(*this),
m_SkyDarkness(0)
{
LOGD("cWorld::cWorld(\"%s\")", a_WorldName.c_str());
cFile::CreateFolder(FILE_IO_PREFIX + m_WorldName);
}
cWorld::~cWorld()
{
delete m_SimulatorManager;
delete m_SandSimulator;
delete m_WaterSimulator;
delete m_LavaSimulator;
delete m_FireSimulator;
delete m_RedstoneSimulator;
UnloadUnusedChunks();
m_Storage.WaitForFinish();
delete m_ChunkMap;
}
void cWorld::CastThunderbolt (int a_BlockX, int a_BlockY, int a_BlockZ)
{
BroadcastThunderbolt(a_BlockX, a_BlockY, a_BlockZ);
}
void cWorld::SetWeather(eWeather a_NewWeather)
{
// Do the plugins agree? Do they want a different weather?
cRoot::Get()->GetPluginManager()->CallHookWeatherChanging(*this, a_NewWeather);
// Set new period for the selected weather:
switch (a_NewWeather)
{
case eWeather_Sunny: m_WeatherInterval = 14400 + (m_TickRand.randInt() % 4800); break; // 12 - 16 minutes
case eWeather_Rain: m_WeatherInterval = 9600 + (m_TickRand.randInt() % 7200); break; // 8 - 14 minutes
case eWeather_ThunderStorm: m_WeatherInterval = 2400 + (m_TickRand.randInt() % 4800); break; // 2 - 6 minutes
default:
{
LOGWARNING("Requested unknown weather %d, setting sunny for a minute instead.", a_NewWeather);
a_NewWeather = eWeather_Sunny;
m_WeatherInterval = 1200;
break;
}
} // switch (NewWeather)
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;
}
void cWorld::SetNextBlockTick(int a_BlockX, int a_BlockY, int a_BlockZ)
{
return m_ChunkMap->SetNextBlockTick(a_BlockX, a_BlockY, a_BlockZ);
}
void cWorld::InitializeSpawn(void)
{
int ChunkX = 0, ChunkY = 0, ChunkZ = 0;
BlockToChunk((int)m_SpawnX, (int)m_SpawnY, (int)m_SpawnZ, ChunkX, ChunkY, ChunkZ);
// For the debugging builds, don't make the server build too much world upon start:
#if defined(_DEBUG) || defined(ANDROID_NDK)
int ViewDist = 9;
#else
int ViewDist = 20; // Always prepare an area 20 chunks across, no matter what the actual cClientHandle::VIEWDISTANCE is
#endif // _DEBUG
LOG("Preparing spawn area in world \"%s\"...", m_WorldName.c_str());
for (int x = 0; x < ViewDist; x++)
{
for (int z = 0; z < ViewDist; z++)
{
m_ChunkMap->TouchChunk(x + ChunkX-(ViewDist - 1) / 2, ZERO_CHUNK_Y, z + ChunkZ-(ViewDist - 1) / 2); // Queue the chunk in the generator / loader
}
}
{
// Display progress during this process:
cWorldLoadProgress Progress(this);
// Wait for the loader to finish loading
m_Storage.WaitForQueuesEmpty();
// Wait for the generator to finish generating
m_Generator.WaitForQueueEmpty();
Progress.Stop();
}
// Light all chunks that have been newly generated:
LOG("Lighting spawn area in world \"%s\"...", m_WorldName.c_str());
for (int x = 0; x < ViewDist; x++)
{
int ChX = x + ChunkX-(ViewDist - 1) / 2;
for (int z = 0; z < ViewDist; z++)
{
int ChZ = z + ChunkZ-(ViewDist - 1) / 2;
if (!m_ChunkMap->IsChunkLighted(ChX, ChZ))
{
m_Lighting.QueueChunk(ChX, ChZ); // Queue the chunk in the lighting thread
}
} // for z
} // for x
{
cWorldLightingProgress Progress(&m_Lighting);
m_Lighting.WaitForQueueEmpty();
Progress.Stop();
}
// TODO: Better spawn detection - move spawn out of the water if it isn't set in the INI already
m_SpawnY = (double)GetHeight((int)m_SpawnX, (int)m_SpawnZ) + 1.6f; // +1.6f eye height
#ifdef TEST_LINEBLOCKTRACER
// DEBUG: Test out the cLineBlockTracer class by tracing a few lines:
class cTracerCallbacks :
public cBlockTracer::cCallbacks
{
virtual bool OnNextBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) override
{
LOGD("Block {%d, %d, %d}: %d:%d (%s)",
a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta,
ItemToString(cItem(a_BlockType, 1, a_BlockMeta)).c_str()
);
return false;
}
virtual bool OnNextBlockNoData(int a_BlockX, int a_BlockY, int a_BlockZ) override
{
LOGD("Block {%d, %d, %d}: no data available",
a_BlockX, a_BlockY, a_BlockZ
);
return false;
}
virtual bool OnOutOfWorld(double a_BlockX, double a_BlockY, double a_BlockZ) override
{
LOGD("Out of world at {%f, %f, %f}", a_BlockX, a_BlockY, a_BlockZ);
return false;
}
virtual bool OnIntoWorld(double a_BlockX, double a_BlockY, double a_BlockZ) override
{
LOGD("Into world at {%f, %f, %f}", a_BlockX, a_BlockY, a_BlockZ);
return false;
}
virtual void OnNoMoreHits(void) override
{
LOGD("No more hits");
}
} Callbacks;
LOGD("Spawn is at {%f, %f, %f}", m_SpawnX, m_SpawnY, m_SpawnZ);
LOGD("Tracing a line along +X:");
cLineBlockTracer::Trace(*this, Callbacks, m_SpawnX - 10, m_SpawnY, m_SpawnZ, m_SpawnX + 10, m_SpawnY, m_SpawnZ);
LOGD("Tracing a line along -Z:");
cLineBlockTracer::Trace(*this, Callbacks, m_SpawnX, m_SpawnY, m_SpawnZ + 10, m_SpawnX, m_SpawnY, m_SpawnZ - 10);
LOGD("Tracing a line along -Y, out of world:");
cLineBlockTracer::Trace(*this, Callbacks, m_SpawnX, 260, m_SpawnZ, m_SpawnX, -5, m_SpawnZ);
LOGD("Tracing a line along XY:");
cLineBlockTracer::Trace(*this, Callbacks, m_SpawnX - 10, m_SpawnY - 10, m_SpawnZ, m_SpawnX + 10, m_SpawnY + 10, m_SpawnZ);
LOGD("Tracing a line in generic direction:");
cLineBlockTracer::Trace(*this, Callbacks, m_SpawnX - 15, m_SpawnY - 5, m_SpawnZ + 7.5, m_SpawnX + 13, m_SpawnY - 10, m_SpawnZ + 8.5);
LOGD("Tracing tests done");
#endif // TEST_LINEBLOCKTRACER
}
void cWorld::Start(void)
{
// TODO: Find a proper spawn location, based on the biomes (not in ocean)
m_SpawnX = (double)((m_TickRand.randInt() % 1000) - 500);
m_SpawnY = cChunkDef::Height;
m_SpawnZ = (double)((m_TickRand.randInt() % 1000) - 500);
m_GameMode = eGameMode_Creative;
cIniFile IniFile;
if (!IniFile.ReadFile(m_IniFileName))
{
LOGWARNING("Cannot read world settings from \"%s\", defaults will be used.", m_IniFileName.c_str());
}
AString Dimension = IniFile.GetValueSet("General", "Dimension", "Overworld");
m_Dimension = StringToDimension(Dimension);
switch (m_Dimension)
{
case dimNether:
case dimOverworld:
case dimEnd:
{
break;
}
default:
{
LOGWARNING("Unknown dimension: \"%s\". Setting to Overworld", Dimension.c_str());
m_Dimension = dimOverworld;
break;
}
} // switch (m_Dimension)
m_SpawnX = IniFile.GetValueSetF("SpawnPosition", "X", m_SpawnX);
m_SpawnY = IniFile.GetValueSetF("SpawnPosition", "Y", m_SpawnY);
m_SpawnZ = IniFile.GetValueSetF("SpawnPosition", "Z", m_SpawnZ);
m_StorageSchema = IniFile.GetValueSet ("Storage", "Schema", m_StorageSchema);
m_MaxCactusHeight = IniFile.GetValueSetI("Plants", "MaxCactusHeight", 3);
m_MaxSugarcaneHeight = IniFile.GetValueSetI("Plants", "MaxSugarcaneHeight", 3);
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_bEnabledPVP = IniFile.GetValueSetB("PVP", "Enabled", true);
m_IsDeepSnowEnabled = IniFile.GetValueSetB("Physics", "DeepSnow", false);
m_GameMode = (eGameMode)IniFile.GetValueSetI("GameMode", "GameMode", m_GameMode);
// Load allowed mobs:
const char * DefaultMonsters = "";
switch (m_Dimension)
{
case dimOverworld: DefaultMonsters = "bat, cavespider, chicken, cow, creeper, enderman, horse, mooshroom, ocelot, pig, sheep, silverfish, skeleton, slime, spider, squid, wolf, zombie"; break;
case dimNether: DefaultMonsters = "blaze, ghast, magmacube, skeleton, zombie, zombiepigman"; break;
case dimEnd: DefaultMonsters = "enderman"; break;
default:
{
ASSERT(!"Unhandled world dimension");
DefaultMonsters = "wither";
break;
}
}
m_bAnimals = IniFile.GetValueSetB("Monsters", "AnimalsOn", true);
AString AllMonsters = IniFile.GetValueSet("Monsters", "Types", DefaultMonsters);
AStringVector SplitList = StringSplitAndTrim(AllMonsters, ",");
for (AStringVector::const_iterator itr = SplitList.begin(), end = SplitList.end(); itr != end; ++itr)
{
cMonster::eType ToAdd = cMonster::StringToMobType(*itr);
if (ToAdd != cMonster::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());
}
}
m_ChunkMap = new cChunkMap(this);
m_LastSave = 0;
m_LastUnload = 0;
// 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 = new 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 = new cSandSimulator(*this, IniFile);
m_FireSimulator = new cFireSimulator(*this, IniFile);
m_RedstoneSimulator = new cRedstoneSimulator(*this);
// Water and Lava simulators get registered in InitializeFluidSimulator()
m_SimulatorManager->RegisterSimulator(m_SandSimulator, 1);
m_SimulatorManager->RegisterSimulator(m_FireSimulator, 1);
m_SimulatorManager->RegisterSimulator(m_RedstoneSimulator, 1);
m_Lighting.Start(this);
m_Storage.Start(this, m_StorageSchema);
m_Generator.Start(this, IniFile);
m_ChunkSender.Start(this);
m_TickThread.Start();
// Init of the spawn monster time (as they are supposed to have different spawn rate)
m_LastSpawnMonster.insert(std::map<cMonster::eFamily, Int64>::value_type(cMonster::mfHostile, 0));
m_LastSpawnMonster.insert(std::map<cMonster::eFamily, Int64>::value_type(cMonster::mfPassive, 0));
m_LastSpawnMonster.insert(std::map<cMonster::eFamily, Int64>::value_type(cMonster::mfAmbient, 0));
m_LastSpawnMonster.insert(std::map<cMonster::eFamily, Int64>::value_type(cMonster::mfWater, 0));
// 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());
}
}
void cWorld::Stop(void)
{
// Delete the clients that have been in this world:
{
cCSLock Lock(m_CSClients);
for (cClientHandleList::iterator itr = m_Clients.begin(); itr != m_Clients.end(); ++itr)
{
(*itr)->Destroy();
delete *itr;
} // for itr - m_Clients[]
m_Clients.clear();
}
m_TickThread.Stop();
m_Lighting.Stop();
m_Generator.Stop();
m_ChunkSender.Stop();
m_Storage.Stop();
}
void cWorld::Tick(float a_Dt)
{
// Call the plugins
cPluginManager::Get()->CallHookWorldTick(*this, a_Dt);
// We need sub-tick precision here, that's why we store the time in seconds and calculate ticks off of it
m_WorldAgeSecs += (double)a_Dt / 1000.0;
m_TimeOfDaySecs += (double)a_Dt / 1000.0;
// Wrap time of day each 20 minutes (1200 seconds)
if (m_TimeOfDaySecs > 1200.0)
{
m_TimeOfDaySecs -= 1200.0;
}
m_WorldAge = (Int64)(m_WorldAgeSecs * 20.0);
m_TimeOfDay = (Int64)(m_TimeOfDaySecs * 20.0);
// Updates the sky darkness based on current time of day
UpdateSkyDarkness();
// Broadcast time update every 40 ticks (2 seconds)
if (m_LastTimeUpdate < m_WorldAge - 40)
{
BroadcastTimeUpdate();
m_LastTimeUpdate = m_WorldAge;
}
m_ChunkMap->Tick(a_Dt);
TickClients(a_Dt);
TickQueuedBlocks();
TickQueuedTasks();
GetSimulatorManager()->Simulate(a_Dt);
TickWeather(a_Dt);
// Asynchronously set blocks:
sSetBlockList FastSetBlockQueueCopy;
{
cCSLock Lock(m_CSFastSetBlock);
std::swap(FastSetBlockQueueCopy, m_FastSetBlockQueue);
}
m_ChunkMap->FastSetBlocks(FastSetBlockQueueCopy);
if (!FastSetBlockQueueCopy.empty())
{
// Some blocks failed, store them for next tick:
cCSLock Lock(m_CSFastSetBlock);
m_FastSetBlockQueue.splice(m_FastSetBlockQueue.end(), FastSetBlockQueueCopy);
}
if (m_WorldAge - m_LastSave > 60 * 5 * 20) // Save each 5 minutes
{
SaveAllChunks();
}
if (m_WorldAge - m_LastUnload > 10 * 20) // Unload every 10 seconds
{
UnloadUnusedChunks();
}
TickMobs(a_Dt);
std::vector<int> m_RSList_copy(m_RSList);
m_RSList.clear();
std::vector<int>::const_iterator cii; // FIXME - Please rename this variable, WTF is cii??? Use human readable variable names or common abbreviations (i, idx, itr, iter)
for (cii = m_RSList_copy.begin(); cii != m_RSList_copy.end();)
{
int tempX = *cii; cii++;
int tempY = *cii; cii++;
int tempZ = *cii; cii++;
int state = *cii; cii++;
if ((state == 11111) && ((int)GetBlock(tempX, tempY, tempZ) == E_BLOCK_REDSTONE_TORCH_OFF))
{
FastSetBlock(tempX, tempY, tempZ, E_BLOCK_REDSTONE_TORCH_ON, (int)GetBlockMeta(tempX, tempY, tempZ));
}
else if ((state == 00000) && ((int)GetBlock(tempX, tempY, tempZ) == E_BLOCK_REDSTONE_TORCH_ON))
{
FastSetBlock(tempX, tempY, tempZ, E_BLOCK_REDSTONE_TORCH_OFF, (int)GetBlockMeta(tempX, tempY, tempZ));
}
}
m_RSList_copy.erase(m_RSList_copy.begin(),m_RSList_copy.end());
}
void cWorld::TickWeather(float 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:
// Pick a new weather. Only reasonable transitions allowed:
eWeather NewWeather = m_Weather;
switch (m_Weather)
{
case eWeather_Sunny: NewWeather = eWeather_Rain; break;
case eWeather_ThunderStorm: NewWeather = eWeather_Rain; break;
case eWeather_Rain:
{
// 1/8 chance of turning into a thunderstorm
NewWeather = ((m_TickRand.randInt() % 256) < 32) ? eWeather_ThunderStorm : eWeather_Sunny;
break;
}
default:
{
LOGWARNING("Unknown current weather: %d. Setting sunny.", m_Weather);
ASSERT(!"Unknown weather");
NewWeather = eWeather_Sunny;
}
}
SetWeather(NewWeather);
} // else (m_WeatherInterval > 0)
if (m_Weather == eWeather_ThunderStorm)
{
// 0.5% chance per tick of thunderbolt
if (m_TickRand.randInt() % 199 == 0)
{
CastThunderbolt(0, 0, 0); // TODO: find random possitions near players to cast thunderbolts.
}
}
}
void cWorld::TickMobs(float 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 (int i = 0; i < ARRAYCOUNT(AllFamilies); i++)
{
cMonster::eFamily Family = AllFamilies[i];
int SpawnDelay = 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] = m_WorldAge;
cMobSpawner Spawner(Family, m_AllowedMobs);
if (Spawner.CanSpawnAnything())
{
m_ChunkMap->SpawnMobs(Spawner);
// do the spawn
for (cMobSpawner::tSpawnedContainer::const_iterator itr2 = Spawner.getSpawned().begin(); itr2 != Spawner.getSpawned().end(); itr2++)
{
SpawnMobFinalize(*itr2);
}
}
} // for i - AllFamilies[]
} // if (Spawning enabled)
// move close mobs
cMobProximityCounter::sIterablePair allCloseEnoughToMoveMobs = MobCensus.GetProximityCounter().getMobWithinThosesDistances(-1, 64 * 16);// MG TODO : deal with this magic number (the 16 is the size of a block)
for(cMobProximityCounter::tDistanceToMonster::const_iterator itr = allCloseEnoughToMoveMobs.m_Begin; itr != allCloseEnoughToMoveMobs.m_End; itr++)
{
itr->second.m_Monster.Tick(a_Dt, itr->second.m_Chunk);
}
// remove too far mobs
cMobProximityCounter::sIterablePair allTooFarMobs = MobCensus.GetProximityCounter().getMobWithinThosesDistances(128 * 16, -1);// MG TODO : deal with this magic number (the 16 is the size of a block)
for(cMobProximityCounter::tDistanceToMonster::const_iterator itr = allTooFarMobs.m_Begin; itr != allTooFarMobs.m_End; itr++)
{
itr->second.m_Monster.Destroy(true);
}
}
void cWorld::TickQueuedTasks(void)
{
// Make a copy of the tasks to avoid deadlocks on accessing m_Tasks
cTasks Tasks;
{
cCSLock Lock(m_CSTasks);
std::swap(Tasks, m_Tasks);
}
// Execute and delete each task:
for (cTasks::iterator itr = Tasks.begin(), end = Tasks.end(); itr != end; ++itr)
{
(*itr)->Run(*this);
delete *itr;
} // for itr - m_Tasks[]
}
void cWorld::TickClients(float a_Dt)
{
cClientHandleList RemoveClients;
{
cCSLock Lock(m_CSClients);
// Remove clients scheduled for removal:
for (cClientHandleList::iterator itr = m_ClientsToRemove.begin(), end = m_ClientsToRemove.end(); itr != end; ++itr)
{
m_Clients.remove(*itr);
} // for itr - m_ClientsToRemove[]
m_ClientsToRemove.clear();
// Add clients scheduled for adding:
for (cClientHandleList::iterator itr = m_ClientsToAdd.begin(), end = m_ClientsToAdd.end(); itr != end; ++itr)
{
if (std::find(m_Clients.begin(), m_Clients.end(), *itr) != m_Clients.end())
{
ASSERT(!"Adding a client that is already in the clientlist");
continue;
}
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 (cClientHandleList::iterator 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 that have been destroyed
for (cClientHandleList::iterator itr = RemoveClients.begin(); itr != RemoveClients.end(); ++itr)
{
delete *itr;
} // for itr - RemoveClients[]
}
void cWorld::UpdateSkyDarkness(void)
{
int TempTime = (int)m_TimeOfDay;
if (TempTime <= TIME_SUNSET)
{
m_SkyDarkness = 0;
}
else if (TempTime <= TIME_NIGHT_START)
{
m_SkyDarkness = (TIME_NIGHT_START - TempTime) / TIME_SPAWN_DIVISOR;
}
else if (TempTime <= TIME_NIGHT_END)
{
m_SkyDarkness = 8;
}
else
{
m_SkyDarkness = (TIME_SUNRISE - TempTime) / TIME_SPAWN_DIVISOR;
}
}
void cWorld::WakeUpSimulators(int a_BlockX, int a_BlockY, int a_BlockZ)
{
return m_ChunkMap->WakeUpSimulators(a_BlockX, a_BlockY, a_BlockZ);
}
/// Wakes up the simulators for the specified area of blocks
void cWorld::WakeUpSimulatorsInArea(int a_MinBlockX, int a_MaxBlockX, int a_MinBlockY, int a_MaxBlockY, int a_MinBlockZ, int a_MaxBlockZ)
{
return m_ChunkMap->WakeUpSimulatorsInArea(a_MinBlockX, a_MaxBlockX, a_MinBlockY, a_MaxBlockY, a_MinBlockZ, a_MaxBlockZ);
}
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: Add damage to entities, add support for pickups, and implement block hardiness
Vector3d explosion_pos = Vector3d(a_BlockX, a_BlockY, a_BlockZ);
cVector3iArray BlocksAffected;
m_ChunkMap->DoExplosionAt(a_ExplosionSize, a_BlockX, a_BlockY, a_BlockZ, BlocksAffected);
BroadcastSoundEffect("random.explode", (int)floor(a_BlockX * 8), (int)floor(a_BlockY * 8), (int)floor(a_BlockZ * 8), 1.0f, 0.6f);
{
cCSLock Lock(m_CSPlayers);
for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr)
{
cClientHandle * ch = (*itr)->GetClientHandle();
if ((ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed())
{
continue;
}
Vector3d distance_explosion = (*itr)->GetPosition() - explosion_pos;
if (distance_explosion.SqrLength() < 4096.0)
{
double real_distance = std::max(0.004, sqrt(distance_explosion.SqrLength()));
double power = a_ExplosionSize / real_distance;
if (power <= 1)
{
power = 0;
}
distance_explosion.Normalize();