forked from cuberite/cuberite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChunk.cpp
2455 lines (1801 loc) · 55.8 KB
/
Chunk.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
#ifndef _WIN32
#include <cstdlib>
#endif
#include "Chunk.h"
#include "World.h"
#include "ClientHandle.h"
#include "Server.h"
#include "zlib/zlib.h"
#include "Defines.h"
#include "BlockEntities/BeaconEntity.h"
#include "BlockEntities/BedEntity.h"
#include "BlockEntities/BrewingstandEntity.h"
#include "BlockEntities/ChestEntity.h"
#include "BlockEntities/CommandBlockEntity.h"
#include "BlockEntities/DispenserEntity.h"
#include "BlockEntities/DropperEntity.h"
#include "BlockEntities/FlowerPotEntity.h"
#include "BlockEntities/FurnaceEntity.h"
#include "BlockEntities/HopperEntity.h"
#include "BlockEntities/JukeboxEntity.h"
#include "BlockEntities/MobHeadEntity.h"
#include "BlockEntities/MobSpawnerEntity.h"
#include "BlockEntities/NoteEntity.h"
#include "BlockEntities/SignEntity.h"
#include "Entities/Pickup.h"
#include "Item.h"
#include "Noise/Noise.h"
#include "Root.h"
#include "Entities/Player.h"
#include "BlockArea.h"
#include "Bindings/PluginManager.h"
#include "Blocks/BlockHandler.h"
#include "Simulator/FluidSimulator.h"
#include "MobCensus.h"
#include "MobSpawner.h"
#include "BlockInServerPluginInterface.h"
#include "SetChunkData.h"
#include "BoundingBox.h"
#include "Blocks/ChunkInterface.h"
#include "json/json.h"
////////////////////////////////////////////////////////////////////////////////
// cChunk:
cChunk::cChunk(
int a_ChunkX, int a_ChunkZ,
cChunkMap * a_ChunkMap, cWorld * a_World,
cChunk * a_NeighborXM, cChunk * a_NeighborXP, cChunk * a_NeighborZM, cChunk * a_NeighborZP,
cAllocationPool<cChunkData::sChunkSection> & a_Pool
):
m_Presence(cpInvalid),
m_ShouldGenerateIfLoadFailed(false),
m_IsLightValid(false),
m_IsDirty(false),
m_IsSaving(false),
m_HasLoadFailed(false),
m_StayCount(0),
m_PosX(a_ChunkX),
m_PosZ(a_ChunkZ),
m_World(a_World),
m_ChunkMap(a_ChunkMap),
m_ChunkData(a_Pool),
m_BlockTickX(0),
m_BlockTickY(0),
m_BlockTickZ(0),
m_NeighborXM(a_NeighborXM),
m_NeighborXP(a_NeighborXP),
m_NeighborZM(a_NeighborZM),
m_NeighborZP(a_NeighborZP),
m_WaterSimulatorData(a_World->GetWaterSimulator()->CreateChunkData()),
m_LavaSimulatorData (a_World->GetLavaSimulator ()->CreateChunkData()),
m_RedstoneSimulatorData(a_World->GetRedstoneSimulator()->CreateChunkData()),
m_AlwaysTicked(0)
{
if (a_NeighborXM != nullptr)
{
a_NeighborXM->m_NeighborXP = this;
}
if (a_NeighborXP != nullptr)
{
a_NeighborXP->m_NeighborXM = this;
}
if (a_NeighborZM != nullptr)
{
a_NeighborZM->m_NeighborZP = this;
}
if (a_NeighborZP != nullptr)
{
a_NeighborZP->m_NeighborZM = this;
}
}
cChunk::~cChunk()
{
cPluginManager::Get()->CallHookChunkUnloaded(*m_World, m_PosX, m_PosZ);
// LOGINFO("### delete cChunk() (%i, %i) from %p, thread 0x%x ###", m_PosX, m_PosZ, this, GetCurrentThreadId());
for (auto & KeyPair : m_BlockEntities)
{
delete KeyPair.second;
}
m_BlockEntities.clear();
// Remove and destroy all entities that are not players:
cEntityList Entities;
std::swap(Entities, m_Entities); // Need another list because cEntity destructors check if they've been removed from chunk
for (auto & Entity : Entities)
{
if (!Entity->IsPlayer())
{
// Scheduling a normal destruction is neither possible (Since this chunk will be gone till the schedule occurs) nor necessary.
Entity->DestroyNoScheduling(false); // No point in broadcasting in an unloading chunk. Chunks unload when no one is nearby.
}
}
if (m_NeighborXM != nullptr)
{
m_NeighborXM->m_NeighborXP = nullptr;
}
if (m_NeighborXP != nullptr)
{
m_NeighborXP->m_NeighborXM = nullptr;
}
if (m_NeighborZM != nullptr)
{
m_NeighborZM->m_NeighborZP = nullptr;
}
if (m_NeighborZP != nullptr)
{
m_NeighborZP->m_NeighborZM = nullptr;
}
delete m_WaterSimulatorData;
m_WaterSimulatorData = nullptr;
delete m_LavaSimulatorData;
m_LavaSimulatorData = nullptr;
delete m_RedstoneSimulatorData;
m_RedstoneSimulatorData = nullptr;
}
void cChunk::SetPresence(cChunk::ePresence a_Presence)
{
m_Presence = a_Presence;
if (a_Presence == cpPresent)
{
m_World->GetChunkMap()->ChunkValidated();
}
}
void cChunk::SetShouldGenerateIfLoadFailed(bool a_ShouldGenerateIfLoadFailed)
{
m_ShouldGenerateIfLoadFailed = a_ShouldGenerateIfLoadFailed;
}
void cChunk::MarkRegenerating(void)
{
// Set as queued again:
SetPresence(cpQueued);
// Tell all clients attached to this chunk that they want this chunk:
for (auto ClientHandle : m_LoadedByClient)
{
ClientHandle->AddWantedChunk(m_PosX, m_PosZ);
} // for itr - m_LoadedByClient[]
}
bool cChunk::CanUnload(void)
{
return
m_LoadedByClient.empty() && // The chunk is not used by any client
!m_IsDirty && // The chunk has been saved properly or hasn't been touched since the load / gen
(m_StayCount == 0) && // The chunk is not in a ChunkStay
(m_Presence != cpQueued) ; // The chunk is not queued for loading / generating (otherwise multi-load / multi-gen could occur)
}
bool cChunk::CanUnloadAfterSaving(void)
{
return
m_LoadedByClient.empty() && // The chunk is not used by any client
m_IsDirty && // The chunk is dirty
(m_StayCount == 0) && // The chunk is not in a ChunkStay
(m_Presence != cpQueued) ; // The chunk is not queued for loading / generating (otherwise multi-load / multi-gen could occur)
}
void cChunk::MarkSaving(void)
{
m_IsSaving = true;
}
void cChunk::MarkSaved(void)
{
if (!m_IsSaving)
{
return;
}
m_IsDirty = false;
}
void cChunk::MarkLoaded(void)
{
m_IsDirty = false;
SetPresence(cpPresent);
}
void cChunk::MarkLoadFailed(void)
{
ASSERT(m_Presence == cpQueued);
// If the chunk is marked as needed, generate it:
if (m_ShouldGenerateIfLoadFailed)
{
m_World->GetGenerator().QueueGenerateChunk({m_PosX, m_PosZ}, false);
}
else
{
m_Presence = cpInvalid;
}
}
void cChunk::GetAllData(cChunkDataCallback & a_Callback)
{
ASSERT(m_Presence == cpPresent);
a_Callback.HeightMap(&m_HeightMap);
a_Callback.BiomeData(&m_BiomeMap);
a_Callback.LightIsValid(m_IsLightValid);
a_Callback.ChunkData(m_ChunkData);
for (const auto & Entity : m_Entities)
{
a_Callback.Entity(Entity.get());
}
for (auto & KeyPair : m_BlockEntities)
{
a_Callback.BlockEntity(KeyPair.second);
}
}
void cChunk::SetAllData(cSetChunkData & a_SetChunkData)
{
ASSERT(a_SetChunkData.IsHeightMapValid());
ASSERT(a_SetChunkData.AreBiomesValid());
memcpy(m_BiomeMap, a_SetChunkData.GetBiomes(), sizeof(m_BiomeMap));
memcpy(m_HeightMap, a_SetChunkData.GetHeightMap(), sizeof(m_HeightMap));
m_ChunkData.Assign(std::move(a_SetChunkData.GetChunkData()));
m_IsLightValid = a_SetChunkData.IsLightValid();
// Clear the block entities present - either the loader / saver has better, or we'll create empty ones:
for (auto & KeyPair : m_BlockEntities)
{
delete KeyPair.second;
}
m_BlockEntities = std::move(a_SetChunkData.GetBlockEntities());
// Check that all block entities have a valid blocktype at their respective coords (DEBUG-mode only):
#ifdef _DEBUG
for (auto & KeyPair : m_BlockEntities)
{
cBlockEntity * Block = KeyPair.second;
BLOCKTYPE EntityBlockType = Block->GetBlockType();
BLOCKTYPE WorldBlockType = GetBlock(Block->GetRelX(), Block->GetPosY(), Block->GetRelZ());
ASSERT(WorldBlockType == EntityBlockType);
} // for KeyPair - m_BlockEntities
#endif // _DEBUG
// Set all block entities' World variable:
for (auto & KeyPair : m_BlockEntities)
{
KeyPair.second->SetWorld(m_World);
}
// Create block entities that the loader didn't load; fill them with defaults
CreateBlockEntities();
// Set the chunk data as valid. This may be needed for some simulators that perform actions upon block adding (Vaporize)
SetPresence(cpPresent);
// Wake up all simulators for their respective blocks:
WakeUpSimulators();
m_HasLoadFailed = false;
}
void cChunk::SetLight(
const cChunkDef::BlockNibbles & a_BlockLight,
const cChunkDef::BlockNibbles & a_SkyLight
)
{
// TODO: We might get cases of wrong lighting when a chunk changes in the middle of a lighting calculation.
// Postponing until we see how bad it is :)
m_ChunkData.SetBlockLight(a_BlockLight);
m_ChunkData.SetSkyLight(a_SkyLight);
m_IsLightValid = true;
}
void cChunk::GetBlockTypes(BLOCKTYPE * a_BlockTypes)
{
m_ChunkData.CopyBlockTypes(a_BlockTypes);
}
void cChunk::WriteBlockArea(cBlockArea & a_Area, int a_MinBlockX, int a_MinBlockY, int a_MinBlockZ, int a_DataTypes)
{
if ((a_DataTypes & (cBlockArea::baTypes | cBlockArea::baMetas)) != (cBlockArea::baTypes | cBlockArea::baMetas))
{
LOGWARNING("cChunk::WriteBlockArea(): unsupported datatype request, can write only types + metas together (0x%x), requested 0x%x. Ignoring.",
(cBlockArea::baTypes | cBlockArea::baMetas), a_DataTypes & (cBlockArea::baTypes | cBlockArea::baMetas)
);
return;
}
// SizeX, SizeZ are the dimensions of the block data to copy to the chunk (size of the geometric union)
int BlockStartX = std::max(a_MinBlockX, m_PosX * cChunkDef::Width);
int BlockEndX = std::min(a_MinBlockX + a_Area.GetSizeX(), (m_PosX + 1) * cChunkDef::Width);
int BlockStartZ = std::max(a_MinBlockZ, m_PosZ * cChunkDef::Width);
int BlockEndZ = std::min(a_MinBlockZ + a_Area.GetSizeZ(), (m_PosZ + 1) * cChunkDef::Width);
int SizeX = BlockEndX - BlockStartX; // Size of the union
int SizeZ = BlockEndZ - BlockStartZ;
int SizeY = std::min(a_Area.GetSizeY(), cChunkDef::Height - a_MinBlockY);
int OffX = BlockStartX - m_PosX * cChunkDef::Width; // Offset within the chunk where the union starts
int OffZ = BlockStartZ - m_PosZ * cChunkDef::Width;
int BaseX = BlockStartX - a_MinBlockX; // Offset within the area where the union starts
int BaseZ = BlockStartZ - a_MinBlockZ;
// Copy blocktype and blockmeta:
BLOCKTYPE * AreaBlockTypes = a_Area.GetBlockTypes();
NIBBLETYPE * AreaBlockMetas = a_Area.GetBlockMetas();
for (int y = 0; y < SizeY; y++)
{
int ChunkY = a_MinBlockY + y;
int AreaY = y;
for (int z = 0; z < SizeZ; z++)
{
int ChunkZ = OffZ + z;
int AreaZ = BaseZ + z;
for (int x = 0; x < SizeX; x++)
{
int ChunkX = OffX + x;
int AreaX = BaseX + x;
auto idx = a_Area.MakeIndex(AreaX, AreaY, AreaZ);
BLOCKTYPE BlockType = AreaBlockTypes[idx];
NIBBLETYPE BlockMeta = AreaBlockMetas[idx];
FastSetBlock(ChunkX, ChunkY, ChunkZ, BlockType, BlockMeta);
} // for x
} // for z
} // for y
// Erase all affected block entities:
cCuboid affectedArea( // In world coordinates
{BlockStartX, a_MinBlockY, BlockStartZ},
{BlockEndX, a_MinBlockY + SizeY - 1, BlockEndZ}
);
for (auto itr = m_BlockEntities.begin(); itr != m_BlockEntities.end();)
{
if (affectedArea.IsInside(itr->second->GetPos()))
{
delete itr->second;
itr = m_BlockEntities.erase(itr);
}
else
{
++itr;
}
}
// Clone block entities from a_Area into this chunk:
if ((a_DataTypes & cBlockArea::baBlockEntities) != 0)
{
for (const auto & keyPair: a_Area.GetBlockEntities())
{
auto & be = keyPair.second;
auto posX = be->GetPosX() + a_MinBlockX;
auto posY = be->GetPosY() + a_MinBlockY;
auto posZ = be->GetPosZ() + a_MinBlockZ;
if (
(posX < m_PosX * cChunkDef::Width) || (posX >= m_PosX * cChunkDef::Width + cChunkDef::Width) ||
(posZ < m_PosZ * cChunkDef::Width) || (posZ >= m_PosZ * cChunkDef::Width + cChunkDef::Width)
)
{
continue;
}
// This block entity is inside the chunk, clone it (and remove any that is there currently):
auto idx = static_cast<size_t>(MakeIndex(posX - m_PosX * cChunkDef::Width, posY, posZ - m_PosZ * cChunkDef::Width));
auto itr = m_BlockEntities.find(idx);
if (itr != m_BlockEntities.end())
{
m_BlockEntities.erase(itr);
}
auto clone = be->Clone({posX, posY, posZ});
clone->SetWorld(m_World);
AddBlockEntityClean(clone);
m_World->BroadcastBlockEntity({posX, posY, posZ});
}
}
}
bool cChunk::HasBlockEntityAt(Vector3i a_BlockPos)
{
return (GetBlockEntity(a_BlockPos) != nullptr);
}
void cChunk::Stay(bool a_Stay)
{
m_StayCount += (a_Stay ? 1 : -1);
ASSERT(m_StayCount >= 0);
}
void cChunk::CollectMobCensus(cMobCensus & toFill)
{
toFill.CollectSpawnableChunk(*this);
std::vector<Vector3d> PlayerPositions;
PlayerPositions.reserve(m_LoadedByClient.size());
for (auto ClientHandle : m_LoadedByClient)
{
const cPlayer * currentPlayer = ClientHandle->GetPlayer();
PlayerPositions.push_back(currentPlayer->GetPosition());
}
Vector3d currentPosition;
for (auto & entity : m_Entities)
{
// LOGD("Counting entity #%i (%s)", (*itr)->GetUniqueID(), (*itr)->GetClass());
if (entity->IsMob())
{
auto & Monster = static_cast<cMonster &>(*entity);
currentPosition = Monster.GetPosition();
for (const auto & PlayerPos : PlayerPositions)
{
toFill.CollectMob(Monster, *this, (currentPosition - PlayerPos).SqrLength());
}
}
} // for itr - m_Entitites[]
}
void cChunk::GetThreeRandomNumbers(int & a_X, int & a_Y, int & a_Z, int a_MaxX, int a_MaxY, int a_MaxZ)
{
ASSERT(
(a_MaxX > 0) && (a_MaxY > 0) && (a_MaxZ > 0) &&
(a_MaxX <= std::numeric_limits<int>::max() / a_MaxY) && // a_MaxX * a_MaxY doesn't overflow
(a_MaxX * a_MaxY <= std::numeric_limits<int>::max() / a_MaxZ) // a_MaxX * a_MaxY * a_MaxZ doesn't overflow
);
// MTRand gives an inclusive range [0, Max] but this gives the exclusive range [0, Max)
int OverallMax = (a_MaxX * a_MaxY * a_MaxZ) - 1;
int Random = m_World->GetTickRandomNumber(OverallMax);
a_X = Random % a_MaxX;
a_Y = (Random / a_MaxX) % a_MaxY;
a_Z = ((Random / a_MaxX) / a_MaxY) % a_MaxZ;
}
void cChunk::GetRandomBlockCoords(int & a_X, int & a_Y, int & a_Z)
{
// MG TODO : check if this kind of optimization (only one random call) is still needed
// MG TODO : if so propagate it
GetThreeRandomNumbers(a_X, a_Y, a_Z, Width, Height - 2, Width);
a_Y++;
}
void cChunk::SpawnMobs(cMobSpawner & a_MobSpawner)
{
int CenterX, CenterY, CenterZ;
GetRandomBlockCoords(CenterX, CenterY, CenterZ);
BLOCKTYPE PackCenterBlock = GetBlock(CenterX, CenterY, CenterZ);
if (!a_MobSpawner.CheckPackCenter(PackCenterBlock))
{
return;
}
a_MobSpawner.NewPack();
int NumberOfTries = 0;
int NumberOfSuccess = 0;
int MaxNbOfSuccess = 4; // This can be changed during the process for Wolves and Ghasts
while ((NumberOfTries < 12) && (NumberOfSuccess < MaxNbOfSuccess))
{
const int HorizontalRange = 20; // MG TODO : relocate
const int VerticalRange = 0; // MG TODO : relocate
int TryX, TryY, TryZ;
GetThreeRandomNumbers(TryX, TryY, TryZ, 2 * HorizontalRange + 1, 2 * VerticalRange + 1, 2 * HorizontalRange + 1);
TryX -= HorizontalRange;
TryY -= VerticalRange;
TryZ -= HorizontalRange;
TryX += CenterX;
TryY += CenterY;
TryZ += CenterZ;
ASSERT(TryY > 0);
ASSERT(TryY < cChunkDef::Height - 1);
EMCSBiome Biome = m_ChunkMap->GetBiomeAt(TryX, TryZ);
// MG TODO :
// Moon cycle (for slime)
// check player and playerspawn presence < 24 blocks
// check mobs presence on the block
// MG TODO : check that "Level" really means Y
/*
NIBBLETYPE SkyLight = 0;
NIBBLETYPE BlockLight = 0;
*/
NumberOfTries++;
if (!IsLightValid())
{
continue;
}
auto newMob = a_MobSpawner.TryToSpawnHere(this, {TryX, TryY, TryZ}, Biome, MaxNbOfSuccess);
if (newMob == nullptr)
{
continue;
}
int WorldX, WorldY, WorldZ;
PositionToWorldPosition(TryX, TryY, TryZ, WorldX, WorldY, WorldZ);
double ActualX = WorldX + 0.5;
double ActualZ = WorldZ + 0.5;
newMob->SetPosition(ActualX, WorldY, ActualZ);
FLOGD("Spawning {0} #{1} at {2}", newMob->GetClass(), newMob->GetUniqueID(), Vector3i{WorldX, WorldY, WorldZ});
NumberOfSuccess++;
} // while (retry)
}
void cChunk::Tick(std::chrono::milliseconds a_Dt)
{
// If we are not valid, tick players and bailout
if (!IsValid())
{
for (const auto & Entity : m_Entities)
{
if (Entity->IsPlayer())
{
Entity->Tick(a_Dt, *this);
}
}
return;
}
BroadcastPendingBlockChanges();
CheckBlocks();
// Tick simulators:
m_World->GetSimulatorManager()->SimulateChunk(a_Dt, m_PosX, m_PosZ, this);
TickBlocks();
// Tick all block entities in this chunk:
for (auto & KeyPair : m_BlockEntities)
{
m_IsDirty = KeyPair.second->Tick(a_Dt, *this) | m_IsDirty;
}
for (auto itr = m_Entities.begin(); itr != m_Entities.end();)
{
// Do not tick mobs that are detached from the world. They're either scheduled for teleportation or for removal.
if (!(*itr)->IsTicking())
{
++itr;
continue;
}
if (!((*itr)->IsMob())) // Mobs are ticked inside cWorld::TickMobs() (as we don't have to tick them if they are far away from players)
{
// Tick all entities in this chunk (except mobs):
ASSERT((*itr)->GetParentChunk() == this);
(*itr)->Tick(a_Dt, *this);
ASSERT((*itr)->GetParentChunk() == this);
}
// Do not move mobs that are detached from the world to neighbors. They're either scheduled for teleportation or for removal.
// Because the schedulded destruction is going to look for them in this chunk. See cEntity::destroy.
if (!(*itr)->IsTicking())
{
++itr;
continue;
}
if (
((*itr)->GetChunkX() != m_PosX) ||
((*itr)->GetChunkZ() != m_PosZ)
)
{
// Mark as dirty if it was a server-generated entity:
if (!(*itr)->IsPlayer())
{
MarkDirty();
}
// This block is very similar to RemoveEntity, except it uses an iterator to avoid scanning the whole m_Entities
// The entity moved out of the chunk, move it to the neighbor
(*itr)->SetParentChunk(nullptr);
MoveEntityToNewChunk(std::move(*itr));
itr = m_Entities.erase(itr);
}
else
{
++itr;
}
} // for itr - m_Entitites[]
ApplyWeatherToTop();
}
void cChunk::TickBlock(int a_RelX, int a_RelY, int a_RelZ)
{
cBlockHandler * Handler = BlockHandler(GetBlock(a_RelX, a_RelY, a_RelZ));
ASSERT(Handler != nullptr); // Happenned on server restart, FS #243
cChunkInterface ChunkInterface(this->GetWorld()->GetChunkMap());
cBlockInServerPluginInterface PluginInterface(*this->GetWorld());
Handler->OnUpdate(ChunkInterface, *this->GetWorld(), PluginInterface, *this, a_RelX, a_RelY, a_RelZ);
}
void cChunk::MoveEntityToNewChunk(OwnedEntity a_Entity)
{
cChunk * Neighbor = GetNeighborChunk(a_Entity->GetChunkX() * cChunkDef::Width, a_Entity->GetChunkZ() * cChunkDef::Width);
if (Neighbor == nullptr)
{
Neighbor = m_ChunkMap->GetChunk(a_Entity->GetChunkX(), a_Entity->GetChunkZ());
if (Neighbor == nullptr) // This will assert inside GetChunk in debug builds
{
LOGWARNING("%s: Failed to move entity, destination chunk unreachable. Entity lost", __FUNCTION__);
return;
}
}
ASSERT(Neighbor != this); // Moving into the same chunk? wtf?
auto & Entity = *a_Entity;
Neighbor->AddEntity(std::move(a_Entity));
class cMover :
public cClientDiffCallback
{
virtual void Removed(cClientHandle * a_Client) override
{
a_Client->SendDestroyEntity(m_Entity);
}
virtual void Added(cClientHandle * a_Client) override
{
m_Entity.SpawnOn(*a_Client);
}
cEntity & m_Entity;
public:
cMover(cEntity & a_CallbackEntity) :
m_Entity(a_CallbackEntity)
{}
} Mover(Entity);
m_ChunkMap->CompareChunkClients(this, Neighbor, Mover);
}
void cChunk::BroadcastPendingBlockChanges(void)
{
if (m_PendingSendBlocks.empty())
{
return;
}
if (m_PendingSendBlocks.size() >= 10240)
{
// Resend the full chunk
for (auto ClientHandle : m_LoadedByClient)
{
m_World->ForceSendChunkTo(m_PosX, m_PosZ, cChunkSender::E_CHUNK_PRIORITY_MEDIUM, ClientHandle);
}
}
else
{
// Only send block changes
for (auto ClientHandle : m_LoadedByClient)
{
ClientHandle->SendBlockChanges(m_PosX, m_PosZ, m_PendingSendBlocks);
}
}
m_PendingSendBlocks.clear();
}
void cChunk::CheckBlocks()
{
if (m_ToTickBlocks.empty())
{
return;
}
std::vector<Vector3i> ToTickBlocks;
std::swap(m_ToTickBlocks, ToTickBlocks);
cChunkInterface ChunkInterface(m_World->GetChunkMap());
cBlockInServerPluginInterface PluginInterface(*m_World);
for (std::vector<Vector3i>::const_iterator itr = ToTickBlocks.begin(), end = ToTickBlocks.end(); itr != end; ++itr)
{
Vector3i Pos = (*itr);
cBlockHandler * Handler = BlockHandler(GetBlock(Pos));
Handler->Check(ChunkInterface, PluginInterface, Pos, *this);
} // for itr - ToTickBlocks[]
}
void cChunk::TickBlocks(void)
{
// Tick dem blocks
// _X: We must limit the random number or else we get a nasty int overflow bug - https://forum.cuberite.org/thread-457.html
int RandomX = m_World->GetTickRandomNumber(0x00ffffff);
int RandomY = m_World->GetTickRandomNumber(0x00ffffff);
int RandomZ = m_World->GetTickRandomNumber(0x00ffffff);
int TickX = m_BlockTickX;
int TickY = m_BlockTickY;
int TickZ = m_BlockTickZ;
cChunkInterface ChunkInterface(this->GetWorld()->GetChunkMap());
cBlockInServerPluginInterface PluginInterface(*this->GetWorld());
// This for loop looks disgusting, but it actually does a simple thing - first processes m_BlockTick, then adds random to it
// This is so that SetNextBlockTick() works
for (int i = 0; i < 50; i++,
// This weird construct (*2, then /2) is needed,
// otherwise the blocktick distribution is too biased towards even coords!
TickX = (TickX + RandomX) % (Width * 2),
TickY = (TickY + RandomY) % (Height * 2),
TickZ = (TickZ + RandomZ) % (Width * 2),
m_BlockTickX = TickX / 2,
m_BlockTickY = TickY / 2,
m_BlockTickZ = TickZ / 2
)
{
if (m_BlockTickY > cChunkDef::GetHeight(m_HeightMap, m_BlockTickX, m_BlockTickZ))
{
continue; // It's all air up here
}
cBlockHandler * Handler = BlockHandler(GetBlock(m_BlockTickX, m_BlockTickY, m_BlockTickZ));
ASSERT(Handler != nullptr); // Happenned on server restart, FS #243
Handler->OnUpdate(ChunkInterface, *this->GetWorld(), PluginInterface, *this, m_BlockTickX, m_BlockTickY, m_BlockTickZ);
} // for i - tickblocks
}
void cChunk::ApplyWeatherToTop()
{
if (
(GetRandomProvider().RandBool(0.99)) ||
(
(m_World->GetWeather() != eWeather_Rain) &&
(m_World->GetWeather() != eWeather_ThunderStorm)
)
)
{
// Not the right weather, or not at this tick; bail out
return;
}
int X = m_World->GetTickRandomNumber(15);
int Z = m_World->GetTickRandomNumber(15);
int Height = GetHeight(X, Z);
if (GetSnowStartHeight(GetBiomeAt(X, Z)) > Height)
{
return;
}
if (GetBlockLight(X, Height, Z) > 10)
{
// Snow only generates on blocks with a block light level of 10 or less.
// Ref: https://minecraft.gamepedia.com/Snow_(layer)#Snowfall
return;
}
BLOCKTYPE TopBlock = GetBlock(X, Height, Z);
NIBBLETYPE TopMeta = GetMeta (X, Height, Z);
if (m_World->IsDeepSnowEnabled() && (TopBlock == E_BLOCK_SNOW))
{
int MaxSize = 7;
BLOCKTYPE BlockType[4];
NIBBLETYPE BlockMeta[4];
UnboundedRelGetBlock(X - 1, Height, Z, BlockType[0], BlockMeta[0]);
UnboundedRelGetBlock(X + 1, Height, Z, BlockType[1], BlockMeta[1]);
UnboundedRelGetBlock(X, Height, Z - 1, BlockType[2], BlockMeta[2]);
UnboundedRelGetBlock(X, Height, Z + 1, BlockType[3], BlockMeta[3]);
for (int i = 0; i < 4; i++)
{
switch (BlockType[i])
{
case E_BLOCK_AIR:
{
MaxSize = 0;
break;
}
case E_BLOCK_SNOW:
{
MaxSize = std::min(BlockMeta[i] + 1, MaxSize);
break;
}
}
}
if (TopMeta < MaxSize)
{
FastSetBlock(X, Height, Z, E_BLOCK_SNOW, TopMeta + 1);
}
else if (TopMeta > MaxSize)
{
FastSetBlock(X, Height, Z, E_BLOCK_SNOW, TopMeta - 1);
}
}
else if (cBlockInfo::IsSnowable(TopBlock) && (Height < cChunkDef::Height - 1))
{
SetBlock({X, Height + 1, Z}, E_BLOCK_SNOW, 0);
}
else if (IsBlockWater(TopBlock) && (TopMeta == 0))
{
SetBlock({X, Height, Z}, E_BLOCK_ICE, 0);
}
else if (
(m_World->IsDeepSnowEnabled()) &&
(
(TopBlock == E_BLOCK_RED_ROSE) ||
(TopBlock == E_BLOCK_YELLOW_FLOWER) ||
(TopBlock == E_BLOCK_RED_MUSHROOM) ||
(TopBlock == E_BLOCK_BROWN_MUSHROOM)
)
)
{
SetBlock({X, Height, Z}, E_BLOCK_SNOW, 0);
}
}
cItems cChunk::PickupsFromBlock(Vector3i a_RelPos, const cEntity * a_Digger, const cItem * a_Tool)
{
BLOCKTYPE blockType;
NIBBLETYPE blockMeta;
GetBlockTypeMeta(a_RelPos, blockType, blockMeta);
auto blockHandler = cBlockInfo::GetHandler(blockType);
auto blockEntity = GetBlockEntityRel(a_RelPos);
auto pickups = blockHandler->ConvertToPickups(blockMeta, blockEntity, a_Digger, a_Tool);
auto absPos = RelativeToAbsolute(a_RelPos);
cRoot::Get()->GetPluginManager()->CallHookBlockToPickups(*m_World, absPos, blockType, blockMeta, blockEntity, a_Digger, a_Tool, pickups);
return pickups;
}
int cChunk::GrowPlantAt(Vector3i a_RelPos, int a_NumStages)
{
auto blockHandler = BlockHandler(GetBlock(a_RelPos));
return blockHandler->Grow(*this, a_RelPos, a_NumStages);
}
bool cChunk::UnboundedRelGetBlock(Vector3i a_RelPos, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const
{
if (!cChunkDef::IsValidHeight(a_RelPos.y))
{