PocketMine-MP 5.28.1 git-04de72e85ec8c8da36e1d527db3cbe4ee855a124
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
94use pocketmine\world\format\LightArray;
109use function abs;
110use function array_filter;
111use function array_key_exists;
112use function array_keys;
113use function array_map;
114use function array_merge;
115use function array_sum;
116use function array_values;
117use function assert;
118use function cos;
119use function count;
120use function floor;
121use function get_class;
122use function gettype;
123use function is_a;
124use function is_object;
125use function max;
126use function microtime;
127use function min;
128use function morton2d_decode;
129use function morton2d_encode;
130use function morton3d_decode;
131use function morton3d_encode;
132use function mt_rand;
133use function preg_match;
134use function spl_object_id;
135use function strtolower;
136use function trim;
137use const M_PI;
138use const PHP_INT_MAX;
139use const PHP_INT_MIN;
140
141#include <rules/World.h>
142
148class World implements ChunkManager{
149
150 private static int $worldIdCounter = 1;
151
152 public const Y_MAX = 320;
153 public const Y_MIN = -64;
154
155 public const TIME_DAY = 1000;
156 public const TIME_NOON = 6000;
157 public const TIME_SUNSET = 12000;
158 public const TIME_NIGHT = 13000;
159 public const TIME_MIDNIGHT = 18000;
160 public const TIME_SUNRISE = 23000;
161
162 public const TIME_FULL = 24000;
163
164 public const DIFFICULTY_PEACEFUL = 0;
165 public const DIFFICULTY_EASY = 1;
166 public const DIFFICULTY_NORMAL = 2;
167 public const DIFFICULTY_HARD = 3;
168
169 public const DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK = 3;
170
171 //TODO: this could probably do with being a lot bigger
172 private const BLOCK_CACHE_SIZE_CAP = 2048;
173
178 private array $players = [];
179
184 private array $entities = [];
189 private array $entityLastKnownPositions = [];
190
195 private array $entitiesByChunk = [];
196
201 public array $updateEntities = [];
202
203 private bool $inDynamicStateRecalculation = false;
208 private array $blockCache = [];
209 private int $blockCacheSize = 0;
214 private array $blockCollisionBoxCache = [];
215
216 private int $sendTimeTicker = 0;
217
218 private int $worldId;
219
220 private int $providerGarbageCollectionTicker = 0;
221
222 private int $minY;
223 private int $maxY;
224
229 private array $registeredTickingChunks = [];
230
237 private array $validTickingChunks = [];
238
244 private array $recheckTickingChunks = [];
245
250 private array $chunkLoaders = [];
251
256 private array $chunkListeners = [];
261 private array $playerChunkListeners = [];
262
267 private array $packetBuffersByChunk = [];
268
273 private array $unloadQueue = [];
274
275 private int $time;
276 public bool $stopTime = false;
277
278 private float $sunAnglePercentage = 0.0;
279 private int $skyLightReduction = 0;
280
281 private string $folderName;
282 private string $displayName;
283
288 private array $chunks = [];
289
294 private array $changedBlocks = [];
295
297 private ReversePriorityQueue $scheduledBlockUpdateQueue;
302 private array $scheduledBlockUpdateQueueIndex = [];
303
305 private \SplQueue $neighbourBlockUpdateQueue;
310 private array $neighbourBlockUpdateQueueIndex = [];
311
316 private array $activeChunkPopulationTasks = [];
321 private array $chunkLock = [];
322 private int $maxConcurrentChunkPopulationTasks = 2;
327 private array $chunkPopulationRequestMap = [];
332 private \SplQueue $chunkPopulationRequestQueue;
337 private array $chunkPopulationRequestQueueIndex = [];
338
343 private array $generatorRegisteredWorkers = [];
344
345 private bool $autoSave = true;
346
347 private int $sleepTicks = 0;
348
349 private int $chunkTickRadius;
350 private int $tickedBlocksPerSubchunkPerTick = self::DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK;
355 private array $randomTickBlocks = [];
356
357 public WorldTimings $timings;
358
359 public float $tickRateTime = 0;
360
361 private bool $doingTick = false;
362
364 private string $generator;
365
366 private bool $unloaded = false;
371 private array $unloadCallbacks = [];
372
373 private ?BlockLightUpdate $blockLightUpdate = null;
374 private ?SkyLightUpdate $skyLightUpdate = null;
375
376 private \Logger $logger;
377
378 private RuntimeBlockStateRegistry $blockStateRegistry;
379
383 public static function chunkHash(int $x, int $z) : int{
384 return morton2d_encode($x, $z);
385 }
386
387 private const MORTON3D_BIT_SIZE = 21;
388 private const BLOCKHASH_Y_BITS = 9;
389 private const BLOCKHASH_Y_PADDING = 64; //size (in blocks) of padding after both boundaries of the Y axis
390 private const BLOCKHASH_Y_OFFSET = self::BLOCKHASH_Y_PADDING - self::Y_MIN;
391 private const BLOCKHASH_Y_MASK = (1 << self::BLOCKHASH_Y_BITS) - 1;
392 private const BLOCKHASH_XZ_MASK = (1 << self::MORTON3D_BIT_SIZE) - 1;
393 private const BLOCKHASH_XZ_EXTRA_BITS = (self::MORTON3D_BIT_SIZE - self::BLOCKHASH_Y_BITS) >> 1;
394 private const BLOCKHASH_XZ_EXTRA_MASK = (1 << self::BLOCKHASH_XZ_EXTRA_BITS) - 1;
395 private const BLOCKHASH_XZ_SIGN_SHIFT = 64 - self::MORTON3D_BIT_SIZE - self::BLOCKHASH_XZ_EXTRA_BITS;
396 private const BLOCKHASH_X_SHIFT = self::BLOCKHASH_Y_BITS;
397 private const BLOCKHASH_Z_SHIFT = self::BLOCKHASH_X_SHIFT + self::BLOCKHASH_XZ_EXTRA_BITS;
398
402 public static function blockHash(int $x, int $y, int $z) : int{
403 $shiftedY = $y + self::BLOCKHASH_Y_OFFSET;
404 if(($shiftedY & (~0 << self::BLOCKHASH_Y_BITS)) !== 0){
405 throw new \InvalidArgumentException("Y coordinate $y is out of range!");
406 }
407 //morton3d gives us 21 bits on each axis, but the Y axis only requires 9
408 //so we use the extra space on Y (12 bits) and add 6 extra bits from X and Z instead.
409 //if we ever need more space for Y (e.g. due to expansion), take bits from X/Z to compensate.
410 return morton3d_encode(
411 $x & self::BLOCKHASH_XZ_MASK,
412 ($shiftedY /* & self::BLOCKHASH_Y_MASK */) |
413 ((($x >> self::MORTON3D_BIT_SIZE) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::BLOCKHASH_X_SHIFT) |
414 ((($z >> self::MORTON3D_BIT_SIZE) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::BLOCKHASH_Z_SHIFT),
415 $z & self::BLOCKHASH_XZ_MASK
416 );
417 }
418
422 public static function chunkBlockHash(int $x, int $y, int $z) : int{
423 return morton3d_encode($x, $y, $z);
424 }
425
432 public static function getBlockXYZ(int $hash, ?int &$x, ?int &$y, ?int &$z) : void{
433 [$baseX, $baseY, $baseZ] = morton3d_decode($hash);
434
435 $extraX = ((($baseY >> self::BLOCKHASH_X_SHIFT) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::MORTON3D_BIT_SIZE);
436 $extraZ = ((($baseY >> self::BLOCKHASH_Z_SHIFT) & self::BLOCKHASH_XZ_EXTRA_MASK) << self::MORTON3D_BIT_SIZE);
437
438 $x = (($baseX & self::BLOCKHASH_XZ_MASK) | $extraX) << self::BLOCKHASH_XZ_SIGN_SHIFT >> self::BLOCKHASH_XZ_SIGN_SHIFT;
439 $y = ($baseY & self::BLOCKHASH_Y_MASK) - self::BLOCKHASH_Y_OFFSET;
440 $z = (($baseZ & self::BLOCKHASH_XZ_MASK) | $extraZ) << self::BLOCKHASH_XZ_SIGN_SHIFT >> self::BLOCKHASH_XZ_SIGN_SHIFT;
441 }
442
448 public static function getXZ(int $hash, ?int &$x, ?int &$z) : void{
449 [$x, $z] = morton2d_decode($hash);
450 }
451
452 public static function getDifficultyFromString(string $str) : int{
453 switch(strtolower(trim($str))){
454 case "0":
455 case "peaceful":
456 case "p":
457 return World::DIFFICULTY_PEACEFUL;
458
459 case "1":
460 case "easy":
461 case "e":
462 return World::DIFFICULTY_EASY;
463
464 case "2":
465 case "normal":
466 case "n":
467 return World::DIFFICULTY_NORMAL;
468
469 case "3":
470 case "hard":
471 case "h":
472 return World::DIFFICULTY_HARD;
473 }
474
475 return -1;
476 }
477
481 public function __construct(
482 private Server $server,
483 string $name, //TODO: this should be folderName (named arguments BC break)
484 private WritableWorldProvider $provider,
485 private AsyncPool $workerPool
486 ){
487 $this->folderName = $name;
488 $this->worldId = self::$worldIdCounter++;
489
490 $this->displayName = $this->provider->getWorldData()->getName();
491 $this->logger = new \PrefixedLogger($server->getLogger(), "World: $this->displayName");
492
493 $this->blockStateRegistry = RuntimeBlockStateRegistry::getInstance();
494 $this->minY = $this->provider->getWorldMinY();
495 $this->maxY = $this->provider->getWorldMaxY();
496
497 $this->server->getLogger()->info($this->server->getLanguage()->translate(KnownTranslationFactory::pocketmine_level_preparing($this->displayName)));
498 $generator = GeneratorManager::getInstance()->getGenerator($this->provider->getWorldData()->getGenerator()) ??
499 throw new AssumptionFailedError("WorldManager should already have checked that the generator exists");
500 $generator->validateGeneratorOptions($this->provider->getWorldData()->getGeneratorOptions());
501 $this->generator = $generator->getGeneratorClass();
502 $this->chunkPopulationRequestQueue = new \SplQueue();
503 $this->addOnUnloadCallback(function() : void{
504 $this->logger->debug("Cancelling unfulfilled generation requests");
505
506 foreach($this->chunkPopulationRequestMap as $chunkHash => $promise){
507 $promise->reject();
508 unset($this->chunkPopulationRequestMap[$chunkHash]);
509 }
510 if(count($this->chunkPopulationRequestMap) !== 0){
511 //TODO: this might actually get hit because generation rejection callbacks might try to schedule new
512 //requests, and we can't prevent that right now because there's no way to detect "unloading" state
513 throw new AssumptionFailedError("New generation requests scheduled during unload");
514 }
515 });
516
517 $this->scheduledBlockUpdateQueue = new ReversePriorityQueue();
518 $this->scheduledBlockUpdateQueue->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
519
520 $this->neighbourBlockUpdateQueue = new \SplQueue();
521
522 $this->time = $this->provider->getWorldData()->getTime();
523
524 $cfg = $this->server->getConfigGroup();
525 $this->chunkTickRadius = min($this->server->getViewDistance(), max(0, $cfg->getPropertyInt(YmlServerProperties::CHUNK_TICKING_TICK_RADIUS, 4)));
526 if($cfg->getPropertyInt("chunk-ticking.per-tick", 40) <= 0){
527 //TODO: this needs l10n
528 $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.");
529 $this->chunkTickRadius = 0;
530 }
531 $this->tickedBlocksPerSubchunkPerTick = $cfg->getPropertyInt(YmlServerProperties::CHUNK_TICKING_BLOCKS_PER_SUBCHUNK_PER_TICK, self::DEFAULT_TICKED_BLOCKS_PER_SUBCHUNK_PER_TICK);
532 $this->maxConcurrentChunkPopulationTasks = $cfg->getPropertyInt(YmlServerProperties::CHUNK_GENERATION_POPULATION_QUEUE_SIZE, 2);
533
534 $this->initRandomTickBlocksFromConfig($cfg);
535
536 $this->timings = new WorldTimings($this);
537
538 $this->workerPool->addWorkerStartHook($workerStartHook = function(int $workerId) : void{
539 if(array_key_exists($workerId, $this->generatorRegisteredWorkers)){
540 $this->logger->debug("Worker $workerId with previously registered generator restarted, flagging as unregistered");
541 unset($this->generatorRegisteredWorkers[$workerId]);
542 }
543 });
544 $workerPool = $this->workerPool;
545 $this->addOnUnloadCallback(static function() use ($workerPool, $workerStartHook) : void{
546 $workerPool->removeWorkerStartHook($workerStartHook);
547 });
548 }
549
550 private function initRandomTickBlocksFromConfig(ServerConfigGroup $cfg) : void{
551 $dontTickBlocks = [];
552 $parser = StringToItemParser::getInstance();
553 foreach($cfg->getProperty(YmlServerProperties::CHUNK_TICKING_DISABLE_BLOCK_TICKING, []) as $name){
554 $name = (string) $name;
555 $item = $parser->parse($name);
556 if($item !== null){
557 $block = $item->getBlock();
558 }elseif(preg_match("/^-?\d+$/", $name) === 1){
559 //TODO: this is a really sketchy hack - remove this as soon as possible
560 try{
561 $blockStateData = GlobalBlockStateHandlers::getUpgrader()->upgradeIntIdMeta((int) $name, 0);
562 }catch(BlockStateDeserializeException){
563 continue;
564 }
565 $block = $this->blockStateRegistry->fromStateId(GlobalBlockStateHandlers::getDeserializer()->deserialize($blockStateData));
566 }else{
567 //TODO: we probably ought to log an error here
568 continue;
569 }
570
571 if($block->getTypeId() !== BlockTypeIds::AIR){
572 $dontTickBlocks[$block->getTypeId()] = $name;
573 }
574 }
575
576 foreach($this->blockStateRegistry->getAllKnownStates() as $state){
577 $dontTickName = $dontTickBlocks[$state->getTypeId()] ?? null;
578 if($dontTickName === null && $state->ticksRandomly()){
579 $this->randomTickBlocks[$state->getStateId()] = true;
580 }
581 }
582 }
583
584 public function getTickRateTime() : float{
585 return $this->tickRateTime;
586 }
587
588 public function registerGeneratorToWorker(int $worker) : void{
589 $this->logger->debug("Registering generator on worker $worker");
590 $this->workerPool->submitTaskToWorker(new GeneratorRegisterTask($this, $this->generator, $this->provider->getWorldData()->getGeneratorOptions()), $worker);
591 $this->generatorRegisteredWorkers[$worker] = true;
592 }
593
594 public function unregisterGenerator() : void{
595 foreach($this->workerPool->getRunningWorkers() as $i){
596 if(isset($this->generatorRegisteredWorkers[$i])){
597 $this->workerPool->submitTaskToWorker(new GeneratorUnregisterTask($this), $i);
598 }
599 }
600 $this->generatorRegisteredWorkers = [];
601 }
602
603 public function getServer() : Server{
604 return $this->server;
605 }
606
607 public function getLogger() : \Logger{
608 return $this->logger;
609 }
610
611 final public function getProvider() : WritableWorldProvider{
612 return $this->provider;
613 }
614
618 final public function getId() : int{
619 return $this->worldId;
620 }
621
622 public function isLoaded() : bool{
623 return !$this->unloaded;
624 }
625
629 public function onUnload() : void{
630 if($this->unloaded){
631 throw new \LogicException("Tried to close a world which is already closed");
632 }
633
634 foreach($this->unloadCallbacks as $callback){
635 $callback();
636 }
637 $this->unloadCallbacks = [];
638
639 foreach($this->chunks as $chunkHash => $chunk){
640 self::getXZ($chunkHash, $chunkX, $chunkZ);
641 $this->unloadChunk($chunkX, $chunkZ, false);
642 }
643 foreach($this->entitiesByChunk as $chunkHash => $entities){
644 self::getXZ($chunkHash, $chunkX, $chunkZ);
645
646 $leakedEntities = 0;
647 foreach($entities as $entity){
648 if(!$entity->isFlaggedForDespawn()){
649 $leakedEntities++;
650 }
651 $entity->close();
652 }
653 if($leakedEntities !== 0){
654 $this->logger->warning("$leakedEntities leaked entities found in ungenerated chunk $chunkX $chunkZ during unload, they won't be saved!");
655 }
656 }
657
658 $this->save();
659
660 $this->unregisterGenerator();
661
662 $this->provider->close();
663 $this->blockCache = [];
664 $this->blockCacheSize = 0;
665 $this->blockCollisionBoxCache = [];
666
667 $this->unloaded = true;
668 }
669
671 public function addOnUnloadCallback(\Closure $callback) : void{
672 $this->unloadCallbacks[spl_object_id($callback)] = $callback;
673 }
674
676 public function removeOnUnloadCallback(\Closure $callback) : void{
677 unset($this->unloadCallbacks[spl_object_id($callback)]);
678 }
679
688 private function filterViewersForPosition(Vector3 $pos, array $allowed) : array{
689 $candidates = $this->getViewersForPosition($pos);
690 $filtered = [];
691 foreach($allowed as $player){
692 $k = spl_object_id($player);
693 if(isset($candidates[$k])){
694 $filtered[$k] = $candidates[$k];
695 }
696 }
697
698 return $filtered;
699 }
700
704 public function addSound(Vector3 $pos, Sound $sound, ?array $players = null) : void{
705 $players ??= $this->getViewersForPosition($pos);
706
707 if(WorldSoundEvent::hasHandlers()){
708 $ev = new WorldSoundEvent($this, $sound, $pos, $players);
709 $ev->call();
710 if($ev->isCancelled()){
711 return;
712 }
713
714 $sound = $ev->getSound();
715 $players = $ev->getRecipients();
716 }
717
718 $pk = $sound->encode($pos);
719 if(count($pk) > 0){
720 if($players === $this->getViewersForPosition($pos)){
721 foreach($pk as $e){
722 $this->broadcastPacketToViewers($pos, $e);
723 }
724 }else{
725 NetworkBroadcastUtils::broadcastPackets($this->filterViewersForPosition($pos, $players), $pk);
726 }
727 }
728 }
729
733 public function addParticle(Vector3 $pos, Particle $particle, ?array $players = null) : void{
734 $players ??= $this->getViewersForPosition($pos);
735
736 if(WorldParticleEvent::hasHandlers()){
737 $ev = new WorldParticleEvent($this, $particle, $pos, $players);
738 $ev->call();
739 if($ev->isCancelled()){
740 return;
741 }
742
743 $particle = $ev->getParticle();
744 $players = $ev->getRecipients();
745 }
746
747 $pk = $particle->encode($pos);
748 if(count($pk) > 0){
749 if($players === $this->getViewersForPosition($pos)){
750 foreach($pk as $e){
751 $this->broadcastPacketToViewers($pos, $e);
752 }
753 }else{
754 NetworkBroadcastUtils::broadcastPackets($this->filterViewersForPosition($pos, $players), $pk);
755 }
756 }
757 }
758
759 public function getAutoSave() : bool{
760 return $this->autoSave;
761 }
762
763 public function setAutoSave(bool $value) : void{
764 $this->autoSave = $value;
765 }
766
776 public function getChunkPlayers(int $chunkX, int $chunkZ) : array{
777 return $this->playerChunkListeners[World::chunkHash($chunkX, $chunkZ)] ?? [];
778 }
779
786 public function getChunkLoaders(int $chunkX, int $chunkZ) : array{
787 return $this->chunkLoaders[World::chunkHash($chunkX, $chunkZ)] ?? [];
788 }
789
796 public function getViewersForPosition(Vector3 $pos) : array{
797 return $this->getChunkPlayers($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
798 }
799
803 public function broadcastPacketToViewers(Vector3 $pos, ClientboundPacket $packet) : void{
804 $this->broadcastPacketToPlayersUsingChunk($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE, $packet);
805 }
806
807 private function broadcastPacketToPlayersUsingChunk(int $chunkX, int $chunkZ, ClientboundPacket $packet) : void{
808 if(!isset($this->packetBuffersByChunk[$index = World::chunkHash($chunkX, $chunkZ)])){
809 $this->packetBuffersByChunk[$index] = [$packet];
810 }else{
811 $this->packetBuffersByChunk[$index][] = $packet;
812 }
813 }
814
815 public function registerChunkLoader(ChunkLoader $loader, int $chunkX, int $chunkZ, bool $autoLoad = true) : void{
816 $loaderId = spl_object_id($loader);
817
818 if(!isset($this->chunkLoaders[$chunkHash = World::chunkHash($chunkX, $chunkZ)])){
819 $this->chunkLoaders[$chunkHash] = [];
820 }elseif(isset($this->chunkLoaders[$chunkHash][$loaderId])){
821 return;
822 }
823
824 $this->chunkLoaders[$chunkHash][$loaderId] = $loader;
825
826 $this->cancelUnloadChunkRequest($chunkX, $chunkZ);
827
828 if($autoLoad){
829 $this->loadChunk($chunkX, $chunkZ);
830 }
831 }
832
833 public function unregisterChunkLoader(ChunkLoader $loader, int $chunkX, int $chunkZ) : void{
834 $chunkHash = World::chunkHash($chunkX, $chunkZ);
835 $loaderId = spl_object_id($loader);
836 if(isset($this->chunkLoaders[$chunkHash][$loaderId])){
837 if(count($this->chunkLoaders[$chunkHash]) === 1){
838 unset($this->chunkLoaders[$chunkHash]);
839 $this->unloadChunkRequest($chunkX, $chunkZ, true);
840 if(isset($this->chunkPopulationRequestMap[$chunkHash]) && !isset($this->activeChunkPopulationTasks[$chunkHash])){
841 $this->chunkPopulationRequestMap[$chunkHash]->reject();
842 unset($this->chunkPopulationRequestMap[$chunkHash]);
843 }
844 }else{
845 unset($this->chunkLoaders[$chunkHash][$loaderId]);
846 }
847 }
848 }
849
853 public function registerChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ) : void{
854 $hash = World::chunkHash($chunkX, $chunkZ);
855 if(isset($this->chunkListeners[$hash])){
856 $this->chunkListeners[$hash][spl_object_id($listener)] = $listener;
857 }else{
858 $this->chunkListeners[$hash] = [spl_object_id($listener) => $listener];
859 }
860 if($listener instanceof Player){
861 $this->playerChunkListeners[$hash][spl_object_id($listener)] = $listener;
862 }
863 }
864
870 public function unregisterChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ) : void{
871 $hash = World::chunkHash($chunkX, $chunkZ);
872 if(isset($this->chunkListeners[$hash])){
873 if(count($this->chunkListeners[$hash]) === 1){
874 unset($this->chunkListeners[$hash]);
875 unset($this->playerChunkListeners[$hash]);
876 }else{
877 unset($this->chunkListeners[$hash][spl_object_id($listener)]);
878 unset($this->playerChunkListeners[$hash][spl_object_id($listener)]);
879 }
880 }
881 }
882
886 public function unregisterChunkListenerFromAll(ChunkListener $listener) : void{
887 foreach($this->chunkListeners as $hash => $listeners){
888 World::getXZ($hash, $chunkX, $chunkZ);
889 $this->unregisterChunkListener($listener, $chunkX, $chunkZ);
890 }
891 }
892
899 public function getChunkListeners(int $chunkX, int $chunkZ) : array{
900 return $this->chunkListeners[World::chunkHash($chunkX, $chunkZ)] ?? [];
901 }
902
906 public function sendTime(Player ...$targets) : void{
907 if(count($targets) === 0){
908 $targets = $this->players;
909 }
910 foreach($targets as $player){
911 $player->getNetworkSession()->syncWorldTime($this->time);
912 }
913 }
914
915 public function isDoingTick() : bool{
916 return $this->doingTick;
917 }
918
922 public function doTick(int $currentTick) : void{
923 if($this->unloaded){
924 throw new \LogicException("Attempted to tick a world which has been closed");
925 }
926
927 $this->timings->doTick->startTiming();
928 $this->doingTick = true;
929 try{
930 $this->actuallyDoTick($currentTick);
931 }finally{
932 $this->doingTick = false;
933 $this->timings->doTick->stopTiming();
934 }
935 }
936
937 protected function actuallyDoTick(int $currentTick) : void{
938 if(!$this->stopTime){
939 //this simulates an overflow, as would happen in any language which doesn't do stupid things to var types
940 if($this->time === PHP_INT_MAX){
941 $this->time = PHP_INT_MIN;
942 }else{
943 $this->time++;
944 }
945 }
946
947 $this->sunAnglePercentage = $this->computeSunAnglePercentage(); //Sun angle depends on the current time
948 $this->skyLightReduction = $this->computeSkyLightReduction(); //Sky light reduction depends on the sun angle
949
950 if(++$this->sendTimeTicker === 200){
951 $this->sendTime();
952 $this->sendTimeTicker = 0;
953 }
954
955 $this->unloadChunks();
956 if(++$this->providerGarbageCollectionTicker >= 6000){
957 $this->provider->doGarbageCollection();
958 $this->providerGarbageCollectionTicker = 0;
959 }
960
961 $this->timings->scheduledBlockUpdates->startTiming();
962 //Delayed updates
963 while($this->scheduledBlockUpdateQueue->count() > 0 && $this->scheduledBlockUpdateQueue->current()["priority"] <= $currentTick){
965 $vec = $this->scheduledBlockUpdateQueue->extract()["data"];
966 unset($this->scheduledBlockUpdateQueueIndex[World::blockHash($vec->x, $vec->y, $vec->z)]);
967 if(!$this->isInLoadedTerrain($vec)){
968 continue;
969 }
970 $block = $this->getBlock($vec);
971 $block->onScheduledUpdate();
972 }
973 $this->timings->scheduledBlockUpdates->stopTiming();
974
975 $this->timings->neighbourBlockUpdates->startTiming();
976 //Normal updates
977 while($this->neighbourBlockUpdateQueue->count() > 0){
978 $index = $this->neighbourBlockUpdateQueue->dequeue();
979 unset($this->neighbourBlockUpdateQueueIndex[$index]);
980 World::getBlockXYZ($index, $x, $y, $z);
981 if(!$this->isChunkLoaded($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)){
982 continue;
983 }
984
985 $block = $this->getBlockAt($x, $y, $z);
986
987 if(BlockUpdateEvent::hasHandlers()){
988 $ev = new BlockUpdateEvent($block);
989 $ev->call();
990 if($ev->isCancelled()){
991 continue;
992 }
993 }
994 foreach($this->getNearbyEntities(AxisAlignedBB::one()->offset($x, $y, $z)) as $entity){
995 $entity->onNearbyBlockChange();
996 }
997 $block->onNearbyBlockChange();
998 }
999
1000 $this->timings->neighbourBlockUpdates->stopTiming();
1001
1002 $this->timings->entityTick->startTiming();
1003 //Update entities that need update
1004 foreach($this->updateEntities as $id => $entity){
1005 if($entity->isClosed() || $entity->isFlaggedForDespawn() || !$entity->onUpdate($currentTick)){
1006 unset($this->updateEntities[$id]);
1007 }
1008 if($entity->isFlaggedForDespawn()){
1009 $entity->close();
1010 }
1011 }
1012 $this->timings->entityTick->stopTiming();
1013
1014 $this->timings->randomChunkUpdates->startTiming();
1015 $this->tickChunks();
1016 $this->timings->randomChunkUpdates->stopTiming();
1017
1018 $this->executeQueuedLightUpdates();
1019
1020 if(count($this->changedBlocks) > 0){
1021 if(count($this->players) > 0){
1022 foreach($this->changedBlocks as $index => $blocks){
1023 if(count($blocks) === 0){ //blocks can be set normally and then later re-set with direct send
1024 continue;
1025 }
1026 World::getXZ($index, $chunkX, $chunkZ);
1027 if(!$this->isChunkLoaded($chunkX, $chunkZ)){
1028 //a previous chunk may have caused this one to be unloaded by a ChunkListener
1029 continue;
1030 }
1031 if(count($blocks) > 512){
1032 $chunk = $this->getChunk($chunkX, $chunkZ) ?? throw new AssumptionFailedError("We already checked that the chunk is loaded");
1033 foreach($this->getChunkPlayers($chunkX, $chunkZ) as $p){
1034 $p->onChunkChanged($chunkX, $chunkZ, $chunk);
1035 }
1036 }else{
1037 foreach($this->createBlockUpdatePackets($blocks) as $packet){
1038 $this->broadcastPacketToPlayersUsingChunk($chunkX, $chunkZ, $packet);
1039 }
1040 }
1041 }
1042 }
1043
1044 $this->changedBlocks = [];
1045
1046 }
1047
1048 if($this->sleepTicks > 0 && --$this->sleepTicks <= 0){
1049 $this->checkSleep();
1050 }
1051
1052 foreach($this->packetBuffersByChunk as $index => $entries){
1053 World::getXZ($index, $chunkX, $chunkZ);
1054 $chunkPlayers = $this->getChunkPlayers($chunkX, $chunkZ);
1055 if(count($chunkPlayers) > 0){
1056 NetworkBroadcastUtils::broadcastPackets($chunkPlayers, $entries);
1057 }
1058 }
1059
1060 $this->packetBuffersByChunk = [];
1061 }
1062
1063 public function checkSleep() : void{
1064 if(count($this->players) === 0){
1065 return;
1066 }
1067
1068 $resetTime = true;
1069 foreach($this->getPlayers() as $p){
1070 if(!$p->isSleeping()){
1071 $resetTime = false;
1072 break;
1073 }
1074 }
1075
1076 if($resetTime){
1077 $time = $this->getTimeOfDay();
1078
1079 if($time >= World::TIME_NIGHT && $time < World::TIME_SUNRISE){
1080 $this->setTime($this->getTime() + World::TIME_FULL - $time);
1081
1082 foreach($this->getPlayers() as $p){
1083 $p->stopSleep();
1084 }
1085 }
1086 }
1087 }
1088
1089 public function setSleepTicks(int $ticks) : void{
1090 $this->sleepTicks = $ticks;
1091 }
1092
1099 public function createBlockUpdatePackets(array $blocks) : array{
1100 $packets = [];
1101
1102 $blockTranslator = TypeConverter::getInstance()->getBlockTranslator();
1103
1104 foreach($blocks as $b){
1105 if(!($b instanceof Vector3)){
1106 throw new \TypeError("Expected Vector3 in blocks array, got " . (is_object($b) ? get_class($b) : gettype($b)));
1107 }
1108
1109 $fullBlock = $this->getBlockAt($b->x, $b->y, $b->z);
1110 $blockPosition = BlockPosition::fromVector3($b);
1111
1112 $tile = $this->getTileAt($b->x, $b->y, $b->z);
1113 if($tile instanceof Spawnable){
1114 $expectedClass = $fullBlock->getIdInfo()->getTileClass();
1115 if($expectedClass !== null && $tile instanceof $expectedClass && count($fakeStateProperties = $tile->getRenderUpdateBugWorkaroundStateProperties($fullBlock)) > 0){
1116 $originalStateData = $blockTranslator->internalIdToNetworkStateData($fullBlock->getStateId());
1117 $fakeStateData = new BlockStateData(
1118 $originalStateData->getName(),
1119 array_merge($originalStateData->getStates(), $fakeStateProperties),
1120 $originalStateData->getVersion()
1121 );
1122 $packets[] = UpdateBlockPacket::create(
1123 $blockPosition,
1124 $blockTranslator->getBlockStateDictionary()->lookupStateIdFromData($fakeStateData) ?? throw new AssumptionFailedError("Unmapped fake blockstate data: " . $fakeStateData->toNbt()),
1125 UpdateBlockPacket::FLAG_NETWORK,
1126 UpdateBlockPacket::DATA_LAYER_NORMAL
1127 );
1128 }
1129 }
1130 $packets[] = UpdateBlockPacket::create(
1131 $blockPosition,
1132 $blockTranslator->internalIdToNetworkId($fullBlock->getStateId()),
1133 UpdateBlockPacket::FLAG_NETWORK,
1134 UpdateBlockPacket::DATA_LAYER_NORMAL
1135 );
1136
1137 if($tile instanceof Spawnable){
1138 $packets[] = BlockActorDataPacket::create($blockPosition, $tile->getSerializedSpawnCompound());
1139 }
1140 }
1141
1142 return $packets;
1143 }
1144
1145 public function clearCache(bool $force = false) : void{
1146 if($force){
1147 $this->blockCache = [];
1148 $this->blockCacheSize = 0;
1149 $this->blockCollisionBoxCache = [];
1150 }else{
1151 //Recalculate this when we're asked - blockCacheSize may be higher than the real size
1152 $this->blockCacheSize = 0;
1153 foreach($this->blockCache as $list){
1154 $this->blockCacheSize += count($list);
1155 if($this->blockCacheSize > self::BLOCK_CACHE_SIZE_CAP){
1156 $this->blockCache = [];
1157 $this->blockCacheSize = 0;
1158 break;
1159 }
1160 }
1161
1162 $count = 0;
1163 foreach($this->blockCollisionBoxCache as $list){
1164 $count += count($list);
1165 if($count > self::BLOCK_CACHE_SIZE_CAP){
1166 //TODO: Is this really the best logic?
1167 $this->blockCollisionBoxCache = [];
1168 break;
1169 }
1170 }
1171 }
1172 }
1173
1174 private function trimBlockCache() : void{
1175 $before = $this->blockCacheSize;
1176 //Since PHP maintains key order, earliest in foreach should be the oldest entries
1177 //Older entries are less likely to be hot, so destroying these should usually have the lowest impact on performance
1178 foreach($this->blockCache as $chunkHash => $blocks){
1179 unset($this->blockCache[$chunkHash]);
1180 $this->blockCacheSize -= count($blocks);
1181 if($this->blockCacheSize < self::BLOCK_CACHE_SIZE_CAP){
1182 break;
1183 }
1184 }
1185 }
1186
1191 public function getRandomTickedBlocks() : array{
1192 return $this->randomTickBlocks;
1193 }
1194
1195 public function addRandomTickedBlock(Block $block) : void{
1196 if($block instanceof UnknownBlock){
1197 throw new \InvalidArgumentException("Cannot do random-tick on unknown block");
1198 }
1199 $this->randomTickBlocks[$block->getStateId()] = true;
1200 }
1201
1202 public function removeRandomTickedBlock(Block $block) : void{
1203 unset($this->randomTickBlocks[$block->getStateId()]);
1204 }
1205
1210 public function getChunkTickRadius() : int{
1211 return $this->chunkTickRadius;
1212 }
1213
1218 public function setChunkTickRadius(int $radius) : void{
1219 $this->chunkTickRadius = $radius;
1220 }
1221
1229 public function getTickingChunks() : array{
1230 return array_keys($this->validTickingChunks);
1231 }
1232
1237 public function registerTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ) : void{
1238 $chunkPosHash = World::chunkHash($chunkX, $chunkZ);
1239 $this->registeredTickingChunks[$chunkPosHash][spl_object_id($ticker)] = $ticker;
1240 $this->recheckTickingChunks[$chunkPosHash] = $chunkPosHash;
1241 }
1242
1247 public function unregisterTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ) : void{
1248 $chunkHash = World::chunkHash($chunkX, $chunkZ);
1249 $tickerId = spl_object_id($ticker);
1250 if(isset($this->registeredTickingChunks[$chunkHash][$tickerId])){
1251 if(count($this->registeredTickingChunks[$chunkHash]) === 1){
1252 unset(
1253 $this->registeredTickingChunks[$chunkHash],
1254 $this->recheckTickingChunks[$chunkHash],
1255 $this->validTickingChunks[$chunkHash]
1256 );
1257 }else{
1258 unset($this->registeredTickingChunks[$chunkHash][$tickerId]);
1259 }
1260 }
1261 }
1262
1263 private function tickChunks() : void{
1264 if($this->chunkTickRadius <= 0 || count($this->registeredTickingChunks) === 0){
1265 return;
1266 }
1267
1268 if(count($this->recheckTickingChunks) > 0){
1269 $this->timings->randomChunkUpdatesChunkSelection->startTiming();
1270
1271 $chunkTickableCache = [];
1272
1273 foreach($this->recheckTickingChunks as $hash => $_){
1274 World::getXZ($hash, $chunkX, $chunkZ);
1275 if($this->isChunkTickable($chunkX, $chunkZ, $chunkTickableCache)){
1276 $this->validTickingChunks[$hash] = $hash;
1277 }
1278 }
1279 $this->recheckTickingChunks = [];
1280
1281 $this->timings->randomChunkUpdatesChunkSelection->stopTiming();
1282 }
1283
1284 foreach($this->validTickingChunks as $index => $_){
1285 World::getXZ($index, $chunkX, $chunkZ);
1286
1287 $this->tickChunk($chunkX, $chunkZ);
1288 }
1289 }
1290
1297 private function isChunkTickable(int $chunkX, int $chunkZ, array &$cache) : bool{
1298 for($cx = -1; $cx <= 1; ++$cx){
1299 for($cz = -1; $cz <= 1; ++$cz){
1300 $chunkHash = World::chunkHash($chunkX + $cx, $chunkZ + $cz);
1301 if(isset($cache[$chunkHash])){
1302 if(!$cache[$chunkHash]){
1303 return false;
1304 }
1305 continue;
1306 }
1307 if($this->isChunkLocked($chunkX + $cx, $chunkZ + $cz)){
1308 $cache[$chunkHash] = false;
1309 return false;
1310 }
1311 $adjacentChunk = $this->getChunk($chunkX + $cx, $chunkZ + $cz);
1312 if($adjacentChunk === null || !$adjacentChunk->isPopulated()){
1313 $cache[$chunkHash] = false;
1314 return false;
1315 }
1316 $lightPopulatedState = $adjacentChunk->isLightPopulated();
1317 if($lightPopulatedState !== true){
1318 if($lightPopulatedState === false){
1319 $this->orderLightPopulation($chunkX + $cx, $chunkZ + $cz);
1320 }
1321 $cache[$chunkHash] = false;
1322 return false;
1323 }
1324
1325 $cache[$chunkHash] = true;
1326 }
1327 }
1328
1329 return true;
1330 }
1331
1341 private function markTickingChunkForRecheck(int $chunkX, int $chunkZ) : void{
1342 for($cx = -1; $cx <= 1; ++$cx){
1343 for($cz = -1; $cz <= 1; ++$cz){
1344 $chunkHash = World::chunkHash($chunkX + $cx, $chunkZ + $cz);
1345 unset($this->validTickingChunks[$chunkHash]);
1346 if(isset($this->registeredTickingChunks[$chunkHash])){
1347 $this->recheckTickingChunks[$chunkHash] = $chunkHash;
1348 }else{
1349 unset($this->recheckTickingChunks[$chunkHash]);
1350 }
1351 }
1352 }
1353 }
1354
1355 private function orderLightPopulation(int $chunkX, int $chunkZ) : void{
1356 $chunkHash = World::chunkHash($chunkX, $chunkZ);
1357 $lightPopulatedState = $this->chunks[$chunkHash]->isLightPopulated();
1358 if($lightPopulatedState === false){
1359 $this->chunks[$chunkHash]->setLightPopulated(null);
1360 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
1361
1362 $this->workerPool->submitTask(new LightPopulationTask(
1363 $this->chunks[$chunkHash],
1364 function(array $blockLight, array $skyLight, array $heightMap) use ($chunkX, $chunkZ) : void{
1371 if($this->unloaded || ($chunk = $this->getChunk($chunkX, $chunkZ)) === null || $chunk->isLightPopulated() === true){
1372 return;
1373 }
1374 //TODO: calculated light information might not be valid if the terrain changed during light calculation
1375
1376 $chunk->setHeightMapArray($heightMap);
1377 foreach($blockLight as $y => $lightArray){
1378 $chunk->getSubChunk($y)->setBlockLightArray($lightArray);
1379 }
1380 foreach($skyLight as $y => $lightArray){
1381 $chunk->getSubChunk($y)->setBlockSkyLightArray($lightArray);
1382 }
1383 $chunk->setLightPopulated(true);
1384 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
1385 }
1386 ));
1387 }
1388 }
1389
1390 private function tickChunk(int $chunkX, int $chunkZ) : void{
1391 $chunk = $this->getChunk($chunkX, $chunkZ);
1392 if($chunk === null){
1393 //the chunk may have been unloaded during a previous chunk's update (e.g. during BlockGrowEvent)
1394 return;
1395 }
1396 foreach($this->getChunkEntities($chunkX, $chunkZ) as $entity){
1397 $entity->onRandomUpdate();
1398 }
1399
1400 $blockFactory = $this->blockStateRegistry;
1401 foreach($chunk->getSubChunks() as $Y => $subChunk){
1402 if(!$subChunk->isEmptyFast()){
1403 $k = 0;
1404 for($i = 0; $i < $this->tickedBlocksPerSubchunkPerTick; ++$i){
1405 if(($i % 5) === 0){
1406 //60 bits will be used by 5 blocks (12 bits each)
1407 $k = mt_rand(0, (1 << 60) - 1);
1408 }
1409 $x = $k & SubChunk::COORD_MASK;
1410 $y = ($k >> SubChunk::COORD_BIT_SIZE) & SubChunk::COORD_MASK;
1411 $z = ($k >> (SubChunk::COORD_BIT_SIZE * 2)) & SubChunk::COORD_MASK;
1412 $k >>= (SubChunk::COORD_BIT_SIZE * 3);
1413
1414 $state = $subChunk->getBlockStateId($x, $y, $z);
1415
1416 if(isset($this->randomTickBlocks[$state])){
1417 $block = $blockFactory->fromStateId($state);
1418 $block->position($this, $chunkX * Chunk::EDGE_LENGTH + $x, ($Y << SubChunk::COORD_BIT_SIZE) + $y, $chunkZ * Chunk::EDGE_LENGTH + $z);
1419 $block->onRandomTick();
1420 }
1421 }
1422 }
1423 }
1424 }
1425
1429 public function __debugInfo() : array{
1430 return [];
1431 }
1432
1433 public function save(bool $force = false) : bool{
1434
1435 if(!$this->getAutoSave() && !$force){
1436 return false;
1437 }
1438
1439 (new WorldSaveEvent($this))->call();
1440
1441 $timings = $this->timings->syncDataSave;
1442 $timings->startTiming();
1443
1444 $this->provider->getWorldData()->setTime($this->time);
1445 $this->saveChunks();
1446 $this->provider->getWorldData()->save();
1447
1448 $timings->stopTiming();
1449
1450 return true;
1451 }
1452
1453 public function saveChunks() : void{
1454 $this->timings->syncChunkSave->startTiming();
1455 try{
1456 foreach($this->chunks as $chunkHash => $chunk){
1457 self::getXZ($chunkHash, $chunkX, $chunkZ);
1458 $this->provider->saveChunk($chunkX, $chunkZ, new ChunkData(
1459 $chunk->getSubChunks(),
1460 $chunk->isPopulated(),
1461 array_map(fn(Entity $e) => $e->saveNBT(), array_values(array_filter($this->getChunkEntities($chunkX, $chunkZ), fn(Entity $e) => $e->canSaveWithChunk()))),
1462 array_map(fn(Tile $t) => $t->saveNBT(), array_values($chunk->getTiles())),
1463 ), $chunk->getTerrainDirtyFlags());
1464 $chunk->clearTerrainDirtyFlags();
1465 }
1466 }finally{
1467 $this->timings->syncChunkSave->stopTiming();
1468 }
1469 }
1470
1475 public function scheduleDelayedBlockUpdate(Vector3 $pos, int $delay) : void{
1476 if(
1477 !$this->isInWorld($pos->x, $pos->y, $pos->z) ||
1478 (isset($this->scheduledBlockUpdateQueueIndex[$index = World::blockHash($pos->x, $pos->y, $pos->z)]) && $this->scheduledBlockUpdateQueueIndex[$index] <= $delay)
1479 ){
1480 return;
1481 }
1482 $this->scheduledBlockUpdateQueueIndex[$index] = $delay;
1483 $this->scheduledBlockUpdateQueue->insert(new Vector3((int) $pos->x, (int) $pos->y, (int) $pos->z), $delay + $this->server->getTick());
1484 }
1485
1486 private function tryAddToNeighbourUpdateQueue(int $x, int $y, int $z) : void{
1487 if($this->isInWorld($x, $y, $z)){
1488 $hash = World::blockHash($x, $y, $z);
1489 if(!isset($this->neighbourBlockUpdateQueueIndex[$hash])){
1490 $this->neighbourBlockUpdateQueue->enqueue($hash);
1491 $this->neighbourBlockUpdateQueueIndex[$hash] = true;
1492 }
1493 }
1494 }
1495
1502 private function internalNotifyNeighbourBlockUpdate(int $x, int $y, int $z) : void{
1503 $this->tryAddToNeighbourUpdateQueue($x, $y, $z);
1504 foreach(Facing::OFFSET as [$dx, $dy, $dz]){
1505 $this->tryAddToNeighbourUpdateQueue($x + $dx, $y + $dy, $z + $dz);
1506 }
1507 }
1508
1516 public function notifyNeighbourBlockUpdate(Vector3 $pos) : void{
1517 $this->internalNotifyNeighbourBlockUpdate($pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ());
1518 }
1519
1524 public function getCollisionBlocks(AxisAlignedBB $bb, bool $targetFirst = false) : array{
1525 $minX = (int) floor($bb->minX - 1);
1526 $minY = (int) floor($bb->minY - 1);
1527 $minZ = (int) floor($bb->minZ - 1);
1528 $maxX = (int) floor($bb->maxX + 1);
1529 $maxY = (int) floor($bb->maxY + 1);
1530 $maxZ = (int) floor($bb->maxZ + 1);
1531
1532 $collides = [];
1533
1534 $collisionInfo = $this->blockStateRegistry->collisionInfo;
1535 if($targetFirst){
1536 for($z = $minZ; $z <= $maxZ; ++$z){
1537 $zOverflow = $z === $minZ || $z === $maxZ;
1538 for($x = $minX; $x <= $maxX; ++$x){
1539 $zxOverflow = $zOverflow || $x === $minX || $x === $maxX;
1540 for($y = $minY; $y <= $maxY; ++$y){
1541 $overflow = $zxOverflow || $y === $minY || $y === $maxY;
1542
1543 $stateCollisionInfo = $this->getBlockCollisionInfo($x, $y, $z, $collisionInfo);
1544 if($overflow ?
1545 $stateCollisionInfo === RuntimeBlockStateRegistry::COLLISION_MAY_OVERFLOW && $this->getBlockAt($x, $y, $z)->collidesWithBB($bb) :
1546 match ($stateCollisionInfo) {
1547 RuntimeBlockStateRegistry::COLLISION_CUBE => true,
1548 RuntimeBlockStateRegistry::COLLISION_NONE => false,
1549 default => $this->getBlockAt($x, $y, $z)->collidesWithBB($bb)
1550 }
1551 ){
1552 return [$this->getBlockAt($x, $y, $z)];
1553 }
1554 }
1555 }
1556 }
1557 }else{
1558 //TODO: duplicated code :( this way is better for performance though
1559 for($z = $minZ; $z <= $maxZ; ++$z){
1560 $zOverflow = $z === $minZ || $z === $maxZ;
1561 for($x = $minX; $x <= $maxX; ++$x){
1562 $zxOverflow = $zOverflow || $x === $minX || $x === $maxX;
1563 for($y = $minY; $y <= $maxY; ++$y){
1564 $overflow = $zxOverflow || $y === $minY || $y === $maxY;
1565
1566 $stateCollisionInfo = $this->getBlockCollisionInfo($x, $y, $z, $collisionInfo);
1567 if($overflow ?
1568 $stateCollisionInfo === RuntimeBlockStateRegistry::COLLISION_MAY_OVERFLOW && $this->getBlockAt($x, $y, $z)->collidesWithBB($bb) :
1569 match ($stateCollisionInfo) {
1570 RuntimeBlockStateRegistry::COLLISION_CUBE => true,
1571 RuntimeBlockStateRegistry::COLLISION_NONE => false,
1572 default => $this->getBlockAt($x, $y, $z)->collidesWithBB($bb)
1573 }
1574 ){
1575 $collides[] = $this->getBlockAt($x, $y, $z);
1576 }
1577 }
1578 }
1579 }
1580 }
1581
1582 return $collides;
1583 }
1584
1589 private function getBlockCollisionInfo(int $x, int $y, int $z, array $collisionInfo) : int{
1590 if(!$this->isInWorld($x, $y, $z)){
1591 return RuntimeBlockStateRegistry::COLLISION_NONE;
1592 }
1593 $chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE);
1594 if($chunk === null){
1595 return RuntimeBlockStateRegistry::COLLISION_NONE;
1596 }
1597 $stateId = $chunk
1598 ->getSubChunk($y >> SubChunk::COORD_BIT_SIZE)
1599 ->getBlockStateId(
1600 $x & SubChunk::COORD_MASK,
1601 $y & SubChunk::COORD_MASK,
1602 $z & SubChunk::COORD_MASK
1603 );
1604 return $collisionInfo[$stateId];
1605 }
1606
1618 private function getBlockCollisionBoxesForCell(int $x, int $y, int $z, array $collisionInfo) : array{
1619 $stateCollisionInfo = $this->getBlockCollisionInfo($x, $y, $z, $collisionInfo);
1620 $boxes = match($stateCollisionInfo){
1621 RuntimeBlockStateRegistry::COLLISION_NONE => [],
1622 RuntimeBlockStateRegistry::COLLISION_CUBE => [AxisAlignedBB::one()->offset($x, $y, $z)],
1623 default => $this->getBlockAt($x, $y, $z)->getCollisionBoxes()
1624 };
1625
1626 //overlapping AABBs can't make any difference if this is a cube, so we can save some CPU cycles in this common case
1627 if($stateCollisionInfo !== RuntimeBlockStateRegistry::COLLISION_CUBE){
1628 $cellBB = null;
1629 foreach(Facing::OFFSET as [$dx, $dy, $dz]){
1630 $offsetX = $x + $dx;
1631 $offsetY = $y + $dy;
1632 $offsetZ = $z + $dz;
1633 $stateCollisionInfo = $this->getBlockCollisionInfo($offsetX, $offsetY, $offsetZ, $collisionInfo);
1634 if($stateCollisionInfo === RuntimeBlockStateRegistry::COLLISION_MAY_OVERFLOW){
1635 //avoid allocating this unless it's needed
1636 $cellBB ??= AxisAlignedBB::one()->offset($x, $y, $z);
1637 $extraBoxes = $this->getBlockAt($offsetX, $offsetY, $offsetZ)->getCollisionBoxes();
1638 foreach($extraBoxes as $extraBox){
1639 if($extraBox->intersectsWith($cellBB)){
1640 $boxes[] = $extraBox;
1641 }
1642 }
1643 }
1644 }
1645 }
1646
1647 return $boxes;
1648 }
1649
1654 public function getBlockCollisionBoxes(AxisAlignedBB $bb) : array{
1655 $minX = (int) floor($bb->minX);
1656 $minY = (int) floor($bb->minY);
1657 $minZ = (int) floor($bb->minZ);
1658 $maxX = (int) floor($bb->maxX);
1659 $maxY = (int) floor($bb->maxY);
1660 $maxZ = (int) floor($bb->maxZ);
1661
1662 $collides = [];
1663
1664 $collisionInfo = $this->blockStateRegistry->collisionInfo;
1665
1666 for($z = $minZ; $z <= $maxZ; ++$z){
1667 for($x = $minX; $x <= $maxX; ++$x){
1668 $chunkPosHash = World::chunkHash($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE);
1669 for($y = $minY; $y <= $maxY; ++$y){
1670 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
1671
1672 $boxes = $this->blockCollisionBoxCache[$chunkPosHash][$relativeBlockHash] ??= $this->getBlockCollisionBoxesForCell($x, $y, $z, $collisionInfo);
1673
1674 foreach($boxes as $blockBB){
1675 if($blockBB->intersectsWith($bb)){
1676 $collides[] = $blockBB;
1677 }
1678 }
1679 }
1680 }
1681 }
1682
1683 return $collides;
1684 }
1685
1693 public function getCollisionBoxes(Entity $entity, AxisAlignedBB $bb, bool $entities = true) : array{
1694 $collides = $this->getBlockCollisionBoxes($bb);
1695
1696 if($entities){
1697 foreach($this->getCollidingEntities($bb->expandedCopy(0.25, 0.25, 0.25), $entity) as $ent){
1698 $collides[] = clone $ent->boundingBox;
1699 }
1700 }
1701
1702 return $collides;
1703 }
1704
1709 public function computeSunAnglePercentage() : float{
1710 $timeProgress = ($this->time % self::TIME_FULL) / self::TIME_FULL;
1711
1712 //0.0 needs to be high noon, not dusk
1713 $sunProgress = $timeProgress + ($timeProgress < 0.25 ? 0.75 : -0.25);
1714
1715 //Offset the sun progress to be above the horizon longer at dusk and dawn
1716 //this is roughly an inverted sine curve, which pushes the sun progress back at dusk and forwards at dawn
1717 $diff = (((1 - ((cos($sunProgress * M_PI) + 1) / 2)) - $sunProgress) / 3);
1718
1719 return $sunProgress + $diff;
1720 }
1721
1725 public function getSunAnglePercentage() : float{
1726 return $this->sunAnglePercentage;
1727 }
1728
1732 public function getSunAngleRadians() : float{
1733 return $this->sunAnglePercentage * 2 * M_PI;
1734 }
1735
1739 public function getSunAngleDegrees() : float{
1740 return $this->sunAnglePercentage * 360.0;
1741 }
1742
1747 public function computeSkyLightReduction() : int{
1748 $percentage = max(0, min(1, -(cos($this->getSunAngleRadians()) * 2 - 0.5)));
1749
1750 //TODO: check rain and thunder level
1751
1752 return (int) ($percentage * 11);
1753 }
1754
1758 public function getSkyLightReduction() : int{
1759 return $this->skyLightReduction;
1760 }
1761
1766 public function getFullLight(Vector3 $pos) : int{
1767 $floorX = $pos->getFloorX();
1768 $floorY = $pos->getFloorY();
1769 $floorZ = $pos->getFloorZ();
1770 return $this->getFullLightAt($floorX, $floorY, $floorZ);
1771 }
1772
1777 public function getFullLightAt(int $x, int $y, int $z) : int{
1778 $skyLight = $this->getRealBlockSkyLightAt($x, $y, $z);
1779 if($skyLight < 15){
1780 return max($skyLight, $this->getBlockLightAt($x, $y, $z));
1781 }else{
1782 return $skyLight;
1783 }
1784 }
1785
1790 public function getHighestAdjacentFullLightAt(int $x, int $y, int $z) : int{
1791 return $this->getHighestAdjacentLight($x, $y, $z, $this->getFullLightAt(...));
1792 }
1793
1798 public function getPotentialLight(Vector3 $pos) : int{
1799 $floorX = $pos->getFloorX();
1800 $floorY = $pos->getFloorY();
1801 $floorZ = $pos->getFloorZ();
1802 return $this->getPotentialLightAt($floorX, $floorY, $floorZ);
1803 }
1804
1809 public function getPotentialLightAt(int $x, int $y, int $z) : int{
1810 return max($this->getPotentialBlockSkyLightAt($x, $y, $z), $this->getBlockLightAt($x, $y, $z));
1811 }
1812
1817 public function getHighestAdjacentPotentialLightAt(int $x, int $y, int $z) : int{
1818 return $this->getHighestAdjacentLight($x, $y, $z, $this->getPotentialLightAt(...));
1819 }
1820
1827 public function getPotentialBlockSkyLightAt(int $x, int $y, int $z) : int{
1828 if(!$this->isInWorld($x, $y, $z)){
1829 return $y >= self::Y_MAX ? 15 : 0;
1830 }
1831 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null && $chunk->isLightPopulated() === true){
1832 return $chunk->getSubChunk($y >> Chunk::COORD_BIT_SIZE)->getBlockSkyLightArray()->get($x & SubChunk::COORD_MASK, $y & SubChunk::COORD_MASK, $z & SubChunk::COORD_MASK);
1833 }
1834 return 0; //TODO: this should probably throw instead (light not calculated yet)
1835 }
1836
1842 public function getRealBlockSkyLightAt(int $x, int $y, int $z) : int{
1843 $light = $this->getPotentialBlockSkyLightAt($x, $y, $z) - $this->skyLightReduction;
1844 return $light < 0 ? 0 : $light;
1845 }
1846
1852 public function getBlockLightAt(int $x, int $y, int $z) : int{
1853 if(!$this->isInWorld($x, $y, $z)){
1854 return 0;
1855 }
1856 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null && $chunk->isLightPopulated() === true){
1857 return $chunk->getSubChunk($y >> Chunk::COORD_BIT_SIZE)->getBlockLightArray()->get($x & SubChunk::COORD_MASK, $y & SubChunk::COORD_MASK, $z & SubChunk::COORD_MASK);
1858 }
1859 return 0; //TODO: this should probably throw instead (light not calculated yet)
1860 }
1861
1862 public function updateAllLight(int $x, int $y, int $z) : void{
1863 if(($chunk = $this->getChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) === null || $chunk->isLightPopulated() !== true){
1864 return;
1865 }
1866
1867 $blockFactory = $this->blockStateRegistry;
1868 $this->timings->doBlockSkyLightUpdates->startTiming();
1869 if($this->skyLightUpdate === null){
1870 $this->skyLightUpdate = new SkyLightUpdate(new SubChunkExplorer($this), $blockFactory->lightFilter, $blockFactory->blocksDirectSkyLight);
1871 }
1872 $this->skyLightUpdate->recalculateNode($x, $y, $z);
1873 $this->timings->doBlockSkyLightUpdates->stopTiming();
1874
1875 $this->timings->doBlockLightUpdates->startTiming();
1876 if($this->blockLightUpdate === null){
1877 $this->blockLightUpdate = new BlockLightUpdate(new SubChunkExplorer($this), $blockFactory->lightFilter, $blockFactory->light);
1878 }
1879 $this->blockLightUpdate->recalculateNode($x, $y, $z);
1880 $this->timings->doBlockLightUpdates->stopTiming();
1881 }
1882
1886 private function getHighestAdjacentLight(int $x, int $y, int $z, \Closure $lightGetter) : int{
1887 $max = 0;
1888 foreach(Facing::OFFSET as [$offsetX, $offsetY, $offsetZ]){
1889 $x1 = $x + $offsetX;
1890 $y1 = $y + $offsetY;
1891 $z1 = $z + $offsetZ;
1892 if(
1893 !$this->isInWorld($x1, $y1, $z1) ||
1894 ($chunk = $this->getChunk($x1 >> Chunk::COORD_BIT_SIZE, $z1 >> Chunk::COORD_BIT_SIZE)) === null ||
1895 $chunk->isLightPopulated() !== true
1896 ){
1897 continue;
1898 }
1899 $max = max($max, $lightGetter($x1, $y1, $z1));
1900 }
1901 return $max;
1902 }
1903
1907 public function getHighestAdjacentPotentialBlockSkyLight(int $x, int $y, int $z) : int{
1908 return $this->getHighestAdjacentLight($x, $y, $z, $this->getPotentialBlockSkyLightAt(...));
1909 }
1910
1915 public function getHighestAdjacentRealBlockSkyLight(int $x, int $y, int $z) : int{
1916 return $this->getHighestAdjacentPotentialBlockSkyLight($x, $y, $z) - $this->skyLightReduction;
1917 }
1918
1922 public function getHighestAdjacentBlockLight(int $x, int $y, int $z) : int{
1923 return $this->getHighestAdjacentLight($x, $y, $z, $this->getBlockLightAt(...));
1924 }
1925
1926 private function executeQueuedLightUpdates() : void{
1927 if($this->blockLightUpdate !== null){
1928 $this->timings->doBlockLightUpdates->startTiming();
1929 $this->blockLightUpdate->execute();
1930 $this->blockLightUpdate = null;
1931 $this->timings->doBlockLightUpdates->stopTiming();
1932 }
1933
1934 if($this->skyLightUpdate !== null){
1935 $this->timings->doBlockSkyLightUpdates->startTiming();
1936 $this->skyLightUpdate->execute();
1937 $this->skyLightUpdate = null;
1938 $this->timings->doBlockSkyLightUpdates->stopTiming();
1939 }
1940 }
1941
1942 public function isInWorld(int $x, int $y, int $z) : bool{
1943 return (
1944 $x <= Limits::INT32_MAX && $x >= Limits::INT32_MIN &&
1945 $y < $this->maxY && $y >= $this->minY &&
1946 $z <= Limits::INT32_MAX && $z >= Limits::INT32_MIN
1947 );
1948 }
1949
1960 public function getBlock(Vector3 $pos, bool $cached = true, bool $addToCache = true) : Block{
1961 return $this->getBlockAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z), $cached, $addToCache);
1962 }
1963
1973 public function getBlockAt(int $x, int $y, int $z, bool $cached = true, bool $addToCache = true) : Block{
1974 $relativeBlockHash = null;
1975 $chunkHash = World::chunkHash($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE);
1976
1977 if($this->isInWorld($x, $y, $z)){
1978 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
1979
1980 if($cached && isset($this->blockCache[$chunkHash][$relativeBlockHash])){
1981 return $this->blockCache[$chunkHash][$relativeBlockHash];
1982 }
1983
1984 $chunk = $this->chunks[$chunkHash] ?? null;
1985 if($chunk !== null){
1986 $block = $this->blockStateRegistry->fromStateId($chunk->getBlockStateId($x & Chunk::COORD_MASK, $y, $z & Chunk::COORD_MASK));
1987 }else{
1988 $addToCache = false;
1989 $block = VanillaBlocks::AIR();
1990 }
1991 }else{
1992 $block = VanillaBlocks::AIR();
1993 }
1994
1995 $block->position($this, $x, $y, $z);
1996
1997 if($this->inDynamicStateRecalculation){
1998 //this call was generated by a parent getBlock() call calculating dynamic stateinfo
1999 //don't calculate dynamic state and don't add to block cache (since it won't have dynamic state calculated).
2000 //this ensures that it's impossible for dynamic state properties to recursively depend on each other.
2001 $addToCache = false;
2002 }else{
2003 $this->inDynamicStateRecalculation = true;
2004 $replacement = $block->readStateFromWorld();
2005 if($replacement !== $block){
2006 $replacement->position($this, $x, $y, $z);
2007 $block = $replacement;
2008 }
2009 $this->inDynamicStateRecalculation = false;
2010 }
2011
2012 if($addToCache && $relativeBlockHash !== null){
2013 $this->blockCache[$chunkHash][$relativeBlockHash] = $block;
2014
2015 if(++$this->blockCacheSize >= self::BLOCK_CACHE_SIZE_CAP){
2016 $this->trimBlockCache();
2017 }
2018 }
2019
2020 return $block;
2021 }
2022
2028 public function setBlock(Vector3 $pos, Block $block, bool $update = true) : void{
2029 $this->setBlockAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z), $block, $update);
2030 }
2031
2040 public function setBlockAt(int $x, int $y, int $z, Block $block, bool $update = true) : void{
2041 if(!$this->isInWorld($x, $y, $z)){
2042 throw new \InvalidArgumentException("Pos x=$x,y=$y,z=$z is outside of the world bounds");
2043 }
2044 $chunkX = $x >> Chunk::COORD_BIT_SIZE;
2045 $chunkZ = $z >> Chunk::COORD_BIT_SIZE;
2046 if($this->loadChunk($chunkX, $chunkZ) === null){ //current expected behaviour is to try to load the terrain synchronously
2047 throw new WorldException("Cannot set a block in un-generated terrain");
2048 }
2049
2050 $this->timings->setBlock->startTiming();
2051
2052 $this->unlockChunk($chunkX, $chunkZ, null);
2053
2054 $block = clone $block;
2055
2056 $block->position($this, $x, $y, $z);
2057 $block->writeStateToWorld();
2058 $pos = new Vector3($x, $y, $z);
2059
2060 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2061 $relativeBlockHash = World::chunkBlockHash($x, $y, $z);
2062
2063 unset($this->blockCache[$chunkHash][$relativeBlockHash]);
2064 $this->blockCacheSize--;
2065 unset($this->blockCollisionBoxCache[$chunkHash][$relativeBlockHash]);
2066 //blocks like fences have collision boxes that reach into neighbouring blocks, so we need to invalidate the
2067 //caches for those blocks as well
2068 foreach(Facing::OFFSET as [$offsetX, $offsetY, $offsetZ]){
2069 $sideChunkPosHash = World::chunkHash(($x + $offsetX) >> Chunk::COORD_BIT_SIZE, ($z + $offsetZ) >> Chunk::COORD_BIT_SIZE);
2070 $sideChunkBlockHash = World::chunkBlockHash($x + $offsetX, $y + $offsetY, $z + $offsetZ);
2071 unset($this->blockCollisionBoxCache[$sideChunkPosHash][$sideChunkBlockHash]);
2072 }
2073
2074 if(!isset($this->changedBlocks[$chunkHash])){
2075 $this->changedBlocks[$chunkHash] = [];
2076 }
2077 $this->changedBlocks[$chunkHash][$relativeBlockHash] = $pos;
2078
2079 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2080 $listener->onBlockChanged($pos);
2081 }
2082
2083 if($update){
2084 $this->updateAllLight($x, $y, $z);
2085 $this->internalNotifyNeighbourBlockUpdate($x, $y, $z);
2086 }
2087
2088 $this->timings->setBlock->stopTiming();
2089 }
2090
2091 public function dropItem(Vector3 $source, Item $item, ?Vector3 $motion = null, int $delay = 10) : ?ItemEntity{
2092 if($item->isNull()){
2093 return null;
2094 }
2095
2096 $itemEntity = new ItemEntity(Location::fromObject($source, $this, Utils::getRandomFloat() * 360, 0), $item);
2097
2098 $itemEntity->setPickupDelay($delay);
2099 $itemEntity->setMotion($motion ?? new Vector3(Utils::getRandomFloat() * 0.2 - 0.1, 0.2, Utils::getRandomFloat() * 0.2 - 0.1));
2100 $itemEntity->spawnToAll();
2101
2102 return $itemEntity;
2103 }
2104
2111 public function dropExperience(Vector3 $pos, int $amount) : array{
2112 $orbs = [];
2113
2114 foreach(ExperienceOrb::splitIntoOrbSizes($amount) as $split){
2115 $orb = new ExperienceOrb(Location::fromObject($pos, $this, Utils::getRandomFloat() * 360, 0), $split);
2116
2117 $orb->setMotion(new Vector3((Utils::getRandomFloat() * 0.2 - 0.1) * 2, Utils::getRandomFloat() * 0.4, (Utils::getRandomFloat() * 0.2 - 0.1) * 2));
2118 $orb->spawnToAll();
2119
2120 $orbs[] = $orb;
2121 }
2122
2123 return $orbs;
2124 }
2125
2134 public function useBreakOn(Vector3 $vector, ?Item &$item = null, ?Player $player = null, bool $createParticles = false, array &$returnedItems = []) : bool{
2135 $vector = $vector->floor();
2136
2137 $chunkX = $vector->getFloorX() >> Chunk::COORD_BIT_SIZE;
2138 $chunkZ = $vector->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2139 if(!$this->isChunkLoaded($chunkX, $chunkZ) || $this->isChunkLocked($chunkX, $chunkZ)){
2140 return false;
2141 }
2142
2143 $target = $this->getBlock($vector);
2144 $affectedBlocks = $target->getAffectedBlocks();
2145
2146 if($item === null){
2147 $item = VanillaItems::AIR();
2148 }
2149
2150 $drops = [];
2151 if($player === null || $player->hasFiniteResources()){
2152 $drops = array_merge(...array_map(fn(Block $block) => $block->getDrops($item), $affectedBlocks));
2153 }
2154
2155 $xpDrop = 0;
2156 if($player !== null && $player->hasFiniteResources()){
2157 $xpDrop = array_sum(array_map(fn(Block $block) => $block->getXpDropForTool($item), $affectedBlocks));
2158 }
2159
2160 if($player !== null){
2161 $ev = new BlockBreakEvent($player, $target, $item, $player->isCreative(), $drops, $xpDrop);
2162
2163 if($target instanceof Air || ($player->isSurvival() && !$target->getBreakInfo()->isBreakable()) || $player->isSpectator()){
2164 $ev->cancel();
2165 }
2166
2167 if($player->isAdventure(true) && !$ev->isCancelled()){
2168 $canBreak = false;
2169 $itemParser = LegacyStringToItemParser::getInstance();
2170 foreach($item->getCanDestroy() as $v){
2171 $entry = $itemParser->parse($v);
2172 if($entry->getBlock()->hasSameTypeId($target)){
2173 $canBreak = true;
2174 break;
2175 }
2176 }
2177
2178 if(!$canBreak){
2179 $ev->cancel();
2180 }
2181 }
2182
2183 $ev->call();
2184 if($ev->isCancelled()){
2185 return false;
2186 }
2187
2188 $drops = $ev->getDrops();
2189 $xpDrop = $ev->getXpDropAmount();
2190
2191 }elseif(!$target->getBreakInfo()->isBreakable()){
2192 return false;
2193 }
2194
2195 foreach($affectedBlocks as $t){
2196 $this->destroyBlockInternal($t, $item, $player, $createParticles, $returnedItems);
2197 }
2198
2199 $item->onDestroyBlock($target, $returnedItems);
2200
2201 if(count($drops) > 0){
2202 $dropPos = $vector->add(0.5, 0.5, 0.5);
2203 foreach($drops as $drop){
2204 if(!$drop->isNull()){
2205 $this->dropItem($dropPos, $drop);
2206 }
2207 }
2208 }
2209
2210 if($xpDrop > 0){
2211 $this->dropExperience($vector->add(0.5, 0.5, 0.5), $xpDrop);
2212 }
2213
2214 return true;
2215 }
2216
2220 private function destroyBlockInternal(Block $target, Item $item, ?Player $player, bool $createParticles, array &$returnedItems) : void{
2221 if($createParticles){
2222 $this->addParticle($target->getPosition()->add(0.5, 0.5, 0.5), new BlockBreakParticle($target));
2223 }
2224
2225 $target->onBreak($item, $player, $returnedItems);
2226
2227 $tile = $this->getTile($target->getPosition());
2228 if($tile !== null){
2229 $tile->onBlockDestroyed();
2230 }
2231 }
2232
2240 public function useItemOn(Vector3 $vector, Item &$item, int $face, ?Vector3 $clickVector = null, ?Player $player = null, bool $playSound = false, array &$returnedItems = []) : bool{
2241 $blockClicked = $this->getBlock($vector);
2242 $blockReplace = $blockClicked->getSide($face);
2243
2244 if($clickVector === null){
2245 $clickVector = new Vector3(0.0, 0.0, 0.0);
2246 }else{
2247 $clickVector = new Vector3(
2248 min(1.0, max(0.0, $clickVector->x)),
2249 min(1.0, max(0.0, $clickVector->y)),
2250 min(1.0, max(0.0, $clickVector->z))
2251 );
2252 }
2253
2254 if(!$this->isInWorld($blockReplace->getPosition()->x, $blockReplace->getPosition()->y, $blockReplace->getPosition()->z)){
2255 //TODO: build height limit messages for custom world heights and mcregion cap
2256 return false;
2257 }
2258 $chunkX = $blockReplace->getPosition()->getFloorX() >> Chunk::COORD_BIT_SIZE;
2259 $chunkZ = $blockReplace->getPosition()->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2260 if(!$this->isChunkLoaded($chunkX, $chunkZ) || $this->isChunkLocked($chunkX, $chunkZ)){
2261 return false;
2262 }
2263
2264 if($blockClicked->getTypeId() === BlockTypeIds::AIR){
2265 return false;
2266 }
2267
2268 if($player !== null){
2269 $ev = new PlayerInteractEvent($player, $item, $blockClicked, $clickVector, $face, PlayerInteractEvent::RIGHT_CLICK_BLOCK);
2270 if($player->isSneaking()){
2271 $ev->setUseItem(false);
2272 $ev->setUseBlock($item->isNull()); //opening doors is still possible when sneaking if using an empty hand
2273 }
2274 if($player->isSpectator()){
2275 $ev->cancel(); //set it to cancelled so plugins can bypass this
2276 }
2277
2278 $ev->call();
2279 if(!$ev->isCancelled()){
2280 if($ev->useBlock() && $blockClicked->onInteract($item, $face, $clickVector, $player, $returnedItems)){
2281 return true;
2282 }
2283
2284 if($ev->useItem()){
2285 $result = $item->onInteractBlock($player, $blockReplace, $blockClicked, $face, $clickVector, $returnedItems);
2286 if($result !== ItemUseResult::NONE){
2287 return $result === ItemUseResult::SUCCESS;
2288 }
2289 }
2290 }else{
2291 return false;
2292 }
2293 }elseif($blockClicked->onInteract($item, $face, $clickVector, $player, $returnedItems)){
2294 return true;
2295 }
2296
2297 if($item->isNull() || !$item->canBePlaced()){
2298 return false;
2299 }
2300 $hand = $item->getBlock($face);
2301 $hand->position($this, $blockReplace->getPosition()->x, $blockReplace->getPosition()->y, $blockReplace->getPosition()->z);
2302
2303 if($hand->canBePlacedAt($blockClicked, $clickVector, $face, true)){
2304 $blockReplace = $blockClicked;
2305 //TODO: while this mimics the vanilla behaviour with replaceable blocks, we should really pass some other
2306 //value like NULL and let place() deal with it. This will look like a bug to anyone who doesn't know about
2307 //the vanilla behaviour.
2308 $face = Facing::UP;
2309 $hand->position($this, $blockReplace->getPosition()->x, $blockReplace->getPosition()->y, $blockReplace->getPosition()->z);
2310 }elseif(!$hand->canBePlacedAt($blockReplace, $clickVector, $face, false)){
2311 return false;
2312 }
2313
2314 $tx = new BlockTransaction($this);
2315 if(!$hand->place($tx, $item, $blockReplace, $blockClicked, $face, $clickVector, $player)){
2316 return false;
2317 }
2318
2319 foreach($tx->getBlocks() as [$x, $y, $z, $block]){
2320 $block->position($this, $x, $y, $z);
2321 foreach($block->getCollisionBoxes() as $collisionBox){
2322 if(count($this->getCollidingEntities($collisionBox)) > 0){
2323 return false; //Entity in block
2324 }
2325 }
2326 }
2327
2328 if($player !== null){
2329 $ev = new BlockPlaceEvent($player, $tx, $blockClicked, $item);
2330 if($player->isSpectator()){
2331 $ev->cancel();
2332 }
2333
2334 if($player->isAdventure(true) && !$ev->isCancelled()){
2335 $canPlace = false;
2336 $itemParser = LegacyStringToItemParser::getInstance();
2337 foreach($item->getCanPlaceOn() as $v){
2338 $entry = $itemParser->parse($v);
2339 if($entry->getBlock()->hasSameTypeId($blockClicked)){
2340 $canPlace = true;
2341 break;
2342 }
2343 }
2344
2345 if(!$canPlace){
2346 $ev->cancel();
2347 }
2348 }
2349
2350 $ev->call();
2351 if($ev->isCancelled()){
2352 return false;
2353 }
2354 }
2355
2356 if(!$tx->apply()){
2357 return false;
2358 }
2359 foreach($tx->getBlocks() as [$x, $y, $z, $_]){
2360 $tile = $this->getTileAt($x, $y, $z);
2361 if($tile !== null){
2362 //TODO: seal this up inside block placement
2363 $tile->copyDataFromItem($item);
2364 }
2365
2366 $this->getBlockAt($x, $y, $z)->onPostPlace();
2367 }
2368
2369 if($playSound){
2370 $this->addSound($hand->getPosition(), new BlockPlaceSound($hand));
2371 }
2372
2373 $item->pop();
2374
2375 return true;
2376 }
2377
2378 public function getEntity(int $entityId) : ?Entity{
2379 return $this->entities[$entityId] ?? null;
2380 }
2381
2388 public function getEntities() : array{
2389 return $this->entities;
2390 }
2391
2402 public function getCollidingEntities(AxisAlignedBB $bb, ?Entity $entity = null) : array{
2403 $nearby = [];
2404
2405 foreach($this->getNearbyEntities($bb, $entity) as $ent){
2406 if($ent->canBeCollidedWith() && ($entity === null || $entity->canCollideWith($ent))){
2407 $nearby[] = $ent;
2408 }
2409 }
2410
2411 return $nearby;
2412 }
2413
2420 public function getNearbyEntities(AxisAlignedBB $bb, ?Entity $entity = null) : array{
2421 $nearby = [];
2422
2423 $minX = ((int) floor($bb->minX - 2)) >> Chunk::COORD_BIT_SIZE;
2424 $maxX = ((int) floor($bb->maxX + 2)) >> Chunk::COORD_BIT_SIZE;
2425 $minZ = ((int) floor($bb->minZ - 2)) >> Chunk::COORD_BIT_SIZE;
2426 $maxZ = ((int) floor($bb->maxZ + 2)) >> Chunk::COORD_BIT_SIZE;
2427
2428 for($x = $minX; $x <= $maxX; ++$x){
2429 for($z = $minZ; $z <= $maxZ; ++$z){
2430 foreach($this->getChunkEntities($x, $z) as $ent){
2431 if($ent !== $entity && $ent->boundingBox->intersectsWith($bb)){
2432 $nearby[] = $ent;
2433 }
2434 }
2435 }
2436 }
2437
2438 return $nearby;
2439 }
2440
2452 public function getNearestEntity(Vector3 $pos, float $maxDistance, string $entityType = Entity::class, bool $includeDead = false) : ?Entity{
2453 assert(is_a($entityType, Entity::class, true));
2454
2455 $minX = ((int) floor($pos->x - $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2456 $maxX = ((int) floor($pos->x + $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2457 $minZ = ((int) floor($pos->z - $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2458 $maxZ = ((int) floor($pos->z + $maxDistance)) >> Chunk::COORD_BIT_SIZE;
2459
2460 $currentTargetDistSq = $maxDistance ** 2;
2461
2466 $currentTarget = null;
2467
2468 for($x = $minX; $x <= $maxX; ++$x){
2469 for($z = $minZ; $z <= $maxZ; ++$z){
2470 foreach($this->getChunkEntities($x, $z) as $entity){
2471 if(!($entity instanceof $entityType) || $entity->isFlaggedForDespawn() || (!$includeDead && !$entity->isAlive())){
2472 continue;
2473 }
2474 $distSq = $entity->getPosition()->distanceSquared($pos);
2475 if($distSq < $currentTargetDistSq){
2476 $currentTargetDistSq = $distSq;
2477 $currentTarget = $entity;
2478 }
2479 }
2480 }
2481 }
2482
2483 return $currentTarget;
2484 }
2485
2492 public function getPlayers() : array{
2493 return $this->players;
2494 }
2495
2502 public function getTile(Vector3 $pos) : ?Tile{
2503 return $this->getTileAt((int) floor($pos->x), (int) floor($pos->y), (int) floor($pos->z));
2504 }
2505
2509 public function getTileAt(int $x, int $y, int $z) : ?Tile{
2510 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;
2511 }
2512
2513 public function getBiomeId(int $x, int $y, int $z) : int{
2514 if(($chunk = $this->loadChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null){
2515 return $chunk->getBiomeId($x & Chunk::COORD_MASK, $y & Chunk::COORD_MASK, $z & Chunk::COORD_MASK);
2516 }
2517 return BiomeIds::OCEAN; //TODO: this should probably throw instead (terrain not generated yet)
2518 }
2519
2520 public function getBiome(int $x, int $y, int $z) : Biome{
2521 return BiomeRegistry::getInstance()->getBiome($this->getBiomeId($x, $y, $z));
2522 }
2523
2524 public function setBiomeId(int $x, int $y, int $z, int $biomeId) : void{
2525 $chunkX = $x >> Chunk::COORD_BIT_SIZE;
2526 $chunkZ = $z >> Chunk::COORD_BIT_SIZE;
2527 $this->unlockChunk($chunkX, $chunkZ, null);
2528 if(($chunk = $this->loadChunk($chunkX, $chunkZ)) !== null){
2529 $chunk->setBiomeId($x & Chunk::COORD_MASK, $y & Chunk::COORD_MASK, $z & Chunk::COORD_MASK, $biomeId);
2530 }else{
2531 //if we allowed this, the modifications would be lost when the chunk is created
2532 throw new WorldException("Cannot set biome in a non-generated chunk");
2533 }
2534 }
2535
2540 public function getLoadedChunks() : array{
2541 return $this->chunks;
2542 }
2543
2544 public function getChunk(int $chunkX, int $chunkZ) : ?Chunk{
2545 return $this->chunks[World::chunkHash($chunkX, $chunkZ)] ?? null;
2546 }
2547
2552 public function getChunkEntities(int $chunkX, int $chunkZ) : array{
2553 return $this->entitiesByChunk[World::chunkHash($chunkX, $chunkZ)] ?? [];
2554 }
2555
2559 public function getOrLoadChunkAtPosition(Vector3 $pos) : ?Chunk{
2560 return $this->loadChunk($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
2561 }
2562
2569 public function getAdjacentChunks(int $x, int $z) : array{
2570 $result = [];
2571 for($xx = -1; $xx <= 1; ++$xx){
2572 for($zz = -1; $zz <= 1; ++$zz){
2573 if($xx === 0 && $zz === 0){
2574 continue; //center chunk
2575 }
2576 $result[World::chunkHash($xx, $zz)] = $this->loadChunk($x + $xx, $z + $zz);
2577 }
2578 }
2579
2580 return $result;
2581 }
2582
2597 public function lockChunk(int $chunkX, int $chunkZ, ChunkLockId $lockId) : void{
2598 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2599 if(isset($this->chunkLock[$chunkHash])){
2600 throw new \InvalidArgumentException("Chunk $chunkX $chunkZ is already locked");
2601 }
2602 $this->chunkLock[$chunkHash] = $lockId;
2603 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
2604 }
2605
2614 public function unlockChunk(int $chunkX, int $chunkZ, ?ChunkLockId $lockId) : bool{
2615 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2616 if(isset($this->chunkLock[$chunkHash]) && ($lockId === null || $this->chunkLock[$chunkHash] === $lockId)){
2617 unset($this->chunkLock[$chunkHash]);
2618 $this->markTickingChunkForRecheck($chunkX, $chunkZ);
2619 return true;
2620 }
2621 return false;
2622 }
2623
2629 public function isChunkLocked(int $chunkX, int $chunkZ) : bool{
2630 return isset($this->chunkLock[World::chunkHash($chunkX, $chunkZ)]);
2631 }
2632
2633 public function setChunk(int $chunkX, int $chunkZ, Chunk $chunk) : void{
2634 $chunkHash = World::chunkHash($chunkX, $chunkZ);
2635 $oldChunk = $this->loadChunk($chunkX, $chunkZ);
2636 if($oldChunk !== null && $oldChunk !== $chunk){
2637 $deletedTiles = 0;
2638 $transferredTiles = 0;
2639 foreach($oldChunk->getTiles() as $oldTile){
2640 $tilePosition = $oldTile->getPosition();
2641 $localX = $tilePosition->getFloorX() & Chunk::COORD_MASK;
2642 $localY = $tilePosition->getFloorY();
2643 $localZ = $tilePosition->getFloorZ() & Chunk::COORD_MASK;
2644
2645 $newBlock = $this->blockStateRegistry->fromStateId($chunk->getBlockStateId($localX, $localY, $localZ));
2646 $expectedTileClass = $newBlock->getIdInfo()->getTileClass();
2647 if(
2648 $expectedTileClass === null || //new block doesn't expect a tile
2649 !($oldTile instanceof $expectedTileClass) || //new block expects a different tile
2650 (($newTile = $chunk->getTile($localX, $localY, $localZ)) !== null && $newTile !== $oldTile) //new chunk already has a different tile
2651 ){
2652 $oldTile->close();
2653 $deletedTiles++;
2654 }else{
2655 $transferredTiles++;
2656 $chunk->addTile($oldTile);
2657 $oldChunk->removeTile($oldTile);
2658 }
2659 }
2660 if($deletedTiles > 0 || $transferredTiles > 0){
2661 $this->logger->debug("Replacement of chunk $chunkX $chunkZ caused deletion of $deletedTiles obsolete/conflicted tiles, and transfer of $transferredTiles");
2662 }
2663 }
2664
2665 $this->chunks[$chunkHash] = $chunk;
2666
2667 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
2668 unset($this->blockCache[$chunkHash]);
2669 unset($this->blockCollisionBoxCache[$chunkHash]);
2670 unset($this->changedBlocks[$chunkHash]);
2671 $chunk->setTerrainDirty();
2672 $this->markTickingChunkForRecheck($chunkX, $chunkZ); //this replacement chunk may not meet the conditions for ticking
2673
2674 if(!$this->isChunkInUse($chunkX, $chunkZ)){
2675 $this->unloadChunkRequest($chunkX, $chunkZ);
2676 }
2677
2678 if($oldChunk === null){
2679 if(ChunkLoadEvent::hasHandlers()){
2680 (new ChunkLoadEvent($this, $chunkX, $chunkZ, $chunk, true))->call();
2681 }
2682
2683 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2684 $listener->onChunkLoaded($chunkX, $chunkZ, $chunk);
2685 }
2686 }else{
2687 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2688 $listener->onChunkChanged($chunkX, $chunkZ, $chunk);
2689 }
2690 }
2691
2692 for($cX = -1; $cX <= 1; ++$cX){
2693 for($cZ = -1; $cZ <= 1; ++$cZ){
2694 foreach($this->getChunkEntities($chunkX + $cX, $chunkZ + $cZ) as $entity){
2695 $entity->onNearbyBlockChange();
2696 }
2697 }
2698 }
2699 }
2700
2707 public function getHighestBlockAt(int $x, int $z) : ?int{
2708 if(($chunk = $this->loadChunk($x >> Chunk::COORD_BIT_SIZE, $z >> Chunk::COORD_BIT_SIZE)) !== null){
2709 return $chunk->getHighestBlockAt($x & Chunk::COORD_MASK, $z & Chunk::COORD_MASK);
2710 }
2711 throw new WorldException("Cannot get highest block in an ungenerated chunk");
2712 }
2713
2717 public function isInLoadedTerrain(Vector3 $pos) : bool{
2718 return $this->isChunkLoaded($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
2719 }
2720
2721 public function isChunkLoaded(int $x, int $z) : bool{
2722 return isset($this->chunks[World::chunkHash($x, $z)]);
2723 }
2724
2725 public function isChunkGenerated(int $x, int $z) : bool{
2726 return $this->loadChunk($x, $z) !== null;
2727 }
2728
2729 public function isChunkPopulated(int $x, int $z) : bool{
2730 $chunk = $this->loadChunk($x, $z);
2731 return $chunk !== null && $chunk->isPopulated();
2732 }
2733
2737 public function getSpawnLocation() : Position{
2738 return Position::fromObject($this->provider->getWorldData()->getSpawn(), $this);
2739 }
2740
2744 public function setSpawnLocation(Vector3 $pos) : void{
2745 $previousSpawn = $this->getSpawnLocation();
2746 $this->provider->getWorldData()->setSpawn($pos);
2747 (new SpawnChangeEvent($this, $previousSpawn))->call();
2748
2749 $location = Position::fromObject($pos, $this);
2750 foreach($this->players as $player){
2751 $player->getNetworkSession()->syncWorldSpawnPoint($location);
2752 }
2753 }
2754
2758 public function addEntity(Entity $entity) : void{
2759 if($entity->isClosed()){
2760 throw new \InvalidArgumentException("Attempted to add a garbage closed Entity to world");
2761 }
2762 if($entity->getWorld() !== $this){
2763 throw new \InvalidArgumentException("Invalid Entity world");
2764 }
2765 if(array_key_exists($entity->getId(), $this->entities)){
2766 if($this->entities[$entity->getId()] === $entity){
2767 throw new \InvalidArgumentException("Entity " . $entity->getId() . " has already been added to this world");
2768 }else{
2769 throw new AssumptionFailedError("Found two different entities sharing entity ID " . $entity->getId());
2770 }
2771 }
2772 $pos = $entity->getPosition()->asVector3();
2773 $this->entitiesByChunk[World::chunkHash($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE)][$entity->getId()] = $entity;
2774 $this->entityLastKnownPositions[$entity->getId()] = $pos;
2775
2776 if($entity instanceof Player){
2777 $this->players[$entity->getId()] = $entity;
2778 }
2779 $this->entities[$entity->getId()] = $entity;
2780 }
2781
2787 public function removeEntity(Entity $entity) : void{
2788 if($entity->getWorld() !== $this){
2789 throw new \InvalidArgumentException("Invalid Entity world");
2790 }
2791 if(!array_key_exists($entity->getId(), $this->entities)){
2792 throw new \InvalidArgumentException("Entity is not tracked by this world (possibly already removed?)");
2793 }
2794 $pos = $this->entityLastKnownPositions[$entity->getId()];
2795 $chunkHash = World::chunkHash($pos->getFloorX() >> Chunk::COORD_BIT_SIZE, $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE);
2796 if(isset($this->entitiesByChunk[$chunkHash][$entity->getId()])){
2797 if(count($this->entitiesByChunk[$chunkHash]) === 1){
2798 unset($this->entitiesByChunk[$chunkHash]);
2799 }else{
2800 unset($this->entitiesByChunk[$chunkHash][$entity->getId()]);
2801 }
2802 }
2803 unset($this->entityLastKnownPositions[$entity->getId()]);
2804
2805 if($entity instanceof Player){
2806 unset($this->players[$entity->getId()]);
2807 $this->checkSleep();
2808 }
2809
2810 unset($this->entities[$entity->getId()]);
2811 unset($this->updateEntities[$entity->getId()]);
2812 }
2813
2817 public function onEntityMoved(Entity $entity) : void{
2818 if(!array_key_exists($entity->getId(), $this->entityLastKnownPositions)){
2819 //this can happen if the entity was teleported before addEntity() was called
2820 return;
2821 }
2822 $oldPosition = $this->entityLastKnownPositions[$entity->getId()];
2823 $newPosition = $entity->getPosition();
2824
2825 $oldChunkX = $oldPosition->getFloorX() >> Chunk::COORD_BIT_SIZE;
2826 $oldChunkZ = $oldPosition->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2827 $newChunkX = $newPosition->getFloorX() >> Chunk::COORD_BIT_SIZE;
2828 $newChunkZ = $newPosition->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2829
2830 if($oldChunkX !== $newChunkX || $oldChunkZ !== $newChunkZ){
2831 $oldChunkHash = World::chunkHash($oldChunkX, $oldChunkZ);
2832 if(isset($this->entitiesByChunk[$oldChunkHash][$entity->getId()])){
2833 if(count($this->entitiesByChunk[$oldChunkHash]) === 1){
2834 unset($this->entitiesByChunk[$oldChunkHash]);
2835 }else{
2836 unset($this->entitiesByChunk[$oldChunkHash][$entity->getId()]);
2837 }
2838 }
2839
2840 $newViewers = $this->getViewersForPosition($newPosition);
2841 foreach($entity->getViewers() as $player){
2842 if(!isset($newViewers[spl_object_id($player)])){
2843 $entity->despawnFrom($player);
2844 }else{
2845 unset($newViewers[spl_object_id($player)]);
2846 }
2847 }
2848 foreach($newViewers as $player){
2849 $entity->spawnTo($player);
2850 }
2851
2852 $newChunkHash = World::chunkHash($newChunkX, $newChunkZ);
2853 $this->entitiesByChunk[$newChunkHash][$entity->getId()] = $entity;
2854 }
2855 $this->entityLastKnownPositions[$entity->getId()] = $newPosition->asVector3();
2856 }
2857
2862 public function addTile(Tile $tile) : void{
2863 if($tile->isClosed()){
2864 throw new \InvalidArgumentException("Attempted to add a garbage closed Tile to world");
2865 }
2866 $pos = $tile->getPosition();
2867 if(!$pos->isValid() || $pos->getWorld() !== $this){
2868 throw new \InvalidArgumentException("Invalid Tile world");
2869 }
2870 if(!$this->isInWorld($pos->getFloorX(), $pos->getFloorY(), $pos->getFloorZ())){
2871 throw new \InvalidArgumentException("Tile position is outside the world bounds");
2872 }
2873
2874 $chunkX = $pos->getFloorX() >> Chunk::COORD_BIT_SIZE;
2875 $chunkZ = $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2876
2877 if(isset($this->chunks[$hash = World::chunkHash($chunkX, $chunkZ)])){
2878 $this->chunks[$hash]->addTile($tile);
2879 }else{
2880 throw new \InvalidArgumentException("Attempted to create tile " . get_class($tile) . " in unloaded chunk $chunkX $chunkZ");
2881 }
2882
2883 //delegate tile ticking to the corresponding block
2884 $this->scheduleDelayedBlockUpdate($pos->asVector3(), 1);
2885 }
2886
2891 public function removeTile(Tile $tile) : void{
2892 $pos = $tile->getPosition();
2893 if(!$pos->isValid() || $pos->getWorld() !== $this){
2894 throw new \InvalidArgumentException("Invalid Tile world");
2895 }
2896
2897 $chunkX = $pos->getFloorX() >> Chunk::COORD_BIT_SIZE;
2898 $chunkZ = $pos->getFloorZ() >> Chunk::COORD_BIT_SIZE;
2899
2900 if(isset($this->chunks[$hash = World::chunkHash($chunkX, $chunkZ)])){
2901 $this->chunks[$hash]->removeTile($tile);
2902 }
2903 foreach($this->getChunkListeners($chunkX, $chunkZ) as $listener){
2904 $listener->onBlockChanged($pos->asVector3());
2905 }
2906 }
2907
2908 public function isChunkInUse(int $x, int $z) : bool{
2909 return isset($this->chunkLoaders[$index = World::chunkHash($x, $z)]) && count($this->chunkLoaders[$index]) > 0;
2910 }
2911
2918 public function loadChunk(int $x, int $z) : ?Chunk{
2919 if(isset($this->chunks[$chunkHash = World::chunkHash($x, $z)])){
2920 return $this->chunks[$chunkHash];
2921 }
2922
2923 $this->timings->syncChunkLoad->startTiming();
2924
2925 $this->cancelUnloadChunkRequest($x, $z);
2926
2927 $this->timings->syncChunkLoadData->startTiming();
2928
2929 $loadedChunkData = null;
2930
2931 try{
2932 $loadedChunkData = $this->provider->loadChunk($x, $z);
2933 }catch(CorruptedChunkException $e){
2934 $this->logger->critical("Failed to load chunk x=$x z=$z: " . $e->getMessage());
2935 }
2936
2937 $this->timings->syncChunkLoadData->stopTiming();
2938
2939 if($loadedChunkData === null){
2940 $this->timings->syncChunkLoad->stopTiming();
2941 return null;
2942 }
2943
2944 $chunkData = $loadedChunkData->getData();
2945 $chunk = new Chunk($chunkData->getSubChunks(), $chunkData->isPopulated());
2946 if(!$loadedChunkData->isUpgraded()){
2947 $chunk->clearTerrainDirtyFlags();
2948 }else{
2949 $this->logger->debug("Chunk $x $z has been upgraded, will be saved at the next autosave opportunity");
2950 }
2951 $this->chunks[$chunkHash] = $chunk;
2952
2953 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
2954 unset($this->blockCache[$chunkHash]);
2955 unset($this->blockCollisionBoxCache[$chunkHash]);
2956
2957 $this->initChunk($x, $z, $chunkData);
2958
2959 if(ChunkLoadEvent::hasHandlers()){
2960 (new ChunkLoadEvent($this, $x, $z, $this->chunks[$chunkHash], false))->call();
2961 }
2962
2963 if(!$this->isChunkInUse($x, $z)){
2964 $this->logger->debug("Newly loaded chunk $x $z has no loaders registered, will be unloaded at next available opportunity");
2965 $this->unloadChunkRequest($x, $z);
2966 }
2967 foreach($this->getChunkListeners($x, $z) as $listener){
2968 $listener->onChunkLoaded($x, $z, $this->chunks[$chunkHash]);
2969 }
2970 $this->markTickingChunkForRecheck($x, $z); //tickers may have been registered before the chunk was loaded
2971
2972 $this->timings->syncChunkLoad->stopTiming();
2973
2974 return $this->chunks[$chunkHash];
2975 }
2976
2977 private function initChunk(int $chunkX, int $chunkZ, ChunkData $chunkData) : void{
2978 $logger = new \PrefixedLogger($this->logger, "Loading chunk $chunkX $chunkZ");
2979
2980 if(count($chunkData->getEntityNBT()) !== 0){
2981 $this->timings->syncChunkLoadEntities->startTiming();
2982 $entityFactory = EntityFactory::getInstance();
2983 foreach($chunkData->getEntityNBT() as $k => $nbt){
2984 try{
2985 $entity = $entityFactory->createFromData($this, $nbt);
2986 }catch(SavedDataLoadingException $e){
2987 $logger->error("Bad entity data at list position $k: " . $e->getMessage());
2988 $logger->logException($e);
2989 continue;
2990 }
2991 if($entity === null){
2992 $saveIdTag = $nbt->getTag("identifier") ?? $nbt->getTag("id");
2993 $saveId = "<unknown>";
2994 if($saveIdTag instanceof StringTag){
2995 $saveId = $saveIdTag->getValue();
2996 }elseif($saveIdTag instanceof IntTag){ //legacy MCPE format
2997 $saveId = "legacy(" . $saveIdTag->getValue() . ")";
2998 }
2999 $logger->warning("Deleted unknown entity type $saveId");
3000 }
3001 //TODO: we can't prevent entities getting added to unloaded chunks if they were saved in the wrong place
3002 //here, because entities currently add themselves to the world
3003 }
3004
3005 $this->timings->syncChunkLoadEntities->stopTiming();
3006 }
3007
3008 if(count($chunkData->getTileNBT()) !== 0){
3009 $this->timings->syncChunkLoadTileEntities->startTiming();
3010 $tileFactory = TileFactory::getInstance();
3011 foreach($chunkData->getTileNBT() as $k => $nbt){
3012 try{
3013 $tile = $tileFactory->createFromData($this, $nbt);
3014 }catch(SavedDataLoadingException $e){
3015 $logger->error("Bad tile entity data at list position $k: " . $e->getMessage());
3016 $logger->logException($e);
3017 continue;
3018 }
3019 if($tile === null){
3020 $logger->warning("Deleted unknown tile entity type " . $nbt->getString("id", "<unknown>"));
3021 continue;
3022 }
3023
3024 $tilePosition = $tile->getPosition();
3025 if(!$this->isChunkLoaded($tilePosition->getFloorX() >> Chunk::COORD_BIT_SIZE, $tilePosition->getFloorZ() >> Chunk::COORD_BIT_SIZE)){
3026 $logger->error("Found tile saved on wrong chunk - unable to fix due to correct chunk not loaded");
3027 }elseif(!$this->isInWorld($tilePosition->getFloorX(), $tilePosition->getFloorY(), $tilePosition->getFloorZ())){
3028 $logger->error("Cannot add tile with position outside the world bounds: x=$tilePosition->x,y=$tilePosition->y,z=$tilePosition->z");
3029 }elseif($this->getTile($tilePosition) !== null){
3030 $logger->error("Cannot add tile at x=$tilePosition->x,y=$tilePosition->y,z=$tilePosition->z: Another tile is already at that position");
3031 }else{
3032 $this->addTile($tile);
3033 }
3034 }
3035
3036 $this->timings->syncChunkLoadTileEntities->stopTiming();
3037 }
3038 }
3039
3040 private function queueUnloadChunk(int $x, int $z) : void{
3041 $this->unloadQueue[World::chunkHash($x, $z)] = microtime(true);
3042 }
3043
3044 public function unloadChunkRequest(int $x, int $z, bool $safe = true) : bool{
3045 if(($safe && $this->isChunkInUse($x, $z)) || $this->isSpawnChunk($x, $z)){
3046 return false;
3047 }
3048
3049 $this->queueUnloadChunk($x, $z);
3050
3051 return true;
3052 }
3053
3054 public function cancelUnloadChunkRequest(int $x, int $z) : void{
3055 unset($this->unloadQueue[World::chunkHash($x, $z)]);
3056 }
3057
3058 public function unloadChunk(int $x, int $z, bool $safe = true, bool $trySave = true) : bool{
3059 if($safe && $this->isChunkInUse($x, $z)){
3060 return false;
3061 }
3062
3063 if(!$this->isChunkLoaded($x, $z)){
3064 return true;
3065 }
3066
3067 $this->timings->doChunkUnload->startTiming();
3068
3069 $chunkHash = World::chunkHash($x, $z);
3070
3071 $chunk = $this->chunks[$chunkHash] ?? null;
3072
3073 if($chunk !== null){
3074 if(ChunkUnloadEvent::hasHandlers()){
3075 $ev = new ChunkUnloadEvent($this, $x, $z, $chunk);
3076 $ev->call();
3077 if($ev->isCancelled()){
3078 $this->timings->doChunkUnload->stopTiming();
3079
3080 return false;
3081 }
3082 }
3083
3084 if($trySave && $this->getAutoSave()){
3085 $this->timings->syncChunkSave->startTiming();
3086 try{
3087 $this->provider->saveChunk($x, $z, new ChunkData(
3088 $chunk->getSubChunks(),
3089 $chunk->isPopulated(),
3090 array_map(fn(Entity $e) => $e->saveNBT(), array_values(array_filter($this->getChunkEntities($x, $z), fn(Entity $e) => $e->canSaveWithChunk()))),
3091 array_map(fn(Tile $t) => $t->saveNBT(), array_values($chunk->getTiles())),
3092 ), $chunk->getTerrainDirtyFlags());
3093 }finally{
3094 $this->timings->syncChunkSave->stopTiming();
3095 }
3096 }
3097
3098 foreach($this->getChunkListeners($x, $z) as $listener){
3099 $listener->onChunkUnloaded($x, $z, $chunk);
3100 }
3101
3102 foreach($this->getChunkEntities($x, $z) as $entity){
3103 if($entity instanceof Player){
3104 continue;
3105 }
3106 $entity->close();
3107 }
3108
3109 $chunk->onUnload();
3110 }
3111
3112 unset($this->chunks[$chunkHash]);
3113 $this->blockCacheSize -= count($this->blockCache[$chunkHash] ?? []);
3114 unset($this->blockCache[$chunkHash]);
3115 unset($this->blockCollisionBoxCache[$chunkHash]);
3116 unset($this->changedBlocks[$chunkHash]);
3117 unset($this->registeredTickingChunks[$chunkHash]);
3118 $this->markTickingChunkForRecheck($x, $z);
3119
3120 if(array_key_exists($chunkHash, $this->chunkPopulationRequestMap)){
3121 $this->logger->debug("Rejecting population promise for chunk $x $z");
3122 $this->chunkPopulationRequestMap[$chunkHash]->reject();
3123 unset($this->chunkPopulationRequestMap[$chunkHash]);
3124 if(isset($this->activeChunkPopulationTasks[$chunkHash])){
3125 $this->logger->debug("Marking population task for chunk $x $z as orphaned");
3126 $this->activeChunkPopulationTasks[$chunkHash] = false;
3127 }
3128 }
3129
3130 $this->timings->doChunkUnload->stopTiming();
3131
3132 return true;
3133 }
3134
3138 public function isSpawnChunk(int $X, int $Z) : bool{
3139 $spawn = $this->getSpawnLocation();
3140 $spawnX = $spawn->x >> Chunk::COORD_BIT_SIZE;
3141 $spawnZ = $spawn->z >> Chunk::COORD_BIT_SIZE;
3142
3143 return abs($X - $spawnX) <= 1 && abs($Z - $spawnZ) <= 1;
3144 }
3145
3153 public function requestSafeSpawn(?Vector3 $spawn = null) : Promise{
3155 $resolver = new PromiseResolver();
3156 $spawn ??= $this->getSpawnLocation();
3157 /*
3158 * TODO: this relies on the assumption that getSafeSpawn() will only alter the Y coordinate of the provided
3159 * position, which is currently OK, but might be a problem in the future.
3160 */
3161 $this->requestChunkPopulation($spawn->getFloorX() >> Chunk::COORD_BIT_SIZE, $spawn->getFloorZ() >> Chunk::COORD_BIT_SIZE, null)->onCompletion(
3162 function() use ($spawn, $resolver) : void{
3163 $spawn = $this->getSafeSpawn($spawn);
3164 $resolver->resolve($spawn);
3165 },
3166 function() use ($resolver) : void{
3167 $resolver->reject();
3168 }
3169 );
3170
3171 return $resolver->getPromise();
3172 }
3173
3180 public function getSafeSpawn(?Vector3 $spawn = null) : Position{
3181 if(!($spawn instanceof Vector3) || $spawn->y <= $this->minY){
3182 $spawn = $this->getSpawnLocation();
3183 }
3184
3185 $max = $this->maxY;
3186 $v = $spawn->floor();
3187 $chunk = $this->getOrLoadChunkAtPosition($v);
3188 if($chunk === null){
3189 throw new WorldException("Cannot find a safe spawn point in non-generated terrain");
3190 }
3191 $x = (int) $v->x;
3192 $z = (int) $v->z;
3193 $y = (int) min($max - 2, $v->y);
3194 $wasAir = $this->getBlockAt($x, $y - 1, $z)->getTypeId() === BlockTypeIds::AIR; //TODO: bad hack, clean up
3195 for(; $y > $this->minY; --$y){
3196 if($this->getBlockAt($x, $y, $z)->isFullCube()){
3197 if($wasAir){
3198 $y++;
3199 }
3200 break;
3201 }else{
3202 $wasAir = true;
3203 }
3204 }
3205
3206 for(; $y >= $this->minY && $y < $max; ++$y){
3207 if(!$this->getBlockAt($x, $y + 1, $z)->isFullCube()){
3208 if(!$this->getBlockAt($x, $y, $z)->isFullCube()){
3209 return new Position($spawn->x, $y === (int) $spawn->y ? $spawn->y : $y, $spawn->z, $this);
3210 }
3211 }else{
3212 ++$y;
3213 }
3214 }
3215
3216 return new Position($spawn->x, $y, $spawn->z, $this);
3217 }
3218
3222 public function getTime() : int{
3223 return $this->time;
3224 }
3225
3229 public function getTimeOfDay() : int{
3230 return $this->time % self::TIME_FULL;
3231 }
3232
3237 public function getDisplayName() : string{
3238 return $this->displayName;
3239 }
3240
3244 public function setDisplayName(string $name) : void{
3245 (new WorldDisplayNameChangeEvent($this, $this->displayName, $name))->call();
3246
3247 $this->displayName = $name;
3248 $this->provider->getWorldData()->setName($name);
3249 }
3250
3254 public function getFolderName() : string{
3255 return $this->folderName;
3256 }
3257
3261 public function setTime(int $time) : void{
3262 $this->time = $time;
3263 $this->sendTime();
3264 }
3265
3269 public function stopTime() : void{
3270 $this->stopTime = true;
3271 $this->sendTime();
3272 }
3273
3277 public function startTime() : void{
3278 $this->stopTime = false;
3279 $this->sendTime();
3280 }
3281
3285 public function getSeed() : int{
3286 return $this->provider->getWorldData()->getSeed();
3287 }
3288
3289 public function getMinY() : int{
3290 return $this->minY;
3291 }
3292
3293 public function getMaxY() : int{
3294 return $this->maxY;
3295 }
3296
3297 public function getDifficulty() : int{
3298 return $this->provider->getWorldData()->getDifficulty();
3299 }
3300
3301 public function setDifficulty(int $difficulty) : void{
3302 if($difficulty < 0 || $difficulty > 3){
3303 throw new \InvalidArgumentException("Invalid difficulty level $difficulty");
3304 }
3305 (new WorldDifficultyChangeEvent($this, $this->getDifficulty(), $difficulty))->call();
3306 $this->provider->getWorldData()->setDifficulty($difficulty);
3307
3308 foreach($this->players as $player){
3309 $player->getNetworkSession()->syncWorldDifficulty($this->getDifficulty());
3310 }
3311 }
3312
3313 private function addChunkHashToPopulationRequestQueue(int $chunkHash) : void{
3314 if(!isset($this->chunkPopulationRequestQueueIndex[$chunkHash])){
3315 $this->chunkPopulationRequestQueue->enqueue($chunkHash);
3316 $this->chunkPopulationRequestQueueIndex[$chunkHash] = true;
3317 }
3318 }
3319
3323 private function enqueuePopulationRequest(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader) : Promise{
3324 $chunkHash = World::chunkHash($chunkX, $chunkZ);
3325 $this->addChunkHashToPopulationRequestQueue($chunkHash);
3327 $resolver = $this->chunkPopulationRequestMap[$chunkHash] = new PromiseResolver();
3328 if($associatedChunkLoader === null){
3329 $temporaryLoader = new class implements ChunkLoader{};
3330 $this->registerChunkLoader($temporaryLoader, $chunkX, $chunkZ);
3331 $resolver->getPromise()->onCompletion(
3332 fn() => $this->unregisterChunkLoader($temporaryLoader, $chunkX, $chunkZ),
3333 static function() : void{}
3334 );
3335 }
3336 return $resolver->getPromise();
3337 }
3338
3339 private function drainPopulationRequestQueue() : void{
3340 $failed = [];
3341 while(count($this->activeChunkPopulationTasks) < $this->maxConcurrentChunkPopulationTasks && !$this->chunkPopulationRequestQueue->isEmpty()){
3342 $nextChunkHash = $this->chunkPopulationRequestQueue->dequeue();
3343 unset($this->chunkPopulationRequestQueueIndex[$nextChunkHash]);
3344 World::getXZ($nextChunkHash, $nextChunkX, $nextChunkZ);
3345 if(isset($this->chunkPopulationRequestMap[$nextChunkHash])){
3346 assert(!($this->activeChunkPopulationTasks[$nextChunkHash] ?? false), "Population for chunk $nextChunkX $nextChunkZ already running");
3347 if(
3348 !$this->orderChunkPopulation($nextChunkX, $nextChunkZ, null)->isResolved() &&
3349 !isset($this->activeChunkPopulationTasks[$nextChunkHash])
3350 ){
3351 $failed[] = $nextChunkHash;
3352 }
3353 }
3354 }
3355
3356 //these requests failed even though they weren't rate limited; we can't directly re-add them to the back of the
3357 //queue because it would result in an infinite loop
3358 foreach($failed as $hash){
3359 $this->addChunkHashToPopulationRequestQueue($hash);
3360 }
3361 }
3362
3368 private function checkChunkPopulationPreconditions(int $chunkX, int $chunkZ) : array{
3369 $chunkHash = World::chunkHash($chunkX, $chunkZ);
3370 $resolver = $this->chunkPopulationRequestMap[$chunkHash] ?? null;
3371 if($resolver !== null && isset($this->activeChunkPopulationTasks[$chunkHash])){
3372 //generation is already running
3373 return [$resolver, false];
3374 }
3375
3376 $temporaryChunkLoader = new class implements ChunkLoader{};
3377 $this->registerChunkLoader($temporaryChunkLoader, $chunkX, $chunkZ);
3378 $chunk = $this->loadChunk($chunkX, $chunkZ);
3379 $this->unregisterChunkLoader($temporaryChunkLoader, $chunkX, $chunkZ);
3380 if($chunk !== null && $chunk->isPopulated()){
3381 //chunk is already populated; return a pre-resolved promise that will directly fire callbacks assigned
3382 $resolver ??= new PromiseResolver();
3383 unset($this->chunkPopulationRequestMap[$chunkHash]);
3384 $resolver->resolve($chunk);
3385 return [$resolver, false];
3386 }
3387 return [$resolver, true];
3388 }
3389
3401 public function requestChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader) : Promise{
3402 [$resolver, $proceedWithPopulation] = $this->checkChunkPopulationPreconditions($chunkX, $chunkZ);
3403 if(!$proceedWithPopulation){
3404 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3405 }
3406
3407 if(count($this->activeChunkPopulationTasks) >= $this->maxConcurrentChunkPopulationTasks){
3408 //too many chunks are already generating; delay resolution of the request until later
3409 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3410 }
3411 return $this->internalOrderChunkPopulation($chunkX, $chunkZ, $associatedChunkLoader, $resolver);
3412 }
3413
3424 public function orderChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader) : Promise{
3425 [$resolver, $proceedWithPopulation] = $this->checkChunkPopulationPreconditions($chunkX, $chunkZ);
3426 if(!$proceedWithPopulation){
3427 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3428 }
3429
3430 return $this->internalOrderChunkPopulation($chunkX, $chunkZ, $associatedChunkLoader, $resolver);
3431 }
3432
3437 private function internalOrderChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader, ?PromiseResolver $resolver) : Promise{
3438 $chunkHash = World::chunkHash($chunkX, $chunkZ);
3439
3440 $timings = $this->timings->chunkPopulationOrder;
3441 $timings->startTiming();
3442
3443 try{
3444 for($xx = -1; $xx <= 1; ++$xx){
3445 for($zz = -1; $zz <= 1; ++$zz){
3446 if($this->isChunkLocked($chunkX + $xx, $chunkZ + $zz)){
3447 //chunk is already in use by another generation request; queue the request for later
3448 return $resolver?->getPromise() ?? $this->enqueuePopulationRequest($chunkX, $chunkZ, $associatedChunkLoader);
3449 }
3450 }
3451 }
3452
3453 $this->activeChunkPopulationTasks[$chunkHash] = true;
3454 if($resolver === null){
3455 $resolver = new PromiseResolver();
3456 $this->chunkPopulationRequestMap[$chunkHash] = $resolver;
3457 }
3458
3459 $chunkPopulationLockId = new ChunkLockId();
3460
3461 $temporaryChunkLoader = new class implements ChunkLoader{
3462 };
3463 for($xx = -1; $xx <= 1; ++$xx){
3464 for($zz = -1; $zz <= 1; ++$zz){
3465 $this->lockChunk($chunkX + $xx, $chunkZ + $zz, $chunkPopulationLockId);
3466 $this->registerChunkLoader($temporaryChunkLoader, $chunkX + $xx, $chunkZ + $zz);
3467 }
3468 }
3469
3470 $centerChunk = $this->loadChunk($chunkX, $chunkZ);
3471 $adjacentChunks = $this->getAdjacentChunks($chunkX, $chunkZ);
3472 $task = new PopulationTask(
3473 $this->worldId,
3474 $chunkX,
3475 $chunkZ,
3476 $centerChunk,
3477 $adjacentChunks,
3478 function(Chunk $centerChunk, array $adjacentChunks) use ($chunkPopulationLockId, $chunkX, $chunkZ, $temporaryChunkLoader) : void{
3479 if(!$this->isLoaded()){
3480 return;
3481 }
3482
3483 $this->generateChunkCallback($chunkPopulationLockId, $chunkX, $chunkZ, $centerChunk, $adjacentChunks, $temporaryChunkLoader);
3484 }
3485 );
3486 $workerId = $this->workerPool->selectWorker();
3487 if(!isset($this->workerPool->getRunningWorkers()[$workerId]) && isset($this->generatorRegisteredWorkers[$workerId])){
3488 $this->logger->debug("Selected worker $workerId previously had generator registered, but is now offline");
3489 unset($this->generatorRegisteredWorkers[$workerId]);
3490 }
3491 if(!isset($this->generatorRegisteredWorkers[$workerId])){
3492 $this->registerGeneratorToWorker($workerId);
3493 }
3494 $this->workerPool->submitTaskToWorker($task, $workerId);
3495
3496 return $resolver->getPromise();
3497 }finally{
3498 $timings->stopTiming();
3499 }
3500 }
3501
3506 private function generateChunkCallback(ChunkLockId $chunkLockId, int $x, int $z, Chunk $chunk, array $adjacentChunks, ChunkLoader $temporaryChunkLoader) : void{
3507 $timings = $this->timings->chunkPopulationCompletion;
3508 $timings->startTiming();
3509
3510 $dirtyChunks = 0;
3511 for($xx = -1; $xx <= 1; ++$xx){
3512 for($zz = -1; $zz <= 1; ++$zz){
3513 $this->unregisterChunkLoader($temporaryChunkLoader, $x + $xx, $z + $zz);
3514 if(!$this->unlockChunk($x + $xx, $z + $zz, $chunkLockId)){
3515 $dirtyChunks++;
3516 }
3517 }
3518 }
3519
3520 $index = World::chunkHash($x, $z);
3521 if(!isset($this->activeChunkPopulationTasks[$index])){
3522 throw new AssumptionFailedError("This should always be set, regardless of whether the task was orphaned or not");
3523 }
3524 if(!$this->activeChunkPopulationTasks[$index]){
3525 $this->logger->debug("Discarding orphaned population result for chunk x=$x,z=$z");
3526 unset($this->activeChunkPopulationTasks[$index]);
3527 }else{
3528 if($dirtyChunks === 0){
3529 $oldChunk = $this->loadChunk($x, $z);
3530 $this->setChunk($x, $z, $chunk);
3531
3532 foreach($adjacentChunks as $relativeChunkHash => $adjacentChunk){
3533 World::getXZ($relativeChunkHash, $relativeX, $relativeZ);
3534 if($relativeX < -1 || $relativeX > 1 || $relativeZ < -1 || $relativeZ > 1){
3535 throw new AssumptionFailedError("Adjacent chunks should be in range -1 ... +1 coordinates");
3536 }
3537 $this->setChunk($x + $relativeX, $z + $relativeZ, $adjacentChunk);
3538 }
3539
3540 if(($oldChunk === null || !$oldChunk->isPopulated()) && $chunk->isPopulated()){
3541 if(ChunkPopulateEvent::hasHandlers()){
3542 (new ChunkPopulateEvent($this, $x, $z, $chunk))->call();
3543 }
3544
3545 foreach($this->getChunkListeners($x, $z) as $listener){
3546 $listener->onChunkPopulated($x, $z, $chunk);
3547 }
3548 }
3549 }else{
3550 $this->logger->debug("Discarding population result for chunk x=$x,z=$z - terrain was modified on the main thread before async population completed");
3551 }
3552
3553 //This needs to be in this specific spot because user code might call back to orderChunkPopulation().
3554 //If it does, and finds the promise, and doesn't find an active task associated with it, it will schedule
3555 //another PopulationTask. We don't want that because we're here processing the results.
3556 //We can't remove the promise from the array before setting the chunks in the world because that would lead
3557 //to the same problem. Therefore, it's necessary that this code be split into two if/else, with this in the
3558 //middle.
3559 unset($this->activeChunkPopulationTasks[$index]);
3560
3561 if($dirtyChunks === 0){
3562 $promise = $this->chunkPopulationRequestMap[$index] ?? null;
3563 if($promise !== null){
3564 unset($this->chunkPopulationRequestMap[$index]);
3565 $promise->resolve($chunk);
3566 }else{
3567 //Handlers of ChunkPopulateEvent, ChunkLoadEvent, or just ChunkListeners can cause this
3568 $this->logger->debug("Unable to resolve population promise for chunk x=$x,z=$z - populated chunk was forcibly unloaded while setting modified chunks");
3569 }
3570 }else{
3571 //request failed, stick it back on the queue
3572 //we didn't resolve the promise or touch it in any way, so any fake chunk loaders are still valid and
3573 //don't need to be added a second time.
3574 $this->addChunkHashToPopulationRequestQueue($index);
3575 }
3576
3577 $this->drainPopulationRequestQueue();
3578 }
3579 $timings->stopTiming();
3580 }
3581
3582 public function doChunkGarbageCollection() : void{
3583 $this->timings->doChunkGC->startTiming();
3584
3585 foreach($this->chunks as $index => $chunk){
3586 if(!isset($this->unloadQueue[$index])){
3587 World::getXZ($index, $X, $Z);
3588 if(!$this->isSpawnChunk($X, $Z)){
3589 $this->unloadChunkRequest($X, $Z, true);
3590 }
3591 }
3592 $chunk->collectGarbage();
3593 }
3594
3595 $this->provider->doGarbageCollection();
3596
3597 $this->timings->doChunkGC->stopTiming();
3598 }
3599
3600 public function unloadChunks(bool $force = false) : void{
3601 if(count($this->unloadQueue) > 0){
3602 $maxUnload = 96;
3603 $now = microtime(true);
3604 foreach($this->unloadQueue as $index => $time){
3605 World::getXZ($index, $X, $Z);
3606
3607 if(!$force){
3608 if($maxUnload <= 0){
3609 break;
3610 }elseif($time > ($now - 30)){
3611 continue;
3612 }
3613 }
3614
3615 //If the chunk can't be unloaded, it stays on the queue
3616 if($this->unloadChunk($X, $Z, true)){
3617 unset($this->unloadQueue[$index]);
3618 --$maxUnload;
3619 }
3620 }
3621 }
3622 }
3623}
despawnFrom(Player $player, bool $send=true)
Definition Entity.php:1554
getBlock(?int $clickedFace=null)
Definition Item.php:491
pop(int $count=1)
Definition Item.php:430
expandedCopy(float $x, float $y, float $z)
removeWorkerStartHook(\Closure $hook)
getChunkListeners(int $chunkX, int $chunkZ)
Definition World.php:899
removeEntity(Entity $entity)
Definition World.php:2787
notifyNeighbourBlockUpdate(Vector3 $pos)
Definition World.php:1516
getCollisionBlocks(AxisAlignedBB $bb, bool $targetFirst=false)
Definition World.php:1524
getHighestAdjacentBlockLight(int $x, int $y, int $z)
Definition World.php:1922
setDisplayName(string $name)
Definition World.php:3244
getPotentialBlockSkyLightAt(int $x, int $y, int $z)
Definition World.php:1827
removeOnUnloadCallback(\Closure $callback)
Definition World.php:676
isChunkLocked(int $chunkX, int $chunkZ)
Definition World.php:2629
setSpawnLocation(Vector3 $pos)
Definition World.php:2744
getPotentialLightAt(int $x, int $y, int $z)
Definition World.php:1809
createBlockUpdatePackets(array $blocks)
Definition World.php:1099
getSafeSpawn(?Vector3 $spawn=null)
Definition World.php:3180
registerChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ)
Definition World.php:853
getBlockAt(int $x, int $y, int $z, bool $cached=true, bool $addToCache=true)
Definition World.php:1973
getChunkEntities(int $chunkX, int $chunkZ)
Definition World.php:2552
addEntity(Entity $entity)
Definition World.php:2758
getBlockLightAt(int $x, int $y, int $z)
Definition World.php:1852
getBlock(Vector3 $pos, bool $cached=true, bool $addToCache=true)
Definition World.php:1960
static chunkHash(int $x, int $z)
Definition World.php:383
broadcastPacketToViewers(Vector3 $pos, ClientboundPacket $packet)
Definition World.php:803
getOrLoadChunkAtPosition(Vector3 $pos)
Definition World.php:2559
static chunkBlockHash(int $x, int $y, int $z)
Definition World.php:422
getHighestAdjacentPotentialBlockSkyLight(int $x, int $y, int $z)
Definition World.php:1907
getFullLight(Vector3 $pos)
Definition World.php:1766
isInWorld(int $x, int $y, int $z)
Definition World.php:1942
unlockChunk(int $chunkX, int $chunkZ, ?ChunkLockId $lockId)
Definition World.php:2614
getChunkLoaders(int $chunkX, int $chunkZ)
Definition World.php:786
getCollisionBoxes(Entity $entity, AxisAlignedBB $bb, bool $entities=true)
Definition World.php:1693
getAdjacentChunks(int $x, int $z)
Definition World.php:2569
getChunkPlayers(int $chunkX, int $chunkZ)
Definition World.php:776
getTileAt(int $x, int $y, int $z)
Definition World.php:2509
getHighestAdjacentFullLightAt(int $x, int $y, int $z)
Definition World.php:1790
setChunkTickRadius(int $radius)
Definition World.php:1218
getViewersForPosition(Vector3 $pos)
Definition World.php:796
getNearestEntity(Vector3 $pos, float $maxDistance, string $entityType=Entity::class, bool $includeDead=false)
Definition World.php:2452
__construct(private Server $server, string $name, private WritableWorldProvider $provider, private AsyncPool $workerPool)
Definition World.php:481
requestChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader)
Definition World.php:3401
addSound(Vector3 $pos, Sound $sound, ?array $players=null)
Definition World.php:704
registerTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ)
Definition World.php:1237
setBlock(Vector3 $pos, Block $block, bool $update=true)
Definition World.php:2028
getNearbyEntities(AxisAlignedBB $bb, ?Entity $entity=null)
Definition World.php:2420
static getXZ(int $hash, ?int &$x, ?int &$z)
Definition World.php:448
getBlockCollisionBoxes(AxisAlignedBB $bb)
Definition World.php:1654
getCollidingEntities(AxisAlignedBB $bb, ?Entity $entity=null)
Definition World.php:2402
isSpawnChunk(int $X, int $Z)
Definition World.php:3138
useBreakOn(Vector3 $vector, ?Item &$item=null, ?Player $player=null, bool $createParticles=false, array &$returnedItems=[])
Definition World.php:2134
getPotentialLight(Vector3 $pos)
Definition World.php:1798
addParticle(Vector3 $pos, Particle $particle, ?array $players=null)
Definition World.php:733
unregisterChunkListenerFromAll(ChunkListener $listener)
Definition World.php:886
loadChunk(int $x, int $z)
Definition World.php:2918
useItemOn(Vector3 $vector, Item &$item, int $face, ?Vector3 $clickVector=null, ?Player $player=null, bool $playSound=false, array &$returnedItems=[])
Definition World.php:2240
getHighestAdjacentPotentialLightAt(int $x, int $y, int $z)
Definition World.php:1817
setBlockAt(int $x, int $y, int $z, Block $block, bool $update=true)
Definition World.php:2040
unregisterTickingChunk(ChunkTicker $ticker, int $chunkX, int $chunkZ)
Definition World.php:1247
getRealBlockSkyLightAt(int $x, int $y, int $z)
Definition World.php:1842
static blockHash(int $x, int $y, int $z)
Definition World.php:402
getTile(Vector3 $pos)
Definition World.php:2502
getFullLightAt(int $x, int $y, int $z)
Definition World.php:1777
getHighestAdjacentRealBlockSkyLight(int $x, int $y, int $z)
Definition World.php:1915
orderChunkPopulation(int $chunkX, int $chunkZ, ?ChunkLoader $associatedChunkLoader)
Definition World.php:3424
dropExperience(Vector3 $pos, int $amount)
Definition World.php:2111
isInLoadedTerrain(Vector3 $pos)
Definition World.php:2717
lockChunk(int $chunkX, int $chunkZ, ChunkLockId $lockId)
Definition World.php:2597
getHighestBlockAt(int $x, int $z)
Definition World.php:2707
scheduleDelayedBlockUpdate(Vector3 $pos, int $delay)
Definition World.php:1475
static getBlockXYZ(int $hash, ?int &$x, ?int &$y, ?int &$z)
Definition World.php:432
addOnUnloadCallback(\Closure $callback)
Definition World.php:671
requestSafeSpawn(?Vector3 $spawn=null)
Definition World.php:3153
unregisterChunkListener(ChunkListener $listener, int $chunkX, int $chunkZ)
Definition World.php:870
getTile(int $x, int $y, int $z)
Definition Chunk.php:229
getHighestBlockAt(int $x, int $z)
Definition Chunk.php:121
getBlockStateId(int $x, int $y, int $z)
Definition Chunk.php:101