PocketMine-MP 5.31.1 git-79e3f2b2814ae3676339d931f659b32a01e19783
Loading...
Searching...
No Matches
World.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
27namespace pocketmine\world;
28
61use pocketmine\item\ItemUseResult;
94use pocketmine\world\format\LightArray;
111use function abs;
112use function array_filter;
113use function array_key_exists;
114use function array_keys;
115use function array_map;
116use function array_merge;
117use function array_sum;
118use function array_values;
119use function assert;
120use function cos;
121use function count;
122use function floor;
123use function get_class;
124use function gettype;
125use function is_a;
126use function is_object;
127use function max;
128use function microtime;
129use function min;
130use function morton2d_decode;
131use function morton2d_encode;
132use function morton3d_decode;
133use function morton3d_encode;
134use function mt_rand;
135use function preg_match;
136use function spl_object_id;
137use function strtolower;
138use function trim;
139use const M_PI;
140use const PHP_INT_MAX;
141use const PHP_INT_MIN;
142
143#include <rules/World.h>
144
150class World implements ChunkManager{
151
152 private static int $worldIdCounter = 1;
153
154 public const Y_MAX = 320;
155 public const Y_MIN = -64;
156
157 public const TIME_DAY = 1000;
158 public const TIME_NOON = 6000;
159 public const TIME_SUNSET = 12000;
160 public const TIME_NIGHT = 13000;
161 public const TIME_MIDNIGHT = 18000;
162 public const TIME_SUNRISE = 23000;
163
164 public const TIME_FULL = 24000;
165
166 public const DIFFICULTY_PEACEFUL = 0;
167 public const DIFFICULTY_EASY = 1;
168 public const DIFFICULTY_NORMAL = 2;
169 public const DIFFICULTY_HARD = 3;
170
171 public const DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK = 3;
172
173 //TODO: this could probably do with being a lot bigger
174 private const BLOCK_CACHE_SIZE_CAP = 2048;
175
180 private array $players = [];
181
186 private array $entities = [];
191 private array $entityLastKnownPositions = [];
192
197 private array $entitiesByChunk = [];
198
203 public array $updateEntities = [];
204
205 private bool $inDynamicStateRecalculation = false;
210 private array $blockCache = [];
211 private int $blockCacheSize = 0;
216 private array $blockCollisionBoxCache = [];
217
218 private int $sendTimeTicker = 0;
219
220 private int $worldId;
221
222 private int $providerGarbageCollectionTicker = 0;
223
224 private int $minY;
225 private int $maxY;
226
231 private array $registeredTickingChunks = [];
232
239 private array $validTickingChunks = [];
240
246 private array $recheckTickingChunks = [];
247
252 private array $chunkLoaders = [];
253
258 private array $chunkListeners = [];
263 private array $playerChunkListeners = [];
264
269 private array $packetBuffersByChunk = [];
270
275 private array $unloadQueue = [];
276
277 private int $time;
278 public bool $stopTime = false;
279
280 private float $sunAnglePercentage = 0.0;
281 private int $skyLightReduction = 0;
282
283 private string $folderName;
284 private string $displayName;
285
290 private array $chunks = [];
291
296 private array $knownUngeneratedChunks = [];
297
302 private array $changedBlocks = [];
303
305 private ReversePriorityQueue $scheduledBlockUpdateQueue;
310 private array $scheduledBlockUpdateQueueIndex = [];
311
313 private \SplQueue $neighbourBlockUpdateQueue;
318 private array $neighbourBlockUpdateQueueIndex = [];
319
324 private array $activeChunkPopulationTasks = [];
329 private array $chunkLock = [];
330 private int $maxConcurrentChunkPopulationTasks = 2;
335 private array $chunkPopulationRequestMap = [];
340 private \SplQueue $chunkPopulationRequestQueue;
345 private array $chunkPopulationRequestQueueIndex = [];
346
347 private readonly GeneratorExecutor $generatorExecutor;
348
349 private bool $autoSave = true;
350
351 private int $sleepTicks = 0;
352
353 private int $chunkTickRadius;
354 private int $tickedBlocksPerSubchunkPerTick = self::DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK;
359 private array $randomTickBlocks = [];
360
361 public WorldTimings $timings;
362
363 public float $tickRateTime = 0;
364
365 private bool $doingTick = false;
366
367 private bool $unloaded = false;
372 private array $unloadCallbacks = [];
373
374 private ?BlockLightUpdate $blockLightUpdate = null;
375 private ?SkyLightUpdate $skyLightUpdate = null;
376
377 private \Logger $logger;
378
379 private RuntimeBlockStateRegistry $blockStateRegistry;
380
384 public static function chunkHash(int $x, int $z) : int{
385 return morton2d_encode($x, $z);
386 }
387
388 private const MORTON3D_BIT_SIZE = 21;
389 private const BLOCKHASH_Y_BITS = 9;
390 private const BLOCKHASH_Y_PADDING = 64; //size (in blocks) of padding after both boundaries of the Y axis
391 private const BLOCKHASH_Y_OFFSET = self::BLOCKHASH_Y_PADDING - self::Y_MIN;
392 private const BLOCKHASH_Y_MASK = (1 << self::BLOCKHASH_Y_BITS) - 1;
393 private const BLOCKHASH_XZ_MASK = (1 << self::MORTON3D_BIT_SIZE) - 1;
394 private const BLOCKHASH_XZ_EXTRA_BITS = (self::MORTON3D_BIT_SIZE - self::BLOCKHASH_Y_BITS) >> 1;
395 private const BLOCKHASH_XZ_EXTRA_MASK = (1 << self::BLOCKHASH_XZ_EXTRA_BITS) - 1;
396 private const BLOCKHASH_XZ_SIGN_SHIFT = 64 - self::MORTON3D_BIT_SIZE - self::BLOCKHASH_XZ_EXTRA_BITS;
397 private const BLOCKHASH_X_SHIFT = self::BLOCKHASH_Y_BITS;
398 private const BLOCKHASH_Z_SHIFT = self::BLOCKHASH_X_SHIFT + self::BLOCKHASH_XZ_EXTRA_BITS;
399
403 public static function blockHash(int $x, int $y, int $z) : int{
404 $shiftedY = $y + self::BLOCKHASH_Y_OFFSET;
405 if(($shiftedY & (~0 << self::BLOCKHASH_Y_BITS)) !== 0){
406 throw new \InvalidArgumentException("Y coordinate $y is out of range!");
407 }
408 //morton3d gives us 21 bits on each axis, but the Y axis only requires 9
409 //so we use the extra space on Y (12 bits) and add 6 extra bits from X and Z instead.
410 //if we ever need more space for Y (e.g. due to expansion), take bits from X/Z to compensate.
411 return morton3d_encode(
412 $x & self::BLOCKHASH_XZ_MASK,
413 ($shiftedY /* & self::BLOCKHASH_Y_MASK */) |
414 ((($x >> self::MORTON3D_BIT_SIZE) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::BLOCKHASH_X_SHIFT) |
415 ((($z >> self::MORTON3D_BIT_SIZE) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::BLOCKHASH_Z_SHIFT),
416 $z & self::BLOCKHASH_XZ_MASK
417 );
418 }
419
423 public static function chunkBlockHash(int $x, int $y, int $z) : int{
424 return morton3d_encode($x, $y, $z);
425 }
426
433 public static function getBlockXYZ(int $hash, ?int &$x, ?int &$y, ?int &$z) : void{
434 [$baseX, $baseY, $baseZ] = morton3d_decode($hash);
435
436 $extraX = ((($baseY >> self::BLOCKHASH_X_SHIFT) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::MORTON3D_BIT_SIZE);
437 $extraZ = ((($baseY >> self::BLOCKHASH_Z_SHIFT) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::MORTON3D_BIT_SIZE);
438
439 $x = (($baseX & self::BLOCKHASH_XZ_MASK) | $extraX) << self::BLOCKHASH_XZ_SIGN_SHIFT >> self::BLOCKHASH_XZ_SIGN_SHIFT;
440 $y = ($baseY & self::BLOCKHASH_Y_MASK) - self::BLOCKHASH_Y_OFFSET;
441 $z = (($baseZ & self::BLOCKHASH_XZ_MASK) | $extraZ) << self::BLOCKHASH_XZ_SIGN_SHIFT >> self::BLOCKHASH_XZ_SIGN_SHIFT;
442 }
443
449 public static function getXZ(int $hash, ?int &$x, ?int &$z) : void{
450 [$x, $z] = morton2d_decode($hash);
451 }
452
453 public static function getDifficultyFromString(string $str) : int{
454 switch(strtolower(trim($str))){
455 case "0":
456 case "peaceful":
457 case "p":
458 return World::DIFFICULTY_PEACEFUL;
459
460 case "1":
461 case "easy":
462 case "e":
463 return World::DIFFICULTY_EASY;
464
465 case "2":
466 case "normal":
467 case "n":
468 return World::DIFFICULTY_NORMAL;
469
470 case "3":
471 case "hard":
472 case "h":
473 return World::DIFFICULTY_HARD;
474 }
475
476 return -1;
477 }
478
482 public function __construct(
483 private Server $server,
484 string $name, //TODO: this should be folderName (named arguments BC break)
485 private WritableWorldProvider $provider,
486 private AsyncPool $workerPool
487 ){
488 $this->folderName = $name;
489 $this->worldId = self::$worldIdCounter++;
490
491 $this->displayName = $this->provider->getWorldData()->getName();
492 $this->logger = new \PrefixedLogger($server->getLogger(), "World: $this->displayName");
493
494 $this->blockStateRegistry = RuntimeBlockStateRegistry::getInstance();
495 $this->minY = $this->provider->getWorldMinY();
496 $this->maxY = $this->provider->getWorldMaxY();
497
498 $this->server->getLogger()->info($this->server->getLanguage()->translate(KnownTranslationFactory::pocketmine_level_preparing($this->displayName)));
499 $generator = GeneratorManager::getInstance()->getGenerator($this->provider->getWorldData()->getGenerator()) ??
500 throw new AssumptionFailedError("WorldManager should already have checked that the generator exists");
501 $generator->validateGeneratorOptions($this->provider->getWorldData()->getGeneratorOptions());
502
503 $executorSetupParameters = new GeneratorExecutorSetupParameters(
504 worldMinY: $this->minY,
505 worldMaxY: $this->maxY,
506 generatorSeed: $this->getSeed(),
507 generatorClass: $generator->getGeneratorClass(),
508 generatorSettings: $this->provider->getWorldData()->getGeneratorOptions()
509 );
510 $this->generatorExecutor = $generator->isFast() ?
511 new SyncGeneratorExecutor($executorSetupParameters) :
513 $this->logger,
514 $this->workerPool,
515 $executorSetupParameters,
516 $this->worldId
517 );
518
519 $this->chunkPopulationRequestQueue = new \SplQueue();
520 $this->addOnUnloadCallback(function() : void{
521 $this->logger->debug("Cancelling unfulfilled generation requests");
522
523 foreach($this->chunkPopulationRequestMap as $chunkHash => $promise){
524 $promise->reject();
525 unset($this->chunkPopulationRequestMap[$chunkHash]);
526 }
527 if(count($this->chunkPopulationRequestMap) !== 0){
528 //TODO: this might actually get hit because generation rejection callbacks might try to schedule new
529 //requests, and we can't prevent that right now because there's no way to detect "unloading" state
530 throw new AssumptionFailedError("New generation requests scheduled during unload");
531 }
532 });
533
534 $this->scheduledBlockUpdateQueue = new ReversePriorityQueue();
535 $this->scheduledBlockUpdateQueue->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
536
537 $this->neighbourBlockUpdateQueue = new \SplQueue();
538
539 $this->time = $this->provider->getWorldData()->getTime();
540
541 $cfg = $this->server->getConfigGroup();
542 $this->chunkTickRadius = min($this->server->getViewDistance(), max(0, $cfg->getPropertyInt(YmlServerProperties::CHUNK_TICKING_TICK_RADIUS, 4)));
543 if($cfg->getPropertyInt("chunk-ticking.per-tick", 40) <= 0){
544 //TODO: this needs l10n
545 $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.");
546 $this->chunkTickRadius = 0;
547 }
548 $this->tickedBlocksPerSubchunkPerTick = $cfg->getPropertyInt(YmlServerProperties::CHUNK_TICKING_BLOCKS_PER_SUBCHUNK_PER_TICK, self::DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK);
549 $this->maxConcurrentChunkPopulationTasks = $cfg->getPropertyInt(YmlServerProperties::CHUNK_GENERATION_POPULATION_QUEUE_SIZE, 2);
550
551 $this->initRandomTickBlocksFromConfig($cfg);
552
553 $this->timings = new WorldTimings($this);
554 }
555
556 private function initRandomTickBlocksFromConfig(ServerConfigGroup $cfg) : void{
557 $dontTickBlocks = [];
558 $parser = StringToItemParser::getInstance();
559 foreach($cfg->getProperty(YmlServerProperties::CHUNK_TICKING_DISABLE_BLOCK_TICKING, []) as $name){
560 $name = (string) $name;
561 $item = $parser->parse($name);
562 if($item !== null){
563 $block = $item->getBlock();
564 }elseif(preg_match("/^-?\d+$/", $name) === 1){
565 //TODO: this is a really sketchy hack - remove this as soon as possible
566 try{
567 $blockStateData = GlobalBlockStateHandlers::getUpgrader()->upgradeIntIdMeta((int) $name, 0);
568 }catch(BlockStateDeserializeException){
569 continue;
570 }
571 $block = $this->blockStateRegistry->fromStateId(GlobalBlockStateHandlers::getDeserializer()->deserialize($blockStateData));
572 }else{
573 //TODO: we probably ought to log an error here
574 continue;
575 }
576
577 if($block->getTypeId() !== BlockTypeIds::AIR){
578 $dontTickBlocks[$block->getTypeId()] = $name;
579 }
580 }
581
582 foreach($this->blockStateRegistry->getAllKnownStates() as $state){
583 $dontTickName = $dontTickBlocks[$state->getTypeId()] ?? null;
584 if($dontTickName === null && $state->ticksRandomly()){
585 $this->randomTickBlocks[$state->getStateId()] = true;
586 }
587 }
588 }
589
590 public function getTickRateTime() : float{
591 return $this->tickRateTime;
592 }
593
594 public function getServer() : Server{
595 return $this->server;
596 }
597
598 public function getLogger() : \Logger{
599 return $this->logger;
600 }
601
602 final public function getProvider() : WritableWorldProvider{
603 return $this->provider;
604 }
605
609 final public function getId() : int{
610 return $this->worldId;
611 }
612
613 public function isLoaded() : bool{
614 return !$this->unloaded;
615 }
616
620 public function onUnload() : void{
621 if($this->unloaded){
622 throw new \LogicException("Tried to close a world which is already closed");
623 }
624
625 foreach($this->unloadCallbacks as $callback){
626 $callback();
627 }
628 $this->unloadCallbacks = [];
629
630 foreach($this->chunks as $chunkHash => $chunk){
631 self::getXZ($chunkHash, $chunkX, $chunkZ);
632 $this->unloadChunk($chunkX, $chunkZ, false);
633 }
634 $this->knownUngeneratedChunks = [];
635 foreach($this->entitiesByChunk as $chunkHash => $entities){
636 self::getXZ($chunkHash, $chunkX, $chunkZ);
637
638 $leakedEntities = 0;
639 foreach($entities as $entity){
640 if(!$entity->isFlaggedForDespawn()){
641 $leakedEntities++;
642 }
643 $entity->close();
644 }
645 if($leakedEntities !== 0){
646 $this->logger->warning("$leakedEntities leaked entities found in ungenerated chunk $chunkX $chunkZ during unload, they won't be saved!");
647 }
648 }
649
650 $this->save();
651
652 $this->generatorExecutor->shutdown();
653
654 $this->provider->close();
655 $this->blockCache = [];
656 $this->blockCacheSize = 0;
657 $this->blockCollisionBoxCache = [];
658
659 $this->unloaded = true;
660 }
661
663 public function addOnUnloadCallback(\Closure $callback) : void{
664 $this->unloadCallbacks[spl_object_id($callback)] = $callback;
665 }
666
668 public function removeOnUnloadCallback(\Closure $callback) : void{
669 unset($this->unloadCallbacks[spl_object_id($callback)]);
670 }
671
680 private function filterViewersForPosition(Vector3 $pos, array $allowed) : array{
681 $candidates = $this->getViewersForPosition($pos);
682 $filtered = [];
683 foreach($allowed as $player){
684 $k = spl_object_id($player);
685 if(isset($candidates[$k])){
686 $filtered[$k] = $candidates[$k];
687 }
688 }
689
690 return $filtered;
691 }
692
696 public function addSound(Vector3 $pos, Sound $sound, ?array $players = null) : void{
697 $players ??= $this->getViewersForPosition($pos);
698
699 if(WorldSoundEvent::hasHandlers()){
700 $ev = new WorldSoundEvent($this, $sound, $pos, $players);
701 $ev->call();
702 if($ev->isCancelled()){
703 return;
704 }
705
706 $sound = $ev->getSound();
707 $players = $ev->getRecipients();
708 }
709
710 $pk = $sound->encode($pos);
711 if(count($pk) > 0){
712 if($players === $this->getViewersForPosition($pos)){
713 foreach($pk as $e){
714 $this->broadcastPacketToViewers($pos, $e);
715 }
716 }else{
717 NetworkBroadcastUtils::broadcastPackets($this->filterViewersForPosition($pos, $players), $pk);
718 }
719 }
720 }
721
725 public function addParticle(Vector3 $pos, Particle $particle, ?array $players = null) : void{
726 $players ??= $this->getViewersForPosition($pos);
727
728 if(WorldParticleEvent::hasHandlers()){
729 $ev = new WorldParticleEvent($this, $particle, $pos, $players);
730 $ev->call();
731 if($ev->isCancelled()){
732 return;
733 }
734
735 $particle = $ev->getParticle();
736 $players = $ev->getRecipients();
737 }
738
739 $pk = $particle->encode($pos);
740 if(count($pk) > 0){
741 if($players === $this->getViewersForPosition($pos)){
742 foreach($pk as $e){
743 $this->broadcastPacketToViewers($pos, $e);
744 }
745 }else{
746 NetworkBroadcastUtils::broadcastPackets($this->filterViewersForPosition($pos, $players), $pk);
747 }
748 }
749 }
750
751 public function getAutoSave() : bool{
752 return $this->autoSave;
753 }
754
755 public function setAutoSave(bool $value) : void{
756 $this->autoSave = $value;
757 }
758
768 public function getChunkPlayers(int $chunkX, int $chunkZ) : array{
769 return $this->playerChunkListeners[World::chunkHash($chunkX, $chunkZ)] ?? [];
770 }
771
778 public function getChunkLoaders(int $chunkX, int $chunkZ) : array{
779 return $this->chunkLoaders[World::chunkHash($chunkX, $chunkZ)] ?? [];
780 }
781
788 public function getViewersForPosition(Vector3 $pos) : array{
789 return $this->getChunkPlayers($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
790 }
791
795 public function broadcastPacketToViewers(Vector3 $pos, ClientboundPacket $packet) : void{
796 $this->broadcastPacketToPlayersUsingChunk($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE, $packet);
797 }
798
799 private function broadcastPacketToPlayersUsingChunk(int $chunkX, int $chunkZ, ClientboundPacket $packet) : void{
800 if(!isset($this->packetBuffersByChunk[$index = World::chunkHash($chunkX, $chunkZ)])){
801 $this->packetBuffersByChunk[$index] = [$packet];
802 }else{
803 $this->packetBuffersByChunk[$index][] = $packet;
804 }
805 }
806
807 public function registerChunkLoader(ChunkLoader $loader, int $chunkX, int $chunkZ, bool $autoLoad = true) : void{
808 $loaderId = spl_object_id($loader);
809
810 if(!isset($this->chunkLoaders[$chunkHash = World::chunkHash($chunkX, $chunkZ)])){
811 $this->chunkLoaders[$chunkHash] = [];
812 }elseif(isset($this->chunkLoaders[$chunkHash][$loaderId])){
813 return;
814 }
815
816 $this->chunkLoaders[$chunkHash][$loaderId] = $loader;
817
818 $this->cancelUnloadChunkRequest($chunkX, $chunkZ);
819
820 if($autoLoad){
821 $this->loadChunk($chunkX, $chunkZ);
822 }
823 }
824
825 public function unregisterChunkLoader(ChunkLoader $loader, int $chunkX, int $chunkZ) : void{
826 $chunkHash = World::chunkHash($chunkX, $chunkZ);
827 $loaderId = spl_object_id($loader);
828 if(isset($this->chunkLoaders[$chunkHash][$loaderId])){
829 if(count($this->chunkLoaders[$chunkHash]) === 1){
830 unset($this->chunkLoaders[$chunkHash]);
831 $this->unloadChunkRequest($chunkX, $chunkZ, true);
832 if(isset($this->chunkPopulationRequestMap[$chunkHash]) && !isset($this->activeChunkPopulationTasks[$chunkHash])){
833 $this->chunkPopulationRequestMap[$chunkHash]->reject();
834 unset($this->chunkPopulationRequestMap[$chunkHash]);
835 }
836 }else{
837 unset($this->chunkLoaders[$chunkHash][$loaderId]);
838 }
839 }
840 }
841
845 public function registerChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ) : void{
846 $hash = World::chunkHash($chunkX, $chunkZ);
847 if(isset($this->chunkListeners[$hash])){
848 $this->chunkListeners[$hash][spl_object_id($listener)] = $listener;
849 }else{
850 $this->chunkListeners[$hash] = [spl_object_id($listener) => $listener];
851 }
852 if($listener instanceof Player){
853 $this->playerChunkListeners[$hash][spl_object_id($listener)] = $listener;
854 }
855 }
856
862 public function unregisterChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ) : void{
863 $hash = World::chunkHash($chunkX, $chunkZ);
864 if(isset($this->chunkListeners[$hash])){
865 if(count($this->chunkListeners[$hash]) === 1){
866 unset($this->chunkListeners[$hash]);
867 unset($this->playerChunkListeners[$hash]);
868 }else{
869 unset($this->chunkListeners[$hash][spl_object_id($listener)]);
870 unset($this->playerChunkListeners[$hash][spl_object_id($listener)]);
871 }
872 }
873 }
874
878 public function unregisterChunkListenerFromAll(ChunkListener $listener) : void{
879 foreach($this->chunkListeners as $hash => $listeners){
880 World::getXZ($hash, $chunkX, $chunkZ);
881 $this->unregisterChunkListener($listener, $chunkX, $chunkZ);
882 }
883 }
884
891 public function getChunkListeners(int $chunkX, int $chunkZ) : array{
892 return $this->chunkListeners[World::chunkHash($chunkX, $chunkZ)] ?? [];
893 }
894
898 public function sendTime(Player ...$targets) : void{
899 if(count($targets) === 0){
900 $targets = $this->players;
901 }
902 foreach($targets as $player){
903 $player->getNetworkSession()->syncWorldTime($this->time);
904 }
905 }
906
907 public function isDoingTick() : bool{
908 return $this->doingTick;
909 }
910
914 public function doTick(int $currentTick) : void{
915 if($this->unloaded){
916 throw new \LogicException("Attempted to tick a world which has been closed");
917 }
918
919 $this->timings->doTick->startTiming();
920 $this->doingTick = true;
921 try{
922 $this->actuallyDoTick($currentTick);
923 }finally{
924 $this->doingTick = false;
925 $this->timings->doTick->stopTiming();
926 }
927 }
928
929 protected function actuallyDoTick(int $currentTick) : void{
930 if(!$this->stopTime){
931 //this simulates an overflow, as would happen in any language which doesn't do stupid things to var types
932 if($this->time === PHP_INT_MAX){
933 $this->time = PHP_INT_MIN;
934 }else{
935 $this->time++;
936 }
937 }
938
939 $this->sunAnglePercentage = $this->computeSunAnglePercentage(); //Sun angle depends on the current time
940 $this->skyLightReduction = $this->computeSkyLightReduction(); //Sky light reduction depends on the sun angle
941
942 if(++$this->sendTimeTicker === 200){
943 $this->sendTime();
944 $this->sendTimeTicker = 0;
945 }
946
947 $this->unloadChunks();
948 if(++$this->providerGarbageCollectionTicker >= 6000){
949 $this->provider->doGarbageCollection();
950 $this->providerGarbageCollectionTicker = 0;
951 }
952
953 $this->timings->scheduledBlockUpdates->startTiming();
954 //Delayed updates
955 while($this->scheduledBlockUpdateQueue->count() > 0 && $this->scheduledBlockUpdateQueue->current()["priority"] <= $currentTick){
957 $vec = $this->scheduledBlockUpdateQueue->extract()["data"];
958 unset($this->scheduledBlockUpdateQueueIndex[World::blockHash($vec->x, $vec->y, $vec->z)]);
959 if(!$this->isInLoadedTerrain($vec)){
960 continue;
961 }
962 $block = $this->getBlock($vec);
963 $block->onScheduledUpdate();
964 }
965 $this->timings->scheduledBlockUpdates->stopTiming();
966
967 $this->timings->neighbourBlockUpdates->startTiming();
968 //Normal updates
969 while($this->neighbourBlockUpdateQueue->count() > 0){
970 $index = $this->neighbourBlockUpdateQueue->dequeue();
971 unset($this->neighbourBlockUpdateQueueIndex[$index]);
972 World::getBlockXYZ($index, $x, $y, $z);
973 if(!$this->isChunkLoaded($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)){
974 continue;
975 }
976
977 $block = $this->getBlockAt($x, $y, $z);
978
979 if(BlockUpdateEvent::hasHandlers()){
980 $ev = new BlockUpdateEvent($block);
981 $ev->call();
982 if($ev->isCancelled()){
983 continue;
984 }
985 }
986 foreach($this->getNearbyEntities(AxisAlignedBB::one()->offset($x, $y, $z)) as $entity){
987 $entity->onNearbyBlockChange();
988 }
989 $block->onNearbyBlockChange();
990 }
991
992 $this->timings->neighbourBlockUpdates->stopTiming();
993
994 $this->timings->entityTick->startTiming();
995 //Update entities that need update
996 foreach($this->updateEntities as $id => $entity){
997 if($entity->isClosed() || $entity->isFlaggedForDespawn() || !$entity->onUpdate($currentTick)){
998 unset($this->updateEntities[$id]);
999 }
1000 if($entity->isFlaggedForDespawn()){
1001 $entity->close();
1002 }
1003 }
1004 $this->timings->entityTick->stopTiming();
1005
1006 $this->timings->randomChunkUpdates->startTiming();
1007 $this->tickChunks();
1008 $this->timings->randomChunkUpdates->stopTiming();
1009
1010 $this->executeQueuedLightUpdates();
1011
1012 if(count($this->changedBlocks) > 0){
1013 if(count($this->players) > 0){
1014 foreach($this->changedBlocks as $index => $blocks){
1015 if(count($blocks) === 0){ //blocks can be set normally and then later re-set with direct send
1016 continue;
1017 }
1018 World::getXZ($index, $chunkX, $chunkZ);
1019 if(!$this->isChunkLoaded($chunkX, $chunkZ)){
1020 //a previous chunk may have caused this one to be unloaded by a ChunkListener
1021 continue;
1022 }
1023 if(count($blocks) > 512){
1024 $chunk = $this->getChunk($chunkX, $chunkZ) ?? throw new AssumptionFailedError("We already checked that the chunk is loaded");
1025 foreach($this->getChunkPlayers($chunkX, $chunkZ) as $p){
1026 $p->onChunkChanged($chunkX, $chunkZ, $chunk);
1027 }
1028 }else{
1029 foreach($this->createBlockUpdatePackets($blocks) as $packet){
1030 $this->broadcastPacketToPlayersUsingChunk($chunkX, $chunkZ, $packet);
1031 }
1032 }
1033 }
1034 }
1035
1036 $this->changedBlocks = [];
1037
1038 }
1039
1040 if($this->sleepTicks > 0 && --$this->sleepTicks <= 0){
1041 $this->checkSleep();
1042 }
1043
1044 foreach($this->packetBuffersByChunk as $index => $entries){
1045 World::getXZ($index, $chunkX, $chunkZ);
1046 $chunkPlayers = $this->getChunkPlayers($chunkX, $chunkZ);
1047 if(count($chunkPlayers) > 0){
1048 NetworkBroadcastUtils::broadcastPackets($chunkPlayers, $entries);
1049 }
1050 }
1051
1052 $this->packetBuffersByChunk = [];
1053 }
1054
1055 public function checkSleep() : void{
1056 if(count($this->players) === 0){
1057 return;
1058 }
1059
1060 $resetTime = true;
1061 foreach($this->getPlayers() as $p){
1062 if(!$p->isSleeping()){
1063 $resetTime = false;
1064 break;
1065 }
1066 }
1067
1068 if($resetTime){
1069 $time = $this->getTimeOfDay();
1070
1071 if($time >= World::TIME_NIGHT && $time < World::TIME_SUNRISE){
1072 $this->setTime($this->getTime() + World::TIME_FULL - $time);
1073
1074 foreach($this->getPlayers() as $p){
1075 $p->stopSleep();
1076 }
1077 }
1078 }
1079 }
1080
1081 public function setSleepTicks(int $ticks) : void{
1082 $this->sleepTicks = $ticks;
1083 }
1084
1091 public function createBlockUpdatePackets(array $blocks) : array{
1092 $packets = [];
1093
1094 $blockTranslator = TypeConverter::getInstance()->getBlockTranslator();
1095
1096 foreach($blocks as $b){
1097 if(!($b instanceof Vector3)){
1098 throw new \TypeError("Expected Vector3 in blocks array, got " . (is_object($b) ? get_class($b) : gettype($b)));
1099 }
1100
1101 $fullBlock = $this->getBlockAt($b->x, $b->y, $b->z);
1102 $blockPosition = BlockPosition::fromVector3($b);
1103
1104 $tile = $this->getTileAt($b->x, $b->y, $b->z);
1105 if($tile instanceof Spawnable){
1106 $expectedClass = $fullBlock->getIdInfo()->getTileClass();
1107 if($expectedClass !== null && $tile instanceof $expectedClass && count($fakeStateProperties = $tile->getRenderUpdateBugWorkaroundStateProperties($fullBlock)) > 0){
1108 $originalStateData = $blockTranslator->internalIdToNetworkStateData($fullBlock->getStateId());
1109 $fakeStateData = new BlockStateData(
1110 $originalStateData->getName(),
1111 array_merge($originalStateData->getStates(), $fakeStateProperties),
1112 $originalStateData->getVersion()
1113 );
1114 $packets[] = UpdateBlockPacket::create(
1115 $blockPosition,
1116 $blockTranslator->getBlockStateDictionary()->lookupStateIdFromData($fakeStateData) ?? throw new AssumptionFailedError("Unmapped fake blockstate data: " . $fakeStateData->toNbt()),
1117 UpdateBlockPacket::FLAG_NETWORK,
1118 UpdateBlockPacket::DATA_LAYER_NORMAL
1119 );
1120 }
1121 }
1122 $packets[] = UpdateBlockPacket::create(
1123 $blockPosition,
1124 $blockTranslator->internalIdToNetworkId($fullBlock->getStateId()),
1125 UpdateBlockPacket::FLAG_NETWORK,
1126 UpdateBlockPacket::DATA_LAYER_NORMAL
1127 );
1128
1129 if($tile instanceof Spawnable){
1130 $packets[] = BlockActorDataPacket::create($blockPosition, $tile->getSerializedSpawnCompound());
1131 }
1132 }
1133
1134 return $packets;
1135 }
1136
1137 public function clearCache(bool $force = false) : void{
1138 if($force){
1139 $this->blockCache = [];
1140 $this->blockCacheSize = 0;
1141 $this->blockCollisionBoxCache = [];
1142 }else{
1143 //Recalculate this when we're asked - blockCacheSize may be higher than the real size
1144 $this->blockCacheSize = 0;
1145 foreach($this->blockCache as $list){
1146 $this->blockCacheSize += count($list);
1147 if($this->blockCacheSize > self::BLOCK_CACHE_SIZE_CAP){
1148 $this->blockCache = [];
1149 $this->blockCacheSize = 0;
1150 break;
1151 }
1152 }
1153
1154 $count = 0;
1155 foreach($this->blockCollisionBoxCache as $list){
1156 $count += count($list);
1157 if($count > self::BLOCK_CACHE_SIZE_CAP){
1158 //TODO: Is this really the best logic?
1159 $this->blockCollisionBoxCache = [];
1160 break;
1161 }
1162 }
1163 }
1164 }
1165
1166 private function trimBlockCache() : void{
1167 $before = $this->blockCacheSize;
1168 //Since PHP maintains key order, earliest in foreach should be the oldest entries
1169 //Older entries are less likely to be hot, so destroying these should usually have the lowest impact on performance
1170 foreach($this->blockCache as $chunkHash => $blocks){
1171 unset($this->blockCache[$chunkHash]);
1172 $this->blockCacheSize -= count($blocks);
1173 if($this->blockCacheSize < self::BLOCK_CACHE_SIZE_CAP){
1174 break;
1175 }
1176 }
1177 }
1178
1183 public function getRandomTickedBlocks() : array{
1184 return $this->randomTickBlocks;
1185 }
1186
1187 public function addRandomTickedBlock(Block $block) : void{
1188 if($block instanceof UnknownBlock){
1189 throw new \InvalidArgumentException("Cannot do random-tick on unknown block");
1190 }
1191 $this->randomTickBlocks[$block->getStateId()] = true;
1192 }
1193
1194 public function removeRandomTickedBlock(Block $block) : void{
1195 unset($this->randomTickBlocks[$block->getStateId()]);
1196 }
1197
1202 public function getChunkTickRadius() : int{
1203 return $this->chunkTickRadius;
1204 }
1205
1210 public function setChunkTickRadius(int $radius) : void{
1211 $this->chunkTickRadius = $radius;
1212 }
1213
1221 public function getTickingChunks() : array{
1222 return array_keys($this->validTickingChunks);
1223 }
1224
1229 public function registerTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ) : void{
1230 $chunkPosHash = World::chunkHash($chunkX, $chunkZ);
1231 $this->registeredTickingChunks[$chunkPosHash][spl_object_id($ticker)] = $ticker;
1232 $this->recheckTickingChunks[$chunkPosHash] = $chunkPosHash;
1233 }
1234
1239 public function unregisterTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ) : void{
1240 $chunkHash = World::chunkHash($chunkX, $chunkZ);
1241 $tickerId = spl_object_id($ticker);
1242 if(isset($this->registeredTickingChunks[$chunkHash][$tickerId])){
1243 if(count($this->registeredTickingChunks[$chunkHash]) === 1){
1244 unset(
1245 $this->registeredTickingChunks[$chunkHash],
1246 $this->recheckTickingChunks[$chunkHash],
1247 $this->validTickingChunks[$chunkHash]
1248 );
1249 }else{
1250 unset($this->registeredTickingChunks[$chunkHash][$tickerId]);
1251 }
1252 }
1253 }
1254
1255 private function tickChunks() : void{
1256 if($this->chunkTickRadius <= 0 || count($this->registeredTickingChunks) === 0){
1257 return;
1258 }
1259
1260 if(count($this->recheckTickingChunks) > 0){
1261 $this->timings->randomChunkUpdatesChunkSelection->startTiming();
1262
1263 $chunkTickableCache = [];
1264
1265 foreach($this->recheckTickingChunks as $hash => $_){
1266 World::getXZ($hash, $chunkX, $chunkZ);
1267 if($this->isChunkTickable($chunkX, $chunkZ, $chunkTickableCache)){
1268 $this->validTickingChunks[$hash] = $hash;
1269 }
1270 }
1271 $this->recheckTickingChunks = [];
1272
1273 $this->timings->randomChunkUpdatesChunkSelection->stopTiming();
1274 }
1275
1276 foreach($this->validTickingChunks as $index => $_){
1277 World::getXZ($index, $chunkX, $chunkZ);
1278
1279 $this->tickChunk($chunkX, $chunkZ);
1280 }
1281 }
1282
1289 private function isChunkTickable(int $chunkX, int $chunkZ, array &$cache) : bool{
1290 for($cx = -1; $cx <= 1; ++$cx){
1291 for($cz = -1; $cz <= 1; ++$cz){
1292 $chunkHash = World::chunkHash($chunkX + $cx, $chunkZ + $cz);
1293 if(isset($cache[$chunkHash])){
1294 if(!$cache[$chunkHash]){
1295 return false;
1296 }
1297 continue;
1298 }
1299 if($this->isChunkLocked($chunkX + $cx, $chunkZ + $cz)){
1300 $cache[$chunkHash] = false;
1301 return false;
1302 }
1303 $adjacentChunk = $this->getChunk($chunkX + $cx, $chunkZ + $cz);
1304 if($adjacentChunk === null || !$adjacentChunk->isPopulated()){
1305 $cache[$chunkHash] = false;
1306 return false;
1307 }
1308 $lightPopulatedState = $adjacentChunk->isLightPopulated();
1309 if($lightPopulatedState !== true){
1310 if($lightPopulatedState === false){
1311 $this->orderLightPopulation($chunkX + $cx, $chunkZ + $cz);
1312 }
1313 $cache[$chunkHash] = false;
1314 return false;
1315 }
1316
1317 $cache[$chunkHash] = true;
1318 }
1319 }
1320
1321 return true;
1322 }
1323
1333 private function markTickingChunkForRecheck(int $chunkX, int $chunkZ) : void{
1334 for($cx = -1; $cx <= 1; ++$cx){
1335 for($cz = -1; $cz <= 1; ++$cz){
1336 $chunkHash = World::chunkHash($chunkX + $cx, $chunkZ + $cz);
1337 unset($this->validTickingChunks[$chunkHash]);
1338 if(isset($this->registeredTickingChunks[$chunkHash])){
1339 $this->recheckTickingChunks[$chunkHash] = $chunkHash;
1340 }else{
1341 unset($this->recheckTickingChunks[$chunkHash]);
1342 }
1343 }
1344 }
1345 }
1346
1347 private function orderLightPopulation(int $chunkX, int $chunkZ) : void{
1348 $chunkHash = World::chunkHash($chunkX, $chunkZ);
1349 $lightPopulatedState = $this->chunks[$chunkHash]->isLightPopulated();
1350 if($lightPopulatedState === false){
1351 $this->chunks[$chunkHash]->setLightPopulated(null);
1352 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
1353
1354 $this->workerPool->submitTask(new LightPopulationTask(
1355 $this->chunks[$chunkHash],
1356 function(array $blockLight, array $skyLight, array $heightMap) use ($chunkX, $chunkZ) : void{
1363 if($this->unloaded || ($chunk = $this->getChunk($chunkX, $chunkZ)) === null || $chunk->isLightPopulated() === true){
1364 return;
1365 }
1366 //TODO: calculated light information might not be valid if the terrain changed during light calculation
1367
1368 $chunk->setHeightMapArray($heightMap);
1369 foreach($blockLight as $y => $lightArray){
1370 $chunk->getSubChunk($y)->setBlockLightArray($lightArray);
1371 }
1372 foreach($skyLight as $y => $lightArray){
1373 $chunk->getSubChunk($y)->setBlockSkyLightArray($lightArray);
1374 }
1375 $chunk->setLightPopulated(true);
1376 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
1377 }
1378 ));
1379 }
1380 }
1381
1382 private function tickChunk(int $chunkX, int $chunkZ) : void{
1383 $chunk = $this->getChunk($chunkX, $chunkZ);
1384 if($chunk === null){
1385 //the chunk may have been unloaded during a previous chunk's update (e.g. during BlockGrowEvent)
1386 return;
1387 }
1388 foreach($this->getChunkEntities($chunkX, $chunkZ) as $entity){
1389 $entity->onRandomUpdate();
1390 }
1391
1392 $blockFactory = $this->blockStateRegistry;
1393 foreach($chunk->getSubChunks() as $Y => $subChunk){
1394 if(!$subChunk->isEmptyFast()){
1395 $k = 0;
1396 for($i = 0; $i < $this->tickedBlocksPerSubchunkPerTick; ++$i){
1397 if(($i % 5) === 0){
1398 //60 bits will be used by 5 blocks (12 bits each)
1399 $k = mt_rand(0, (1 << 60) - 1);
1400 }
1401 $x = $k & SubChunk::COORD_MASK;
1402 $y = ($k >> SubChunk::COORD_BIT_SIZE) & SubChunk::COORD_MASK;
1403 $z = ($k >> (SubChunk::COORD_BIT_SIZE * 2)) & SubChunk::COORD_MASK;
1404 $k >>= (SubChunk::COORD_BIT_SIZE * 3);
1405
1406 $state = $subChunk->getBlockStateId($x, $y, $z);
1407
1408 if(isset($this->randomTickBlocks[$state])){
1409 $block = $blockFactory->fromStateId($state);
1410 $block->position($this, $chunkX * Chunk::EDGE_LENGTH + $x, ($Y << SubChunk::COORD_BIT_SIZE) + $y, $chunkZ * Chunk::EDGE_LENGTH + $z);
1411 $block->onRandomTick();
1412 }
1413 }
1414 }
1415 }
1416 }
1417
1421 public function __debugInfo() : array{
1422 return [];
1423 }
1424
1425 public function save(bool $force = false) : bool{
1426
1427 if(!$this->getAutoSave() && !$force){
1428 return false;
1429 }
1430
1431 (new WorldSaveEvent($this))->call();
1432
1433 $timings = $this->timings->syncDataSave;
1434 $timings->startTiming();
1435
1436 $this->provider->getWorldData()->setTime($this->time);
1437 $this->saveChunks();
1438 $this->provider->getWorldData()->save();
1439
1440 $timings->stopTiming();
1441
1442 return true;
1443 }
1444
1445 public function saveChunks() : void{
1446 $this->timings->syncChunkSave->startTiming();
1447 try{
1448 foreach($this->chunks as $chunkHash => $chunk){
1449 self::getXZ($chunkHash, $chunkX, $chunkZ);
1450 $this->provider->saveChunk($chunkX, $chunkZ, new ChunkData(
1451 $chunk->getSubChunks(),
1452 $chunk->isPopulated(),
1453 array_map(fn(Entity $e) => $e->saveNBT(), array_values(array_filter($this->getChunkEntities($chunkX, $chunkZ), fn(Entity $e) => $e->canSaveWithChunk()))),
1454 array_map(fn(Tile $t) => $t->saveNBT(), array_values($chunk->getTiles())),
1455 ), $chunk->getTerrainDirtyFlags());
1456 $chunk->clearTerrainDirtyFlags();
1457 }
1458 }finally{
1459 $this->timings->syncChunkSave->stopTiming();
1460 }
1461 }
1462
1467 public function scheduleDelayedBlockUpdate(Vector3 $pos, int $delay) : void{
1468 if(
1469 !$this->isInWorld($pos->x, $pos->y, $pos->z) ||
1470 (isset($this->scheduledBlockUpdateQueueIndex[$index = World::blockHash($pos->x, $pos->y, $pos->z)]) && $this->scheduledBlockUpdateQueueIndex[$index] <= $delay)
1471 ){
1472 return;
1473 }
1474 $this->scheduledBlockUpdateQueueIndex[$index] = $delay;
1475 $this->scheduledBlockUpdateQueue->insert(new Vector3((int) $pos->x, (int) $pos->y, (int) $pos->z), $delay + $this->server->getTick());
1476 }
1477
1478 private function tryAddToNeighbourUpdateQueue(int $x, int $y, int $z) : void{
1479 if($this->isInWorld($x, $y, $z)){
1480 $hash = World::blockHash($x, $y, $z);
1481 if(!isset($this->neighbourBlockUpdateQueueIndex[$hash])){
1482 $this->neighbourBlockUpdateQueue->enqueue($hash);
1483 $this->neighbourBlockUpdateQueueIndex[$hash] = true;
1484 }
1485 }
1486 }
1487
1494 private function internalNotifyNeighbourBlockUpdate(int $x, int $y, int $z) : void{
1495 $this->tryAddToNeighbourUpdateQueue($x, $y, $z);
1496 foreach(Facing::OFFSET as [$dx, $dy, $dz]){
1497 $this->tryAddToNeighbourUpdateQueue($x + $dx, $y + $dy, $z + $dz);
1498 }
1499 }
1500
1508 public function notifyNeighbourBlockUpdate(Vector3 $pos) : void{
1509 $this->internalNotifyNeighbourBlockUpdate($pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ());
1510 }
1511
1516 public function getCollisionBlocks(AxisAlignedBB $bb, bool $targetFirst = false) : array{
1517 $minX = (int) floor($bb->minX - 1);
1518 $minY = (int) floor($bb->minY - 1);
1519 $minZ = (int) floor($bb->minZ - 1);
1520 $maxX = (int) floor($bb->maxX + 1);
1521 $maxY = (int) floor($bb->maxY + 1);
1522 $maxZ = (int) floor($bb->maxZ + 1);
1523
1524 $collides = [];
1525
1526 $collisionInfo = $this->blockStateRegistry->collisionInfo;
1527 if($targetFirst){
1528 for($z = $minZ; $z <= $maxZ; ++$z){
1529 $zOverflow = $z === $minZ || $z === $maxZ;
1530 for($x = $minX; $x <= $maxX; ++$x){
1531 $zxOverflow = $zOverflow || $x === $minX || $x === $maxX;
1532 for($y = $minY; $y <= $maxY; ++$y){
1533 $overflow = $zxOverflow || $y === $minY || $y === $maxY;
1534
1535 $stateCollisionInfo = $this->getBlockCollisionInfo($x, $y, $z, $collisionInfo);
1536 if($overflow ?
1537 $stateCollisionInfo === RuntimeBlockStateRegistry::COLLISION_MAY_OVERFLOW && $this->getBlockAt($x, $y, $z)->collidesWithBB($bb) :
1538 match ($stateCollisionInfo) {
1539 RuntimeBlockStateRegistry::COLLISION_CUBE => true,
1540 RuntimeBlockStateRegistry::COLLISION_NONE => false,
1541 default => $this->getBlockAt($x, $y, $z)->collidesWithBB($bb)
1542 }
1543 ){
1544 return [$this->getBlockAt($x, $y, $z)];
1545 }
1546 }
1547 }
1548 }
1549 }else{
1550 //TODO: duplicated code :( this way is better for performance though
1551 for($z = $minZ; $z <= $maxZ; ++$z){
1552 $zOverflow = $z === $minZ || $z === $maxZ;
1553 for($x = $minX; $x <= $maxX; ++$x){
1554 $zxOverflow = $zOverflow || $x === $minX || $x === $maxX;
1555 for($y = $minY; $y <= $maxY; ++$y){
1556 $overflow = $zxOverflow || $y === $minY || $y === $maxY;
1557
1558 $stateCollisionInfo = $this->getBlockCollisionInfo($x, $y, $z, $collisionInfo);
1559 if($overflow ?
1560 $stateCollisionInfo === RuntimeBlockStateRegistry::COLLISION_MAY_OVERFLOW && $this->getBlockAt($x, $y, $z)->collidesWithBB($bb) :
1561 match ($stateCollisionInfo) {
1562 RuntimeBlockStateRegistry::COLLISION_CUBE => true,
1563 RuntimeBlockStateRegistry::COLLISION_NONE => false,
1564 default => $this->getBlockAt($x, $y, $z)->collidesWithBB($bb)
1565 }
1566 ){
1567 $collides[] = $this->getBlockAt($x, $y, $z);
1568 }
1569 }
1570 }
1571 }
1572 }
1573
1574 return $collides;
1575 }
1576
1581 private function getBlockCollisionInfo(int $x, int $y, int $z, array $collisionInfo) : int{
1582 if(!$this->isInWorld($x, $y, $z)){
1583 return RuntimeBlockStateRegistry::COLLISION_NONE;
1584 }
1585 $chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE);
1586 if($chunk === null){
1587 return RuntimeBlockStateRegistry::COLLISION_NONE;
1588 }
1589 $stateId = $chunk
1590 ->getSubChunk($y >> SubChunk::COORD_BIT_SIZE)
1591 ->getBlockStateId(
1592 $x & SubChunk::COORD_MASK,
1593 $y & SubChunk::COORD_MASK,
1594 $z & SubChunk::COORD_MASK
1595 );
1596 return $collisionInfo[$stateId];
1597 }
1598
1610 private function getBlockCollisionBoxesForCell(int $x, int $y, int $z, array $collisionInfo) : array{
1611 $stateCollisionInfo = $this->getBlockCollisionInfo($x, $y, $z, $collisionInfo);
1612 $boxes = match($stateCollisionInfo){
1613 RuntimeBlockStateRegistry::COLLISION_NONE => [],
1614 RuntimeBlockStateRegistry::COLLISION_CUBE => [AxisAlignedBB::one()->offset($x, $y, $z)],
1615 default => $this->getBlockAt($x, $y, $z)->getCollisionBoxes()
1616 };
1617
1618 //overlapping AABBs can't make any difference if this is a cube, so we can save some CPU cycles in this common case
1619 if($stateCollisionInfo !== RuntimeBlockStateRegistry::COLLISION_CUBE){
1620 $cellBB = null;
1621 foreach(Facing::OFFSET as [$dx, $dy, $dz]){
1622 $offsetX = $x + $dx;
1623 $offsetY = $y + $dy;
1624 $offsetZ = $z + $dz;
1625 $stateCollisionInfo = $this->getBlockCollisionInfo($offsetX, $offsetY, $offsetZ, $collisionInfo);
1626 if($stateCollisionInfo === RuntimeBlockStateRegistry::COLLISION_MAY_OVERFLOW){
1627 //avoid allocating this unless it's needed
1628 $cellBB ??= AxisAlignedBB::one()->offset($x, $y, $z);
1629 $extraBoxes = $this->getBlockAt($offsetX, $offsetY, $offsetZ)->getCollisionBoxes();
1630 foreach($extraBoxes as $extraBox){
1631 if($extraBox->intersectsWith($cellBB)){
1632 $boxes[] = $extraBox;
1633 }
1634 }
1635 }
1636 }
1637 }
1638
1639 return $boxes;
1640 }
1641
1646 public function getBlockCollisionBoxes(AxisAlignedBB $bb) : array{
1647 $minX = (int) floor($bb->minX);
1648 $minY = (int) floor($bb->minY);
1649 $minZ = (int) floor($bb->minZ);
1650 $maxX = (int) floor($bb->maxX);
1651 $maxY = (int) floor($bb->maxY);
1652 $maxZ = (int) floor($bb->maxZ);
1653
1654 $collides = [];
1655
1656 $collisionInfo = $this->blockStateRegistry->collisionInfo;
1657
1658 for($z = $minZ; $z <= $maxZ; ++$z){
1659 for($x = $minX; $x <= $maxX; ++$x){
1660 $chunkPosHash = World::chunkHash($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE);
1661 for($y = $minY; $y <= $maxY; ++$y){
1662 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
1663
1664 $boxes = $this->blockCollisionBoxCache[$chunkPosHash][$relativeBlockHash] ??= $this->getBlockCollisionBoxesForCell($x, $y, $z, $collisionInfo);
1665
1666 foreach($boxes as $blockBB){
1667 if($blockBB->intersectsWith($bb)){
1668 $collides[] = $blockBB;
1669 }
1670 }
1671 }
1672 }
1673 }
1674
1675 return $collides;
1676 }
1677
1682 public function computeSunAnglePercentage() : float{
1683 $timeProgress = ($this->time % self::TIME_FULL) / self::TIME_FULL;
1684
1685 //0.0 needs to be high noon, not dusk
1686 $sunProgress = $timeProgress + ($timeProgress < 0.25 ? 0.75 : -0.25);
1687
1688 //Offset the sun progress to be above the horizon longer at dusk and dawn
1689 //this is roughly an inverted sine curve, which pushes the sun progress back at dusk and forwards at dawn
1690 $diff = (((1 - ((cos($sunProgress * M_PI) + 1) / 2)) - $sunProgress) / 3);
1691
1692 return $sunProgress + $diff;
1693 }
1694
1698 public function getSunAnglePercentage() : float{
1699 return $this->sunAnglePercentage;
1700 }
1701
1705 public function getSunAngleRadians() : float{
1706 return $this->sunAnglePercentage * 2 * M_PI;
1707 }
1708
1712 public function getSunAngleDegrees() : float{
1713 return $this->sunAnglePercentage * 360.0;
1714 }
1715
1720 public function computeSkyLightReduction() : int{
1721 $percentage = max(0, min(1, -(cos($this->getSunAngleRadians()) * 2 - 0.5)));
1722
1723 //TODO: check rain and thunder level
1724
1725 return (int) ($percentage * 11);
1726 }
1727
1731 public function getSkyLightReduction() : int{
1732 return $this->skyLightReduction;
1733 }
1734
1739 public function getFullLight(Vector3 $pos) : int{
1740 $floorX = $pos->getFloorX();
1741 $floorY = $pos->getFloorY();
1742 $floorZ = $pos->getFloorZ();
1743 return $this->getFullLightAt($floorX, $floorY, $floorZ);
1744 }
1745
1750 public function getFullLightAt(int $x, int $y, int $z) : int{
1751 $skyLight = $this->getRealBlockSkyLightAt($x, $y, $z);
1752 if($skyLight < 15){
1753 return max($skyLight, $this->getBlockLightAt($x, $y, $z));
1754 }else{
1755 return $skyLight;
1756 }
1757 }
1758
1763 public function getHighestAdjacentFullLightAt(int $x, int $y, int $z) : int{
1764 return $this->getHighestAdjacentLight($x, $y, $z, $this->getFullLightAt(...));
1765 }
1766
1771 public function getPotentialLight(Vector3 $pos) : int{
1772 $floorX = $pos->getFloorX();
1773 $floorY = $pos->getFloorY();
1774 $floorZ = $pos->getFloorZ();
1775 return $this->getPotentialLightAt($floorX, $floorY, $floorZ);
1776 }
1777
1782 public function getPotentialLightAt(int $x, int $y, int $z) : int{
1783 return max($this->getPotentialBlockSkyLightAt($x, $y, $z), $this->getBlockLightAt($x, $y, $z));
1784 }
1785
1790 public function getHighestAdjacentPotentialLightAt(int $x, int $y, int $z) : int{
1791 return $this->getHighestAdjacentLight($x, $y, $z, $this->getPotentialLightAt(...));
1792 }
1793
1800 public function getPotentialBlockSkyLightAt(int $x, int $y, int $z) : int{
1801 if(!$this->isInWorld($x, $y, $z)){
1802 return $y >= self::Y_MAX ? 15 : 0;
1803 }
1804 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null && $chunk->isLightPopulated() === true){
1805 return $chunk->getSubChunk($y >> Chunk::COORD_BIT_SIZE)->getBlockSkyLightArray()->get($x & SubChunk::COORD_MASK, $y & SubChunk::COORD_MASK, $z & SubChunk::COORD_MASK);
1806 }
1807 return 0; //TODO: this should probably throw instead (light not calculated yet)
1808 }
1809
1815 public function getRealBlockSkyLightAt(int $x, int $y, int $z) : int{
1816 $light = $this->getPotentialBlockSkyLightAt($x, $y, $z) - $this->skyLightReduction;
1817 return $light < 0 ? 0 : $light;
1818 }
1819
1825 public function getBlockLightAt(int $x, int $y, int $z) : int{
1826 if(!$this->isInWorld($x, $y, $z)){
1827 return 0;
1828 }
1829 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null && $chunk->isLightPopulated() === true){
1830 return $chunk->getSubChunk($y >> Chunk::COORD_BIT_SIZE)->getBlockLightArray()->get($x & SubChunk::COORD_MASK, $y & SubChunk::COORD_MASK, $z & SubChunk::COORD_MASK);
1831 }
1832 return 0; //TODO: this should probably throw instead (light not calculated yet)
1833 }
1834
1835 public function updateAllLight(int $x, int $y, int $z) : void{
1836 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) === null || $chunk->isLightPopulated() !== true){
1837 return;
1838 }
1839
1840 $blockFactory = $this->blockStateRegistry;
1841 $this->timings->doBlockSkyLightUpdates->startTiming();
1842 if($this->skyLightUpdate === null){
1843 $this->skyLightUpdate = new SkyLightUpdate(new SubChunkExplorer($this), $blockFactory->lightFilter, $blockFactory->blocksDirectSkyLight);
1844 }
1845 $this->skyLightUpdate->recalculateNode($x, $y, $z);
1846 $this->timings->doBlockSkyLightUpdates->stopTiming();
1847
1848 $this->timings->doBlockLightUpdates->startTiming();
1849 if($this->blockLightUpdate === null){
1850 $this->blockLightUpdate = new BlockLightUpdate(new SubChunkExplorer($this), $blockFactory->lightFilter, $blockFactory->light);
1851 }
1852 $this->blockLightUpdate->recalculateNode($x, $y, $z);
1853 $this->timings->doBlockLightUpdates->stopTiming();
1854 }
1855
1859 private function getHighestAdjacentLight(int $x, int $y, int $z, \Closure $lightGetter) : int{
1860 $max = 0;
1861 foreach(Facing::OFFSET as [$offsetX, $offsetY, $offsetZ]){
1862 $x1 = $x + $offsetX;
1863 $y1 = $y + $offsetY;
1864 $z1 = $z + $offsetZ;
1865 if(
1866 !$this->isInWorld($x1, $y1, $z1) ||
1867 ($chunk = $this->getChunk($x1 >> Chunk::COORD_BIT_SIZE, $z1 >> Chunk::COORD_BIT_SIZE)) === null ||
1868 $chunk->isLightPopulated() !== true
1869 ){
1870 continue;
1871 }
1872 $max = max($max, $lightGetter($x1, $y1, $z1));
1873 }
1874 return $max;
1875 }
1876
1880 public function getHighestAdjacentPotentialBlockSkyLight(int $x, int $y, int $z) : int{
1881 return $this->getHighestAdjacentLight($x, $y, $z, $this->getPotentialBlockSkyLightAt(...));
1882 }
1883
1888 public function getHighestAdjacentRealBlockSkyLight(int $x, int $y, int $z) : int{
1889 return $this->getHighestAdjacentPotentialBlockSkyLight($x, $y, $z) - $this->skyLightReduction;
1890 }
1891
1895 public function getHighestAdjacentBlockLight(int $x, int $y, int $z) : int{
1896 return $this->getHighestAdjacentLight($x, $y, $z, $this->getBlockLightAt(...));
1897 }
1898
1899 private function executeQueuedLightUpdates() : void{
1900 if($this->blockLightUpdate !== null){
1901 $this->timings->doBlockLightUpdates->startTiming();
1902 $this->blockLightUpdate->execute();
1903 $this->blockLightUpdate = null;
1904 $this->timings->doBlockLightUpdates->stopTiming();
1905 }
1906
1907 if($this->skyLightUpdate !== null){
1908 $this->timings->doBlockSkyLightUpdates->startTiming();
1909 $this->skyLightUpdate->execute();
1910 $this->skyLightUpdate = null;
1911 $this->timings->doBlockSkyLightUpdates->stopTiming();
1912 }
1913 }
1914
1915 public function isInWorld(int $x, int $y, int $z) : bool{
1916 return (
1917 $x <= Limits::INT32_MAX && $x >= Limits::INT32_MIN &&
1918 $y < $this->maxY && $y >= $this->minY &&
1919 $z <= Limits::INT32_MAX && $z >= Limits::INT32_MIN
1920 );
1921 }
1922
1933 public function getBlock(Vector3 $pos, bool $cached = true, bool $addToCache = true) : Block{
1934 return $this->getBlockAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z), $cached, $addToCache);
1935 }
1936
1946 public function getBlockAt(int $x, int $y, int $z, bool $cached = true, bool $addToCache = true) : Block{
1947 $relativeBlockHash = null;
1948 $chunkHash = World::chunkHash($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE);
1949
1950 if($this->isInWorld($x, $y, $z)){
1951 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
1952
1953 if($cached && isset($this->blockCache[$chunkHash][$relativeBlockHash])){
1954 return $this->blockCache[$chunkHash][$relativeBlockHash];
1955 }
1956
1957 $chunk = $this->chunks[$chunkHash] ?? null;
1958 if($chunk !== null){
1959 $block = $this->blockStateRegistry->fromStateId($chunk->getBlockStateId($x & Chunk::COORD_MASK, $y, $z & Chunk::COORD_MASK));
1960 }else{
1961 $addToCache = false;
1962 $block = VanillaBlocks::AIR();
1963 }
1964 }else{
1965 $block = VanillaBlocks::AIR();
1966 }
1967
1968 $block->position($this, $x, $y, $z);
1969
1970 if($this->inDynamicStateRecalculation){
1971 //this call was generated by a parent getBlock() call calculating dynamic stateinfo
1972 //don't calculate dynamic state and don't add to block cache (since it won't have dynamic state calculated).
1973 //this ensures that it's impossible for dynamic state properties to recursively depend on each other.
1974 $addToCache = false;
1975 }else{
1976 $this->inDynamicStateRecalculation = true;
1977 $replacement = $block->readStateFromWorld();
1978 if($replacement !== $block){
1979 $replacement->position($this, $x, $y, $z);
1980 $block = $replacement;
1981 }
1982 $this->inDynamicStateRecalculation = false;
1983 }
1984
1985 if($addToCache && $relativeBlockHash !== null){
1986 $this->blockCache[$chunkHash][$relativeBlockHash] = $block;
1987
1988 if(++$this->blockCacheSize >= self::BLOCK_CACHE_SIZE_CAP){
1989 $this->trimBlockCache();
1990 }
1991 }
1992
1993 return $block;
1994 }
1995
2001 public function setBlock(Vector3 $pos, Block $block, bool $update = true) : void{
2002 $this->setBlockAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z), $block, $update);
2003 }
2004
2013 public function setBlockAt(int $x, int $y, int $z, Block $block, bool $update = true) : void{
2014 if(!$this->isInWorld($x, $y, $z)){
2015 throw new \InvalidArgumentException("Pos x=$x,y=$y,z=$z is outside of the world bounds");
2016 }
2017 $chunkX = $x >> Chunk::COORD_BIT_SIZE;
2018 $chunkZ = $z >> Chunk::COORD_BIT_SIZE;
2019 if($this->loadChunk($chunkX, $chunkZ) === null){ //current expected behaviour is to try to load the terrain synchronously
2020 throw new WorldException("Cannot set a block in un-generated terrain");
2021 }
2022
2023 //TODO: this computes state ID twice (we do it again in writeStateToWorld()). Not great for performance :(
2024 $stateId = $block->getStateId();
2025 if(!$this->blockStateRegistry->hasStateId($stateId)){
2026 throw new \LogicException("Block state ID not known to RuntimeBlockStateRegistry (probably not registered)");
2027 }
2028 if(!GlobalBlockStateHandlers::getSerializer()->isRegistered($block)){
2029 throw new \LogicException("Block not registered with GlobalBlockStateHandlers serializer");
2030 }
2031
2032 $this->timings->setBlock->startTiming();
2033
2034 $this->unlockChunk($chunkX, $chunkZ, null);
2035
2036 $block = clone $block;
2037
2038 $block->position($this, $x, $y, $z);
2039 $block->writeStateToWorld();
2040 $pos = new Vector3($x, $y, $z);
2041
2042 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2043 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
2044
2045 unset($this->blockCache[$chunkHash][$relativeBlockHash]);
2046 $this->blockCacheSize--;
2047 unset($this->blockCollisionBoxCache[$chunkHash][$relativeBlockHash]);
2048 //blocks like fences have collision boxes that reach into neighbouring blocks, so we need to invalidate the
2049 //caches for those blocks as well
2050 foreach(Facing::OFFSET as [$offsetX, $offsetY, $offsetZ]){
2051 $sideChunkPosHash = World::chunkHash(($x + $offsetX) >> Chunk::COORD_BIT_SIZE, ($z + $offsetZ) >> Chunk::COORD_BIT_SIZE);
2052 $sideChunkBlockHash = World::chunkBlockHash($x + $offsetX, $y + $offsetY, $z + $offsetZ);
2053 unset($this->blockCollisionBoxCache[$sideChunkPosHash][$sideChunkBlockHash]);
2054 }
2055
2056 if(!isset($this->changedBlocks[$chunkHash])){
2057 $this->changedBlocks[$chunkHash] = [];
2058 }
2059 $this->changedBlocks[$chunkHash][$relativeBlockHash] = $pos;
2060
2061 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2062 $listener->onBlockChanged($pos);
2063 }
2064
2065 if($update){
2066 $this->updateAllLight($x, $y, $z);
2067 $this->internalNotifyNeighbourBlockUpdate($x, $y, $z);
2068 }
2069
2070 $this->timings->setBlock->stopTiming();
2071 }
2072
2073 public function dropItem(Vector3 $source, Item $item, ?Vector3 $motion = null, int $delay = 10) : ?ItemEntity{
2074 if($item->isNull()){
2075 return null;
2076 }
2077
2078 $itemEntity = new ItemEntity(Location::fromObject($source, $this, Utils::getRandomFloat() * 360, 0), $item);
2079
2080 $itemEntity->setPickupDelay($delay);
2081 $itemEntity->setMotion($motion ?? new Vector3(Utils::getRandomFloat() * 0.2 - 0.1, 0.2, Utils::getRandomFloat() * 0.2 - 0.1));
2082 $itemEntity->spawnToAll();
2083
2084 return $itemEntity;
2085 }
2086
2093 public function dropExperience(Vector3 $pos, int $amount) : array{
2094 $orbs = [];
2095
2096 foreach(ExperienceOrb::splitIntoOrbSizes($amount) as $split){
2097 $orb = new ExperienceOrb(Location::fromObject($pos, $this, Utils::getRandomFloat() * 360, 0), $split);
2098
2099 $orb->setMotion(new Vector3((Utils::getRandomFloat() * 0.2 - 0.1) * 2, Utils::getRandomFloat() * 0.4, (Utils::getRandomFloat() * 0.2 - 0.1) * 2));
2100 $orb->spawnToAll();
2101
2102 $orbs[] = $orb;
2103 }
2104
2105 return $orbs;
2106 }
2107
2116 public function useBreakOn(Vector3 $vector, ?Item &$item = null, ?Player $player = null, bool $createParticles = false, array &$returnedItems = []) : bool{
2117 $vector = $vector->floor();
2118
2119 $chunkX = $vector->getFloorX() >> Chunk::COORD_BIT_SIZE;
2120 $chunkZ = $vector->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2121 if(!$this->isChunkLoaded($chunkX, $chunkZ) || $this->isChunkLocked($chunkX, $chunkZ)){
2122 return false;
2123 }
2124
2125 $target = $this->getBlock($vector);
2126 $affectedBlocks = $target->getAffectedBlocks();
2127
2128 if($item === null){
2129 $item = VanillaItems::AIR();
2130 }
2131
2132 $drops = [];
2133 if($player === null || $player->hasFiniteResources()){
2134 $drops = array_merge(...array_map(fn(Block $block) => $block->getDrops($item), $affectedBlocks));
2135 }
2136
2137 $xpDrop = 0;
2138 if($player !== null && $player->hasFiniteResources()){
2139 $xpDrop = array_sum(array_map(fn(Block $block) => $block->getXpDropForTool($item), $affectedBlocks));
2140 }
2141
2142 if($player !== null){
2143 $ev = new BlockBreakEvent($player, $target, $item, $player->isCreative(), $drops, $xpDrop);
2144
2145 if($target instanceof Air || ($player->isSurvival() && !$target->getBreakInfo()->isBreakable()) || $player->isSpectator()){
2146 $ev->cancel();
2147 }
2148
2149 if($player->isAdventure(true) && !$ev->isCancelled()){
2150 $canBreak = false;
2151 $itemParser = LegacyStringToItemParser::getInstance();
2152 foreach($item->getCanDestroy() as $v){
2153 $entry = $itemParser->parse($v);
2154 if($entry->getBlock()->hasSameTypeId($target)){
2155 $canBreak = true;
2156 break;
2157 }
2158 }
2159
2160 if(!$canBreak){
2161 $ev->cancel();
2162 }
2163 }
2164
2165 $ev->call();
2166 if($ev->isCancelled()){
2167 return false;
2168 }
2169
2170 $drops = $ev->getDrops();
2171 $xpDrop = $ev->getXpDropAmount();
2172
2173 }elseif(!$target->getBreakInfo()->isBreakable()){
2174 return false;
2175 }
2176
2177 foreach($affectedBlocks as $t){
2178 $this->destroyBlockInternal($t, $item, $player, $createParticles, $returnedItems);
2179 }
2180
2181 $item->onDestroyBlock($target, $returnedItems);
2182
2183 if(count($drops) > 0){
2184 $dropPos = $vector->add(0.5, 0.5, 0.5);
2185 foreach($drops as $drop){
2186 if(!$drop->isNull()){
2187 $this->dropItem($dropPos, $drop);
2188 }
2189 }
2190 }
2191
2192 if($xpDrop > 0){
2193 $this->dropExperience($vector->add(0.5, 0.5, 0.5), $xpDrop);
2194 }
2195
2196 return true;
2197 }
2198
2202 private function destroyBlockInternal(Block $target, Item $item, ?Player $player, bool $createParticles, array &$returnedItems) : void{
2203 if($createParticles){
2204 $this->addParticle($target->getPosition()->add(0.5, 0.5, 0.5), new BlockBreakParticle($target));
2205 }
2206
2207 $target->onBreak($item, $player, $returnedItems);
2208
2209 $tile = $this->getTile($target->getPosition());
2210 if($tile !== null){
2211 $tile->onBlockDestroyed();
2212 }
2213 }
2214
2222 public function useItemOn(Vector3 $vector, Item &$item, int $face, ?Vector3 $clickVector = null, ?Player $player = null, bool $playSound = false, array &$returnedItems = []) : bool{
2223 $blockClicked = $this->getBlock($vector);
2224 $blockReplace = $blockClicked->getSide($face);
2225
2226 if($clickVector === null){
2227 $clickVector = new Vector3(0.0, 0.0, 0.0);
2228 }else{
2229 $clickVector = new Vector3(
2230 min(1.0, max(0.0, $clickVector->x)),
2231 min(1.0, max(0.0, $clickVector->y)),
2232 min(1.0, max(0.0, $clickVector->z))
2233 );
2234 }
2235
2236 if(!$this->isInWorld($blockReplace->getPosition()->x, $blockReplace->getPosition()->y, $blockReplace->getPosition()->z)){
2237 //TODO: build height limit messages for custom world heights and mcregion cap
2238 return false;
2239 }
2240 $chunkX = $blockReplace->getPosition()->getFloorX() >> Chunk::COORD_BIT_SIZE;
2241 $chunkZ = $blockReplace->getPosition()->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2242 if(!$this->isChunkLoaded($chunkX, $chunkZ) || $this->isChunkLocked($chunkX, $chunkZ)){
2243 return false;
2244 }
2245
2246 if($blockClicked->getTypeId() === BlockTypeIds::AIR){
2247 return false;
2248 }
2249
2250 if($player !== null){
2251 $ev = new PlayerInteractEvent($player, $item, $blockClicked, $clickVector, $face, PlayerInteractEvent::RIGHT_CLICK_BLOCK);
2252 if($player->isSneaking()){
2253 $ev->setUseItem(false);
2254 $ev->setUseBlock($item->isNull()); //opening doors is still possible when sneaking if using an empty hand
2255 }
2256 if($player->isSpectator()){
2257 $ev->cancel(); //set it to cancelled so plugins can bypass this
2258 }
2259
2260 $ev->call();
2261 if(!$ev->isCancelled()){
2262 if($ev->useBlock() && $blockClicked->onInteract($item, $face, $clickVector, $player, $returnedItems)){
2263 return true;
2264 }
2265
2266 if($ev->useItem()){
2267 $result = $item->onInteractBlock($player, $blockReplace, $blockClicked, $face, $clickVector, $returnedItems);
2268 if($result !== ItemUseResult::NONE){
2269 return $result === ItemUseResult::SUCCESS;
2270 }
2271 }
2272 }else{
2273 return false;
2274 }
2275 }elseif($blockClicked->onInteract($item, $face, $clickVector, $player, $returnedItems)){
2276 return true;
2277 }
2278
2279 if($item->isNull() || !$item->canBePlaced()){
2280 return false;
2281 }
2282 $hand = $item->getBlock($face);
2283 $hand->position($this, $blockReplace->getPosition()->x, $blockReplace->getPosition()->y, $blockReplace->getPosition()->z);
2284
2285 if($hand->canBePlacedAt($blockClicked, $clickVector, $face, true)){
2286 $blockReplace = $blockClicked;
2287 //TODO: while this mimics the vanilla behaviour with replaceable blocks, we should really pass some other
2288 //value like NULL and let place() deal with it. This will look like a bug to anyone who doesn't know about
2289 //the vanilla behaviour.
2290 $face = Facing::UP;
2291 $hand->position($this, $blockReplace->getPosition()->x, $blockReplace->getPosition()->y, $blockReplace->getPosition()->z);
2292 }elseif(!$hand->canBePlacedAt($blockReplace, $clickVector, $face, false)){
2293 return false;
2294 }
2295
2296 $tx = new BlockTransaction($this);
2297 if(!$hand->place($tx, $item, $blockReplace, $blockClicked, $face, $clickVector, $player)){
2298 return false;
2299 }
2300
2301 foreach($tx->getBlocks() as [$x, $y, $z, $block]){
2302 $block->position($this, $x, $y, $z);
2303 foreach($block->getCollisionBoxes() as $collisionBox){
2304 if(count($this->getCollidingEntities($collisionBox)) > 0){
2305 return false; //Entity in block
2306 }
2307 }
2308 }
2309
2310 if($player !== null){
2311 $ev = new BlockPlaceEvent($player, $tx, $blockClicked, $item);
2312 if($player->isSpectator()){
2313 $ev->cancel();
2314 }
2315
2316 if($player->isAdventure(true) && !$ev->isCancelled()){
2317 $canPlace = false;
2318 $itemParser = LegacyStringToItemParser::getInstance();
2319 foreach($item->getCanPlaceOn() as $v){
2320 $entry = $itemParser->parse($v);
2321 if($entry->getBlock()->hasSameTypeId($blockClicked)){
2322 $canPlace = true;
2323 break;
2324 }
2325 }
2326
2327 if(!$canPlace){
2328 $ev->cancel();
2329 }
2330 }
2331
2332 $ev->call();
2333 if($ev->isCancelled()){
2334 return false;
2335 }
2336 }
2337
2338 if(!$tx->apply()){
2339 return false;
2340 }
2341 foreach($tx->getBlocks() as [$x, $y, $z, $_]){
2342 $tile = $this->getTileAt($x, $y, $z);
2343 if($tile !== null){
2344 //TODO: seal this up inside block placement
2345 $tile->copyDataFromItem($item);
2346 }
2347
2348 $this->getBlockAt($x, $y, $z)->onPostPlace();
2349 }
2350
2351 if($playSound){
2352 $this->addSound($hand->getPosition(), new BlockPlaceSound($hand));
2353 }
2354
2355 $item->pop();
2356
2357 return true;
2358 }
2359
2360 public function getEntity(int $entityId) : ?Entity{
2361 return $this->entities[$entityId] ?? null;
2362 }
2363
2370 public function getEntities() : array{
2371 return $this->entities;
2372 }
2373
2384 public function getCollidingEntities(AxisAlignedBB $bb, ?Entity $entity = null) : array{
2385 $nearby = [];
2386
2387 foreach($this->getNearbyEntities($bb, $entity) as $ent){
2388 if($ent->canBeCollidedWith() && ($entity === null || $entity->canCollideWith($ent))){
2389 $nearby[] = $ent;
2390 }
2391 }
2392
2393 return $nearby;
2394 }
2395
2402 public function getNearbyEntities(AxisAlignedBB $bb, ?Entity $entity = null) : array{
2403 $nearby = [];
2404
2405 $minX = ((int) floor($bb->minX - 2)) >> Chunk::COORD_BIT_SIZE;
2406 $maxX = ((int) floor($bb->maxX + 2)) >> Chunk::COORD_BIT_SIZE;
2407 $minZ = ((int) floor($bb->minZ - 2)) >> Chunk::COORD_BIT_SIZE;
2408 $maxZ = ((int) floor($bb->maxZ + 2)) >> Chunk::COORD_BIT_SIZE;
2409
2410 for($x = $minX; $x <= $maxX; ++$x){
2411 for($z = $minZ; $z <= $maxZ; ++$z){
2412 foreach($this->getChunkEntities($x, $z) as $ent){
2413 if($ent !== $entity && $ent->boundingBox->intersectsWith($bb)){
2414 $nearby[] = $ent;
2415 }
2416 }
2417 }
2418 }
2419
2420 return $nearby;
2421 }
2422
2434 public function getNearestEntity(Vector3 $pos, float $maxDistance, string $entityType = Entity::class, bool $includeDead = false) : ?Entity{
2435 assert(is_a($entityType, Entity::class, true));
2436
2437 $minX = ((int) floor($pos->x - $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2438 $maxX = ((int) floor($pos->x + $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2439 $minZ = ((int) floor($pos->z - $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2440 $maxZ = ((int) floor($pos->z + $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2441
2442 $currentTargetDistSq = $maxDistance ** 2;
2443
2448 $currentTarget = null;
2449
2450 for($x = $minX; $x <= $maxX; ++$x){
2451 for($z = $minZ; $z <= $maxZ; ++$z){
2452 foreach($this->getChunkEntities($x, $z) as $entity){
2453 if(!($entity instanceof $entityType) || $entity->isFlaggedForDespawn() || (!$includeDead && !$entity->isAlive())){
2454 continue;
2455 }
2456 $distSq = $entity->getPosition()->distanceSquared($pos);
2457 if($distSq < $currentTargetDistSq){
2458 $currentTargetDistSq = $distSq;
2459 $currentTarget = $entity;
2460 }
2461 }
2462 }
2463 }
2464
2465 return $currentTarget;
2466 }
2467
2474 public function getPlayers() : array{
2475 return $this->players;
2476 }
2477
2484 public function getTile(Vector3 $pos) : ?Tile{
2485 return $this->getTileAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z));
2486 }
2487
2491 public function getTileAt(int $x, int $y, int $z) : ?Tile{
2492 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;
2493 }
2494
2495 public function getBiomeId(int $x, int $y, int $z) : int{
2496 if(($chunk = $this->loadChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null){
2497 return $chunk->getBiomeId($x & Chunk::COORD_MASK, $y & Chunk::COORD_MASK, $z & Chunk::COORD_MASK);
2498 }
2499 return BiomeIds::OCEAN; //TODO: this should probably throw instead (terrain not generated yet)
2500 }
2501
2502 public function getBiome(int $x, int $y, int $z) : Biome{
2503 return BiomeRegistry::getInstance()->getBiome($this->getBiomeId($x, $y, $z));
2504 }
2505
2506 public function setBiomeId(int $x, int $y, int $z, int $biomeId) : void{
2507 $chunkX = $x >> Chunk::COORD_BIT_SIZE;
2508 $chunkZ = $z >> Chunk::COORD_BIT_SIZE;
2509 $this->unlockChunk($chunkX, $chunkZ, null);
2510 if(($chunk = $this->loadChunk($chunkX, $chunkZ)) !== null){
2511 $chunk->setBiomeId($x & Chunk::COORD_MASK, $y & Chunk::COORD_MASK, $z & Chunk::COORD_MASK, $biomeId);
2512 }else{
2513 //if we allowed this, the modifications would be lost when the chunk is created
2514 throw new WorldException("Cannot set biome in a non-generated chunk");
2515 }
2516 }
2517
2522 public function getLoadedChunks() : array{
2523 return $this->chunks;
2524 }
2525
2526 public function getChunk(int $chunkX, int $chunkZ) : ?Chunk{
2527 return $this->chunks[World::chunkHash($chunkX, $chunkZ)] ?? null;
2528 }
2529
2534 public function getChunkEntities(int $chunkX, int $chunkZ) : array{
2535 return $this->entitiesByChunk[World::chunkHash($chunkX, $chunkZ)] ?? [];
2536 }
2537
2541 public function getOrLoadChunkAtPosition(Vector3 $pos) : ?Chunk{
2542 return $this->loadChunk($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
2543 }
2544
2551 public function getAdjacentChunks(int $x, int $z) : array{
2552 $result = [];
2553 for($xx = -1; $xx <= 1; ++$xx){
2554 for($zz = -1; $zz <= 1; ++$zz){
2555 if($xx === 0 && $zz === 0){
2556 continue; //center chunk
2557 }
2558 $result[World::chunkHash($xx, $zz)] = $this->loadChunk($x + $xx, $z + $zz);
2559 }
2560 }
2561
2562 return $result;
2563 }
2564
2579 public function lockChunk(int $chunkX, int $chunkZ, ChunkLockId $lockId) : void{
2580 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2581 if(isset($this->chunkLock[$chunkHash])){
2582 throw new \InvalidArgumentException("Chunk $chunkX $chunkZ is already locked");
2583 }
2584 $this->chunkLock[$chunkHash] = $lockId;
2585 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
2586 }
2587
2596 public function unlockChunk(int $chunkX, int $chunkZ, ?ChunkLockId $lockId) : bool{
2597 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2598 if(isset($this->chunkLock[$chunkHash]) && ($lockId === null || $this->chunkLock[$chunkHash] === $lockId)){
2599 unset($this->chunkLock[$chunkHash]);
2600 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
2601 return true;
2602 }
2603 return false;
2604 }
2605
2611 public function isChunkLocked(int $chunkX, int $chunkZ) : bool{
2612 return isset($this->chunkLock[World::chunkHash($chunkX, $chunkZ)]);
2613 }
2614
2615 public function setChunk(int $chunkX, int $chunkZ, Chunk $chunk) : void{
2616 foreach($chunk->getSubChunks() as $subChunk){
2617 foreach($subChunk->getBlockLayers() as $blockLayer){
2618 foreach($blockLayer->getPalette() as $blockStateId){
2619 if(!$this->blockStateRegistry->hasStateId($blockStateId)){
2620 throw new \InvalidArgumentException("Provided chunk contains unknown/unregistered blocks (found unknown state ID $blockStateId)");
2621 }
2622 }
2623 }
2624 }
2625
2626 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2627 $oldChunk = $this->loadChunk($chunkX, $chunkZ);
2628 if($oldChunk !== null && $oldChunk !== $chunk){
2629 $deletedTiles = 0;
2630 $transferredTiles = 0;
2631 foreach($oldChunk->getTiles() as $oldTile){
2632 $tilePosition = $oldTile->getPosition();
2633 $localX = $tilePosition->getFloorX() & Chunk::COORD_MASK;
2634 $localY = $tilePosition->getFloorY();
2635 $localZ = $tilePosition->getFloorZ() & Chunk::COORD_MASK;
2636
2637 $newBlock = $this->blockStateRegistry->fromStateId($chunk->getBlockStateId($localX, $localY, $localZ));
2638 $expectedTileClass = $newBlock->getIdInfo()->getTileClass();
2639 if(
2640 $expectedTileClass === null || //new block doesn't expect a tile
2641 !($oldTile instanceof $expectedTileClass) || //new block expects a different tile
2642 (($newTile = $chunk->getTile($localX, $localY, $localZ)) !== null && $newTile !== $oldTile) //new chunk already has a different tile
2643 ){
2644 $oldTile->close();
2645 $deletedTiles++;
2646 }else{
2647 $transferredTiles++;
2648 $chunk->addTile($oldTile);
2649 $oldChunk->removeTile($oldTile);
2650 }
2651 }
2652 if($deletedTiles > 0 || $transferredTiles > 0){
2653 $this->logger->debug("Replacement of chunk $chunkX $chunkZ caused deletion of $deletedTiles obsolete/conflicted tiles, and transfer of $transferredTiles");
2654 }
2655 }
2656
2657 $this->chunks[$chunkHash] = $chunk;
2658 unset($this->knownUngeneratedChunks[$chunkHash]);
2659
2660 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
2661 unset($this->blockCache[$chunkHash]);
2662 unset($this->blockCollisionBoxCache[$chunkHash]);
2663 unset($this->changedBlocks[$chunkHash]);
2664 $chunk->setTerrainDirty();
2665 $this->markTickingChunkForRecheck($chunkX, $chunkZ); //this replacement chunk may not meet the conditions for ticking
2666
2667 if(!$this->isChunkInUse($chunkX, $chunkZ)){
2668 $this->unloadChunkRequest($chunkX, $chunkZ);
2669 }
2670
2671 if($oldChunk === null){
2672 if(ChunkLoadEvent::hasHandlers()){
2673 (new ChunkLoadEvent($this, $chunkX, $chunkZ, $chunk, true))->call();
2674 }
2675
2676 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2677 $listener->onChunkLoaded($chunkX, $chunkZ, $chunk);
2678 }
2679 }else{
2680 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2681 $listener->onChunkChanged($chunkX, $chunkZ, $chunk);
2682 }
2683 }
2684
2685 for($cX = -1; $cX <= 1; ++$cX){
2686 for($cZ = -1; $cZ <= 1; ++$cZ){
2687 foreach($this->getChunkEntities($chunkX + $cX, $chunkZ + $cZ) as $entity){
2688 $entity->onNearbyBlockChange();
2689 }
2690 }
2691 }
2692 }
2693
2700 public function getHighestBlockAt(int $x, int $z) : ?int{
2701 if(($chunk = $this->loadChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null){
2702 return $chunk->getHighestBlockAt($x & Chunk::COORD_MASK, $z & Chunk::COORD_MASK);
2703 }
2704 throw new WorldException("Cannot get highest block in an ungenerated chunk");
2705 }
2706
2710 public function isInLoadedTerrain(Vector3 $pos) : bool{
2711 return $this->isChunkLoaded($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
2712 }
2713
2714 public function isChunkLoaded(int $x, int $z) : bool{
2715 return isset($this->chunks[World::chunkHash($x, $z)]);
2716 }
2717
2718 public function isChunkGenerated(int $x, int $z) : bool{
2719 return $this->loadChunk($x, $z) !== null;
2720 }
2721
2722 public function isChunkPopulated(int $x, int $z) : bool{
2723 $chunk = $this->loadChunk($x, $z);
2724 return $chunk !== null && $chunk->isPopulated();
2725 }
2726
2730 public function getSpawnLocation() : Position{
2731 return Position::fromObject($this->provider->getWorldData()->getSpawn(), $this);
2732 }
2733
2737 public function setSpawnLocation(Vector3 $pos) : void{
2738 $previousSpawn = $this->getSpawnLocation();
2739 $this->provider->getWorldData()->setSpawn($pos);
2740 (new SpawnChangeEvent($this, $previousSpawn))->call();
2741
2742 $location = Position::fromObject($pos, $this);
2743 foreach($this->players as $player){
2744 $player->getNetworkSession()->syncWorldSpawnPoint($location);
2745 }
2746 }
2747
2751 public function addEntity(Entity $entity) : void{
2752 if($entity->isClosed()){
2753 throw new \InvalidArgumentException("Attempted to add a garbage closed Entity to world");
2754 }
2755 if($entity->getWorld() !== $this){
2756 throw new \InvalidArgumentException("Invalid Entity world");
2757 }
2758 if(array_key_exists($entity->getId(), $this->entities)){
2759 if($this->entities[$entity->getId()] === $entity){
2760 throw new \InvalidArgumentException("Entity " . $entity->getId() . " has already been added to this world");
2761 }else{
2762 throw new AssumptionFailedError("Found two different entities sharing entity ID " . $entity->getId());
2763 }
2764 }
2765 if(!EntityFactory::getInstance()->isRegistered($entity::class) && !$entity instanceof Player){
2766 //canSaveWithChunk is mutable, so that means it could be toggled after adding the entity and cause a crash
2767 //later on. Better we just force all entities to have a save ID, even if it might not be needed.
2768 throw new \LogicException("Entity " . $entity::class . " is not registered for a save ID in EntityFactory");
2769 }
2770 $pos = $entity->getPosition()->asVector3();
2771 $this->entitiesByChunk[World::chunkHash($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE)][$entity->getId()] = $entity;
2772 $this->entityLastKnownPositions[$entity->getId()] = $pos;
2773
2774 if($entity instanceof Player){
2775 $this->players[$entity->getId()] = $entity;
2776 }
2777 $this->entities[$entity->getId()] = $entity;
2778 }
2779
2785 public function removeEntity(Entity $entity) : void{
2786 if($entity->getWorld() !== $this){
2787 throw new \InvalidArgumentException("Invalid Entity world");
2788 }
2789 if(!array_key_exists($entity->getId(), $this->entities)){
2790 throw new \InvalidArgumentException("Entity is not tracked by this world (possibly already removed?)");
2791 }
2792 $pos = $this->entityLastKnownPositions[$entity->getId()];
2793 $chunkHash = World::chunkHash($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
2794 if(isset($this->entitiesByChunk[$chunkHash][$entity->getId()])){
2795 if(count($this->entitiesByChunk[$chunkHash]) === 1){
2796 unset($this->entitiesByChunk[$chunkHash]);
2797 }else{
2798 unset($this->entitiesByChunk[$chunkHash][$entity->getId()]);
2799 }
2800 }
2801 unset($this->entityLastKnownPositions[$entity->getId()]);
2802
2803 if($entity instanceof Player){
2804 unset($this->players[$entity->getId()]);
2805 $this->checkSleep();
2806 }
2807
2808 unset($this->entities[$entity->getId()]);
2809 unset($this->updateEntities[$entity->getId()]);
2810 }
2811
2815 public function onEntityMoved(Entity $entity) : void{
2816 if(!array_key_exists($entity->getId(), $this->entityLastKnownPositions)){
2817 //this can happen if the entity was teleported before addEntity() was called
2818 return;
2819 }
2820 $oldPosition = $this->entityLastKnownPositions[$entity->getId()];
2821 $newPosition = $entity->getPosition();
2822
2823 $oldChunkX = $oldPosition->getFloorX() >> Chunk::COORD_BIT_SIZE;
2824 $oldChunkZ = $oldPosition->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2825 $newChunkX = $newPosition->getFloorX() >> Chunk::COORD_BIT_SIZE;
2826 $newChunkZ = $newPosition->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2827
2828 if($oldChunkX !== $newChunkX || $oldChunkZ !== $newChunkZ){
2829 $oldChunkHash = World::chunkHash($oldChunkX, $oldChunkZ);
2830 if(isset($this->entitiesByChunk[$oldChunkHash][$entity->getId()])){
2831 if(count($this->entitiesByChunk[$oldChunkHash]) === 1){
2832 unset($this->entitiesByChunk[$oldChunkHash]);
2833 }else{
2834 unset($this->entitiesByChunk[$oldChunkHash][$entity->getId()]);
2835 }
2836 }
2837
2838 $newViewers = $this->getViewersForPosition($newPosition);
2839 foreach($entity->getViewers() as $player){
2840 if(!isset($newViewers[spl_object_id($player)])){
2841 $entity->despawnFrom($player);
2842 }else{
2843 unset($newViewers[spl_object_id($player)]);
2844 }
2845 }
2846 foreach($newViewers as $player){
2847 $entity->spawnTo($player);
2848 }
2849
2850 $newChunkHash = World::chunkHash($newChunkX, $newChunkZ);
2851 $this->entitiesByChunk[$newChunkHash][$entity->getId()] = $entity;
2852 }
2853 $this->entityLastKnownPositions[$entity->getId()] = $newPosition->asVector3();
2854 }
2855
2860 public function addTile(Tile $tile) : void{
2861 if($tile->isClosed()){
2862 throw new \InvalidArgumentException("Attempted to add a garbage closed Tile to world");
2863 }
2864 $pos = $tile->getPosition();
2865 if(!$pos->isValid() || $pos->getWorld() !== $this){
2866 throw new \InvalidArgumentException("Invalid Tile world");
2867 }
2868 if(!$this->isInWorld($pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ())){
2869 throw new \InvalidArgumentException("Tile position is outside the world bounds");
2870 }
2871 if(!TileFactory::getInstance()->isRegistered($tile::class)){
2872 throw new \LogicException("Tile " . $tile::class . " is not registered for a save ID in TileFactory");
2873 }
2874
2875 $chunkX = $pos->getFloorX() >> Chunk::COORD_BIT_SIZE;
2876 $chunkZ = $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2877
2878 if(isset($this->chunks[$hash = World::chunkHash($chunkX, $chunkZ)])){
2879 $this->chunks[$hash]->addTile($tile);
2880 }else{
2881 throw new \InvalidArgumentException("Attempted to create tile " . get_class($tile) . " in unloaded chunk $chunkX $chunkZ");
2882 }
2883
2884 //delegate tile ticking to the corresponding block
2885 $this->scheduleDelayedBlockUpdate($pos->asVector3(), 1);
2886 }
2887
2892 public function removeTile(Tile $tile) : void{
2893 $pos = $tile->getPosition();
2894 if(!$pos->isValid() || $pos->getWorld() !== $this){
2895 throw new \InvalidArgumentException("Invalid Tile world");
2896 }
2897
2898 $chunkX = $pos->getFloorX() >> Chunk::COORD_BIT_SIZE;
2899 $chunkZ = $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2900
2901 if(isset($this->chunks[$hash = World::chunkHash($chunkX, $chunkZ)])){
2902 $this->chunks[$hash]->removeTile($tile);
2903 }
2904 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2905 $listener->onBlockChanged($pos->asVector3());
2906 }
2907 }
2908
2909 public function isChunkInUse(int $x, int $z) : bool{
2910 return isset($this->chunkLoaders[$index = World::chunkHash($x, $z)]) && count($this->chunkLoaders[$index]) > 0;
2911 }
2912
2919 public function loadChunk(int $x, int $z) : ?Chunk{
2920 if(isset($this->chunks[$chunkHash = World::chunkHash($x, $z)])){
2921 return $this->chunks[$chunkHash];
2922 }
2923 if(isset($this->knownUngeneratedChunks[$chunkHash])){
2924 return null;
2925 }
2926
2927 $this->timings->syncChunkLoad->startTiming();
2928
2929 $this->cancelUnloadChunkRequest($x, $z);
2930
2931 $this->timings->syncChunkLoadData->startTiming();
2932
2933 $loadedChunkData = null;
2934
2935 try{
2936 $loadedChunkData = $this->provider->loadChunk($x, $z);
2937 }catch(CorruptedChunkException $e){
2938 $this->logger->critical("Failed to load chunk x=$x z=$z: " . $e->getMessage());
2939 }
2940
2941 $this->timings->syncChunkLoadData->stopTiming();
2942
2943 if($loadedChunkData === null){
2944 $this->timings->syncChunkLoad->stopTiming();
2945 $this->knownUngeneratedChunks[$chunkHash] = true;
2946 return null;
2947 }
2948
2949 $chunkData = $loadedChunkData->getData();
2950 $chunk = new Chunk($chunkData->getSubChunks(), $chunkData->isPopulated());
2951 if(!$loadedChunkData->isUpgraded()){
2952 $chunk->clearTerrainDirtyFlags();
2953 }else{
2954 $this->logger->debug("Chunk $x $z has been upgraded, will be saved at the next autosave opportunity");
2955 }
2956 $this->chunks[$chunkHash] = $chunk;
2957
2958 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
2959 unset($this->blockCache[$chunkHash]);
2960 unset($this->blockCollisionBoxCache[$chunkHash]);
2961
2962 $this->initChunk($x, $z, $chunkData);
2963
2964 if(ChunkLoadEvent::hasHandlers()){
2965 (new ChunkLoadEvent($this, $x, $z, $this->chunks[$chunkHash], false))->call();
2966 }
2967
2968 if(!$this->isChunkInUse($x, $z)){
2969 $this->logger->debug("Newly loaded chunk $x $z has no loaders registered, will be unloaded at next available opportunity");
2970 $this->unloadChunkRequest($x, $z);
2971 }
2972 foreach($this->getChunkListeners($x, $z) as $listener){
2973 $listener->onChunkLoaded($x, $z, $this->chunks[$chunkHash]);
2974 }
2975 $this->markTickingChunkForRecheck($x, $z); //tickers may have been registered before the chunk was loaded
2976
2977 $this->timings->syncChunkLoad->stopTiming();
2978
2979 return $this->chunks[$chunkHash];
2980 }
2981
2982 private function initChunk(int $chunkX, int $chunkZ, ChunkData $chunkData) : void{
2983 $logger = new \PrefixedLogger($this->logger, "Loading chunk $chunkX $chunkZ");
2984
2985 if(count($chunkData->getEntityNBT()) !== 0){
2986 $this->timings->syncChunkLoadEntities->startTiming();
2987 $entityFactory = EntityFactory::getInstance();
2988
2989 $deletedEntities = [];
2990 foreach($chunkData->getEntityNBT() as $k => $nbt){
2991 try{
2992 $entity = $entityFactory->createFromData($this, $nbt);
2993 }catch(SavedDataLoadingException $e){
2994 $logger->error("Bad entity data at list position $k: " . $e->getMessage());
2995 $logger->logException($e);
2996 continue;
2997 }
2998 if($entity === null){
2999 $saveIdTag = $nbt->getTag("identifier") ?? $nbt->getTag("id");
3000 $saveId = "<unknown>";
3001 if($saveIdTag instanceof StringTag){
3002 $saveId = $saveIdTag->getValue();
3003 }elseif($saveIdTag instanceof IntTag){ //legacy MCPE format
3004 $saveId = "legacy(" . $saveIdTag->getValue() . ")";
3005 }
3006 $deletedEntities[$saveId] = ($deletedEntities[$saveId] ?? 0) + 1;
3007 }
3008 //TODO: we can't prevent entities getting added to unloaded chunks if they were saved in the wrong place
3009 //here, because entities currently add themselves to the world
3010 }
3011
3012 foreach(Utils::promoteKeys($deletedEntities) as $saveId => $count){
3013 $logger->warning("Deleted unknown entity type $saveId x$count");
3014 }
3015 $this->timings->syncChunkLoadEntities->stopTiming();
3016 }
3017
3018 if(count($chunkData->getTileNBT()) !== 0){
3019 $this->timings->syncChunkLoadTileEntities->startTiming();
3020 $tileFactory = TileFactory::getInstance();
3021
3022 $deletedTiles = [];
3023 foreach($chunkData->getTileNBT() as $k => $nbt){
3024 try{
3025 $tile = $tileFactory->createFromData($this, $nbt);
3026 }catch(SavedDataLoadingException $e){
3027 $logger->error("Bad tile entity data at list position $k: " . $e->getMessage());
3028 $logger->logException($e);
3029 continue;
3030 }
3031 if($tile === null){
3032 $saveId = $nbt->getString("id", "<unknown>");
3033 $deletedTiles[$saveId] = ($deletedTiles[$saveId] ?? 0) + 1;
3034 continue;
3035 }
3036
3037 $tilePosition = $tile->getPosition();
3038 if(!$this->isChunkLoaded($tilePosition->getFloorX() >> Chunk::COORD_BIT_SIZE, $tilePosition->getFloorZ() >> Chunk::COORD_BIT_SIZE)){
3039 $logger->error("Found tile saved on wrong chunk - unable to fix due to correct chunk not loaded");
3040 }elseif(!$this->isInWorld($tilePosition->getFloorX(), $tilePosition->getFloorY(), $tilePosition->getFloorZ())){
3041 $logger->error("Cannot add tile with position outside the world bounds: x=$tilePosition->x,y=$tilePosition->y,z=$tilePosition->z");
3042 }elseif($this->getTile($tilePosition) !== null){
3043 $logger->error("Cannot add tile at x=$tilePosition->x,y=$tilePosition->y,z=$tilePosition->z: Another tile is already at that position");
3044 }else{
3045 $this->addTile($tile);
3046 }
3047 }
3048
3049 foreach(Utils::promoteKeys($deletedTiles) as $saveId => $count){
3050 $logger->warning("Deleted unknown tile entity type $saveId x$count");
3051 }
3052
3053 $this->timings->syncChunkLoadTileEntities->stopTiming();
3054 }
3055 }
3056
3057 private function queueUnloadChunk(int $x, int $z) : void{
3058 $this->unloadQueue[World::chunkHash($x, $z)] = microtime(true);
3059 }
3060
3061 public function unloadChunkRequest(int $x, int $z, bool $safe = true) : bool{
3062 if(($safe && $this->isChunkInUse($x, $z)) || $this->isSpawnChunk($x, $z)){
3063 return false;
3064 }
3065
3066 $this->queueUnloadChunk($x, $z);
3067
3068 return true;
3069 }
3070
3071 public function cancelUnloadChunkRequest(int $x, int $z) : void{
3072 unset($this->unloadQueue[World::chunkHash($x, $z)]);
3073 }
3074
3075 public function unloadChunk(int $x, int $z, bool $safe = true, bool $trySave = true) : bool{
3076 if($safe && $this->isChunkInUse($x, $z)){
3077 return false;
3078 }
3079
3080 if(!$this->isChunkLoaded($x, $z)){
3081 return true;
3082 }
3083
3084 $this->timings->doChunkUnload->startTiming();
3085
3086 $chunkHash = World::chunkHash($x, $z);
3087
3088 $chunk = $this->chunks[$chunkHash] ?? null;
3089
3090 if($chunk !== null){
3091 if(ChunkUnloadEvent::hasHandlers()){
3092 $ev = new ChunkUnloadEvent($this, $x, $z, $chunk);
3093 $ev->call();
3094 if($ev->isCancelled()){
3095 $this->timings->doChunkUnload->stopTiming();
3096
3097 return false;
3098 }
3099 }
3100
3101 if($trySave && $this->getAutoSave()){
3102 $this->timings->syncChunkSave->startTiming();
3103 try{
3104 $this->provider->saveChunk($x, $z, new ChunkData(
3105 $chunk->getSubChunks(),
3106 $chunk->isPopulated(),
3107 array_map(fn(Entity $e) => $e->saveNBT(), array_values(array_filter($this->getChunkEntities($x, $z), fn(Entity $e) => $e->canSaveWithChunk()))),
3108 array_map(fn(Tile $t) => $t->saveNBT(), array_values($chunk->getTiles())),
3109 ), $chunk->getTerrainDirtyFlags());
3110 }finally{
3111 $this->timings->syncChunkSave->stopTiming();
3112 }
3113 }
3114
3115 foreach($this->getChunkListeners($x, $z) as $listener){
3116 $listener->onChunkUnloaded($x, $z, $chunk);
3117 }
3118
3119 foreach($this->getChunkEntities($x, $z) as $entity){
3120 if($entity instanceof Player){
3121 continue;
3122 }
3123 $entity->close();
3124 }
3125
3126 $chunk->onUnload();
3127 }
3128
3129 unset($this->chunks[$chunkHash]);
3130 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
3131 unset($this->blockCache[$chunkHash]);
3132 unset($this->blockCollisionBoxCache[$chunkHash]);
3133 unset($this->changedBlocks[$chunkHash]);
3134 unset($this->registeredTickingChunks[$chunkHash]);
3135 $this->markTickingChunkForRecheck($x, $z);
3136
3137 if(array_key_exists($chunkHash, $this->chunkPopulationRequestMap)){
3138 $this->logger->debug("Rejecting population promise for chunk $x $z");
3139 $this->chunkPopulationRequestMap[$chunkHash]->reject();
3140 unset($this->chunkPopulationRequestMap[$chunkHash]);
3141 if(isset($this->activeChunkPopulationTasks[$chunkHash])){
3142 $this->logger->debug("Marking population task for chunk $x $z as orphaned");
3143 $this->activeChunkPopulationTasks[$chunkHash] = false;
3144 }
3145 }
3146
3147 $this->timings->doChunkUnload->stopTiming();
3148
3149 return true;
3150 }
3151
3155 public function isSpawnChunk(int $X, int $Z) : bool{
3156 $spawn = $this->getSpawnLocation();
3157 $spawnX = $spawn->x >> Chunk::COORD_BIT_SIZE;
3158 $spawnZ = $spawn->z >> Chunk::COORD_BIT_SIZE;
3159
3160 return abs($X - $spawnX) <= 1 && abs($Z - $spawnZ) <= 1;
3161 }
3162
3170 public function requestSafeSpawn(?Vector3 $spawn = null) : Promise{
3172 $resolver = new PromiseResolver();
3173 $spawn ??= $this->getSpawnLocation();
3174 /*
3175 * TODO: this relies on the assumption that getSafeSpawn() will only alter the Y coordinate of the provided
3176 * position, which is currently OK, but might be a problem in the future.
3177 */
3178 $this->requestChunkPopulation($spawn->getFloorX() >> Chunk::COORD_BIT_SIZE, $spawn->getFloorZ() >> Chunk::COORD_BIT_SIZE, null)->onCompletion(
3179 function() use ($spawn, $resolver) : void{
3180 $spawn = $this->getSafeSpawn($spawn);
3181 $resolver->resolve($spawn);
3182 },
3183 function() use ($resolver) : void{
3184 $resolver->reject();
3185 }
3186 );
3187
3188 return $resolver->getPromise();
3189 }
3190
3197 public function getSafeSpawn(?Vector3 $spawn = null) : Position{
3198 if(!($spawn instanceof Vector3) || $spawn->y <= $this->minY){
3199 $spawn = $this->getSpawnLocation();
3200 }
3201
3202 $max = $this->maxY;
3203 $v = $spawn->floor();
3204 $chunk = $this->getOrLoadChunkAtPosition($v);
3205 if($chunk === null){
3206 throw new WorldException("Cannot find a safe spawn point in non-generated terrain");
3207 }
3208 $x = (int) $v->x;
3209 $z = (int) $v->z;
3210 $y = (int) min($max - 2, $v->y);
3211 $wasAir = $this->getBlockAt($x, $y - 1, $z)->getTypeId() === BlockTypeIds::AIR; //TODO: bad hack, clean up
3212 for(; $y > $this->minY; --$y){
3213 if($this->getBlockAt($x, $y, $z)->isFullCube()){
3214 if($wasAir){
3215 $y++;
3216 }
3217 break;
3218 }else{
3219 $wasAir = true;
3220 }
3221 }
3222
3223 for(; $y >= $this->minY && $y < $max; ++$y){
3224 if(!$this->getBlockAt($x, $y + 1, $z)->isFullCube()){
3225 if(!$this->getBlockAt($x, $y, $z)->isFullCube()){
3226 return new Position($spawn->x, $y === (int) $spawn->y ? $spawn->y : $y, $spawn->z, $this);
3227 }
3228 }else{
3229 ++$y;
3230 }
3231 }
3232
3233 return new Position($spawn->x, $y, $spawn->z, $this);
3234 }
3235
3239 public function getTime() : int{
3240 return $this->time;
3241 }
3242
3246 public function getTimeOfDay() : int{
3247 return $this->time % self::TIME_FULL;
3248 }
3249
3254 public function getDisplayName() : string{
3255 return $this->displayName;
3256 }
3257
3261 public function setDisplayName(string $name) : void{
3262 (new WorldDisplayNameChangeEvent($this, $this->displayName, $name))->call();
3263
3264 $this->displayName = $name;
3265 $this->provider->getWorldData()->setName($name);
3266 }
3267
3271 public function getFolderName() : string{
3272 return $this->folderName;
3273 }
3274
3278 public function setTime(int $time) : void{
3279 $this->time = $time;
3280 $this->sendTime();
3281 }
3282
3286 public function stopTime() : void{
3287 $this->stopTime = true;
3288 $this->sendTime();
3289 }
3290
3294 public function startTime() : void{
3295 $this->stopTime = false;
3296 $this->sendTime();
3297 }
3298
3302 public function getSeed() : int{
3303 return $this->provider->getWorldData()->getSeed();
3304 }
3305
3306 public function getMinY() : int{
3307 return $this->minY;
3308 }
3309
3310 public function getMaxY() : int{
3311 return $this->maxY;
3312 }
3313
3314 public function getDifficulty() : int{
3315 return $this->provider->getWorldData()->getDifficulty();
3316 }
3317
3318 public function setDifficulty(int $difficulty) : void{
3319 if($difficulty < 0 || $difficulty > 3){
3320 throw new \InvalidArgumentException("Invalid difficulty level $difficulty");
3321 }
3322 (new WorldDifficultyChangeEvent($this, $this->getDifficulty(), $difficulty))->call();
3323 $this->provider->getWorldData()->setDifficulty($difficulty);
3324
3325 foreach($this->players as $player){
3326 $player->getNetworkSession()->syncWorldDifficulty($this->getDifficulty());
3327 }
3328 }
3329
3330 private function addChunkHashToPopulationRequestQueue(int $chunkHash) : void{
3331 if(!isset($this->chunkPopulationRequestQueueIndex[$chunkHash])){
3332 $this->chunkPopulationRequestQueue->enqueue($chunkHash);
3333 $this->chunkPopulationRequestQueueIndex[$chunkHash] = true;
3334 }
3335 }
3336
3340 private function enqueuePopulationRequest(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader) : Promise{
3341 $chunkHash = World::chunkHash($chunkX, $chunkZ);
3342 $this->addChunkHashToPopulationRequestQueue($chunkHash);
3344 $resolver = $this->chunkPopulationRequestMap[$chunkHash] = new PromiseResolver();
3345 if($associatedChunkLoader === null){
3346 $temporaryLoader = new ChunkLoader();
3347 $this->registerChunkLoader($temporaryLoader, $chunkX, $chunkZ);
3348 $resolver->getPromise()->onCompletion(
3349 fn() => $this->unregisterChunkLoader($temporaryLoader, $chunkX, $chunkZ),
3350 static function() : void{}
3351 );
3352 }
3353 return $resolver->getPromise();
3354 }
3355
3356 private function drainPopulationRequestQueue() : void{
3357 $failed = [];
3358 while(count($this->activeChunkPopulationTasks) < $this->maxConcurrentChunkPopulationTasks && !$this->chunkPopulationRequestQueue->isEmpty()){
3359 $nextChunkHash = $this->chunkPopulationRequestQueue->dequeue();
3360 unset($this->chunkPopulationRequestQueueIndex[$nextChunkHash]);
3361 World::getXZ($nextChunkHash, $nextChunkX, $nextChunkZ);
3362 if(isset($this->chunkPopulationRequestMap[$nextChunkHash])){
3363 assert(!($this->activeChunkPopulationTasks[$nextChunkHash] ?? false), "Population for chunk $nextChunkX $nextChunkZ already running");
3364 if(
3365 !$this->orderChunkPopulation($nextChunkX, $nextChunkZ, null)->isResolved() &&
3366 !isset($this->activeChunkPopulationTasks[$nextChunkHash])
3367 ){
3368 $failed[] = $nextChunkHash;
3369 }
3370 }
3371 }
3372
3373 //these requests failed even though they weren't rate limited; we can't directly re-add them to the back of the
3374 //queue because it would result in an infinite loop
3375 foreach($failed as $hash){
3376 $this->addChunkHashToPopulationRequestQueue($hash);
3377 }
3378 }
3379
3385 private function checkChunkPopulationPreconditions(int $chunkX, int $chunkZ) : array{
3386 $chunkHash = World::chunkHash($chunkX, $chunkZ);
3387 $resolver = $this->chunkPopulationRequestMap[$chunkHash] ?? null;
3388 if($resolver !== null && isset($this->activeChunkPopulationTasks[$chunkHash])){
3389 //generation is already running
3390 return [$resolver, false];
3391 }
3392
3393 $temporaryChunkLoader = new ChunkLoader();
3394 $this->registerChunkLoader($temporaryChunkLoader, $chunkX, $chunkZ);
3395 $chunk = $this->loadChunk($chunkX, $chunkZ);
3396 $this->unregisterChunkLoader($temporaryChunkLoader, $chunkX, $chunkZ);
3397 if($chunk !== null && $chunk->isPopulated()){
3398 //chunk is already populated; return a pre-resolved promise that will directly fire callbacks assigned
3399 $resolver ??= new PromiseResolver();
3400 unset($this->chunkPopulationRequestMap[$chunkHash]);
3401 $resolver->resolve($chunk);
3402 return [$resolver, false];
3403 }
3404 return [$resolver, true];
3405 }
3406
3418 public function requestChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader) : Promise{
3419 [$resolver, $proceedWithPopulation] = $this->checkChunkPopulationPreconditions($chunkX, $chunkZ);
3420 if(!$proceedWithPopulation){
3421 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3422 }
3423
3424 if(count($this->activeChunkPopulationTasks) >= $this->maxConcurrentChunkPopulationTasks){
3425 //too many chunks are already generating; delay resolution of the request until later
3426 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3427 }
3428 return $this->internalOrderChunkPopulation($chunkX, $chunkZ, $associatedChunkLoader, $resolver);
3429 }
3430
3441 public function orderChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader) : Promise{
3442 [$resolver, $proceedWithPopulation] = $this->checkChunkPopulationPreconditions($chunkX, $chunkZ);
3443 if(!$proceedWithPopulation){
3444 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3445 }
3446
3447 return $this->internalOrderChunkPopulation($chunkX, $chunkZ, $associatedChunkLoader, $resolver);
3448 }
3449
3454 private function internalOrderChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader, ?PromiseResolver $resolver) : Promise{
3455 $chunkHash = World::chunkHash($chunkX, $chunkZ);
3456
3457 $timings = $this->timings->chunkPopulationOrder;
3458 $timings->startTiming();
3459
3460 try{
3461 for($xx = -1; $xx <= 1; ++$xx){
3462 for($zz = -1; $zz <= 1; ++$zz){
3463 if($this->isChunkLocked($chunkX + $xx, $chunkZ + $zz)){
3464 //chunk is already in use by another generation request; queue the request for later
3465 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3466 }
3467 }
3468 }
3469
3470 $this->activeChunkPopulationTasks[$chunkHash] = true;
3471 if($resolver === null){
3472 $resolver = new PromiseResolver();
3473 $this->chunkPopulationRequestMap[$chunkHash] = $resolver;
3474 }
3475
3476 $chunkPopulationLockId = new ChunkLockId();
3477
3478 $temporaryChunkLoader = new ChunkLoader();
3479 for($xx = -1; $xx <= 1; ++$xx){
3480 for($zz = -1; $zz <= 1; ++$zz){
3481 $this->lockChunk($chunkX + $xx, $chunkZ + $zz, $chunkPopulationLockId);
3482 $this->registerChunkLoader($temporaryChunkLoader, $chunkX + $xx, $chunkZ + $zz);
3483 }
3484 }
3485
3486 $centerChunk = $this->loadChunk($chunkX, $chunkZ);
3487 $adjacentChunks = $this->getAdjacentChunks($chunkX, $chunkZ);
3488
3489 $this->generatorExecutor->populate(
3490 $chunkX,
3491 $chunkZ,
3492 $centerChunk,
3493 $adjacentChunks,
3494 function(Chunk $centerChunk, array $adjacentChunks) use ($chunkPopulationLockId, $chunkX, $chunkZ, $temporaryChunkLoader) : void{
3495 if(!$this->isLoaded()){
3496 return;
3497 }
3498
3499 $this->generateChunkCallback($chunkPopulationLockId, $chunkX, $chunkZ, $centerChunk, $adjacentChunks, $temporaryChunkLoader);
3500 }
3501 );
3502
3503 return $resolver->getPromise();
3504 }finally{
3505 $timings->stopTiming();
3506 }
3507 }
3508
3513 private function generateChunkCallback(ChunkLockId $chunkLockId, int $x, int $z, Chunk $chunk, array $adjacentChunks, ChunkLoader $temporaryChunkLoader) : void{
3514 $timings = $this->timings->chunkPopulationCompletion;
3515 $timings->startTiming();
3516
3517 $dirtyChunks = 0;
3518 for($xx = -1; $xx <= 1; ++$xx){
3519 for($zz = -1; $zz <= 1; ++$zz){
3520 $this->unregisterChunkLoader($temporaryChunkLoader, $x + $xx, $z + $zz);
3521 if(!$this->unlockChunk($x + $xx, $z + $zz, $chunkLockId)){
3522 $dirtyChunks++;
3523 }
3524 }
3525 }
3526
3527 $index = World::chunkHash($x, $z);
3528 if(!isset($this->activeChunkPopulationTasks[$index])){
3529 throw new AssumptionFailedError("This should always be set, regardless of whether the task was orphaned or not");
3530 }
3531 if(!$this->activeChunkPopulationTasks[$index]){
3532 $this->logger->debug("Discarding orphaned population result for chunk x=$x,z=$z");
3533 unset($this->activeChunkPopulationTasks[$index]);
3534 }else{
3535 if($dirtyChunks === 0){
3536 $oldChunk = $this->loadChunk($x, $z);
3537 $this->setChunk($x, $z, $chunk);
3538
3539 foreach($adjacentChunks as $relativeChunkHash => $adjacentChunk){
3540 World::getXZ($relativeChunkHash, $relativeX, $relativeZ);
3541 if($relativeX < -1 || $relativeX > 1 || $relativeZ < -1 || $relativeZ > 1){
3542 throw new AssumptionFailedError("Adjacent chunks should be in range -1 ... +1 coordinates");
3543 }
3544 $this->setChunk($x + $relativeX, $z + $relativeZ, $adjacentChunk);
3545 }
3546
3547 if(($oldChunk === null || !$oldChunk->isPopulated()) && $chunk->isPopulated()){
3548 if(ChunkPopulateEvent::hasHandlers()){
3549 (new ChunkPopulateEvent($this, $x, $z, $chunk))->call();
3550 }
3551
3552 foreach($this->getChunkListeners($x, $z) as $listener){
3553 $listener->onChunkPopulated($x, $z, $chunk);
3554 }
3555 }
3556 }else{
3557 $this->logger->debug("Discarding population result for chunk x=$x,z=$z - terrain was modified on the main thread before async population completed");
3558 }
3559
3560 //This needs to be in this specific spot because user code might call back to orderChunkPopulation().
3561 //If it does, and finds the promise, and doesn't find an active task associated with it, it will schedule
3562 //another PopulationTask. We don't want that because we're here processing the results.
3563 //We can't remove the promise from the array before setting the chunks in the world because that would lead
3564 //to the same problem. Therefore, it's necessary that this code be split into two if/else, with this in the
3565 //middle.
3566 unset($this->activeChunkPopulationTasks[$index]);
3567
3568 if($dirtyChunks === 0){
3569 $promise = $this->chunkPopulationRequestMap[$index] ?? null;
3570 if($promise !== null){
3571 unset($this->chunkPopulationRequestMap[$index]);
3572 $promise->resolve($chunk);
3573 }else{
3574 //Handlers of ChunkPopulateEvent, ChunkLoadEvent, or just ChunkListeners can cause this
3575 $this->logger->debug("Unable to resolve population promise for chunk x=$x,z=$z - populated chunk was forcibly unloaded while setting modified chunks");
3576 }
3577 }else{
3578 //request failed, stick it back on the queue
3579 //we didn't resolve the promise or touch it in any way, so any fake chunk loaders are still valid and
3580 //don't need to be added a second time.
3581 $this->addChunkHashToPopulationRequestQueue($index);
3582 }
3583
3584 $this->drainPopulationRequestQueue();
3585 }
3586 $timings->stopTiming();
3587 }
3588
3589 public function doChunkGarbageCollection() : void{
3590 $this->timings->doChunkGC->startTiming();
3591
3592 foreach($this->chunks as $index => $chunk){
3593 if(!isset($this->unloadQueue[$index])){
3594 World::getXZ($index, $X, $Z);
3595 if(!$this->isSpawnChunk($X, $Z)){
3596 $this->unloadChunkRequest($X, $Z, true);
3597 }
3598 }
3599 $chunk->collectGarbage();
3600 }
3601
3602 $this->provider->doGarbageCollection();
3603
3604 $this->timings->doChunkGC->stopTiming();
3605 }
3606
3607 public function unloadChunks(bool $force = false) : void{
3608 if(count($this->unloadQueue) > 0){
3609 $maxUnload = 96;
3610 $now = microtime(true);
3611 foreach($this->unloadQueue as $index => $time){
3612 World::getXZ($index, $X, $Z);
3613
3614 if(!$force){
3615 if($maxUnload <= 0){
3616 break;
3617 }elseif($time > ($now - 30)){
3618 continue;
3619 }
3620 }
3621
3622 //If the chunk can't be unloaded, it stays on the queue
3623 if($this->unloadChunk($X, $Z, true)){
3624 unset($this->unloadQueue[$index]);
3625 --$maxUnload;
3626 }
3627 }
3628 }
3629 }
3630}
getBlock(?int $clickedFace=null)
Definition Item.php:494
pop(int $count=1)
Definition Item.php:433
getChunkListeners(int $chunkX, int $chunkZ)
Definition World.php:891
removeEntity(Entity $entity)
Definition World.php:2785
notifyNeighbourBlockUpdate(Vector3 $pos)
Definition World.php:1508
getCollisionBlocks(AxisAlignedBB $bb, bool $targetFirst=false)
Definition World.php:1516
getHighestAdjacentBlockLight(int $x, int $y, int $z)
Definition World.php:1895
setDisplayName(string $name)
Definition World.php:3261
getPotentialBlockSkyLightAt(int $x, int $y, int $z)
Definition World.php:1800
removeOnUnloadCallback(\Closure $callback)
Definition World.php:668
isChunkLocked(int $chunkX, int $chunkZ)
Definition World.php:2611
setSpawnLocation(Vector3 $pos)
Definition World.php:2737
getPotentialLightAt(int $x, int $y, int $z)
Definition World.php:1782
createBlockUpdatePackets(array $blocks)
Definition World.php:1091
getSafeSpawn(?Vector3 $spawn=null)
Definition World.php:3197
registerChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ)
Definition World.php:845
getBlockAt(int $x, int $y, int $z, bool $cached=true, bool $addToCache=true)
Definition World.php:1946
getChunkEntities(int $chunkX, int $chunkZ)
Definition World.php:2534
addEntity(Entity $entity)
Definition World.php:2751
getBlockLightAt(int $x, int $y, int $z)
Definition World.php:1825
getBlock(Vector3 $pos, bool $cached=true, bool $addToCache=true)
Definition World.php:1933
static chunkHash(int $x, int $z)
Definition World.php:384
broadcastPacketToViewers(Vector3 $pos, ClientboundPacket $packet)
Definition World.php:795
getOrLoadChunkAtPosition(Vector3 $pos)
Definition World.php:2541
static chunkBlockHash(int $x, int $y, int $z)
Definition World.php:423
getHighestAdjacentPotentialBlockSkyLight(int $x, int $y, int $z)
Definition World.php:1880
getFullLight(Vector3 $pos)
Definition World.php:1739
isInWorld(int $x, int $y, int $z)
Definition World.php:1915
unlockChunk(int $chunkX, int $chunkZ, ?ChunkLockId $lockId)
Definition World.php:2596
getChunkLoaders(int $chunkX, int $chunkZ)
Definition World.php:778
getAdjacentChunks(int $x, int $z)
Definition World.php:2551
getChunkPlayers(int $chunkX, int $chunkZ)
Definition World.php:768
getTileAt(int $x, int $y, int $z)
Definition World.php:2491
getHighestAdjacentFullLightAt(int $x, int $y, int $z)
Definition World.php:1763
setChunkTickRadius(int $radius)
Definition World.php:1210
getViewersForPosition(Vector3 $pos)
Definition World.php:788
getNearestEntity(Vector3 $pos, float $maxDistance, string $entityType=Entity::class, bool $includeDead=false)
Definition World.php:2434
__construct(private Server $server, string $name, private WritableWorldProvider $provider, private AsyncPool $workerPool)
Definition World.php:482
requestChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader)
Definition World.php:3418
addSound(Vector3 $pos, Sound $sound, ?array $players=null)
Definition World.php:696
registerTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ)
Definition World.php:1229
setBlock(Vector3 $pos, Block $block, bool $update=true)
Definition World.php:2001
getNearbyEntities(AxisAlignedBB $bb, ?Entity $entity=null)
Definition World.php:2402
static getXZ(int $hash, ?int &$x, ?int &$z)
Definition World.php:449
getBlockCollisionBoxes(AxisAlignedBB $bb)
Definition World.php:1646
getCollidingEntities(AxisAlignedBB $bb, ?Entity $entity=null)
Definition World.php:2384
isSpawnChunk(int $X, int $Z)
Definition World.php:3155
useBreakOn(Vector3 $vector, ?Item &$item=null, ?Player $player=null, bool $createParticles=false, array &$returnedItems=[])
Definition World.php:2116
getPotentialLight(Vector3 $pos)
Definition World.php:1771
addParticle(Vector3 $pos, Particle $particle, ?array $players=null)
Definition World.php:725
unregisterChunkListenerFromAll(ChunkListener $listener)
Definition World.php:878
loadChunk(int $x, int $z)
Definition World.php:2919
useItemOn(Vector3 $vector, Item &$item, int $face, ?Vector3 $clickVector=null, ?Player $player=null, bool $playSound=false, array &$returnedItems=[])
Definition World.php:2222
getHighestAdjacentPotentialLightAt(int $x, int $y, int $z)
Definition World.php:1790
setBlockAt(int $x, int $y, int $z, Block $block, bool $update=true)
Definition World.php:2013
unregisterTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ)
Definition World.php:1239
getRealBlockSkyLightAt(int $x, int $y, int $z)
Definition World.php:1815
static blockHash(int $x, int $y, int $z)
Definition World.php:403
getTile(Vector3 $pos)
Definition World.php:2484
getFullLightAt(int $x, int $y, int $z)
Definition World.php:1750
getHighestAdjacentRealBlockSkyLight(int $x, int $y, int $z)
Definition World.php:1888
orderChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader)
Definition World.php:3441
dropExperience(Vector3 $pos, int $amount)
Definition World.php:2093
isInLoadedTerrain(Vector3 $pos)
Definition World.php:2710
lockChunk(int $chunkX, int $chunkZ, ChunkLockId $lockId)
Definition World.php:2579
getHighestBlockAt(int $x, int $z)
Definition World.php:2700
scheduleDelayedBlockUpdate(Vector3 $pos, int $delay)
Definition World.php:1467
static getBlockXYZ(int $hash, ?int &$x, ?int &$y, ?int &$z)
Definition World.php:433
addOnUnloadCallback(\Closure $callback)
Definition World.php:663
requestSafeSpawn(?Vector3 $spawn=null)
Definition World.php:3170
unregisterChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ)
Definition World.php:862