150 private static int $worldIdCounter = 1;
152 public const Y_MAX = 320;
153 public const Y_MIN = -64;
155 public const TIME_DAY = 1000;
156 public const TIME_NOON = 6000;
157 public const TIME_SUNSET = 12000;
158 public const TIME_NIGHT = 13000;
159 public const TIME_MIDNIGHT = 18000;
160 public const TIME_SUNRISE = 23000;
162 public const TIME_FULL = 24000;
164 public const DIFFICULTY_PEACEFUL = 0;
165 public const DIFFICULTY_EASY = 1;
166 public const DIFFICULTY_NORMAL = 2;
167 public const DIFFICULTY_HARD = 3;
169 public const DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK = 3;
172 private const BLOCK_CACHE_SIZE_CAP = 2048;
178 private array $players = [];
184 private array $entities = [];
189 private array $entityLastKnownPositions = [];
195 private array $entitiesByChunk = [];
201 public array $updateEntities = [];
203 private bool $inDynamicStateRecalculation =
false;
208 private array $blockCache = [];
209 private int $blockCacheSize = 0;
214 private array $blockCollisionBoxCache = [];
216 private int $sendTimeTicker = 0;
218 private int $worldId;
220 private int $providerGarbageCollectionTicker = 0;
229 private array $registeredTickingChunks = [];
237 private array $validTickingChunks = [];
244 private array $recheckTickingChunks = [];
250 private array $chunkLoaders = [];
256 private array $chunkListeners = [];
261 private array $playerChunkListeners = [];
267 private array $packetBuffersByChunk = [];
273 private array $unloadQueue = [];
276 public bool $stopTime =
false;
278 private float $sunAnglePercentage = 0.0;
279 private int $skyLightReduction = 0;
281 private string $folderName;
282 private string $displayName;
288 private array $chunks = [];
294 private array $changedBlocks = [];
302 private array $scheduledBlockUpdateQueueIndex = [];
305 private \SplQueue $neighbourBlockUpdateQueue;
310 private array $neighbourBlockUpdateQueueIndex = [];
316 private array $activeChunkPopulationTasks = [];
321 private array $chunkLock = [];
322 private int $maxConcurrentChunkPopulationTasks = 2;
327 private array $chunkPopulationRequestMap = [];
332 private \SplQueue $chunkPopulationRequestQueue;
337 private array $chunkPopulationRequestQueueIndex = [];
343 private array $generatorRegisteredWorkers = [];
345 private bool $autoSave =
true;
347 private int $sleepTicks = 0;
349 private int $chunkTickRadius;
350 private int $tickedBlocksPerSubchunkPerTick = self::DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK;
355 private array $randomTickBlocks = [];
359 public float $tickRateTime = 0;
361 private bool $doingTick =
false;
364 private string $generator;
366 private bool $unloaded =
false;
371 private array $unloadCallbacks = [];
376 private \Logger $logger;
382 return morton2d_encode($x, $z);
385 private const MORTON3D_BIT_SIZE = 21;
386 private const BLOCKHASH_Y_BITS = 9;
387 private const BLOCKHASH_Y_PADDING = 64;
388 private const BLOCKHASH_Y_OFFSET = self::BLOCKHASH_Y_PADDING - self::Y_MIN;
389 private const BLOCKHASH_Y_MASK = (1 << self::BLOCKHASH_Y_BITS) - 1;
390 private const BLOCKHASH_XZ_MASK = (1 << self::MORTON3D_BIT_SIZE) - 1;
391 private const BLOCKHASH_XZ_EXTRA_BITS = (self::MORTON3D_BIT_SIZE - self::BLOCKHASH_Y_BITS) >> 1;
392 private const BLOCKHASH_XZ_EXTRA_MASK = (1 << self::BLOCKHASH_XZ_EXTRA_BITS) - 1;
393 private const BLOCKHASH_XZ_SIGN_SHIFT = 64 - self::MORTON3D_BIT_SIZE - self::BLOCKHASH_XZ_EXTRA_BITS;
394 private const BLOCKHASH_X_SHIFT = self::BLOCKHASH_Y_BITS;
395 private const BLOCKHASH_Z_SHIFT = self::BLOCKHASH_X_SHIFT + self::BLOCKHASH_XZ_EXTRA_BITS;
400 public static function blockHash(
int $x,
int $y,
int $z) : int{
401 $shiftedY = $y + self::BLOCKHASH_Y_OFFSET;
402 if(($shiftedY & (~0 << self::BLOCKHASH_Y_BITS)) !== 0){
403 throw new \InvalidArgumentException(
"Y coordinate $y is out of range!");
408 return morton3d_encode(
409 $x & self::BLOCKHASH_XZ_MASK,
411 ((($x >> self::MORTON3D_BIT_SIZE) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::BLOCKHASH_X_SHIFT) |
412 ((($z >> self::MORTON3D_BIT_SIZE) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::BLOCKHASH_Z_SHIFT),
413 $z & self::BLOCKHASH_XZ_MASK
421 return morton3d_encode($x, $y, $z);
430 public static function getBlockXYZ(
int $hash, ?
int &$x, ?
int &$y, ?
int &$z) : void{
431 [$baseX, $baseY, $baseZ] = morton3d_decode($hash);
433 $extraX = ((($baseY >> self::BLOCKHASH_X_SHIFT) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::MORTON3D_BIT_SIZE);
434 $extraZ = ((($baseY >> self::BLOCKHASH_Z_SHIFT) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::MORTON3D_BIT_SIZE);
436 $x = (($baseX & self::BLOCKHASH_XZ_MASK) | $extraX) << self::BLOCKHASH_XZ_SIGN_SHIFT >> self::BLOCKHASH_XZ_SIGN_SHIFT;
437 $y = ($baseY & self::BLOCKHASH_Y_MASK) - self::BLOCKHASH_Y_OFFSET;
438 $z = (($baseZ & self::BLOCKHASH_XZ_MASK) | $extraZ) << self::BLOCKHASH_XZ_SIGN_SHIFT >> self::BLOCKHASH_XZ_SIGN_SHIFT;
446 public static function getXZ(
int $hash, ?
int &$x, ?
int &$z) : void{
447 [$x, $z] = morton2d_decode($hash);
450 public static function getDifficultyFromString(
string $str) : int{
451 switch(strtolower(trim($str))){
455 return World::DIFFICULTY_PEACEFUL;
460 return World::DIFFICULTY_EASY;
465 return World::DIFFICULTY_NORMAL;
470 return World::DIFFICULTY_HARD;
485 $this->folderName = $name;
486 $this->worldId = self::$worldIdCounter++;
488 $this->displayName = $this->provider->getWorldData()->getName();
489 $this->logger = new \PrefixedLogger($server->getLogger(),
"World: $this->displayName");
491 $this->minY = $this->provider->getWorldMinY();
492 $this->maxY = $this->provider->getWorldMaxY();
494 $this->
server->getLogger()->info($this->
server->getLanguage()->translate(KnownTranslationFactory::pocketmine_level_preparing($this->displayName)));
495 $generator = GeneratorManager::getInstance()->getGenerator($this->provider->getWorldData()->getGenerator()) ??
496 throw new AssumptionFailedError(
"WorldManager should already have checked that the generator exists");
497 $generator->validateGeneratorOptions($this->provider->getWorldData()->getGeneratorOptions());
498 $this->generator = $generator->getGeneratorClass();
499 $this->chunkPopulationRequestQueue = new \SplQueue();
500 $this->addOnUnloadCallback(
function() :
void{
501 $this->logger->debug(
"Cancelling unfulfilled generation requests");
503 foreach($this->chunkPopulationRequestMap as $chunkHash => $promise){
505 unset($this->chunkPopulationRequestMap[$chunkHash]);
507 if(count($this->chunkPopulationRequestMap) !== 0){
515 $this->scheduledBlockUpdateQueue->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
517 $this->neighbourBlockUpdateQueue = new \SplQueue();
519 $this->time = $this->provider->getWorldData()->getTime();
521 $cfg = $this->
server->getConfigGroup();
522 $this->chunkTickRadius = min($this->
server->getViewDistance(), max(0, $cfg->getPropertyInt(YmlServerProperties::CHUNK_TICKING_TICK_RADIUS, 4)));
523 if($cfg->getPropertyInt(
"chunk-ticking.per-tick", 40) <= 0){
525 $this->logger->warning(
"\"chunk-ticking.per-tick\" setting is deprecated, but you've used it to disable chunk ticking. Set \"chunk-ticking.tick-radius\" to 0 in \"pocketmine.yml\" instead.");
526 $this->chunkTickRadius = 0;
528 $this->tickedBlocksPerSubchunkPerTick = $cfg->getPropertyInt(YmlServerProperties::CHUNK_TICKING_BLOCKS_PER_SUBCHUNK_PER_TICK, self::DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK);
529 $this->maxConcurrentChunkPopulationTasks = $cfg->getPropertyInt(YmlServerProperties::CHUNK_GENERATION_POPULATION_QUEUE_SIZE, 2);
531 $this->initRandomTickBlocksFromConfig($cfg);
535 $this->workerPool->addWorkerStartHook($workerStartHook =
function(
int $workerId) :
void{
536 if(array_key_exists($workerId, $this->generatorRegisteredWorkers)){
537 $this->logger->debug(
"Worker $workerId with previously registered generator restarted, flagging as unregistered");
538 unset($this->generatorRegisteredWorkers[$workerId]);
541 $workerPool = $this->workerPool;
542 $this->addOnUnloadCallback(
static function() use ($workerPool, $workerStartHook) :
void{
548 $dontTickBlocks = [];
549 $parser = StringToItemParser::getInstance();
550 foreach($cfg->getProperty(YmlServerProperties::CHUNK_TICKING_DISABLE_BLOCK_TICKING, []) as $name){
551 $name = (string) $name;
552 $item = $parser->parse($name);
554 $block = $item->getBlock();
555 }elseif(preg_match(
"/^-?\d+$/", $name) === 1){
558 $blockStateData = GlobalBlockStateHandlers::getUpgrader()->upgradeIntIdMeta((
int) $name, 0);
559 }
catch(BlockStateDeserializeException){
562 $block = RuntimeBlockStateRegistry::getInstance()->fromStateId(GlobalBlockStateHandlers::getDeserializer()->deserialize($blockStateData));
568 if($block->getTypeId() !== BlockTypeIds::AIR){
569 $dontTickBlocks[$block->getTypeId()] = $name;
573 foreach(RuntimeBlockStateRegistry::getInstance()->getAllKnownStates() as $state){
574 $dontTickName = $dontTickBlocks[$state->getTypeId()] ??
null;
575 if($dontTickName ===
null && $state->ticksRandomly()){
576 $this->randomTickBlocks[$state->getStateId()] =
true;
581 public function getTickRateTime() : float{
582 return $this->tickRateTime;
585 public function registerGeneratorToWorker(
int $worker) : void{
586 $this->logger->debug(
"Registering generator on worker $worker");
587 $this->workerPool->submitTaskToWorker(
new GeneratorRegisterTask($this, $this->generator, $this->provider->getWorldData()->getGeneratorOptions()), $worker);
588 $this->generatorRegisteredWorkers[$worker] =
true;
591 public function unregisterGenerator() : void{
592 foreach($this->workerPool->getRunningWorkers() as $i){
593 if(isset($this->generatorRegisteredWorkers[$i])){
594 $this->workerPool->submitTaskToWorker(
new GeneratorUnregisterTask($this), $i);
597 $this->generatorRegisteredWorkers = [];
600 public function getServer() : Server{
604 public function getLogger() : \
Logger{
605 return $this->logger;
608 final public function getProvider() : WritableWorldProvider{
609 return $this->provider;
615 final public function getId() : int{
616 return $this->worldId;
619 public function isLoaded() : bool{
620 return !$this->unloaded;
626 public function onUnload() : void{
628 throw new \LogicException(
"Tried to close a world which is already closed");
631 foreach($this->unloadCallbacks as $callback){
634 $this->unloadCallbacks = [];
636 foreach($this->chunks as $chunkHash => $chunk){
637 self::getXZ($chunkHash, $chunkX, $chunkZ);
638 $this->unloadChunk($chunkX, $chunkZ,
false);
640 foreach($this->entitiesByChunk as $chunkHash => $entities){
641 self::getXZ($chunkHash, $chunkX, $chunkZ);
644 foreach($entities as $entity){
645 if(!$entity->isFlaggedForDespawn()){
650 if($leakedEntities !== 0){
651 $this->logger->warning(
"$leakedEntities leaked entities found in ungenerated chunk $chunkX $chunkZ during unload, they won't be saved!");
657 $this->unregisterGenerator();
659 $this->provider->close();
660 $this->blockCache = [];
661 $this->blockCacheSize = 0;
662 $this->blockCollisionBoxCache = [];
664 $this->unloaded =
true;
669 $this->unloadCallbacks[spl_object_id($callback)] = $callback;
674 unset($this->unloadCallbacks[spl_object_id($callback)]);
685 private function filterViewersForPosition(
Vector3 $pos, array $allowed) : array{
686 $candidates = $this->getViewersForPosition($pos);
688 foreach($allowed as $player){
689 $k = spl_object_id($player);
690 if(isset($candidates[$k])){
691 $filtered[$k] = $candidates[$k];
702 $players ??= $this->getViewersForPosition($pos);
704 if(WorldSoundEvent::hasHandlers()){
707 if($ev->isCancelled()){
711 $sound = $ev->getSound();
712 $players = $ev->getRecipients();
715 $pk = $sound->
encode($pos);
717 if($players === $this->getViewersForPosition($pos)){
719 $this->broadcastPacketToViewers($pos, $e);
722 NetworkBroadcastUtils::broadcastPackets($this->filterViewersForPosition($pos, $players), $pk);
731 $players ??= $this->getViewersForPosition($pos);
733 if(WorldParticleEvent::hasHandlers()){
736 if($ev->isCancelled()){
740 $particle = $ev->getParticle();
741 $players = $ev->getRecipients();
744 $pk = $particle->
encode($pos);
746 if($players === $this->getViewersForPosition($pos)){
748 $this->broadcastPacketToViewers($pos, $e);
751 NetworkBroadcastUtils::broadcastPackets($this->filterViewersForPosition($pos, $players), $pk);
756 public function getAutoSave() : bool{
757 return $this->autoSave;
760 public function setAutoSave(
bool $value) : void{
761 $this->autoSave = $value;
774 return $this->playerChunkListeners[
World::chunkHash($chunkX, $chunkZ)] ?? [];
784 return $this->chunkLoaders[
World::chunkHash($chunkX, $chunkZ)] ?? [];
794 return $this->getChunkPlayers($pos->getFloorX() >>
Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >>
Chunk::COORD_BIT_SIZE);
801 $this->broadcastPacketToPlayersUsingChunk($pos->getFloorX() >>
Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >>
Chunk::COORD_BIT_SIZE, $packet);
804 private function broadcastPacketToPlayersUsingChunk(
int $chunkX,
int $chunkZ,
ClientboundPacket $packet) : void{
805 if(!isset($this->packetBuffersByChunk[$index =
World::chunkHash($chunkX, $chunkZ)])){
806 $this->packetBuffersByChunk[$index] = [$packet];
808 $this->packetBuffersByChunk[$index][] = $packet;
812 public function registerChunkLoader(ChunkLoader $loader,
int $chunkX,
int $chunkZ,
bool $autoLoad =
true) : void{
813 $loaderId = spl_object_id($loader);
815 if(!isset($this->chunkLoaders[$chunkHash = World::chunkHash($chunkX, $chunkZ)])){
816 $this->chunkLoaders[$chunkHash] = [];
817 }elseif(isset($this->chunkLoaders[$chunkHash][$loaderId])){
821 $this->chunkLoaders[$chunkHash][$loaderId] = $loader;
823 $this->cancelUnloadChunkRequest($chunkX, $chunkZ);
826 $this->loadChunk($chunkX, $chunkZ);
830 public function unregisterChunkLoader(ChunkLoader $loader,
int $chunkX,
int $chunkZ) : void{
831 $chunkHash = World::chunkHash($chunkX, $chunkZ);
832 $loaderId = spl_object_id($loader);
833 if(isset($this->chunkLoaders[$chunkHash][$loaderId])){
834 if(count($this->chunkLoaders[$chunkHash]) === 1){
835 unset($this->chunkLoaders[$chunkHash]);
836 $this->unloadChunkRequest($chunkX, $chunkZ,
true);
837 if(isset($this->chunkPopulationRequestMap[$chunkHash]) && !isset($this->activeChunkPopulationTasks[$chunkHash])){
838 $this->chunkPopulationRequestMap[$chunkHash]->reject();
839 unset($this->chunkPopulationRequestMap[$chunkHash]);
842 unset($this->chunkLoaders[$chunkHash][$loaderId]);
851 $hash =
World::chunkHash($chunkX, $chunkZ);
852 if(isset($this->chunkListeners[$hash])){
853 $this->chunkListeners[$hash][spl_object_id($listener)] = $listener;
855 $this->chunkListeners[$hash] = [spl_object_id($listener) => $listener];
857 if($listener instanceof
Player){
858 $this->playerChunkListeners[$hash][spl_object_id($listener)] = $listener;
868 $hash =
World::chunkHash($chunkX, $chunkZ);
869 if(isset($this->chunkListeners[$hash])){
870 if(count($this->chunkListeners[$hash]) === 1){
871 unset($this->chunkListeners[$hash]);
872 unset($this->playerChunkListeners[$hash]);
874 unset($this->chunkListeners[$hash][spl_object_id($listener)]);
875 unset($this->playerChunkListeners[$hash][spl_object_id($listener)]);
884 foreach($this->chunkListeners as $hash => $listeners){
885 World::getXZ($hash, $chunkX, $chunkZ);
886 $this->unregisterChunkListener($listener, $chunkX, $chunkZ);
897 return $this->chunkListeners[
World::chunkHash($chunkX, $chunkZ)] ?? [];
903 public function sendTime(
Player ...$targets) : void{
904 if(count($targets) === 0){
905 $targets = $this->players;
907 foreach($targets as $player){
908 $player->getNetworkSession()->syncWorldTime($this->time);
912 public function isDoingTick() : bool{
913 return $this->doingTick;
919 public function doTick(
int $currentTick) : void{
921 throw new \LogicException(
"Attempted to tick a world which has been closed");
924 $this->timings->doTick->startTiming();
925 $this->doingTick =
true;
927 $this->actuallyDoTick($currentTick);
929 $this->doingTick =
false;
930 $this->timings->doTick->stopTiming();
934 protected function actuallyDoTick(
int $currentTick) : void{
935 if(!$this->stopTime){
937 if($this->time === PHP_INT_MAX){
938 $this->time = PHP_INT_MIN;
944 $this->sunAnglePercentage = $this->computeSunAnglePercentage();
945 $this->skyLightReduction = $this->computeSkyLightReduction();
947 if(++$this->sendTimeTicker === 200){
949 $this->sendTimeTicker = 0;
952 $this->unloadChunks();
953 if(++$this->providerGarbageCollectionTicker >= 6000){
954 $this->provider->doGarbageCollection();
955 $this->providerGarbageCollectionTicker = 0;
958 $this->timings->scheduledBlockUpdates->startTiming();
960 while($this->scheduledBlockUpdateQueue->count() > 0 && $this->scheduledBlockUpdateQueue->current()[
"priority"] <= $currentTick){
962 $vec = $this->scheduledBlockUpdateQueue->extract()[
"data"];
963 unset($this->scheduledBlockUpdateQueueIndex[World::blockHash($vec->x, $vec->y, $vec->z)]);
964 if(!$this->isInLoadedTerrain($vec)){
967 $block = $this->getBlock($vec);
968 $block->onScheduledUpdate();
970 $this->timings->scheduledBlockUpdates->stopTiming();
972 $this->timings->neighbourBlockUpdates->startTiming();
974 while($this->neighbourBlockUpdateQueue->count() > 0){
975 $index = $this->neighbourBlockUpdateQueue->dequeue();
976 unset($this->neighbourBlockUpdateQueueIndex[$index]);
977 World::getBlockXYZ($index, $x, $y, $z);
978 if(!$this->isChunkLoaded($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)){
982 $block = $this->getBlockAt($x, $y, $z);
984 if(BlockUpdateEvent::hasHandlers()){
985 $ev =
new BlockUpdateEvent($block);
987 if($ev->isCancelled()){
991 foreach($this->getNearbyEntities(AxisAlignedBB::one()->offset($x, $y, $z)) as $entity){
992 $entity->onNearbyBlockChange();
994 $block->onNearbyBlockChange();
997 $this->timings->neighbourBlockUpdates->stopTiming();
999 $this->timings->entityTick->startTiming();
1001 foreach($this->updateEntities as $id => $entity){
1002 if($entity->isClosed() || $entity->isFlaggedForDespawn() || !$entity->onUpdate($currentTick)){
1003 unset($this->updateEntities[$id]);
1005 if($entity->isFlaggedForDespawn()){
1009 $this->timings->entityTick->stopTiming();
1011 $this->timings->randomChunkUpdates->startTiming();
1012 $this->tickChunks();
1013 $this->timings->randomChunkUpdates->stopTiming();
1015 $this->executeQueuedLightUpdates();
1017 if(count($this->changedBlocks) > 0){
1018 if(count($this->players) > 0){
1019 foreach($this->changedBlocks as $index => $blocks){
1020 if(count($blocks) === 0){
1023 World::getXZ($index, $chunkX, $chunkZ);
1024 if(!$this->isChunkLoaded($chunkX, $chunkZ)){
1028 if(count($blocks) > 512){
1029 $chunk = $this->getChunk($chunkX, $chunkZ) ??
throw new AssumptionFailedError(
"We already checked that the chunk is loaded");
1030 foreach($this->getChunkPlayers($chunkX, $chunkZ) as $p){
1031 $p->onChunkChanged($chunkX, $chunkZ, $chunk);
1034 foreach($this->createBlockUpdatePackets($blocks) as $packet){
1035 $this->broadcastPacketToPlayersUsingChunk($chunkX, $chunkZ, $packet);
1041 $this->changedBlocks = [];
1045 if($this->sleepTicks > 0 && --$this->sleepTicks <= 0){
1046 $this->checkSleep();
1049 foreach($this->packetBuffersByChunk as $index => $entries){
1050 World::getXZ($index, $chunkX, $chunkZ);
1051 $chunkPlayers = $this->getChunkPlayers($chunkX, $chunkZ);
1052 if(count($chunkPlayers) > 0){
1053 NetworkBroadcastUtils::broadcastPackets($chunkPlayers, $entries);
1057 $this->packetBuffersByChunk = [];
1060 public function checkSleep() : void{
1061 if(count($this->players) === 0){
1066 foreach($this->getPlayers() as $p){
1067 if(!$p->isSleeping()){
1074 $time = $this->getTimeOfDay();
1076 if($time >= World::TIME_NIGHT && $time < World::TIME_SUNRISE){
1077 $this->setTime($this->getTime() + World::TIME_FULL - $time);
1079 foreach($this->getPlayers() as $p){
1086 public function setSleepTicks(
int $ticks) : void{
1087 $this->sleepTicks = $ticks;
1099 $blockTranslator = TypeConverter::getInstance()->getBlockTranslator();
1101 foreach($blocks as $b){
1103 throw new \TypeError(
"Expected Vector3 in blocks array, got " . (is_object($b) ? get_class($b) : gettype($b)));
1106 $fullBlock = $this->getBlockAt($b->x, $b->y, $b->z);
1107 $blockPosition = BlockPosition::fromVector3($b);
1109 $tile = $this->getTileAt($b->x, $b->y, $b->z);
1111 $expectedClass = $fullBlock->getIdInfo()->getTileClass();
1112 if($expectedClass !==
null && $tile instanceof $expectedClass && count($fakeStateProperties = $tile->getRenderUpdateBugWorkaroundStateProperties($fullBlock)) > 0){
1113 $originalStateData = $blockTranslator->internalIdToNetworkStateData($fullBlock->getStateId());
1115 $originalStateData->getName(),
1116 array_merge($originalStateData->getStates(), $fakeStateProperties),
1117 $originalStateData->getVersion()
1119 $packets[] = UpdateBlockPacket::create(
1121 $blockTranslator->getBlockStateDictionary()->lookupStateIdFromData($fakeStateData) ??
throw new AssumptionFailedError(
"Unmapped fake blockstate data: " . $fakeStateData->toNbt()),
1122 UpdateBlockPacket::FLAG_NETWORK,
1123 UpdateBlockPacket::DATA_LAYER_NORMAL
1127 $packets[] = UpdateBlockPacket::create(
1129 $blockTranslator->internalIdToNetworkId($fullBlock->getStateId()),
1130 UpdateBlockPacket::FLAG_NETWORK,
1131 UpdateBlockPacket::DATA_LAYER_NORMAL
1135 $packets[] = BlockActorDataPacket::create($blockPosition, $tile->getSerializedSpawnCompound());
1142 public function clearCache(
bool $force =
false) : void{
1144 $this->blockCache = [];
1145 $this->blockCacheSize = 0;
1146 $this->blockCollisionBoxCache = [];
1149 $this->blockCacheSize = 0;
1150 foreach($this->blockCache as $list){
1151 $this->blockCacheSize += count($list);
1152 if($this->blockCacheSize > self::BLOCK_CACHE_SIZE_CAP){
1153 $this->blockCache = [];
1154 $this->blockCacheSize = 0;
1160 foreach($this->blockCollisionBoxCache as $list){
1161 $count += count($list);
1162 if($count > self::BLOCK_CACHE_SIZE_CAP){
1164 $this->blockCollisionBoxCache = [];
1171 private function trimBlockCache() : void{
1172 $before = $this->blockCacheSize;
1175 foreach($this->blockCache as $chunkHash => $blocks){
1176 unset($this->blockCache[$chunkHash]);
1177 $this->blockCacheSize -= count($blocks);
1178 if($this->blockCacheSize < self::BLOCK_CACHE_SIZE_CAP){
1189 return $this->randomTickBlocks;
1192 public function addRandomTickedBlock(
Block $block) : void{
1194 throw new \InvalidArgumentException(
"Cannot do random-tick on unknown block");
1196 $this->randomTickBlocks[$block->getStateId()] =
true;
1199 public function removeRandomTickedBlock(Block $block) : void{
1200 unset($this->randomTickBlocks[$block->getStateId()]);
1208 return $this->chunkTickRadius;
1216 $this->chunkTickRadius = $radius;
1227 return array_keys($this->validTickingChunks);
1235 $chunkPosHash =
World::chunkHash($chunkX, $chunkZ);
1236 $this->registeredTickingChunks[$chunkPosHash][spl_object_id($ticker)] = $ticker;
1237 $this->recheckTickingChunks[$chunkPosHash] = $chunkPosHash;
1245 $chunkHash =
World::chunkHash($chunkX, $chunkZ);
1246 $tickerId = spl_object_id($ticker);
1247 if(isset($this->registeredTickingChunks[$chunkHash][$tickerId])){
1248 if(count($this->registeredTickingChunks[$chunkHash]) === 1){
1250 $this->registeredTickingChunks[$chunkHash],
1251 $this->recheckTickingChunks[$chunkHash],
1252 $this->validTickingChunks[$chunkHash]
1255 unset($this->registeredTickingChunks[$chunkHash][$tickerId]);
1260 private function tickChunks() : void{
1261 if($this->chunkTickRadius <= 0 || count($this->registeredTickingChunks) === 0){
1265 if(count($this->recheckTickingChunks) > 0){
1266 $this->timings->randomChunkUpdatesChunkSelection->startTiming();
1268 $chunkTickableCache = [];
1270 foreach($this->recheckTickingChunks as $hash => $_){
1271 World::getXZ($hash, $chunkX, $chunkZ);
1272 if($this->isChunkTickable($chunkX, $chunkZ, $chunkTickableCache)){
1273 $this->validTickingChunks[$hash] = $hash;
1276 $this->recheckTickingChunks = [];
1278 $this->timings->randomChunkUpdatesChunkSelection->stopTiming();
1281 foreach($this->validTickingChunks as $index => $_){
1282 World::getXZ($index, $chunkX, $chunkZ);
1284 $this->tickChunk($chunkX, $chunkZ);
1294 private function isChunkTickable(
int $chunkX,
int $chunkZ, array &$cache) : bool{
1295 for($cx = -1; $cx <= 1; ++$cx){
1296 for($cz = -1; $cz <= 1; ++$cz){
1297 $chunkHash = World::chunkHash($chunkX + $cx, $chunkZ + $cz);
1298 if(isset($cache[$chunkHash])){
1299 if(!$cache[$chunkHash]){
1304 if($this->isChunkLocked($chunkX + $cx, $chunkZ + $cz)){
1305 $cache[$chunkHash] =
false;
1308 $adjacentChunk = $this->getChunk($chunkX + $cx, $chunkZ + $cz);
1309 if($adjacentChunk ===
null || !$adjacentChunk->isPopulated()){
1310 $cache[$chunkHash] =
false;
1313 $lightPopulatedState = $adjacentChunk->isLightPopulated();
1314 if($lightPopulatedState !==
true){
1315 if($lightPopulatedState ===
false){
1316 $this->orderLightPopulation($chunkX + $cx, $chunkZ + $cz);
1318 $cache[$chunkHash] =
false;
1322 $cache[$chunkHash] =
true;
1338 private function markTickingChunkForRecheck(
int $chunkX,
int $chunkZ) : void{
1339 for($cx = -1; $cx <= 1; ++$cx){
1340 for($cz = -1; $cz <= 1; ++$cz){
1341 $chunkHash = World::chunkHash($chunkX + $cx, $chunkZ + $cz);
1342 unset($this->validTickingChunks[$chunkHash]);
1343 if(isset($this->registeredTickingChunks[$chunkHash])){
1344 $this->recheckTickingChunks[$chunkHash] = $chunkHash;
1346 unset($this->recheckTickingChunks[$chunkHash]);
1352 private function orderLightPopulation(
int $chunkX,
int $chunkZ) : void{
1353 $chunkHash = World::chunkHash($chunkX, $chunkZ);
1354 $lightPopulatedState = $this->chunks[$chunkHash]->isLightPopulated();
1355 if($lightPopulatedState ===
false){
1356 $this->chunks[$chunkHash]->setLightPopulated(
null);
1357 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
1359 $this->workerPool->submitTask(
new LightPopulationTask(
1360 $this->chunks[$chunkHash],
1361 function(array $blockLight, array $skyLight, array $heightMap) use ($chunkX, $chunkZ) :
void{
1368 if($this->unloaded || ($chunk = $this->getChunk($chunkX, $chunkZ)) ===
null || $chunk->isLightPopulated() ===
true){
1373 $chunk->setHeightMapArray($heightMap);
1374 foreach($blockLight as $y => $lightArray){
1375 $chunk->getSubChunk($y)->setBlockLightArray($lightArray);
1377 foreach($skyLight as $y => $lightArray){
1378 $chunk->getSubChunk($y)->setBlockSkyLightArray($lightArray);
1380 $chunk->setLightPopulated(
true);
1381 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
1387 private function tickChunk(
int $chunkX,
int $chunkZ) : void{
1388 $chunk = $this->getChunk($chunkX, $chunkZ);
1389 if($chunk ===
null){
1393 foreach($this->getChunkEntities($chunkX, $chunkZ) as $entity){
1394 $entity->onRandomUpdate();
1397 $blockFactory = RuntimeBlockStateRegistry::getInstance();
1398 foreach($chunk->getSubChunks() as $Y => $subChunk){
1399 if(!$subChunk->isEmptyFast()){
1401 for($i = 0; $i < $this->tickedBlocksPerSubchunkPerTick; ++$i){
1404 $k = mt_rand(0, (1 << 60) - 1);
1406 $x = $k & SubChunk::COORD_MASK;
1407 $y = ($k >> SubChunk::COORD_BIT_SIZE) & SubChunk::COORD_MASK;
1408 $z = ($k >> (SubChunk::COORD_BIT_SIZE * 2)) & SubChunk::COORD_MASK;
1409 $k >>= (SubChunk::COORD_BIT_SIZE * 3);
1411 $state = $subChunk->getBlockStateId($x, $y, $z);
1413 if(isset($this->randomTickBlocks[$state])){
1414 $block = $blockFactory->fromStateId($state);
1415 $block->position($this, $chunkX * Chunk::EDGE_LENGTH + $x, ($Y << SubChunk::COORD_BIT_SIZE) + $y, $chunkZ * Chunk::EDGE_LENGTH + $z);
1416 $block->onRandomTick();
1430 public function save(
bool $force =
false) : bool{
1432 if(!$this->getAutoSave() && !$force){
1436 (
new WorldSaveEvent($this))->call();
1438 $timings = $this->timings->syncDataSave;
1439 $timings->startTiming();
1441 $this->provider->getWorldData()->setTime($this->time);
1442 $this->saveChunks();
1443 $this->provider->getWorldData()->save();
1445 $timings->stopTiming();
1450 public function saveChunks() : void{
1451 $this->timings->syncChunkSave->startTiming();
1453 foreach($this->chunks as $chunkHash => $chunk){
1454 self::getXZ($chunkHash, $chunkX, $chunkZ);
1455 $this->provider->saveChunk($chunkX, $chunkZ,
new ChunkData(
1456 $chunk->getSubChunks(),
1457 $chunk->isPopulated(),
1458 array_map(fn(Entity $e) => $e->saveNBT(), array_values(array_filter($this->getChunkEntities($chunkX, $chunkZ), fn(Entity $e) => $e->canSaveWithChunk()))),
1459 array_map(fn(Tile $t) => $t->saveNBT(), array_values($chunk->getTiles())),
1460 ), $chunk->getTerrainDirtyFlags());
1461 $chunk->clearTerrainDirtyFlags();
1464 $this->timings->syncChunkSave->stopTiming();
1474 !$this->isInWorld($pos->x, $pos->y, $pos->z) ||
1475 (isset($this->scheduledBlockUpdateQueueIndex[$index =
World::blockHash($pos->x, $pos->y, $pos->z)]) && $this->scheduledBlockUpdateQueueIndex[$index] <= $delay)
1479 $this->scheduledBlockUpdateQueueIndex[$index] = $delay;
1480 $this->scheduledBlockUpdateQueue->insert(
new Vector3((
int) $pos->x, (
int) $pos->y, (
int) $pos->z), $delay + $this->server->getTick());
1483 private function tryAddToNeighbourUpdateQueue(
int $x,
int $y,
int $z) : void{
1484 if($this->isInWorld($x, $y, $z)){
1485 $hash = World::blockHash($x, $y, $z);
1486 if(!isset($this->neighbourBlockUpdateQueueIndex[$hash])){
1487 $this->neighbourBlockUpdateQueue->enqueue($hash);
1488 $this->neighbourBlockUpdateQueueIndex[$hash] =
true;
1499 private function internalNotifyNeighbourBlockUpdate(
int $x,
int $y,
int $z) : void{
1500 $this->tryAddToNeighbourUpdateQueue($x, $y, $z);
1501 foreach(Facing::OFFSET as [$dx, $dy, $dz]){
1502 $this->tryAddToNeighbourUpdateQueue($x + $dx, $y + $dy, $z + $dz);
1514 $this->internalNotifyNeighbourBlockUpdate($pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ());
1522 $minX = (int) floor($bb->minX - 1);
1523 $minY = (int) floor($bb->minY - 1);
1524 $minZ = (int) floor($bb->minZ - 1);
1525 $maxX = (int) floor($bb->maxX + 1);
1526 $maxY = (int) floor($bb->maxY + 1);
1527 $maxZ = (int) floor($bb->maxZ + 1);
1532 for($z = $minZ; $z <= $maxZ; ++$z){
1533 for($x = $minX; $x <= $maxX; ++$x){
1534 for($y = $minY; $y <= $maxY; ++$y){
1535 $block = $this->getBlockAt($x, $y, $z);
1536 if($block->collidesWithBB($bb)){
1543 for($z = $minZ; $z <= $maxZ; ++$z){
1544 for($x = $minX; $x <= $maxX; ++$x){
1545 for($y = $minY; $y <= $maxY; ++$y){
1546 $block = $this->getBlockAt($x, $y, $z);
1547 if($block->collidesWithBB($bb)){
1548 $collides[] = $block;
1566 private function getBlockCollisionBoxesForCell(
int $x,
int $y,
int $z) : array{
1567 $block = $this->getBlockAt($x, $y, $z);
1568 $boxes = $block->getCollisionBoxes();
1570 $cellBB = AxisAlignedBB::one()->offset($x, $y, $z);
1571 foreach(Facing::OFFSET as [$dx, $dy, $dz]){
1572 $extraBoxes = $this->getBlockAt($x + $dx, $y + $dy, $z + $dz)->getCollisionBoxes();
1573 foreach($extraBoxes as $extraBox){
1574 if($extraBox->intersectsWith($cellBB)){
1575 $boxes[] = $extraBox;
1588 $minX = (int) floor($bb->minX);
1589 $minY = (int) floor($bb->minY);
1590 $minZ = (int) floor($bb->minZ);
1591 $maxX = (int) floor($bb->maxX);
1592 $maxY = (int) floor($bb->maxY);
1593 $maxZ = (int) floor($bb->maxZ);
1597 for($z = $minZ; $z <= $maxZ; ++$z){
1598 for($x = $minX; $x <= $maxX; ++$x){
1599 $chunkPosHash = World::chunkHash($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE);
1600 for($y = $minY; $y <= $maxY; ++$y){
1601 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
1603 $boxes = $this->blockCollisionBoxCache[$chunkPosHash][$relativeBlockHash] ??= $this->getBlockCollisionBoxesForCell($x, $y, $z);
1605 foreach($boxes as $blockBB){
1606 if($blockBB->intersectsWith($bb)){
1607 $collides[] = $blockBB;
1622 $timeProgress = ($this->time % self::TIME_FULL) / self::TIME_FULL;
1625 $sunProgress = $timeProgress + ($timeProgress < 0.25 ? 0.75 : -0.25);
1629 $diff = (((1 - ((cos($sunProgress * M_PI) + 1) / 2)) - $sunProgress) / 3);
1631 return $sunProgress + $diff;
1638 return $this->sunAnglePercentage;
1645 return $this->sunAnglePercentage * 2 * M_PI;
1652 return $this->sunAnglePercentage * 360.0;
1660 $percentage = max(0, min(1, -(cos($this->getSunAngleRadians()) * 2 - 0.5)));
1664 return (
int) ($percentage * 11);
1671 return $this->skyLightReduction;
1679 $floorX = $pos->getFloorX();
1680 $floorY = $pos->getFloorY();
1681 $floorZ = $pos->getFloorZ();
1682 return $this->getFullLightAt($floorX, $floorY, $floorZ);
1690 $skyLight = $this->getRealBlockSkyLightAt($x, $y, $z);
1692 return max($skyLight, $this->getBlockLightAt($x, $y, $z));
1703 return $this->getHighestAdjacentLight($x, $y, $z, $this->getFullLightAt(...));
1711 $floorX = $pos->getFloorX();
1712 $floorY = $pos->getFloorY();
1713 $floorZ = $pos->getFloorZ();
1714 return $this->getPotentialLightAt($floorX, $floorY, $floorZ);
1722 return max($this->getPotentialBlockSkyLightAt($x, $y, $z), $this->getBlockLightAt($x, $y, $z));
1730 return $this->getHighestAdjacentLight($x, $y, $z, $this->getPotentialLightAt(...));
1740 if(!$this->isInWorld($x, $y, $z)){
1741 return $y >= self::Y_MAX ? 15 : 0;
1743 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !==
null && $chunk->isLightPopulated() ===
true){
1744 return $chunk->getSubChunk($y >> Chunk::COORD_BIT_SIZE)->getBlockSkyLightArray()->get($x & SubChunk::COORD_MASK, $y & SubChunk::COORD_MASK, $z & SubChunk::COORD_MASK);
1755 $light = $this->getPotentialBlockSkyLightAt($x, $y, $z) - $this->skyLightReduction;
1756 return $light < 0 ? 0 : $light;
1765 if(!$this->isInWorld($x, $y, $z)){
1768 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !==
null && $chunk->isLightPopulated() ===
true){
1769 return $chunk->getSubChunk($y >> Chunk::COORD_BIT_SIZE)->getBlockLightArray()->get($x & SubChunk::COORD_MASK, $y & SubChunk::COORD_MASK, $z & SubChunk::COORD_MASK);
1774 public function updateAllLight(
int $x,
int $y,
int $z) : void{
1775 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) === null || $chunk->isLightPopulated() !== true){
1779 $blockFactory = RuntimeBlockStateRegistry::getInstance();
1780 $this->timings->doBlockSkyLightUpdates->startTiming();
1781 if($this->skyLightUpdate ===
null){
1782 $this->skyLightUpdate =
new SkyLightUpdate(
new SubChunkExplorer($this), $blockFactory->lightFilter, $blockFactory->blocksDirectSkyLight);
1784 $this->skyLightUpdate->recalculateNode($x, $y, $z);
1785 $this->timings->doBlockSkyLightUpdates->stopTiming();
1787 $this->timings->doBlockLightUpdates->startTiming();
1788 if($this->blockLightUpdate ===
null){
1789 $this->blockLightUpdate =
new BlockLightUpdate(
new SubChunkExplorer($this), $blockFactory->lightFilter, $blockFactory->light);
1791 $this->blockLightUpdate->recalculateNode($x, $y, $z);
1792 $this->timings->doBlockLightUpdates->stopTiming();
1798 private function getHighestAdjacentLight(
int $x,
int $y,
int $z, \Closure $lightGetter) : int{
1800 foreach(Facing::OFFSET as [$offsetX, $offsetY, $offsetZ]){
1801 $x1 = $x + $offsetX;
1802 $y1 = $y + $offsetY;
1803 $z1 = $z + $offsetZ;
1805 !$this->isInWorld($x1, $y1, $z1) ||
1806 ($chunk = $this->getChunk($x1 >> Chunk::COORD_BIT_SIZE, $z1 >> Chunk::COORD_BIT_SIZE)) ===
null ||
1807 $chunk->isLightPopulated() !==
true
1811 $max = max($max, $lightGetter($x1, $y1, $z1));
1820 return $this->getHighestAdjacentLight($x, $y, $z, $this->getPotentialBlockSkyLightAt(...));
1828 return $this->getHighestAdjacentPotentialBlockSkyLight($x, $y, $z) - $this->skyLightReduction;
1835 return $this->getHighestAdjacentLight($x, $y, $z, $this->getBlockLightAt(...));
1838 private function executeQueuedLightUpdates() : void{
1839 if($this->blockLightUpdate !== null){
1840 $this->timings->doBlockLightUpdates->startTiming();
1841 $this->blockLightUpdate->execute();
1842 $this->blockLightUpdate =
null;
1843 $this->timings->doBlockLightUpdates->stopTiming();
1846 if($this->skyLightUpdate !==
null){
1847 $this->timings->doBlockSkyLightUpdates->startTiming();
1848 $this->skyLightUpdate->execute();
1849 $this->skyLightUpdate =
null;
1850 $this->timings->doBlockSkyLightUpdates->stopTiming();
1857 $y < $this->maxY && $y >= $this->minY &&
1873 return $this->getBlockAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z), $cached, $addToCache);
1885 public function getBlockAt(
int $x,
int $y,
int $z,
bool $cached =
true,
bool $addToCache =
true) :
Block{
1886 $relativeBlockHash = null;
1887 $chunkHash = World::chunkHash($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE);
1889 if($this->isInWorld($x, $y, $z)){
1890 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
1892 if($cached && isset($this->blockCache[$chunkHash][$relativeBlockHash])){
1893 return $this->blockCache[$chunkHash][$relativeBlockHash];
1896 $chunk = $this->chunks[$chunkHash] ??
null;
1897 if($chunk !==
null){
1898 $block = RuntimeBlockStateRegistry::getInstance()->fromStateId($chunk->getBlockStateId($x & Chunk::COORD_MASK, $y, $z & Chunk::COORD_MASK));
1900 $addToCache =
false;
1901 $block = VanillaBlocks::AIR();
1904 $block = VanillaBlocks::AIR();
1907 $block->position($this, $x, $y, $z);
1909 if($this->inDynamicStateRecalculation){
1913 $addToCache =
false;
1915 $this->inDynamicStateRecalculation =
true;
1916 $replacement = $block->readStateFromWorld();
1917 if($replacement !== $block){
1918 $replacement->position($this, $x, $y, $z);
1919 $block = $replacement;
1921 $this->inDynamicStateRecalculation =
false;
1924 if($addToCache && $relativeBlockHash !==
null){
1925 $this->blockCache[$chunkHash][$relativeBlockHash] = $block;
1927 if(++$this->blockCacheSize >= self::BLOCK_CACHE_SIZE_CAP){
1928 $this->trimBlockCache();
1941 $this->setBlockAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z), $block, $update);
1952 public function setBlockAt(
int $x,
int $y,
int $z,
Block $block,
bool $update =
true) : void{
1953 if(!$this->isInWorld($x, $y, $z)){
1954 throw new \InvalidArgumentException(
"Pos x=$x,y=$y,z=$z is outside of the world bounds");
1956 $chunkX = $x >> Chunk::COORD_BIT_SIZE;
1957 $chunkZ = $z >> Chunk::COORD_BIT_SIZE;
1958 if($this->loadChunk($chunkX, $chunkZ) ===
null){
1959 throw new WorldException(
"Cannot set a block in un-generated terrain");
1962 $this->timings->setBlock->startTiming();
1964 $this->unlockChunk($chunkX, $chunkZ,
null);
1966 $block = clone $block;
1968 $block->position($this, $x, $y, $z);
1969 $block->writeStateToWorld();
1970 $pos =
new Vector3($x, $y, $z);
1972 $chunkHash = World::chunkHash($chunkX, $chunkZ);
1973 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
1975 unset($this->blockCache[$chunkHash][$relativeBlockHash]);
1976 $this->blockCacheSize--;
1977 unset($this->blockCollisionBoxCache[$chunkHash][$relativeBlockHash]);
1980 foreach(Facing::OFFSET as [$offsetX, $offsetY, $offsetZ]){
1981 $sideChunkPosHash = World::chunkHash(($x + $offsetX) >> Chunk::COORD_BIT_SIZE, ($z + $offsetZ) >> Chunk::COORD_BIT_SIZE);
1982 $sideChunkBlockHash = World::chunkBlockHash($x + $offsetX, $y + $offsetY, $z + $offsetZ);
1983 unset($this->blockCollisionBoxCache[$sideChunkPosHash][$sideChunkBlockHash]);
1986 if(!isset($this->changedBlocks[$chunkHash])){
1987 $this->changedBlocks[$chunkHash] = [];
1989 $this->changedBlocks[$chunkHash][$relativeBlockHash] = $pos;
1991 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
1992 $listener->onBlockChanged($pos);
1996 $this->updateAllLight($x, $y, $z);
1997 $this->internalNotifyNeighbourBlockUpdate($x, $y, $z);
2000 $this->timings->setBlock->stopTiming();
2003 public function dropItem(Vector3 $source, Item $item, ?Vector3 $motion =
null,
int $delay = 10) : ?ItemEntity{
2004 if($item->isNull()){
2008 $itemEntity =
new ItemEntity(Location::fromObject($source, $this, Utils::getRandomFloat() * 360, 0), $item);
2010 $itemEntity->setPickupDelay($delay);
2011 $itemEntity->setMotion($motion ??
new Vector3(Utils::getRandomFloat() * 0.2 - 0.1, 0.2, Utils::getRandomFloat() * 0.2 - 0.1));
2012 $itemEntity->spawnToAll();
2026 foreach(ExperienceOrb::splitIntoOrbSizes($amount) as $split){
2027 $orb =
new ExperienceOrb(Location::fromObject($pos, $this, Utils::getRandomFloat() * 360, 0), $split);
2029 $orb->setMotion(
new Vector3((Utils::getRandomFloat() * 0.2 - 0.1) * 2, Utils::getRandomFloat() * 0.4, (Utils::getRandomFloat() * 0.2 - 0.1) * 2));
2046 public function useBreakOn(
Vector3 $vector, ?
Item &$item =
null, ?
Player $player =
null,
bool $createParticles =
false, array &$returnedItems = []) : bool{
2047 $vector = $vector->floor();
2049 $chunkX = $vector->getFloorX() >> Chunk::COORD_BIT_SIZE;
2050 $chunkZ = $vector->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2051 if(!$this->isChunkLoaded($chunkX, $chunkZ) || $this->isChunkLocked($chunkX, $chunkZ)){
2055 $target = $this->getBlock($vector);
2056 $affectedBlocks = $target->getAffectedBlocks();
2059 $item = VanillaItems::AIR();
2063 if($player ===
null || $player->hasFiniteResources()){
2064 $drops = array_merge(...array_map(fn(Block $block) => $block->getDrops($item), $affectedBlocks));
2068 if($player !==
null && $player->hasFiniteResources()){
2069 $xpDrop = array_sum(array_map(fn(Block $block) => $block->getXpDropForTool($item), $affectedBlocks));
2072 if($player !==
null){
2073 $ev =
new BlockBreakEvent($player, $target, $item, $player->isCreative(), $drops, $xpDrop);
2075 if($target instanceof Air || ($player->isSurvival() && !$target->getBreakInfo()->isBreakable()) || $player->isSpectator()){
2079 if($player->isAdventure(
true) && !$ev->isCancelled()){
2081 $itemParser = LegacyStringToItemParser::getInstance();
2082 foreach($item->getCanDestroy() as $v){
2083 $entry = $itemParser->parse($v);
2084 if($entry->getBlock()->hasSameTypeId($target)){
2096 if($ev->isCancelled()){
2100 $drops = $ev->getDrops();
2101 $xpDrop = $ev->getXpDropAmount();
2103 }elseif(!$target->getBreakInfo()->isBreakable()){
2107 foreach($affectedBlocks as $t){
2108 $this->destroyBlockInternal($t, $item, $player, $createParticles, $returnedItems);
2111 $item->onDestroyBlock($target, $returnedItems);
2113 if(count($drops) > 0){
2114 $dropPos = $vector->add(0.5, 0.5, 0.5);
2115 foreach($drops as $drop){
2116 if(!$drop->isNull()){
2117 $this->dropItem($dropPos, $drop);
2123 $this->dropExperience($vector->add(0.5, 0.5, 0.5), $xpDrop);
2132 private function destroyBlockInternal(Block $target, Item $item, ?Player $player,
bool $createParticles, array &$returnedItems) : void{
2133 if($createParticles){
2134 $this->addParticle($target->getPosition()->add(0.5, 0.5, 0.5),
new BlockBreakParticle($target));
2137 $target->onBreak($item, $player, $returnedItems);
2139 $tile = $this->getTile($target->getPosition());
2141 $tile->onBlockDestroyed();
2152 public function useItemOn(
Vector3 $vector,
Item &$item,
int $face, ?
Vector3 $clickVector =
null, ?
Player $player =
null,
bool $playSound =
false, array &$returnedItems = []) : bool{
2153 $blockClicked = $this->getBlock($vector);
2154 $blockReplace = $blockClicked->getSide($face);
2156 if($clickVector ===
null){
2157 $clickVector =
new Vector3(0.0, 0.0, 0.0);
2160 min(1.0, max(0.0, $clickVector->x)),
2161 min(1.0, max(0.0, $clickVector->y)),
2162 min(1.0, max(0.0, $clickVector->z))
2166 if(!$this->isInWorld($blockReplace->getPosition()->x, $blockReplace->getPosition()->y, $blockReplace->getPosition()->z)){
2170 $chunkX = $blockReplace->getPosition()->getFloorX() >> Chunk::COORD_BIT_SIZE;
2171 $chunkZ = $blockReplace->getPosition()->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2172 if(!$this->isChunkLoaded($chunkX, $chunkZ) || $this->isChunkLocked($chunkX, $chunkZ)){
2176 if($blockClicked->getTypeId() === BlockTypeIds::AIR){
2180 if($player !==
null){
2181 $ev = new PlayerInteractEvent($player, $item, $blockClicked, $clickVector, $face, PlayerInteractEvent::RIGHT_CLICK_BLOCK);
2182 if($player->isSneaking()){
2183 $ev->setUseItem(false);
2184 $ev->setUseBlock($item->isNull());
2186 if($player->isSpectator()){
2191 if(!$ev->isCancelled()){
2192 if($ev->useBlock() && $blockClicked->onInteract($item, $face, $clickVector, $player, $returnedItems)){
2197 $result = $item->onInteractBlock($player, $blockReplace, $blockClicked, $face, $clickVector, $returnedItems);
2198 if($result !== ItemUseResult::NONE){
2199 return $result === ItemUseResult::SUCCESS;
2205 }elseif($blockClicked->onInteract($item, $face, $clickVector, $player, $returnedItems)){
2209 if($item->isNull() || !$item->canBePlaced()){
2213 $hand->position($this, $blockReplace->getPosition()->x, $blockReplace->getPosition()->y, $blockReplace->getPosition()->z);
2215 if($hand->canBePlacedAt($blockClicked, $clickVector, $face,
true)){
2216 $blockReplace = $blockClicked;
2221 $hand->position($this, $blockReplace->getPosition()->x, $blockReplace->getPosition()->y, $blockReplace->getPosition()->z);
2222 }elseif(!$hand->canBePlacedAt($blockReplace, $clickVector, $face,
false)){
2226 $tx =
new BlockTransaction($this);
2227 if(!$hand->place($tx, $item, $blockReplace, $blockClicked, $face, $clickVector, $player)){
2231 foreach($tx->getBlocks() as [$x, $y, $z, $block]){
2232 $block->position($this, $x, $y, $z);
2233 foreach($block->getCollisionBoxes() as $collisionBox){
2234 if(count($this->getCollidingEntities($collisionBox)) > 0){
2240 if($player !==
null){
2241 $ev =
new BlockPlaceEvent($player, $tx, $blockClicked, $item);
2242 if($player->isSpectator()){
2246 if($player->isAdventure(
true) && !$ev->isCancelled()){
2248 $itemParser = LegacyStringToItemParser::getInstance();
2250 $entry = $itemParser->parse($v);
2251 if($entry->getBlock()->hasSameTypeId($blockClicked)){
2263 if($ev->isCancelled()){
2271 foreach($tx->getBlocks() as [$x, $y, $z, $_]){
2272 $tile = $this->getTileAt($x, $y, $z);
2275 $tile->copyDataFromItem($item);
2278 $this->getBlockAt($x, $y, $z)->onPostPlace();
2282 $this->addSound($hand->getPosition(),
new BlockPlaceSound($hand));
2290 public function getEntity(
int $entityId) : ?Entity{
2291 return $this->entities[$entityId] ?? null;
2301 return $this->entities;
2317 foreach($this->getNearbyEntities($bb, $entity) as $ent){
2318 if($ent->canBeCollidedWith() && ($entity ===
null || $entity->canCollideWith($ent))){
2335 $minX = ((int) floor($bb->minX - 2)) >> Chunk::COORD_BIT_SIZE;
2336 $maxX = ((int) floor($bb->maxX + 2)) >> Chunk::COORD_BIT_SIZE;
2337 $minZ = ((int) floor($bb->minZ - 2)) >> Chunk::COORD_BIT_SIZE;
2338 $maxZ = ((int) floor($bb->maxZ + 2)) >> Chunk::COORD_BIT_SIZE;
2340 for($x = $minX; $x <= $maxX; ++$x){
2341 for($z = $minZ; $z <= $maxZ; ++$z){
2342 foreach($this->getChunkEntities($x, $z) as $ent){
2343 if($ent !== $entity && $ent->boundingBox->intersectsWith($bb)){
2365 assert(is_a($entityType,
Entity::class, true));
2367 $minX = ((int) floor($pos->x - $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2368 $maxX = ((int) floor($pos->x + $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2369 $minZ = ((int) floor($pos->z - $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2370 $maxZ = ((int) floor($pos->z + $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2372 $currentTargetDistSq = $maxDistance ** 2;
2378 $currentTarget =
null;
2380 for($x = $minX; $x <= $maxX; ++$x){
2381 for($z = $minZ; $z <= $maxZ; ++$z){
2382 foreach($this->getChunkEntities($x, $z) as $entity){
2383 if(!($entity instanceof $entityType) || $entity->isFlaggedForDespawn() || (!$includeDead && !$entity->isAlive())){
2386 $distSq = $entity->getPosition()->distanceSquared($pos);
2387 if($distSq < $currentTargetDistSq){
2388 $currentTargetDistSq = $distSq;
2389 $currentTarget = $entity;
2395 return $currentTarget;
2405 return $this->players;
2415 return $this->getTileAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z));
2422 return ($chunk = $this->loadChunk($x >>
Chunk::COORD_BIT_SIZE, $z >>
Chunk::COORD_BIT_SIZE)) !== null ? $chunk->getTile($x &
Chunk::COORD_MASK, $y, $z &
Chunk::COORD_MASK) : null;
2425 public function getBiomeId(
int $x,
int $y,
int $z) : int{
2426 if(($chunk = $this->loadChunk($x >>
Chunk::COORD_BIT_SIZE, $z >>
Chunk::COORD_BIT_SIZE)) !== null){
2427 return $chunk->getBiomeId($x & Chunk::COORD_MASK, $y & Chunk::COORD_MASK, $z & Chunk::COORD_MASK);
2429 return BiomeIds::OCEAN;
2432 public function getBiome(
int $x,
int $y,
int $z) : Biome{
2433 return BiomeRegistry::getInstance()->getBiome($this->getBiomeId($x, $y, $z));
2436 public function setBiomeId(
int $x,
int $y,
int $z,
int $biomeId) : void{
2437 $chunkX = $x >> Chunk::COORD_BIT_SIZE;
2438 $chunkZ = $z >> Chunk::COORD_BIT_SIZE;
2439 $this->unlockChunk($chunkX, $chunkZ,
null);
2440 if(($chunk = $this->loadChunk($chunkX, $chunkZ)) !==
null){
2441 $chunk->setBiomeId($x & Chunk::COORD_MASK, $y & Chunk::COORD_MASK, $z & Chunk::COORD_MASK, $biomeId);
2444 throw new WorldException(
"Cannot set biome in a non-generated chunk");
2453 return $this->chunks;
2456 public function getChunk(
int $chunkX,
int $chunkZ) : ?
Chunk{
2457 return $this->chunks[
World::chunkHash($chunkX, $chunkZ)] ?? null;
2465 return $this->entitiesByChunk[
World::chunkHash($chunkX, $chunkZ)] ?? [];
2472 return $this->loadChunk($pos->getFloorX() >>
Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >>
Chunk::COORD_BIT_SIZE);
2483 for($xx = -1; $xx <= 1; ++$xx){
2484 for($zz = -1; $zz <= 1; ++$zz){
2485 if($xx === 0 && $zz === 0){
2488 $result[World::chunkHash($xx, $zz)] = $this->loadChunk($x + $xx, $z + $zz);
2510 $chunkHash =
World::chunkHash($chunkX, $chunkZ);
2511 if(isset($this->chunkLock[$chunkHash])){
2512 throw new \InvalidArgumentException(
"Chunk $chunkX $chunkZ is already locked");
2514 $this->chunkLock[$chunkHash] = $lockId;
2515 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
2527 $chunkHash =
World::chunkHash($chunkX, $chunkZ);
2528 if(isset($this->chunkLock[$chunkHash]) && ($lockId ===
null || $this->chunkLock[$chunkHash] === $lockId)){
2529 unset($this->chunkLock[$chunkHash]);
2530 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
2542 return isset($this->chunkLock[
World::chunkHash($chunkX, $chunkZ)]);
2545 public function setChunk(
int $chunkX,
int $chunkZ,
Chunk $chunk) : void{
2546 $chunkHash =
World::chunkHash($chunkX, $chunkZ);
2547 $oldChunk = $this->loadChunk($chunkX, $chunkZ);
2548 if($oldChunk !==
null && $oldChunk !== $chunk){
2550 $transferredTiles = 0;
2551 foreach($oldChunk->getTiles() as $oldTile){
2552 $tilePosition = $oldTile->getPosition();
2553 $localX = $tilePosition->getFloorX() & Chunk::COORD_MASK;
2554 $localY = $tilePosition->getFloorY();
2555 $localZ = $tilePosition->getFloorZ() & Chunk::COORD_MASK;
2557 $newBlock = RuntimeBlockStateRegistry::getInstance()->fromStateId($chunk->
getBlockStateId($localX, $localY, $localZ));
2558 $expectedTileClass = $newBlock->getIdInfo()->getTileClass();
2560 $expectedTileClass ===
null ||
2561 !($oldTile instanceof $expectedTileClass) ||
2562 (($newTile = $chunk->
getTile($localX, $localY, $localZ)) !==
null && $newTile !== $oldTile)
2567 $transferredTiles++;
2568 $chunk->addTile($oldTile);
2569 $oldChunk->removeTile($oldTile);
2572 if($deletedTiles > 0 || $transferredTiles > 0){
2573 $this->logger->debug(
"Replacement of chunk $chunkX $chunkZ caused deletion of $deletedTiles obsolete/conflicted tiles, and transfer of $transferredTiles");
2577 $this->chunks[$chunkHash] = $chunk;
2579 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
2580 unset($this->blockCache[$chunkHash]);
2581 unset($this->blockCollisionBoxCache[$chunkHash]);
2582 unset($this->changedBlocks[$chunkHash]);
2583 $chunk->setTerrainDirty();
2584 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
2586 if(!$this->isChunkInUse($chunkX, $chunkZ)){
2587 $this->unloadChunkRequest($chunkX, $chunkZ);
2590 if($oldChunk ===
null){
2591 if(ChunkLoadEvent::hasHandlers()){
2592 (
new ChunkLoadEvent($this, $chunkX, $chunkZ, $chunk,
true))->call();
2595 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2596 $listener->onChunkLoaded($chunkX, $chunkZ, $chunk);
2599 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2600 $listener->onChunkChanged($chunkX, $chunkZ, $chunk);
2604 for($cX = -1; $cX <= 1; ++$cX){
2605 for($cZ = -1; $cZ <= 1; ++$cZ){
2606 foreach($this->getChunkEntities($chunkX + $cX, $chunkZ + $cZ) as $entity){
2607 $entity->onNearbyBlockChange();
2620 if(($chunk = $this->loadChunk($x >>
Chunk::COORD_BIT_SIZE, $z >>
Chunk::COORD_BIT_SIZE)) !== null){
2621 return $chunk->
getHighestBlockAt($x & Chunk::COORD_MASK, $z & Chunk::COORD_MASK);
2623 throw new WorldException(
"Cannot get highest block in an ungenerated chunk");
2630 return $this->isChunkLoaded($pos->getFloorX() >>
Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >>
Chunk::COORD_BIT_SIZE);
2633 public function isChunkLoaded(
int $x,
int $z) : bool{
2634 return isset($this->chunks[
World::chunkHash($x, $z)]);
2637 public function isChunkGenerated(
int $x,
int $z) : bool{
2638 return $this->loadChunk($x, $z) !== null;
2641 public function isChunkPopulated(
int $x,
int $z) : bool{
2642 $chunk = $this->loadChunk($x, $z);
2643 return $chunk !==
null && $chunk->isPopulated();
2650 return
Position::fromObject($this->provider->getWorldData()->getSpawn(), $this);
2657 $previousSpawn = $this->getSpawnLocation();
2658 $this->provider->getWorldData()->setSpawn($pos);
2661 $location = Position::fromObject($pos, $this);
2662 foreach($this->players as $player){
2663 $player->getNetworkSession()->syncWorldSpawnPoint($location);
2671 if($entity->isClosed()){
2672 throw new \InvalidArgumentException(
"Attempted to add a garbage closed Entity to world");
2674 if($entity->getWorld() !== $this){
2675 throw new \InvalidArgumentException(
"Invalid Entity world");
2677 if(array_key_exists($entity->getId(), $this->entities)){
2678 if($this->entities[$entity->getId()] === $entity){
2679 throw new \InvalidArgumentException(
"Entity " . $entity->getId() .
" has already been added to this world");
2681 throw new AssumptionFailedError(
"Found two different entities sharing entity ID " . $entity->getId());
2684 $pos = $entity->getPosition()->
asVector3();
2685 $this->entitiesByChunk[World::chunkHash($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE)][$entity->getId()] = $entity;
2686 $this->entityLastKnownPositions[$entity->getId()] = $pos;
2688 if($entity instanceof Player){
2689 $this->players[$entity->getId()] = $entity;
2691 $this->entities[$entity->getId()] = $entity;
2700 if($entity->getWorld() !== $this){
2701 throw new \InvalidArgumentException(
"Invalid Entity world");
2703 if(!array_key_exists($entity->getId(), $this->entities)){
2704 throw new \InvalidArgumentException(
"Entity is not tracked by this world (possibly already removed?)");
2706 $pos = $this->entityLastKnownPositions[$entity->getId()];
2707 $chunkHash = World::chunkHash($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
2708 if(isset($this->entitiesByChunk[$chunkHash][$entity->getId()])){
2709 if(count($this->entitiesByChunk[$chunkHash]) === 1){
2710 unset($this->entitiesByChunk[$chunkHash]);
2712 unset($this->entitiesByChunk[$chunkHash][$entity->getId()]);
2715 unset($this->entityLastKnownPositions[$entity->getId()]);
2717 if($entity instanceof Player){
2718 unset($this->players[$entity->getId()]);
2719 $this->checkSleep();
2722 unset($this->entities[$entity->getId()]);
2723 unset($this->updateEntities[$entity->getId()]);
2729 public function onEntityMoved(Entity $entity) : void{
2730 if(!array_key_exists($entity->getId(), $this->entityLastKnownPositions)){
2734 $oldPosition = $this->entityLastKnownPositions[$entity->getId()];
2735 $newPosition = $entity->getPosition();
2737 $oldChunkX = $oldPosition->getFloorX() >> Chunk::COORD_BIT_SIZE;
2738 $oldChunkZ = $oldPosition->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2739 $newChunkX = $newPosition->getFloorX() >> Chunk::COORD_BIT_SIZE;
2740 $newChunkZ = $newPosition->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2742 if($oldChunkX !== $newChunkX || $oldChunkZ !== $newChunkZ){
2743 $oldChunkHash = World::chunkHash($oldChunkX, $oldChunkZ);
2744 if(isset($this->entitiesByChunk[$oldChunkHash][$entity->getId()])){
2745 if(count($this->entitiesByChunk[$oldChunkHash]) === 1){
2746 unset($this->entitiesByChunk[$oldChunkHash]);
2748 unset($this->entitiesByChunk[$oldChunkHash][$entity->getId()]);
2752 $newViewers = $this->getViewersForPosition($newPosition);
2753 foreach($entity->getViewers() as $player){
2754 if(!isset($newViewers[spl_object_id($player)])){
2755 $entity->despawnFrom($player);
2757 unset($newViewers[spl_object_id($player)]);
2760 foreach($newViewers as $player){
2761 $entity->spawnTo($player);
2764 $newChunkHash = World::chunkHash($newChunkX, $newChunkZ);
2765 $this->entitiesByChunk[$newChunkHash][$entity->getId()] = $entity;
2767 $this->entityLastKnownPositions[$entity->getId()] = $newPosition->asVector3();
2774 public function addTile(Tile $tile) : void{
2775 if($tile->isClosed()){
2776 throw new \InvalidArgumentException(
"Attempted to add a garbage closed Tile to world");
2778 $pos = $tile->getPosition();
2779 if(!$pos->isValid() || $pos->getWorld() !== $this){
2780 throw new \InvalidArgumentException(
"Invalid Tile world");
2782 if(!$this->isInWorld($pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ())){
2783 throw new \InvalidArgumentException(
"Tile position is outside the world bounds");
2786 $chunkX = $pos->getFloorX() >> Chunk::COORD_BIT_SIZE;
2787 $chunkZ = $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2789 if(isset($this->chunks[$hash = World::chunkHash($chunkX, $chunkZ)])){
2790 $this->chunks[$hash]->addTile($tile);
2792 throw new \InvalidArgumentException(
"Attempted to create tile " . get_class($tile) .
" in unloaded chunk $chunkX $chunkZ");
2796 $this->scheduleDelayedBlockUpdate($pos->
asVector3(), 1);
2803 public function removeTile(Tile $tile) : void{
2805 if(!$pos->isValid() || $pos->getWorld() !== $this){
2806 throw new \InvalidArgumentException(
"Invalid Tile world");
2809 $chunkX = $pos->getFloorX() >> Chunk::COORD_BIT_SIZE;
2810 $chunkZ = $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2812 if(isset($this->chunks[$hash = World::chunkHash($chunkX, $chunkZ)])){
2813 $this->chunks[$hash]->removeTile($tile);
2815 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2816 $listener->onBlockChanged($pos->
asVector3());
2820 public function isChunkInUse(
int $x,
int $z) : bool{
2821 return isset($this->chunkLoaders[$index = World::chunkHash($x, $z)]) && count($this->chunkLoaders[$index]) > 0;
2831 if(isset($this->chunks[$chunkHash =
World::chunkHash($x, $z)])){
2832 return $this->chunks[$chunkHash];
2835 $this->timings->syncChunkLoad->startTiming();
2837 $this->cancelUnloadChunkRequest($x, $z);
2839 $this->timings->syncChunkLoadData->startTiming();
2841 $loadedChunkData =
null;
2844 $loadedChunkData = $this->provider->loadChunk($x, $z);
2845 }
catch(CorruptedChunkException $e){
2846 $this->logger->critical(
"Failed to load chunk x=$x z=$z: " . $e->getMessage());
2849 $this->timings->syncChunkLoadData->stopTiming();
2851 if($loadedChunkData ===
null){
2852 $this->timings->syncChunkLoad->stopTiming();
2856 $chunkData = $loadedChunkData->getData();
2857 $chunk =
new Chunk($chunkData->getSubChunks(), $chunkData->isPopulated());
2858 if(!$loadedChunkData->isUpgraded()){
2859 $chunk->clearTerrainDirtyFlags();
2861 $this->logger->debug(
"Chunk $x $z has been upgraded, will be saved at the next autosave opportunity");
2863 $this->chunks[$chunkHash] = $chunk;
2865 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
2866 unset($this->blockCache[$chunkHash]);
2867 unset($this->blockCollisionBoxCache[$chunkHash]);
2869 $this->initChunk($x, $z, $chunkData);
2871 if(ChunkLoadEvent::hasHandlers()){
2872 (
new ChunkLoadEvent($this, $x, $z, $this->chunks[$chunkHash],
false))->call();
2875 if(!$this->isChunkInUse($x, $z)){
2876 $this->logger->debug(
"Newly loaded chunk $x $z has no loaders registered, will be unloaded at next available opportunity");
2877 $this->unloadChunkRequest($x, $z);
2879 foreach($this->getChunkListeners($x, $z) as $listener){
2880 $listener->onChunkLoaded($x, $z, $this->chunks[$chunkHash]);
2882 $this->markTickingChunkForRecheck($x, $z);
2884 $this->timings->syncChunkLoad->stopTiming();
2886 return $this->chunks[$chunkHash];
2889 private function initChunk(
int $chunkX,
int $chunkZ, ChunkData $chunkData) : void{
2890 $logger = new \
PrefixedLogger($this->logger,
"Loading chunk $chunkX $chunkZ");
2892 if(count($chunkData->getEntityNBT()) !== 0){
2893 $this->timings->syncChunkLoadEntities->startTiming();
2894 $entityFactory = EntityFactory::getInstance();
2895 foreach($chunkData->getEntityNBT() as $k => $nbt){
2897 $entity = $entityFactory->createFromData($this, $nbt);
2898 }catch(SavedDataLoadingException $e){
2899 $logger->error(
"Bad entity data at list position $k: " . $e->getMessage());
2900 $logger->logException($e);
2903 if($entity === null){
2904 $saveIdTag = $nbt->getTag(
"identifier") ?? $nbt->getTag(
"id");
2905 $saveId =
"<unknown>";
2906 if($saveIdTag instanceof StringTag){
2907 $saveId = $saveIdTag->getValue();
2908 }elseif($saveIdTag instanceof IntTag){
2909 $saveId =
"legacy(" . $saveIdTag->getValue() .
")";
2911 $logger->warning(
"Deleted unknown entity type $saveId");
2917 $this->timings->syncChunkLoadEntities->stopTiming();
2920 if(count($chunkData->getTileNBT()) !== 0){
2921 $this->timings->syncChunkLoadTileEntities->startTiming();
2922 $tileFactory = TileFactory::getInstance();
2923 foreach($chunkData->getTileNBT() as $k => $nbt){
2925 $tile = $tileFactory->createFromData($this, $nbt);
2926 }catch(SavedDataLoadingException $e){
2927 $logger->error(
"Bad tile entity data at list position $k: " . $e->getMessage());
2928 $logger->logException($e);
2932 $logger->warning(
"Deleted unknown tile entity type " . $nbt->getString(
"id",
"<unknown>"));
2936 $tilePosition = $tile->getPosition();
2937 if(!$this->isChunkLoaded($tilePosition->getFloorX() >> Chunk::COORD_BIT_SIZE, $tilePosition->getFloorZ() >> Chunk::COORD_BIT_SIZE)){
2938 $logger->error(
"Found tile saved on wrong chunk - unable to fix due to correct chunk not loaded");
2939 }elseif(!$this->isInWorld($tilePosition->getFloorX(), $tilePosition->getFloorY(), $tilePosition->getFloorZ())){
2940 $logger->error(
"Cannot add tile with position outside the world bounds: x=$tilePosition->x,y=$tilePosition->y,z=$tilePosition->z");
2941 }elseif($this->getTile($tilePosition) !== null){
2942 $logger->error(
"Cannot add tile at x=$tilePosition->x,y=$tilePosition->y,z=$tilePosition->z: Another tile is already at that position");
2944 $this->addTile($tile);
2948 $this->timings->syncChunkLoadTileEntities->stopTiming();
2952 private function queueUnloadChunk(
int $x,
int $z) : void{
2953 $this->unloadQueue[World::chunkHash($x, $z)] = microtime(true);
2956 public function unloadChunkRequest(
int $x,
int $z,
bool $safe =
true) : bool{
2957 if(($safe && $this->isChunkInUse($x, $z)) || $this->isSpawnChunk($x, $z)){
2961 $this->queueUnloadChunk($x, $z);
2966 public function cancelUnloadChunkRequest(
int $x,
int $z) : void{
2967 unset($this->unloadQueue[World::chunkHash($x, $z)]);
2970 public function unloadChunk(
int $x,
int $z,
bool $safe =
true,
bool $trySave =
true) : bool{
2971 if($safe && $this->isChunkInUse($x, $z)){
2975 if(!$this->isChunkLoaded($x, $z)){
2979 $this->timings->doChunkUnload->startTiming();
2981 $chunkHash = World::chunkHash($x, $z);
2983 $chunk = $this->chunks[$chunkHash] ??
null;
2985 if($chunk !==
null){
2986 if(ChunkUnloadEvent::hasHandlers()){
2987 $ev =
new ChunkUnloadEvent($this, $x, $z, $chunk);
2989 if($ev->isCancelled()){
2990 $this->timings->doChunkUnload->stopTiming();
2996 if($trySave && $this->getAutoSave()){
2997 $this->timings->syncChunkSave->startTiming();
2999 $this->provider->saveChunk($x, $z,
new ChunkData(
3001 $chunk->isPopulated(),
3002 array_map(fn(Entity $e) => $e->saveNBT(), array_values(array_filter($this->getChunkEntities($x, $z), fn(Entity $e) => $e->canSaveWithChunk()))),
3003 array_map(fn(Tile $t) => $t->saveNBT(), array_values($chunk->
getTiles())),
3004 ), $chunk->getTerrainDirtyFlags());
3006 $this->timings->syncChunkSave->stopTiming();
3010 foreach($this->getChunkListeners($x, $z) as $listener){
3011 $listener->onChunkUnloaded($x, $z, $chunk);
3014 foreach($this->getChunkEntities($x, $z) as $entity){
3015 if($entity instanceof Player){
3024 unset($this->chunks[$chunkHash]);
3025 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
3026 unset($this->blockCache[$chunkHash]);
3027 unset($this->blockCollisionBoxCache[$chunkHash]);
3028 unset($this->changedBlocks[$chunkHash]);
3029 unset($this->registeredTickingChunks[$chunkHash]);
3030 $this->markTickingChunkForRecheck($x, $z);
3032 if(array_key_exists($chunkHash, $this->chunkPopulationRequestMap)){
3033 $this->logger->debug(
"Rejecting population promise for chunk $x $z");
3034 $this->chunkPopulationRequestMap[$chunkHash]->reject();
3035 unset($this->chunkPopulationRequestMap[$chunkHash]);
3036 if(isset($this->activeChunkPopulationTasks[$chunkHash])){
3037 $this->logger->debug(
"Marking population task for chunk $x $z as orphaned");
3038 $this->activeChunkPopulationTasks[$chunkHash] =
false;
3042 $this->timings->doChunkUnload->stopTiming();
3051 $spawn = $this->getSpawnLocation();
3052 $spawnX = $spawn->x >> Chunk::COORD_BIT_SIZE;
3053 $spawnZ = $spawn->z >> Chunk::COORD_BIT_SIZE;
3055 return abs($X - $spawnX) <= 1 && abs($Z - $spawnZ) <= 1;
3068 $spawn ??= $this->getSpawnLocation();
3073 $this->requestChunkPopulation($spawn->getFloorX() >> Chunk::COORD_BIT_SIZE, $spawn->getFloorZ() >> Chunk::COORD_BIT_SIZE,
null)->onCompletion(
3074 function() use ($spawn, $resolver) :
void{
3075 $spawn = $this->getSafeSpawn($spawn);
3076 $resolver->resolve($spawn);
3078 function() use ($resolver) : void{
3079 $resolver->reject();
3083 return $resolver->getPromise();
3093 if(!($spawn instanceof
Vector3) || $spawn->y <= $this->minY){
3094 $spawn = $this->getSpawnLocation();
3098 $v = $spawn->floor();
3099 $chunk = $this->getOrLoadChunkAtPosition($v);
3100 if($chunk ===
null){
3101 throw new WorldException(
"Cannot find a safe spawn point in non-generated terrain");
3105 $y = (int) min($max - 2, $v->y);
3106 $wasAir = $this->getBlockAt($x, $y - 1, $z)->getTypeId() === BlockTypeIds::AIR;
3107 for(; $y > $this->minY; --$y){
3108 if($this->getBlockAt($x, $y, $z)->isFullCube()){
3118 for(; $y >= $this->minY && $y < $max; ++$y){
3119 if(!$this->getBlockAt($x, $y + 1, $z)->isFullCube()){
3120 if(!$this->getBlockAt($x, $y, $z)->isFullCube()){
3121 return new Position($spawn->x, $y === (
int) $spawn->y ? $spawn->y : $y, $spawn->z, $this);
3128 return new Position($spawn->x, $y, $spawn->z, $this);
3142 return $this->time % self::TIME_FULL;
3150 return $this->displayName;
3159 $this->displayName = $name;
3160 $this->provider->getWorldData()->setName($name);
3167 return $this->folderName;
3174 $this->time = $time;
3182 $this->stopTime = true;
3190 $this->stopTime = false;
3198 return $this->provider->getWorldData()->getSeed();
3209 public function getDifficulty() : int{
3210 return $this->provider->getWorldData()->getDifficulty();
3213 public function setDifficulty(
int $difficulty) : void{
3214 if($difficulty < 0 || $difficulty > 3){
3215 throw new \InvalidArgumentException(
"Invalid difficulty level $difficulty");
3217 (
new WorldDifficultyChangeEvent($this, $this->getDifficulty(), $difficulty))->call();
3218 $this->provider->getWorldData()->setDifficulty($difficulty);
3220 foreach($this->players as $player){
3221 $player->getNetworkSession()->syncWorldDifficulty($this->getDifficulty());
3225 private function addChunkHashToPopulationRequestQueue(
int $chunkHash) : void{
3226 if(!isset($this->chunkPopulationRequestQueueIndex[$chunkHash])){
3227 $this->chunkPopulationRequestQueue->enqueue($chunkHash);
3228 $this->chunkPopulationRequestQueueIndex[$chunkHash] =
true;
3235 private function enqueuePopulationRequest(
int $chunkX,
int $chunkZ, ?ChunkLoader $associatedChunkLoader) : Promise{
3236 $chunkHash = World::chunkHash($chunkX, $chunkZ);
3237 $this->addChunkHashToPopulationRequestQueue($chunkHash);
3239 $resolver = $this->chunkPopulationRequestMap[$chunkHash] =
new PromiseResolver();
3240 if($associatedChunkLoader ===
null){
3241 $temporaryLoader =
new class implements ChunkLoader{};
3242 $this->registerChunkLoader($temporaryLoader, $chunkX, $chunkZ);
3243 $resolver->getPromise()->onCompletion(
3244 fn() => $this->unregisterChunkLoader($temporaryLoader, $chunkX, $chunkZ),
3245 static function() :
void{}
3248 return $resolver->getPromise();
3251 private function drainPopulationRequestQueue() : void{
3253 while(count($this->activeChunkPopulationTasks) < $this->maxConcurrentChunkPopulationTasks && !$this->chunkPopulationRequestQueue->isEmpty()){
3254 $nextChunkHash = $this->chunkPopulationRequestQueue->dequeue();
3255 unset($this->chunkPopulationRequestQueueIndex[$nextChunkHash]);
3256 World::getXZ($nextChunkHash, $nextChunkX, $nextChunkZ);
3257 if(isset($this->chunkPopulationRequestMap[$nextChunkHash])){
3258 assert(!($this->activeChunkPopulationTasks[$nextChunkHash] ??
false),
"Population for chunk $nextChunkX $nextChunkZ already running");
3260 !$this->orderChunkPopulation($nextChunkX, $nextChunkZ,
null)->isResolved() &&
3261 !isset($this->activeChunkPopulationTasks[$nextChunkHash])
3263 $failed[] = $nextChunkHash;
3270 foreach($failed as $hash){
3271 $this->addChunkHashToPopulationRequestQueue($hash);
3280 private function checkChunkPopulationPreconditions(
int $chunkX,
int $chunkZ) : array{
3281 $chunkHash = World::chunkHash($chunkX, $chunkZ);
3282 $resolver = $this->chunkPopulationRequestMap[$chunkHash] ??
null;
3283 if($resolver !==
null && isset($this->activeChunkPopulationTasks[$chunkHash])){
3285 return [$resolver,
false];
3288 $temporaryChunkLoader =
new class implements ChunkLoader{};
3289 $this->registerChunkLoader($temporaryChunkLoader, $chunkX, $chunkZ);
3290 $chunk = $this->loadChunk($chunkX, $chunkZ);
3291 $this->unregisterChunkLoader($temporaryChunkLoader, $chunkX, $chunkZ);
3292 if($chunk !==
null && $chunk->isPopulated()){
3294 $resolver ??=
new PromiseResolver();
3295 unset($this->chunkPopulationRequestMap[$chunkHash]);
3296 $resolver->resolve($chunk);
3297 return [$resolver,
false];
3299 return [$resolver,
true];
3314 [$resolver, $proceedWithPopulation] = $this->checkChunkPopulationPreconditions($chunkX, $chunkZ);
3315 if(!$proceedWithPopulation){
3316 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3319 if(count($this->activeChunkPopulationTasks) >= $this->maxConcurrentChunkPopulationTasks){
3321 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3323 return $this->internalOrderChunkPopulation($chunkX, $chunkZ, $associatedChunkLoader, $resolver);
3337 [$resolver, $proceedWithPopulation] = $this->checkChunkPopulationPreconditions($chunkX, $chunkZ);
3338 if(!$proceedWithPopulation){
3339 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3342 return $this->internalOrderChunkPopulation($chunkX, $chunkZ, $associatedChunkLoader, $resolver);
3349 private function internalOrderChunkPopulation(
int $chunkX,
int $chunkZ, ?ChunkLoader $associatedChunkLoader, ?
PromiseResolver $resolver) :
Promise{
3350 $chunkHash =
World::chunkHash($chunkX, $chunkZ);
3352 $timings = $this->timings->chunkPopulationOrder;
3353 $timings->startTiming();
3356 for($xx = -1; $xx <= 1; ++$xx){
3357 for($zz = -1; $zz <= 1; ++$zz){
3358 if($this->isChunkLocked($chunkX + $xx, $chunkZ + $zz)){
3360 return $resolver?->
getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3365 $this->activeChunkPopulationTasks[$chunkHash] =
true;
3366 if($resolver ===
null){
3367 $resolver =
new PromiseResolver();
3368 $this->chunkPopulationRequestMap[$chunkHash] = $resolver;
3371 $chunkPopulationLockId =
new ChunkLockId();
3373 $temporaryChunkLoader =
new class implements ChunkLoader{
3375 for($xx = -1; $xx <= 1; ++$xx){
3376 for($zz = -1; $zz <= 1; ++$zz){
3377 $this->lockChunk($chunkX + $xx, $chunkZ + $zz, $chunkPopulationLockId);
3378 $this->registerChunkLoader($temporaryChunkLoader, $chunkX + $xx, $chunkZ + $zz);
3382 $centerChunk = $this->loadChunk($chunkX, $chunkZ);
3383 $adjacentChunks = $this->getAdjacentChunks($chunkX, $chunkZ);
3384 $task =
new PopulationTask(
3390 function(Chunk $centerChunk, array $adjacentChunks) use ($chunkPopulationLockId, $chunkX, $chunkZ, $temporaryChunkLoader) :
void{
3391 if(!$this->isLoaded()){
3395 $this->generateChunkCallback($chunkPopulationLockId, $chunkX, $chunkZ, $centerChunk, $adjacentChunks, $temporaryChunkLoader);
3398 $workerId = $this->workerPool->selectWorker();
3399 if(!isset($this->workerPool->getRunningWorkers()[$workerId]) && isset($this->generatorRegisteredWorkers[$workerId])){
3400 $this->logger->debug(
"Selected worker $workerId previously had generator registered, but is now offline");
3401 unset($this->generatorRegisteredWorkers[$workerId]);
3403 if(!isset($this->generatorRegisteredWorkers[$workerId])){
3404 $this->registerGeneratorToWorker($workerId);
3406 $this->workerPool->submitTaskToWorker($task, $workerId);
3410 $timings->stopTiming();
3418 private function generateChunkCallback(ChunkLockId $chunkLockId,
int $x,
int $z, Chunk $chunk, array $adjacentChunks, ChunkLoader $temporaryChunkLoader) : void{
3419 $timings = $this->timings->chunkPopulationCompletion;
3420 $timings->startTiming();
3423 for($xx = -1; $xx <= 1; ++$xx){
3424 for($zz = -1; $zz <= 1; ++$zz){
3425 $this->unregisterChunkLoader($temporaryChunkLoader, $x + $xx, $z + $zz);
3426 if(!$this->unlockChunk($x + $xx, $z + $zz, $chunkLockId)){
3432 $index = World::chunkHash($x, $z);
3433 if(!isset($this->activeChunkPopulationTasks[$index])){
3434 throw new AssumptionFailedError(
"This should always be set, regardless of whether the task was orphaned or not");
3436 if(!$this->activeChunkPopulationTasks[$index]){
3437 $this->logger->debug(
"Discarding orphaned population result for chunk x=$x,z=$z");
3438 unset($this->activeChunkPopulationTasks[$index]);
3440 if($dirtyChunks === 0){
3441 $oldChunk = $this->loadChunk($x, $z);
3442 $this->setChunk($x, $z, $chunk);
3444 foreach($adjacentChunks as $relativeChunkHash => $adjacentChunk){
3445 World::getXZ($relativeChunkHash, $relativeX, $relativeZ);
3446 if($relativeX < -1 || $relativeX > 1 || $relativeZ < -1 || $relativeZ > 1){
3447 throw new AssumptionFailedError(
"Adjacent chunks should be in range -1 ... +1 coordinates");
3449 $this->setChunk($x + $relativeX, $z + $relativeZ, $adjacentChunk);
3452 if(($oldChunk ===
null || !$oldChunk->isPopulated()) && $chunk->isPopulated()){
3453 if(ChunkPopulateEvent::hasHandlers()){
3454 (
new ChunkPopulateEvent($this, $x, $z, $chunk))->call();
3457 foreach($this->getChunkListeners($x, $z) as $listener){
3458 $listener->onChunkPopulated($x, $z, $chunk);
3462 $this->logger->debug(
"Discarding population result for chunk x=$x,z=$z - terrain was modified on the main thread before async population completed");
3471 unset($this->activeChunkPopulationTasks[$index]);
3473 if($dirtyChunks === 0){
3474 $promise = $this->chunkPopulationRequestMap[$index] ??
null;
3475 if($promise !==
null){
3476 unset($this->chunkPopulationRequestMap[$index]);
3477 $promise->resolve($chunk);
3480 $this->logger->debug(
"Unable to resolve population promise for chunk x=$x,z=$z - populated chunk was forcibly unloaded while setting modified chunks");
3486 $this->addChunkHashToPopulationRequestQueue($index);
3489 $this->drainPopulationRequestQueue();
3491 $timings->stopTiming();
3494 public function doChunkGarbageCollection() : void{
3495 $this->timings->doChunkGC->startTiming();
3497 foreach($this->chunks as $index => $chunk){
3498 if(!isset($this->unloadQueue[$index])){
3499 World::getXZ($index, $X, $Z);
3500 if(!$this->isSpawnChunk($X, $Z)){
3501 $this->unloadChunkRequest($X, $Z,
true);
3504 $chunk->collectGarbage();
3507 $this->provider->doGarbageCollection();
3509 $this->timings->doChunkGC->stopTiming();
3512 public function unloadChunks(
bool $force =
false) : void{
3513 if(count($this->unloadQueue) > 0){
3515 $now = microtime(
true);
3516 foreach($this->unloadQueue as $index => $time){
3517 World::getXZ($index, $X, $Z);
3520 if($maxUnload <= 0){
3522 }elseif($time > ($now - 30)){
3528 if($this->unloadChunk($X, $Z,
true)){
3529 unset($this->unloadQueue[$index]);