From 2b90f6499e8d0891b276e0266787f40a292dff90 Mon Sep 17 00:00:00 2001 From: Sunch <120295462+Sunch233@users.noreply.github.com> Date: Mon, 28 Apr 2025 19:49:29 +0800 Subject: [PATCH] more canonical codestyle --- .php-cs-fixer.php | 3 - src/API/AchievementAPI.php | 2 +- src/API/BlockAPI.php | 8 +- src/API/ConsoleAPI.php | 10 +- src/API/EntityAPI.php | 4 +- src/API/PluginAPI.php | 10 +- src/Player.php | 1076 ++++++++--------- src/PocketMinecraftServer.php | 348 +++--- src/installer/Installer.php | 90 +- src/material/Block.php | 2 +- src/material/Item.php | 2 +- src/material/block/solid/LeavesBlock.php | 2 +- src/plugin/DummyPlugin.php | 10 +- src/plugin/OtherPluginRequirement.php | 2 +- src/recipes/CraftingRecipes.php | 46 +- src/recipes/FuelData.php | 4 +- src/recipes/SmeltingData.php | 4 +- src/utils/RailLogic.php | 218 ++-- src/utils/Utils.php | 2 +- src/world/Level.php | 524 ++++---- src/world/LevelImport.php | 58 +- src/world/MobSpawner.php | 65 +- src/world/MovingObjectPosition.php | 12 +- src/world/PocketChunkParser.php | 86 +- src/world/Position.php | 20 +- src/world/Tile.php | 162 ++- .../generator/noise/NoiseGeneratorOctaves.php | 18 +- .../generator/noise/NoiseGeneratorPerlin.php | 38 +- .../generator/vanilla/VanillaGenerator.php | 211 ++-- .../generator/vanilla/feature/TreeFeature.php | 40 +- 30 files changed, 1388 insertions(+), 1689 deletions(-) diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php index 307fb27e..6d0926a1 100644 --- a/.php-cs-fixer.php +++ b/.php-cs-fixer.php @@ -17,9 +17,6 @@ return (new PhpCsFixer\Config) 'cast_spaces' => [ 'space' => 'single' ], - 'concat_space' => [ - 'spacing' => 'one' - ], 'elseif' => true, 'indentation_type' => true, 'no_closing_tag' => true, diff --git a/src/API/AchievementAPI.php b/src/API/AchievementAPI.php index 526da14d..be89f3b7 100644 --- a/src/API/AchievementAPI.php +++ b/src/API/AchievementAPI.php @@ -184,7 +184,7 @@ class AchievementAPI{ if(count($achs) <= 0){ return "Player {$params[0]} unlocked 0 achievements"; } - $output = "Unlocked Achievements(" . count($achs) . "/" . count(self::$achievements) . "): "; + $output = "Unlocked Achievements(".count($achs)."/".count(self::$achievements)."): "; foreach($achs as $achievement => $unlocked){ if($unlocked && isset(self::$achievements[$achievement])){ $info = self::$achievements[$achievement]; diff --git a/src/API/BlockAPI.php b/src/API/BlockAPI.php index 42f2f34d..7368f121 100755 --- a/src/API/BlockAPI.php +++ b/src/API/BlockAPI.php @@ -235,7 +235,7 @@ class BlockAPI{ break; } $itemheld = $issuer->getSlot($issuer->slot); - $output = self::getItem($itemheld->getID(), $itemheld->getMetadata()) . ""; + $output = self::getItem($itemheld->getID(), $itemheld->getMetadata()).""; break; case "setblock": if(!($issuer instanceof Player)){ @@ -289,7 +289,7 @@ class BlockAPI{ break; }else{ $level->setBlock($pos, $block, true, false, true); - $output .= "Placed $block in " . implode(", ", $coords) . ", w:" . $level->getName(); + $output .= "Placed $block in ".implode(", ", $coords).", w:".$level->getName(); } break; case "give": @@ -311,7 +311,7 @@ class BlockAPI{ } $player->addItem($item->getID(), $item->getMetadata(), $item->count); - $output .= "Giving " . $item->count . " of " . $item->getName() . " (" . $item->getID() . ":" . $item->getMetadata() . ") to " . $player->username; + $output .= "Giving ".$item->count." of ".$item->getName()." (".$item->getID().":".$item->getMetadata().") to ".$player->username; break; }else{ $item = self::fromString($args[0] ?? ""); @@ -334,7 +334,7 @@ class BlockAPI{ } $issuer->addItem($item->getID(), $item->getMetadata(), $item->count); - $output .= "Giving " . $item->count . " of " . $item->getName() . " (" . $item->getID() . ":" . $item->getMetadata() . ") to " . $issuer->username; + $output .= "Giving ".$item->count." of ".$item->getName()." (".$item->getID().":".$item->getMetadata().") to ".$issuer->username; break; } } diff --git a/src/API/ConsoleAPI.php b/src/API/ConsoleAPI.php index 56f7624b..804486c4 100644 --- a/src/API/ConsoleAPI.php +++ b/src/API/ConsoleAPI.php @@ -272,19 +272,19 @@ class ConsoleAPI{ } public static function debug($msg){ - console("[DEBUG] " . $msg, true, true, 2); + console("[DEBUG] ".$msg, true, true, 2); } public static function info($msg){ - console("[INFO] " . $msg); + console("[INFO] ".$msg); } public static function notice($msg){ - console("[NOTICE] " . $msg); + console("[NOTICE] ".$msg); } public static function warn($msg){ - console("[WARNING] " . $msg); + console("[WARNING] ".$msg); } public static function error($msg){ - console("[ERROR] " . $msg); + console("[ERROR] ".$msg); } } diff --git a/src/API/EntityAPI.php b/src/API/EntityAPI.php index b9978dca..26d691a4 100644 --- a/src/API/EntityAPI.php +++ b/src/API/EntityAPI.php @@ -36,7 +36,7 @@ class EntityAPI{ $output = ""; switch($cmd){ case "entcnt": - return "Total amount of entities: " . count($this->entities); + return "Total amount of entities: ". count($this->entities); case "summon": case "spawnmob": if(!($issuer instanceof Player)){ @@ -81,7 +81,7 @@ class EntityAPI{ $this->summon($pos, ENTITY_MOB, $type, ["IsBaby" => $isBaby]); } - return "$amount " . ($isBaby ? "Baby " : "") . "$mobName(s) spawned in $x, $y, $z."; + return "$amount ".($isBaby ? "Baby " : "")."$mobName(s) spawned in $x, $y, $z."; } elseif(strtolower($args[1]) == "baby"){//summon [baby] $this->summon($pos, ENTITY_MOB, $type, ["IsBaby" => 1]); diff --git a/src/API/PluginAPI.php b/src/API/PluginAPI.php index 6596c783..facda55b 100644 --- a/src/API/PluginAPI.php +++ b/src/API/PluginAPI.php @@ -139,8 +139,8 @@ class PluginAPI extends stdClass{ if($ext2 === "phar"){ ++$pharCnt; $pluginInfo = []; //TODO: A PluginInfo class? - $filePath = $this->pluginsPath() . $file; - $p = new Phar($this->pluginsPath() . $file, 0); + $filePath = $this->pluginsPath().$file; + $p = new Phar($this->pluginsPath().$file, 0); foreach (new RecursiveIteratorIterator($p) as $file) { $name = $file->getFileName(); $content = file_get_contents($file->getPathName()); @@ -149,7 +149,7 @@ class PluginAPI extends stdClass{ break; } } - console("[INFO] Loading PHAR plugin \"" . FORMAT_GREEN . $pluginInfo["name"] . FORMAT_RESET . "\" " . FORMAT_AQUA . $pluginInfo["version"] . FORMAT_RESET . " by " . FORMAT_AQUA . $pluginInfo["author"] . FORMAT_RESET); + console("[INFO] Loading PHAR plugin \"".FORMAT_GREEN.$pluginInfo["name"].FORMAT_RESET."\" ".FORMAT_AQUA.$pluginInfo["version"].FORMAT_RESET." by ".FORMAT_AQUA.$pluginInfo["author"].FORMAT_RESET); $aver = CURRENT_API_VERSION; if(!in_array((string) CURRENT_API_VERSION, $pluginInfo["api"])){ @@ -159,13 +159,13 @@ class PluginAPI extends stdClass{ } $phr = "phar://$filePath/"; - include($phr . "/src/" . $pluginInfo["classLoader"]); + include($phr."/src/".$pluginInfo["classLoader"]); $class = $pluginInfo["CLClass"]; $loader = new $class(); $loader->loadAll($phr); $pluginName = PharUtils::getNameSpaceClass($pluginInfo["mainFile"]); - include($phr . "/src/" . $pluginInfo["mainFile"]); + include($phr."/src/".$pluginInfo["mainFile"]); $plugin = new $pluginName($this->server->api, false); if(!($plugin instanceof Plugin)){ console("[ERROR] Plugin \"" . $pluginInfo["name"] . "\" doesn't use the Plugin Interface"); diff --git a/src/Player.php b/src/Player.php index 136dbbac..f293319f 100755 --- a/src/Player.php +++ b/src/Player.php @@ -1,10 +1,8 @@ bigCnt = 0; $this->MTU = min($MTU, 1492); $this->server = ServerAPI::request(); @@ -129,14 +126,14 @@ class Player { console("[DEBUG] New Session started with " . $ip . ":" . $port . ". MTU " . $this->MTU . ", Client ID " . $this->clientID, true, true, 2); } - public function __get($name) { - if(isset($this->{$name})) { + public function __get($name){ + if(isset($this->{$name})){ return ($this->{$name}); } return null; } - public function getSpawn() { + public function getSpawn(){ return $this->spawnPosition; } @@ -144,10 +141,10 @@ class Player { * * @return boolean */ - public function sleepOn(Vector3 $pos) { - foreach($this->server->api->player->getAll($this->level) as $p) { - if($p->isSleeping instanceof Vector3) { - if($pos->distance($p->isSleeping) <= 0.1) { + public function sleepOn(Vector3 $pos){ + foreach($this->server->api->player->getAll($this->level) as $p){ + if($p->isSleeping instanceof Vector3){ + if($pos->distance($p->isSleeping) <= 0.1){ return false; } } @@ -156,14 +153,13 @@ class Player { $this->sleepingTime = 0; $this->teleport(new Position($pos->x + 0.5, $pos->y + 1, $pos->z + 0.5, $this->level), false, false, false, false); //TODO change player hitbox size after he starts sleeping - if($this->entity instanceof Entity) { + if($this->entity instanceof Entity){ $this->entity->updateMetadata(); } $spawnPoint = BedBlock::findStandUpPosition($this->level, $pos->x, $pos->y, $pos->z); - if($spawnPoint == null) { - $spawnPoint = $pos->add(0.5, 1, 0.5); - } else { + if($spawnPoint == null) $spawnPoint = $pos->add(0.5, 1, 0.5); + else{ $spawnPoint->x += 0.5; $spawnPoint->z += 0.5; } @@ -171,7 +167,7 @@ class Player { return true; } - public function setSlotCount($cnt) { + public function setSlotCount($cnt){ $this->slotCount = $cnt; $this->data->set("slot-count", $this->slotCount); } @@ -184,29 +180,29 @@ class Player { * * @return boolean */ - public function teleport(Vector3 $pos, $yaw = false, $pitch = false, $terrain = true, $force = true) { - if($this->entity instanceof Entity and $this->level instanceof Level) { + public function teleport(Vector3 $pos, $yaw = false, $pitch = false, $terrain = true, $force = true){ + if($this->entity instanceof Entity and $this->level instanceof Level){ $this->entity->check = false; - if($yaw === false) { + if($yaw === false){ $yaw = $this->entity->yaw; } - if($pitch === false) { + if($pitch === false){ $pitch = $this->entity->pitch; } - if($this->server->api->dhandle("player.teleport", ["player" => $this, "target" => $pos]) === false) { + if($this->server->api->dhandle("player.teleport", ["player" => $this, "target" => $pos]) === false){ $this->entity->check = true; return false; } - if($pos instanceof Position and $pos->level instanceof Level and $pos->level !== $this->level) { - if($this->server->api->dhandle("player.teleport.level", ["player" => $this, "origin" => $this->level, "target" => $pos->level]) === false) { + if($pos instanceof Position and $pos->level instanceof Level and $pos->level !== $this->level){ + if($this->server->api->dhandle("player.teleport.level", ["player" => $this, "origin" => $this->level, "target" => $pos->level]) === false){ $this->entity->check = true; return false; } - foreach($this->level->entityList as $e) { - if($e->eid !== $this->entity->eid) { - if($e->isPlayer()) { + foreach($this->level->entityList as $e){ + if($e->eid !== $this->entity->eid){ + if($e->isPlayer()){ $pk = new MovePlayerPacket(); $pk->eid = $this->entity->eid; $pk->x = -256; @@ -227,7 +223,7 @@ class Player { $pk->bodyYaw = 0; $this->dataPacket($pk); - } else { + }else{ $pk = new MoveEntityPacket_PosRot(); $pk->eid = $e->eid; $pk->x = -256; @@ -251,9 +247,9 @@ class Player { $this->chunksLoaded = []; $this->server->api->entity->spawnToAll($this->entity); //$this->server->api->entity->spawnAll($this); - foreach($this->level->entityList as $e) { - if($e->eid !== $this->entity->eid) { - if(!$e->isPlayer()) { + foreach($this->level->entityList as $e){ + if($e->eid !== $this->entity->eid){ + if(!$e->isPlayer()){ $pk = new MoveEntityPacket_PosRot(); $pk->eid = $e->eid; $pk->x = $e->x; @@ -270,8 +266,8 @@ class Player { $pk->time = $this->level->getTime(); $this->dataPacket($pk); $terrain = true; - foreach($this->level->players as $player) { - if($player !== $this and $player->entity instanceof Entity) { + foreach($this->level->players as $player){ + if($player !== $this and $player->entity instanceof Entity){ $pk = new MoveEntityPacket_PosRot; $pk->eid = $player->entity->eid; $pk->x = $player->entity->x; @@ -300,7 +296,7 @@ class Player { } $resyncpos = new Position($pos->x, $pos->y, $pos->z, $pos->level); - } else { + }else{ $resyncpos = new Vector3($pos->x, $pos->y, $pos->z); } @@ -312,14 +308,12 @@ class Player { $this->entity->resetSpeed(); $this->entity->updateLast(); $this->entity->calculateVelocity(); - if($terrain === true) { + if($terrain === true){ $this->orderChunks(); - if($this->spawned) { - $this->getNextChunk($this->level); - } + if($this->spawned) $this->getNextChunk($this->level); } $this->entity->check = true; - if($force === true) { + if($force === true){ $this->forceMovement = $resyncpos; } } @@ -346,23 +340,23 @@ class Player { * * @return array|bool */ - public function dataPacket(RakNetDataPacket $packet) { - if($this->connected === false) { + public function dataPacket(RakNetDataPacket $packet){ + if($this->connected === false){ return false; } - if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) { + if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY){ return; } $packet->encode(); $len = strlen($packet->buffer) + 1; $MTU = $this->MTU - 24; - if($len > $MTU) { + if($len > $MTU){ return $this->directBigRawPacket($packet); } - if(($this->bufferLen + $len) >= $MTU) { + if(($this->bufferLen + $len) >= $MTU){ $this->sendBuffer(); } @@ -373,23 +367,21 @@ class Player { return []; } - private function directBigRawPacket(RakNetDataPacket $packet) { - if($this->connected === false) { + private function directBigRawPacket(RakNetDataPacket $packet){ + if($this->connected === false){ return false; } $sendtime = microtime(true); $size = $this->MTU - 34; - if($size <= 0) { - return false; - } + if($size <= 0) return false; $buffer = str_split($packet->buffer, $size); $bigCnt = $this->bigCnt; $this->bigCnt = ($this->bigCnt + 1) % 0x10000; $cnts = []; $bufCount = count($buffer); - foreach($buffer as $i => $buf) { + foreach($buffer as $i => $buf){ $cnts[] = $count = $this->counter[0]++; $pk = new UnknownPacket; @@ -412,16 +404,16 @@ class Player { return $cnts; } - public function send(RakNetPacket $packet) { - if($this->connected === true) { + public function send(RakNetPacket $packet){ + if($this->connected === true){ $packet->ip = $this->ip; $packet->port = $this->port; $this->bandwidthRaw += $this->server->send($packet); } } - public function sendBuffer() { - if($this->bufferLen > 0 and $this->buffer instanceof RakNetPacket) { + public function sendBuffer(){ + if($this->bufferLen > 0 and $this->buffer instanceof RakNetPacket){ $this->buffer->seqNumber = $this->counter[0]++; $this->recoveryQueue[$this->buffer->seqNumber] = $this->buffer; $this->buffer->sendtime = microtime(true); @@ -438,7 +430,7 @@ class Player { * * @return Item */ - public function getSlot($slot) { + public function getSlot($slot){ return $this->inventory[(int) $slot] ?? BlockAPI::getItem(AIR, 0, 0); } @@ -448,9 +440,9 @@ class Player { * * @return boolean */ - public function setSlot($slot, Item $item, $send = true) { + public function setSlot($slot, Item $item, $send = true){ $this->inventory[(int) $slot] = $item; - if($send === true) { + if($send === true){ $this->sendInventorySlot((int) $slot); } return true; @@ -459,41 +451,41 @@ class Player { /** * @param Player|string|boolean|void $player */ - public function sendArmor($player = false) { + public function sendArmor($player = false){ $data = [ "player" => $this, "eid" => $this->eid, "slots" => [] ]; - for($i = 0; $i < 4; ++$i) { - if(isset($this->armor[$i]) and ($this->armor[$i] instanceof Item) and $this->armor[$i]->getID() > AIR) { + for($i = 0; $i < 4; ++$i){ + if(isset($this->armor[$i]) and ($this->armor[$i] instanceof Item) and $this->armor[$i]->getID() > AIR){ $data["slots"][$i] = $this->armor[$i]->getID() !== AIR ? $this->armor[$i]->getID() - 256 : 0; - } else { + }else{ $this->armor[$i] = BlockAPI::getItem(AIR, 0, 0); $data["slots"][$i] = 255; } } - if($player instanceof Player) { - if($player === $this) { + if($player instanceof Player){ + if($player === $this){ $pk = new ContainerSetContentPacket; $pk->windowid = 0x78; //Armor window id $pk->slots = $this->armor; $this->dataPacket($pk); - } else { + }else{ $pk = new PlayerArmorEquipmentPacket; $pk->eid = $this->eid; $pk->slots = $data["slots"]; $player->dataPacket($pk); } - } else { + }else{ $this->server->api->dhandle("player.armor", $data); } } public $lastOrderX = 0; public $lastOrderZ = 0; - public function orderChunks() { - if(!($this->entity instanceof Entity) or $this->connected === false) { + public function orderChunks(){ + if(!($this->entity instanceof Entity) or $this->connected === false){ return false; } $X = ((int) $this->entity->x) >> 4; @@ -501,28 +493,28 @@ class Player { $this->chunksOrder = []; $this->lastOrderX = $X; $this->lastOrderZ = $Z; - if(self::$smallChunks) { + if(self::$smallChunks){ $Y = ((int) $this->entity->y) >> 4; $v = new Vector3($X, $Y, $Z); - for($x = 0; $x < 16; ++$x) { - for($z = 0; $z < 16; ++$z) { - for($y = 0; $y < 8; ++$y) { + for($x = 0; $x < 16; ++$x){ + for($z = 0; $z < 16; ++$z){ + for($y = 0; $y < 8; ++$y){ $dist = $v->distance(new Vector3($x, $y, $z)); $d = $x . ":" . $y . ":" . $z; - if(!isset($this->chunksLoaded[$d])) { + if(!isset($this->chunksLoaded[$d])){ $this->chunksOrder[$d] = $dist; } } } } - } else { + }else{ $v = new Vector2($X, $Z); - for($x = 0; $x < 16; ++$x) { - for($z = 0; $z < 16; ++$z) { + for($x = 0; $x < 16; ++$x){ + for($z = 0; $z < 16; ++$z){ $dist = $v->distance(new Vector2($x, $z)); - for($y = 0; $y < 8; ++$y) { + for($y = 0; $y < 8; ++$y){ $d = $x . ":" . $y . ":" . $z; - if(!isset($this->chunksLoaded[$d])) { + if(!isset($this->chunksLoaded[$d])){ $this->chunksOrder[$d] = $dist; } } @@ -533,18 +525,18 @@ class Player { asort($this->chunksOrder); } - public function loaddAllChunks() { - for($x = 0; $x < 16; $x++) { - for($z = 0; $z < 16; $z++) { + public function loaddAllChunks(){ + for($x = 0; $x < 16; $x++){ + for($z = 0; $z < 16; $z++){ $this->useChunk($x, $z); } } } - public function useChunk($X, $Z) { + public function useChunk($X, $Z){ $Yndex = 0; - for($iY = 0; $iY < 8; ++$iY) { - if(isset($this->chunksOrder["$X:$iY:$Z"])) { + for($iY = 0; $iY < 8; ++$iY){ + if(isset($this->chunksOrder["$X:$iY:$Z"])){ unset($this->chunksOrder["$X:$iY:$Z"]); $this->chunksLoaded["$X:$iY:$Z"] = true; $Yndex |= 1 << $iY; @@ -563,44 +555,44 @@ class Player { $tiles = $this->server->query("SELECT ID FROM tiles WHERE spawnable = 1 AND level = '{$this->level->getName()}' AND x >= $minX AND x <= $maxX AND z >= $minZ AND z <= $maxZ;"); $this->lastChunk = false; - if($tiles !== false and $tiles !== true) { - while(($tile = $tiles->fetchArray(SQLITE3_ASSOC)) !== false) { + if($tiles !== false and $tiles !== true){ + while(($tile = $tiles->fetchArray(SQLITE3_ASSOC)) !== false){ $tile = $this->server->api->tile->getByID($tile["ID"]); - if($tile instanceof Tile) { + if($tile instanceof Tile){ $tile->spawn($this); } } } - if($cnt === false) { + if($cnt === false){ return false; } } - public function getNextChunk($world) { - if($this->connected === false or $world != $this->level) { + public function getNextChunk($world){ + if($this->connected === false or $world != $this->level){ return false; } - foreach($this->chunkCount as $count => $t) { - if(isset($this->recoveryQueue[$count]) or isset($this->resendQueue[$count])) { + foreach($this->chunkCount as $count => $t){ + if(isset($this->recoveryQueue[$count]) or isset($this->resendQueue[$count])){ $this->server->schedule(MAX_CHUNK_RATE, [$this, "getNextChunk"], $world); return; - } else { + }else{ unset($this->chunkCount[$count]); } } - if(is_array($this->lastChunk)) { + if(is_array($this->lastChunk)){ $minX = $this->lastChunk[0]; $maxX = $this->lastChunk[0] + 15; $minZ = $this->lastChunk[1]; $maxZ = $this->lastChunk[1] + 15; $tiles = $this->server->query("SELECT ID, x, y, z FROM tiles WHERE level = '{$this->level->getName()}' AND x >= $minX AND x <= $maxX AND z >= $minZ AND z <= $maxZ;"); $this->lastChunk = false; - if($tiles !== false and $tiles !== true) { - while(($tile = $tiles->fetchArray(SQLITE3_ASSOC)) !== false) { + if($tiles !== false and $tiles !== true){ + while(($tile = $tiles->fetchArray(SQLITE3_ASSOC)) !== false){ $tile = $this->server->api->tile->getByID($tile["ID"]); - if($tile instanceof Tile) { + if($tile instanceof Tile){ $tile->spawn($this); } } @@ -609,7 +601,7 @@ class Player { $c = key($this->chunksOrder); $d = $c != null ? $this->chunksOrder[$c] : null; - if($c === null or $d === null) { + if($c === null or $d === null){ $this->server->schedule(40, [$this, "getNextChunk"], $world); return false; } @@ -625,8 +617,8 @@ class Player { $y = $Y << 4; $this->level->useChunk($X, $Z, $this); $Yndex = 1 << $Y; - for($iY = 0; $iY < 8; ++$iY) { - if(isset($this->chunksOrder["$X:$iY:$Z"])) { + for($iY = 0; $iY < 8; ++$iY){ + if(isset($this->chunksOrder["$X:$iY:$Z"])){ unset($this->chunksOrder["$X:$iY:$Z"]); $this->chunksLoaded["$X:$iY:$Z"] = true; $Yndex |= 1 << $iY; @@ -637,25 +629,25 @@ class Player { $pk->chunkZ = $Z; $pk->data = $this->level->getOrderedChunk($X, $Z, $Yndex); $cnt = $this->dataPacket($pk); - if($cnt === false) { + if($cnt === false){ return false; } $this->chunkCount = []; - foreach($cnt as $i => $count) { + foreach($cnt as $i => $count){ $this->chunkCount[$count] = true; } $this->lastChunk = [$x, $z]; - if($this->lastOrderX != ($this->entity->x >> 4) || $this->lastOrderZ != ($this->entity->z >> 4)) { + if($this->lastOrderX != ($this->entity->x >> 4) || $this->lastOrderZ != ($this->entity->z >> 4)){ $this->orderChunks(); } $this->server->schedule(MAX_CHUNK_RATE, [$this, "getNextChunk"], $world); } - public function setSpawn(Vector3 $pos) { - if(!($pos instanceof Position)) { + public function setSpawn(Vector3 $pos){ + if(!($pos instanceof Position)){ $level = $this->entity->level; - } else { + }else{ $level = $pos->level; } $this->spawnPosition = new Position($pos->x, $pos->y, $pos->z, $level); @@ -666,17 +658,17 @@ class Player { $this->dataPacket($pk); } - public function sendInventorySlot($s) { + public function sendInventorySlot($s){ $this->sendInventory(); return true; } - public function sendInventory() { - if(($this->gamemode & 0x01) === CREATIVE) { + public function sendInventory(){ + if(($this->gamemode & 0x01) === CREATIVE){ return; } $hotbar = []; - foreach($this->hotbar as $slot) { + foreach($this->hotbar as $slot){ $hotbar[] = $slot <= -1 ? -1 : $slot + 9; } $pk = new ContainerSetContentPacket; @@ -689,26 +681,26 @@ class Player { * * @return boolean */ - public function hasSpace($type, $damage, $count) { + public function hasSpace($type, $damage, $count){ $inv = $this->inventory; - while($count > 0) { + while($count > 0){ $add = 0; - foreach($inv as $s => $item) { - if($item->getID() === AIR) { + foreach($inv as $s => $item){ + if($item->getID() === AIR){ $add = min($item->getMaxStackSize(), $count); $inv[$s] = BlockAPI::getItem($type, $damage, $add); break; - } elseif($item->getID() === $type and $item->getMetadata() === $damage) { + }elseif($item->getID() === $type and $item->getMetadata() === $damage){ $add = min($item->getMaxStackSize() - $item->count, $count); - if($add <= 0) { + if($add <= 0){ continue; } $inv[$s] = BlockAPI::getItem($type, $damage, $item->count + $add); break; } } - if($add <= 0) { + if($add <= 0){ return false; } $count -= $add; @@ -721,13 +713,13 @@ class Player { * * @return Item */ - public function getArmor($slot) { + public function getArmor($slot){ return $this->armor[(int) $slot] ?? BlockAPI::getItem(AIR, 0, 0); } - public function setArmor($slot, Item $armor, $send = true) { + public function setArmor($slot, Item $armor, $send = true){ $this->armor[(int) $slot] = $armor; - if($send === true) { + if($send === true){ $this->sendArmor($this); } return true; @@ -737,8 +729,8 @@ class Player { * @param mixed $data * @param string $event */ - public function eventHandler($data, $event) { - switch($event) { + public function eventHandler($data, $event){ + switch($event){ case "entity.link": $pk = new SetEntityLinkPacket(); $pk->rider = $data["rider"] == $this->entity->eid ? 0 : $data["rider"]; @@ -747,10 +739,10 @@ class Player { $this->dataPacket($pk); break; case "tile.update": - if($data->level === $this->level) { - if($data->class === TILE_FURNACE) { - foreach($this->windows as $id => $w) { - if($w === $data) { + if($data->level === $this->level){ + if($data->class === TILE_FURNACE){ + foreach($this->windows as $id => $w){ + if($w === $data){ $pk = new ContainerSetDataPacket; $pk->windowid = $id; $pk->property = 0; //Smelting @@ -768,9 +760,9 @@ class Player { } break; case "tile.container.slot": - if($data["tile"]->level === $this->level) { - foreach($this->windows as $id => $w) { - if($w === $data["tile"]) { + if($data["tile"]->level === $this->level){ + foreach($this->windows as $id => $w){ + if($w === $data["tile"]){ $pk = new ContainerSetSlotPacket; $pk->windowid = $id; $pk->slot = $data["slot"] + ($data["offset"] ?? 0); @@ -781,8 +773,8 @@ class Player { } break; case "player.armor": - if($data["player"]->level === $this->level) { - if($data["eid"] === $this->eid) { + if($data["player"]->level === $this->level){ + if($data["eid"] === $this->eid){ $this->sendArmor($this); break; } @@ -793,16 +785,16 @@ class Player { } break; case "player.pickup": - if($data["eid"] === $this->eid) { + if($data["eid"] === $this->eid){ $data["eid"] = 0; $pk = new TakeItemEntityPacket; $pk->eid = 0; $pk->target = $data["entity"]->eid; $this->dataPacket($pk); - if(($this->gamemode & 0x01) === 0x00) { + if(($this->gamemode & 0x01) === 0x00){ $this->addItem($data["entity"]->itemID, $data["entity"]->meta, $data["entity"]->stack, false); } - switch($data["entity"]->itemID) { + switch($data["entity"]->itemID){ case WOOD: AchievementAPI::grantAchievement($this, "mineWood"); break; @@ -813,7 +805,7 @@ class Player { AchievementAPI::grantAchievement($this, "leather"); break; } - } elseif($data["entity"]->level === $this->level) { + }elseif($data["entity"]->level === $this->level){ $pk = new TakeItemEntityPacket; $pk->eid = $data["eid"]; $pk->target = $data["entity"]->eid; @@ -821,7 +813,7 @@ class Player { } break; case "player.equipment.change": - if($data["eid"] === $this->eid or $data["player"]->level !== $this->level) { + if($data["eid"] === $this->eid or $data["player"]->level !== $this->level){ break; } $data["slot"] = 0; @@ -835,10 +827,10 @@ class Player { break; case "entity.motion": - if($data->eid === $this->eid or $data->level !== $this->level) { + if($data->eid === $this->eid or $data->level !== $this->level){ break; } - if(($data->speedX === 0 && $data->speedY === 0 && $data->speedZ === 0) || ($data->speedX === $data->lastSpeedX && $data->speedY === $data->lastSpeedY && $data->lastSpeedZ === $data->speedZ)) { + if(($data->speedX === 0 && $data->speedY === 0 && $data->speedZ === 0) || ($data->speedX === $data->lastSpeedX && $data->speedY === $data->lastSpeedY && $data->lastSpeedZ === $data->speedZ)){ break; } $pk = new SetEntityMotionPacket; @@ -856,12 +848,12 @@ class Player { $this->dataPacket($pk); break; case "entity.metadata": - if($data->eid === $this->eid) { + if($data->eid === $this->eid){ $eid = 0; - } else { + }else{ $eid = $data->eid; } - if($data->level === $this->level) { + if($data->level === $this->level){ $pk = new SetEntityDataPacket; $pk->eid = $eid; $pk->metadata = $data->getMetadata(); @@ -869,12 +861,12 @@ class Player { } break; case "entity.event": - if($data["entity"]->eid === $this->eid) { + if($data["entity"]->eid === $this->eid){ $eid = 0; - } else { + }else{ $eid = $data["entity"]->eid; } - if($data["entity"]->level === $this->level) { + if($data["entity"]->level === $this->level){ $pk = new EntityEventPacket; $pk->eid = $eid; $pk->event = $data["event"]; @@ -882,14 +874,14 @@ class Player { } break; case "server.chat": - if(($data instanceof Container) === true) { - if(!$data->check($this->username) and !$data->check($this->iusername)) { + if(($data instanceof Container) === true){ + if(!$data->check($this->username) and !$data->check($this->iusername)){ return; - } else { + }else{ $message = $data->get(); $this->sendChat(preg_replace('/\x1b\[[0-9;]*m/', "", $message["message"]), $message["player"]); //Remove ANSI codes from chat } - } else { + }else{ $message = (string) $data; $this->sendChat(preg_replace('/\x1b\[[0-9;]*m/', "", (string) $data)); //Remove ANSI codes from chat } @@ -903,43 +895,33 @@ class Player { * * @return boolean */ - public function addItem($type, $damage, $count, $send = true) { + public function addItem($type, $damage, $count, $send = true){ - foreach($this->inventory as $s => $item) { //force check the inventory for non-full stacks of this item first - if($item->getID() === $type and $item->getMetadata() === $damage) { + foreach($this->inventory as $s => $item){ //force check the inventory for non-full stacks of this item first + if($item->getID() === $type and $item->getMetadata() === $damage){ $add = min($item->getMaxStackSize() - $item->count, $count); - if($add <= 0) { + if($add <= 0){ continue; } $item->count += $add; - if($send) { - $this->sendInventorySlot($s); - } + if($send) $this->sendInventorySlot($s); $count -= $add; - if($count <= 0) { - return true; - } + if($count <= 0) return true; } } $toadd = BlockAPI::getItem($type, $damage, $count); - foreach($this->inventory as $s => $item) { - if($item->getID() === AIR) { + foreach($this->inventory as $s => $item){ + if($item->getID() === AIR){ $add = min($toadd->getMaxStackSize(), $count); $this->inventory[$s] = BlockAPI::getItem($type, $damage, $add); - if($send) { - $this->sendInventorySlot($s); - } + if($send) $this->sendInventorySlot($s); $count -= $add; - if($count <= 0) { - return true; - } + if($count <= 0) return true; } } - if($count <= 0) { - return true; - } + if($count <= 0) return true; return false; } @@ -947,18 +929,18 @@ class Player { * @param string $message * @param string $author */ - public function sendChat($message, $author = "") { + public function sendChat($message, $author = ""){ $mes = explode("\n", $message); - foreach($mes as $m) { - if(preg_match_all('#@([@A-Za-z_]{1,})#', $m, $matches, PREG_OFFSET_CAPTURE) > 0) { + foreach($mes as $m){ + if(preg_match_all('#@([@A-Za-z_]{1,})#', $m, $matches, PREG_OFFSET_CAPTURE) > 0){ $offsetshift = 0; - foreach($matches[1] as $selector) { - if($selector[0][0] === "@") { //Escape! + foreach($matches[1] as $selector){ + if($selector[0][0] === "@"){ //Escape! $m = substr_replace($m, $selector[0], $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1); --$offsetshift; continue; } - switch(strtolower($selector[0])) { + switch(strtolower($selector[0])){ case "player": case "username": $m = substr_replace($m, $this->username, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1); @@ -968,7 +950,7 @@ class Player { } } - if($m !== "") { + if($m !== ""){ $pk = new MessagePacket; $pk->source = ($author instanceof Player) ? $author->username : $author; $pk->message = TextFormat::clean($m); //Colors not implemented :( @@ -976,18 +958,18 @@ class Player { } } } - public function makeInvisibleForOnePlayer(Player $player) { + public function makeInvisibleForOnePlayer(Player $player){ $pk = new RemoveEntityPacket; $pk->eid = $this->entity->eid; $player->dataPacket($pk); } - public function makeInvisibleForAllPlayers() { + public function makeInvisibleForAllPlayers(){ $pk = new RemoveEntityPacket; $pk->eid = $this->entity->eid; $this->server->api->player->broadcastPacket($this->server->api->player->getAll($this->level), $pk); } - public function getGamemode() { - switch($this->gamemode) { + public function getGamemode(){ + switch($this->gamemode){ case SURVIVAL: return "survival"; case CREATIVE: @@ -999,16 +981,14 @@ class Player { } } - public function checkSpawnPosition() { - if($this->server->api->dhandle("player.checkspawnpos", ["player" => $this]) === false) { - return; - } + public function checkSpawnPosition(){ + if($this->server->api->dhandle("player.checkspawnpos", ["player" => $this]) === false) return; $level = $this->spawnPosition->level; - if(!isset($this->server->api->level->levels[$level->getName()])) { + if(!isset($this->server->api->level->levels[$level->getName()])){ ConsoleAPI::warn("Level to respawn {$this->iusername} was unloaded, changing spawnpoint to default."); $level = $this->server->api->level->getDefault(); $this->spawnPosition = $level->getSpawn(); - } else { + }else{ $x0 = floor($this->spawnPosition->x - $this->entity->width / 2); $x1 = floor($this->spawnPosition->x + $this->entity->width / 2 + 1); $y0 = floor($this->spawnPosition->y); @@ -1020,11 +1000,11 @@ class Player { for($z = $z0; $z < $z1; ++$z) { for($y = $y0; $y < $y1; ++$y) { $bid = $this->entity->level->level->getBlockID($x, $y, $z); - if($bid > 0 && StaticBlock::getIsSolid($bid)) { + if($bid > 0 && StaticBlock::getIsSolid($bid)){ $blockBounds = StaticBlock::$prealloc[$bid]::getCollisionBoundingBoxes($this->entity->level, $x, $y, $z, $this->entity); - foreach($blockBounds as $blockBound) { - if($this->entity->boundingBox->intersectsWith($blockBound)) { + foreach($blockBounds as $blockBound){ + if($this->entity->boundingBox->intersectsWith($blockBound)){ $this->sendChat("Your spawn positon is obstructed."); goto reset_spawn_pos; } @@ -1039,36 +1019,36 @@ class Player { } } - public function setGamemode($gm) { - if($gm < 0 or $gm > 3 or $this->gamemode === $gm) { + public function setGamemode($gm){ + if($gm < 0 or $gm > 3 or $this->gamemode === $gm){ return false; } - if($this->server->api->dhandle("player.gamemode.change", ["player" => $this, "gamemode" => $gm]) === false) { + if($this->server->api->dhandle("player.gamemode.change", ["player" => $this, "gamemode" => $gm]) === false){ return false; } $inv = &$this->inventory; - if($gm === VIEW) { + if($gm === VIEW){ $this->armor = []; $this->sendArmor(); } - if(($this->gamemode & 0x01) === ($gm & 0x01)) { - if(($gm & 0x01) === 0x01 and ($gm & 0x02) === 0x02) { + if(($this->gamemode & 0x01) === ($gm & 0x01)){ + if(($gm & 0x01) === 0x01 and ($gm & 0x02) === 0x02){ $inv = []; - foreach(BlockAPI::$creative as $item) { + foreach(BlockAPI::$creative as $item){ $inv[] = BlockAPI::getItem(0, 0, 1); } - } elseif(($gm & 0x01) === 0x01) { + }elseif(($gm & 0x01) === 0x01){ $inv = []; - foreach(BlockAPI::$creative as $item) { + foreach(BlockAPI::$creative as $item){ $inv[] = BlockAPI::getItem($item[0], $item[1], 1); } } $this->gamemode = $gm; $this->sendChat("Your gamemode has been changed to " . $this->getGamemode() . ".\n"); - } else { - foreach($this->inventory as $slot => $item) { + }else{ + foreach($this->inventory as $slot => $item){ $inv[$slot] = BlockAPI::getItem(AIR, 0, 0); } $this->hotbar = [0, 1, 2, 3, 4, 5, 6, 7, 8]; @@ -1079,10 +1059,10 @@ class Player { $this->server->schedule(30, [$this, "close"], "gamemode change", false, true); //Forces a kick } - if($this->gamemode === SPECTATOR) { + if($this->gamemode === SPECTATOR){ $this->makeInvisibleForAllPlayers(); } - if($this->gamemode === CREATIVE) { + if($this->gamemode === CREATIVE){ $this->server->api->player->spawnToAllPlayers($this); } @@ -1092,7 +1072,7 @@ class Player { return true; } - public function sendSettings($nametags = true) { + public function sendSettings($nametags = true){ /* bit mask | flag name 0b00000001 allowInteract @@ -1105,11 +1085,11 @@ class Player { 0b10000000 - unused */ $flags = 0; - if(($this->gamemode & 0x02) === 0x02) { + if(($this->gamemode & 0x02) === 0x02){ $flags |= 0x01; //Do not allow placing/breaking blocks, adventure mode } - if($nametags !== false) { + if($nametags !== false){ $flags |= 0x20; //Show Nametags } @@ -1121,13 +1101,13 @@ class Player { $this->dataPacket($pk); } - public function measureLag() { - if($this->connected === false) { + public function measureLag(){ + if($this->connected === false){ return false; } - if($this->packetStats[1] > 2) { + if($this->packetStats[1] > 2){ $this->packetLoss = $this->packetStats[1] / max(1, $this->packetStats[0] + $this->packetStats[1]); - } else { + }else{ $this->packetLoss = 0; } $this->packetStats = [0, 0]; @@ -1140,53 +1120,53 @@ class Player { $this->lastMeasure = microtime(true); } - public function getLag() { + public function getLag(){ return $this->lagStat * 1000; } - public function getPacketLoss() { + public function getPacketLoss(){ return $this->packetLoss; } - public function getBandwidth() { + public function getBandwidth(){ return array_sum($this->bandwidthStats) / max(1, count($this->bandwidthStats)); } - public function clearQueue() { - if($this->connected === false) { + public function clearQueue(){ + if($this->connected === false){ return false; } - if(($cnt = count($this->received)) > PLAYER_MAX_QUEUE) { + if(($cnt = count($this->received)) > PLAYER_MAX_QUEUE){ ksort($this->received); - foreach($this->received as $c => $t) { + foreach($this->received as $c => $t){ unset($this->received[$c]); --$cnt; - if($cnt <= PLAYER_MAX_QUEUE) { + if($cnt <= PLAYER_MAX_QUEUE){ break; } } } } - public function handlePacketQueues() { - if($this->connected === false) { + public function handlePacketQueues(){ + if($this->connected === false){ return false; } $time = microtime(true); - if($time > $this->timeout) { + if($time > $this->timeout){ $this->close("timeout"); return false; } - if(($ackCnt = count($this->ackQueue)) > 0) { + if(($ackCnt = count($this->ackQueue)) > 0){ rsort($this->ackQueue); $safeCount = (int) (($this->MTU - 1) / 4); $packetCnt = (int) ($ackCnt / $safeCount + 1); - for($p = 0; $p < $packetCnt; ++$p) { + for($p = 0; $p < $packetCnt; ++$p){ $pk = new RakNetPacket(RakNetInfo::ACK); $pk->packets = []; - for($c = 0; $c < $safeCount; ++$c) { - if(($k = array_pop($this->ackQueue)) === null) { + for($c = 0; $c < $safeCount; ++$c){ + if(($k = array_pop($this->ackQueue)) === null){ break; } $pk->packets[] = $k; @@ -1196,20 +1176,20 @@ class Player { $this->ackQueue = []; } - if(($receiveCnt = count($this->receiveQueue)) > 0) { + if(($receiveCnt = count($this->receiveQueue)) > 0){ ksort($this->receiveQueue); - foreach($this->receiveQueue as $count => $packets) { + foreach($this->receiveQueue as $count => $packets){ unset($this->receiveQueue[$count]); - foreach($packets as $p) { - if($p instanceof RakNetDataPacket and $p->hasSplit === false) { - if(isset($p->messageIndex) and $p->messageIndex !== false) { - if($p->messageIndex > $this->receiveCount) { + foreach($packets as $p){ + if($p instanceof RakNetDataPacket and $p->hasSplit === false){ + if(isset($p->messageIndex) and $p->messageIndex !== false){ + if($p->messageIndex > $this->receiveCount){ $this->receiveCount = $p->messageIndex; - } elseif($p->messageIndex !== 0) { - if(isset($this->received[$p->messageIndex])) { + }elseif($p->messageIndex !== 0){ + if(isset($this->received[$p->messageIndex])){ continue; } - switch($p->pid()) { + switch($p->pid()){ case 0x01: case ProtocolInfo::PING_PACKET: case ProtocolInfo::PONG_PACKET: @@ -1229,38 +1209,37 @@ class Player { } } - if($this->bufferLen > 0) { + if($this->bufferLen > 0){ $this->sendBuffer(); } $limit = $time - 5; //max lag - foreach($this->recoveryQueue as $count => $data) { - if($data->sendtime > $limit) { + foreach($this->recoveryQueue as $count => $data){ + if($data->sendtime > $limit){ break; } unset($this->recoveryQueue[$count]); $this->resendQueue[$count] = $data; } - if(($resendCnt = count($this->resendQueue)) > 0) { - foreach($this->resendQueue as $count => $data) { + if(($resendCnt = count($this->resendQueue)) > 0){ + foreach($this->resendQueue as $count => $data){ unset($this->resendQueue[$count]); $this->packetStats[1]++; $this->lag[] = $time - $data->sendtime; $data->sendtime = $time; $cnt = $this->send($data); - if(isset($this->chunkCount[$count])) { + if(isset($this->chunkCount[$count])){ unset($this->chunkCount[$count]); - if(!is_null($cnt) and !is_null($cnt[0])) { + if(!is_null($cnt) and !is_null($cnt[0])) $this->chunkCount[$cnt[0]] = true; - } } } } } - public function sendEntityMovementUpdateQueue() { - if($this->entityMovementQueueLength > 0 && $this->entityMovementQueue instanceof RakNetPacket) { + public function sendEntityMovementUpdateQueue(){ + if($this->entityMovementQueueLength > 0 && $this->entityMovementQueue instanceof RakNetPacket){ $this->entityMovementQueue->seqNumber = $this->counter[0]++; $this->send($this->entityMovementQueue); } @@ -1269,8 +1248,8 @@ class Player { $this->entityMovementQueue->data = []; } - public function sendBlockUpdateQueue() { - if($this->blockUpdateQueueLength > 0 && $this->blockUpdateQueue instanceof RakNetPacket) { + public function sendBlockUpdateQueue(){ + if($this->blockUpdateQueueLength > 0 && $this->blockUpdateQueue instanceof RakNetPacket){ $this->blockUpdateQueue->seqNumber = $this->counter[0]++; $this->recoveryQueue[$this->blockUpdateQueue->seqNumber] = $this->blockUpdateQueue; $this->blockUpdateQueue->sendtime = microtime(true); @@ -1281,7 +1260,7 @@ class Player { $this->blockUpdateQueue->data = []; } - public function addBlockUpdateIntoQueue($x, $y, $z, $id, $meta) { + public function addBlockUpdateIntoQueue($x, $y, $z, $id, $meta){ $packet = new UpdateBlockPacket(); $packet->x = $x; $packet->y = $y; @@ -1293,7 +1272,7 @@ class Player { $len = 1 + strlen($packet->buffer); $MTU = $this->MTU - 24; - if(($this->blockUpdateQueueLength + $len) >= $MTU) { + if(($this->blockUpdateQueueLength + $len) >= $MTU){ $this->sendBlockUpdateQueue(); } @@ -1303,18 +1282,18 @@ class Player { $this->blockUpdateQueueLength += 6 + $len; } - public function addEntityMovementUpdateToQueue(Entity $e) { + public function addEntityMovementUpdateToQueue(Entity $e){ $len = 0; $packets = 0; $motionSent = false; $moveSent = false; $headSent = false; $svdYSpeed = $e->speedY; - if($e->modifySpeedY) { + if($e->modifySpeedY){ $e->speedY = $e->modifedSpeedY; } - if($e->speedX != 0 || $e->speedY != 0 || $e->speedZ != 0 || $e->speedY != $e->lastSpeedY || $e->speedX != $e->lastSpeedX || $e->speedZ != $e->lastSpeedZ) { - if(!($e->speedY < 0 && $e->onGround) || $e->speedX != 0 || $e->speedZ != 0 || $e->speedY != $e->lastSpeedY || $e->speedX != $e->lastSpeedX || $e->speedZ != $e->lastSpeedZ) { + if($e->speedX != 0 || $e->speedY != 0 || $e->speedZ != 0 || $e->speedY != $e->lastSpeedY || $e->speedX != $e->lastSpeedX || $e->speedZ != $e->lastSpeedZ){ + if(!($e->speedY < 0 && $e->onGround) || $e->speedX != 0 || $e->speedZ != 0 || $e->speedY != $e->lastSpeedY || $e->speedX != $e->lastSpeedX || $e->speedZ != $e->lastSpeedZ){ $motion = new SetEntityMotionPacket(); $motion->eid = $e->eid; $motion->speedX = $e->speedX; @@ -1326,13 +1305,13 @@ class Player { $motionSent = true; } } - if($e->modifySpeedY) { + if($e->modifySpeedY){ $e->speedY = $svdYSpeed; $e->modifySpeedY = false; } - if($e->x != $e->lastX || $e->y != $e->lastY || $e->z != $e->lastZ || $e->yaw != $e->lastYaw || $e->pitch != $e->lastPitch) { - if($e->headYaw != $e->lastHeadYaw) { + if($e->x != $e->lastX || $e->y != $e->lastY || $e->z != $e->lastZ || $e->yaw != $e->lastYaw || $e->pitch != $e->lastPitch){ + if($e->headYaw != $e->lastHeadYaw){ $move = new MovePlayerPacket(); $move->eid = $e->eid; $move->x = $e->x; @@ -1342,7 +1321,7 @@ class Player { $move->pitch = $e->pitch; $move->bodyYaw = $e->headYaw; $move->encode(); - } else { + }else{ $move = new MoveEntityPacket_PosRot(); $move->eid = $e->eid; $move->x = $e->x; @@ -1356,7 +1335,7 @@ class Player { $len += strlen($move->buffer) + 1; ++$packets; $moveSent = true; - } elseif($e->headYaw != $e->lastHeadYaw) { + }elseif($e->headYaw != $e->lastHeadYaw){ $headyaw = new RotateHeadPacket(); $headyaw->eid = $e->eid; $headyaw->yaw = $e->headYaw; @@ -1365,25 +1344,23 @@ class Player { ++$packets; $headSent = true; } - if($packets <= 0) { - return; - } + if($packets <= 0) return; //console("Update {$e}: $packets, mot: $motionSent, mov: $moveSent, hed: $headSent"); $MTU = $this->MTU - 24; - if(($this->entityMovementQueueLength + $len) >= $MTU) { + if(($this->entityMovementQueueLength + $len) >= $MTU){ $this->sendEntityMovementUpdateQueue(); } - if($motionSent) { + if($motionSent){ $motion->messageIndex = 0; //force 0 cuz reliability 0 $motion->reliability = 0; $this->entityMovementQueue->data[] = $motion; } - if($moveSent) { + if($moveSent){ $move->messageIndex = 0; $move->reliability = 0; $this->entityMovementQueue->data[] = $move; } - if($headSent) { + if($headSent){ $headyaw->messageIndex = 0; $headyaw->reliability = 0; $this->entityMovementQueue->data[] = $headyaw; @@ -1396,12 +1373,12 @@ class Player { * @param string $reason Reason for closing connection * @param boolean $msg Set to false to silently disconnect player. No broadcast. */ - public function close($reason = "", $msg = true) { - if($this->connected === true) { - foreach($this->evid as $ev) { + public function close($reason = "", $msg = true){ + if($this->connected === true){ + foreach($this->evid as $ev){ $this->server->deleteEvent($ev); } - if($this->username != "") { + if($this->username != ""){ $this->server->api->handle("player.quit", $this); $this->save(); } @@ -1419,7 +1396,7 @@ class Player { $this->resendQueue = []; $this->ackQueue = []; $this->server->api->player->remove($this->CID); - if($msg === true and $this->username != "" and $this->spawned !== false) { + if($msg === true and $this->username != "" and $this->spawned !== false){ $this->server->api->chat->broadcast($this->username . " left the game: " . $reason); } $this->spawned = false; @@ -1436,8 +1413,8 @@ class Player { } } - public function save() { - if($this->entity instanceof Entity) { + public function save(){ + if($this->entity instanceof Entity){ $this->data->set("achievements", $this->achievements); $this->data->set("position", [ "level" => $this->entity->level->getName(), @@ -1454,9 +1431,9 @@ class Player { "z" => $this->spawnPosition->z ]); $inv = []; - foreach($this->inventory as $slot => $item) { - if($item instanceof Item) { - if($slot < (($this->gamemode & 0x01) === 0 ? PLAYER_SURVIVAL_SLOTS : PLAYER_CREATIVE_SLOTS)) { + foreach($this->inventory as $slot => $item){ + if($item instanceof Item){ + if($slot < (($this->gamemode & 0x01) === 0 ? PLAYER_SURVIVAL_SLOTS : PLAYER_CREATIVE_SLOTS)){ $inv[$slot] = [$item->getID(), $item->getMetadata(), $item->count]; } } @@ -1465,25 +1442,25 @@ class Player { $this->data->set("hotbar", $this->hotbar); $armor = []; - foreach($this->armor as $slot => $item) { - if($item instanceof Item) { + foreach($this->armor as $slot => $item){ + if($item instanceof Item){ $armor[$slot] = [$item->getID(), $item->getMetadata()]; } } $this->data->set("armor", $armor); - if($this->entity instanceof Entity) { + if($this->entity instanceof Entity){ $this->data->set("health", $this->entity->getHealth()); } $this->data->set("gamemode", $this->gamemode); } } - public function directDataPacket(RakNetDataPacket $packet, $reliability = 0, $recover = true) { - if($this->connected === false) { + public function directDataPacket(RakNetDataPacket $packet, $reliability = 0, $recover = true){ + if($this->connected === false){ return false; } - if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) { + if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY){ return []; } @@ -1492,20 +1469,18 @@ class Player { $pk->data[] = $packet; $pk->seqNumber = $this->counter[0]++; $pk->sendtime = microtime(true); - if($recover !== false) { + if($recover !== false){ $this->recoveryQueue[$pk->seqNumber] = $pk; } $this->send($pk); return [$pk->seqNumber]; } - public function entityTick() { - if($this->isSleeping) { - ++$this->sleepingTime; - } + public function entityTick(){ + if($this->isSleeping) ++$this->sleepingTime; - if($this->server->difficulty == 0 && $this->entity->counter % (20 * 15) == 0) { - if($this->entity->health < 20 && $this->entity->health > 0) { + if($this->server->difficulty == 0 && $this->entity->counter % (20 * 15) == 0){ + if($this->entity->health < 20 && $this->entity->health > 0){ $this->entity->setHealth(min(20, $this->entity->health + 1), "regeneration"); } } @@ -1522,21 +1497,21 @@ class Player { return $this->lastPing; } - public function handleDataPacket(RakNetDataPacket $packet) { - if($this->connected === false) { + public function handleDataPacket(RakNetDataPacket $packet){ + if($this->connected === false){ return; } - if(EventHandler::callEvent(new DataPacketReceiveEvent($this, $packet)) === BaseEvent::DENY) { + if(EventHandler::callEvent(new DataPacketReceiveEvent($this, $packet)) === BaseEvent::DENY){ return; } - switch($packet->pid()) { + switch($packet->pid()){ case 0x01: break; case ProtocolInfo::PONG_PACKET: $currentTime = intdiv(hrtime(true), 1_000_000); - if($currentTime > $packet->ptime) { + if($currentTime > $packet->ptime){ $this->lastPing = $currentTime - $packet->ptime; } break; @@ -1550,7 +1525,7 @@ class Player { $this->close("client disconnect"); break; case ProtocolInfo::CLIENT_CONNECT_PACKET: - if($this->loggedIn === true) { + if($this->loggedIn === true){ break; } $pk = new ServerHandshakePacket; @@ -1560,27 +1535,27 @@ class Player { $this->dataPacket($pk); break; case ProtocolInfo::CLIENT_HANDSHAKE_PACKET: - if($this->loggedIn === true) { + if($this->loggedIn === true){ break; } break; case ProtocolInfo::LOGIN_PACKET: - if($this->loggedIn === true) { + if($this->loggedIn === true){ break; } $this->username = $packet->username; $this->iusername = strtolower($this->username); $this->loginData = ["clientId" => $packet->clientId, "loginData" => $packet->loginData]; - if(count($this->server->clients) > $this->server->maxClients and !$this->server->api->ban->isOp($this->iusername)) { + if(count($this->server->clients) > $this->server->maxClients and !$this->server->api->ban->isOp($this->iusername)){ $this->close("server is full!", false); return; } - if($packet->protocol1 !== ProtocolInfo::CURRENT_PROTOCOL) { - if($packet->protocol1 < ProtocolInfo::CURRENT_PROTOCOL) { + if($packet->protocol1 !== ProtocolInfo::CURRENT_PROTOCOL){ + if($packet->protocol1 < ProtocolInfo::CURRENT_PROTOCOL){ $pk = new LoginStatusPacket; $pk->status = 1; $this->directDataPacket($pk); - } else { + }else{ $pk = new LoginStatusPacket; $pk->status = 2; $this->directDataPacket($pk); @@ -1588,55 +1563,55 @@ class Player { $this->close("Incorrect protocol #" . $packet->protocol1, false); return; } - if(preg_match('#[^a-zA-Z0-9_]#', $this->username) > 0 || $this->username === "" || $this->iusername === "rcon" || $this->iusername === "console" || $this->iusername === "server" || strlen($this->iusername) > 16) { + if(preg_match('#[^a-zA-Z0-9_]#', $this->username) > 0 || $this->username === "" || $this->iusername === "rcon" || $this->iusername === "console" || $this->iusername === "server" || strlen($this->iusername) > 16){ $this->close("Bad username", false); return; } - if($this->server->api->handle("player.connect", $this) === false) { + if($this->server->api->handle("player.connect", $this) === false){ $this->close("Unknown reason", false); return; } - if($this->server->whitelist === true and !$this->server->api->ban->inWhitelist($this->iusername)) { + if($this->server->whitelist === true and !$this->server->api->ban->inWhitelist($this->iusername)){ $this->close("Server is white-listed", false); return; - } elseif($this->server->api->ban->isBanned($this->iusername) or $this->server->api->ban->isIPBanned($this->ip)) { + }elseif($this->server->api->ban->isBanned($this->iusername) or $this->server->api->ban->isIPBanned($this->ip)){ $this->close("You are banned!", false); return; } $this->loggedIn = true; - if(!isset($this->CID) or $this->CID == null) { + if(!isset($this->CID) or $this->CID == null){ console("[DEBUG] Player " . $this->username . " does not have a CID", true, true, 2); $this->CID = Utils::readLong(Utils::getRandomBytes(8, false)); } $u = $this->server->api->player->get($this->iusername, false); - if($u !== false) { + if($u !== false){ $u = $this->server->clients[$this->CID]; $u->close("this player already in game"); } $this->server->api->player->add($this->CID); - if($this->server->api->handle("player.join", $this) === false) { + if($this->server->api->handle("player.join", $this) === false){ $this->close("join cancelled", false); return; } - if(!($this->data instanceof Config)) { + if(!($this->data instanceof Config)){ $this->close("no config created", false); return; } $this->auth = true; - if(!$this->data->exists("inventory") or ($this->gamemode & 0x01) === 0x01) { - if(($this->gamemode & 0x01) === 0x01) { + if(!$this->data->exists("inventory") or ($this->gamemode & 0x01) === 0x01){ + if(($this->gamemode & 0x01) === 0x01){ $inv = []; - if(($this->gamemode & 0x02) === 0x02) { - foreach(BlockAPI::$creative as $item) { + if(($this->gamemode & 0x02) === 0x02){ + foreach(BlockAPI::$creative as $item){ $inv[] = [0, 0, 1]; } - } else { - foreach(BlockAPI::$creative as $item) { + }else{ + foreach(BlockAPI::$creative as $item){ $inv[] = [$item[0], $item[1], 1]; } } @@ -1646,15 +1621,15 @@ class Player { $this->achievements = $this->data->get("achievements"); $this->data->set("caseusername", $this->username); $this->inventory = []; - foreach($this->data->get("inventory") as $slot => $item) { - if(!is_array($item) or count($item) < 3) { + foreach($this->data->get("inventory") as $slot => $item){ + if(!is_array($item) or count($item) < 3){ $item = [AIR, 0, 0]; } $this->inventory[$slot] = BlockAPI::getItem($item[0], $item[1], $item[2]); } $this->armor = []; - foreach($this->data->get("armor") as $slot => $item) { + foreach($this->data->get("armor") as $slot => $item){ $this->armor[$slot] = BlockAPI::getItem($item[0], $item[1], $item[0] === 0 ? 0 : 1); } @@ -1677,27 +1652,23 @@ class Player { $pk->eid = 0; $this->dataPacket($pk); - if(($this->gamemode & 0x01) === 0x01) { + if(($this->gamemode & 0x01) === 0x01){ $this->slot = 0; $this->hotbar = []; - } elseif($this->data->exists("hotbar")) { + }elseif($this->data->exists("hotbar")){ $this->hotbar = $this->data->get("hotbar"); $this->slot = $this->hotbar[0]; - } else { + }else{ $this->slot = 0; $this->hotbar = [0, 1, 2, 3, 4, 5, 6, 7, 8]; } - for($i = 0; $i < count($this->hotbar); ++$i) { - if($this->hotbar[$i] > 36) { - $this->hotbar[$i] = -1; - } //XXX unsafe? - if($this->hotbar[$i] < -1) { - $this->hotbar[$i] = -1; - } + for($i = 0; $i < count($this->hotbar); ++$i){ + if($this->hotbar[$i] > 36) $this->hotbar[$i] = -1; //XXX unsafe? + if($this->hotbar[$i] < -1) $this->hotbar[$i] = -1; } - if($this->data->exists("slot-count")) { + if($this->data->exists("slot-count")){ $this->slotCount = $this->data->get("slot-count"); - } else { + }else{ $this->data->set("slot-count", $this->slotCount); } @@ -1707,7 +1678,7 @@ class Player { $this->entity->x = $this->data->get("position")["x"]; $this->entity->y = $this->data->get("position")["y"]; $this->entity->z = $this->data->get("position")["z"]; - if(($level = $this->server->api->level->get($this->data->get("spawn")["level"])) !== false) { + if(($level = $this->server->api->level->get($this->data->get("spawn")["level"])) !== false){ $this->spawnPosition = new Position($this->data->get("spawn")["x"], $this->data->get("spawn")["y"], $this->data->get("spawn")["z"], $level); $pk = new SetSpawnPositionPacket; @@ -1741,12 +1712,12 @@ class Player { console("[INFO] " . FORMAT_AQUA . $this->username . FORMAT_RESET . "[/" . $this->ip . ":" . $this->port . "] logged in with entity id " . $this->eid . " at (" . $this->entity->level->getName() . ", " . round($this->entity->x, 2) . ", " . round($this->entity->y, 2) . ", " . round($this->entity->z, 2) . ")"); break; case ProtocolInfo::READY_PACKET: - if($this->loggedIn === false) { + if($this->loggedIn === false){ break; } - switch($packet->status) { + switch($packet->status){ case 1: //Spawn!! - if($this->spawned !== false) { + if($this->spawned !== false){ break; } @@ -1764,8 +1735,8 @@ class Player { //$this->server->schedule(2, [$this->entity, "updateMovement"], [], true); $this->sendArmor(); $array = explode("@n", (string) $this->server->motd); - foreach($array as $msg) { - $this->sendChat($msg . "\n"); + foreach($array as $msg){ + $this->sendChat($msg."\n"); } $this->sendInventory(); @@ -1781,50 +1752,48 @@ class Player { } break; case ProtocolInfo::ROTATE_HEAD_PACKET: - if($this->spawned === false) { + if($this->spawned === false){ break; } - if(($this->entity instanceof Entity)) { - if($this->blocked === true or $this->server->api->handle("player.move", $this->entity) === false) { - if($this->lastCorrect instanceof Vector3 && !$this->entity->dead) { + if(($this->entity instanceof Entity)){ + if($this->blocked === true or $this->server->api->handle("player.move", $this->entity) === false){ + if($this->lastCorrect instanceof Vector3 && !$this->entity->dead){ $this->teleport($this->lastCorrect, $this->entity->yaw, $this->entity->pitch, false); } - } else { + }else{ $this->entity->setPosition($this->entity, $packet->yaw, $this->entity->pitch); } } break; case ProtocolInfo::MOVE_PLAYER_PACKET: - if($this->spawned === false) { + if($this->spawned === false){ break; } - if($this->isSleeping) { - break; - } - if(($this->entity instanceof Entity) and $packet->messageIndex > $this->lastMovement) { + if($this->isSleeping) break; + if(($this->entity instanceof Entity) and $packet->messageIndex > $this->lastMovement){ $this->lastMovement = $packet->messageIndex; $newPos = new Vector3($packet->x, $packet->y, $packet->z); - if($this->forceMovement instanceof Vector3) { - if($this->forceMovement->distance($newPos) <= 0.7) { + if($this->forceMovement instanceof Vector3){ + if($this->forceMovement->distance($newPos) <= 0.7){ $this->forceMovement = false; - } else { + }else{ $this->teleport($this->forceMovement, $this->entity->yaw, $this->entity->pitch, false); break; } } $speed = $this->entity->getSpeedMeasure(); - if($this->blocked === true or ($this->server->api->getProperty("allow-flight") !== true and (($speed > 9 and ($this->gamemode & 0x01) === 0x00) or $speed > 20 or $this->entity->distance($newPos) > 7)) or $this->server->api->handle("player.move", $this->entity) === false) { - if($this->lastCorrect instanceof Vector3 && !$this->entity->dead) { + if($this->blocked === true or ($this->server->api->getProperty("allow-flight") !== true and (($speed > 9 and ($this->gamemode & 0x01) === 0x00) or $speed > 20 or $this->entity->distance($newPos) > 7)) or $this->server->api->handle("player.move", $this->entity) === false){ + if($this->lastCorrect instanceof Vector3 && !$this->entity->dead){ $this->teleport($this->lastCorrect, $this->entity->yaw, $this->entity->pitch, false); } - } else { + }else{ $this->entity->setPosition($newPos, $packet->yaw, $packet->pitch, $packet->bodyYaw); } $this->entity->updateAABB(); } break; case ProtocolInfo::PLAYER_EQUIPMENT_PACKET: - if($this->spawned === false) { + if($this->spawned === false){ break; } $packet->eid = $this->eid; @@ -1833,53 +1802,49 @@ class Player { $data["eid"] = $packet->eid; $data["player"] = $this; - if($packet->slot === 0) { + if($packet->slot === 0){ $data["slot"] = -1; $data["item"] = BlockAPI::getItem(AIR, 0, 0); - if($this->server->handle("player.equipment.change", $data) !== false) { + if($this->server->handle("player.equipment.change", $data) !== false){ $this->slot = -1; } break; - } elseif($packet->slot > 0) { + }elseif($packet->slot > 0){ $packet->slot -= 9; } - if(($this->gamemode & 0x01) === SURVIVAL) { + if(($this->gamemode & 0x01) === SURVIVAL){ $data["item"] = $this->getSlot($packet->slot); - if(!($data["item"] instanceof Item)) { + if(!($data["item"] instanceof Item)){ break; } - } elseif(($this->gamemode & 0x01) === CREATIVE) { + }elseif(($this->gamemode & 0x01) === CREATIVE){ $packet->slot = false; - foreach(BlockAPI::$creative as $i => $d) { - if($d[0] === $packet->item and $d[1] === $packet->meta) { + foreach(BlockAPI::$creative as $i => $d){ + if($d[0] === $packet->item and $d[1] === $packet->meta){ $packet->slot = $i; } } - if($packet->slot !== false) { + if($packet->slot !== false){ $data["item"] = $this->getSlot($packet->slot); - } else { + }else{ break; } - } else { + }else{ break;//????? } $data["slot"] = $packet->slot; - if($this->server->handle("player.equipment.change", $data) !== false) { - if(!Player::$experimentalHotbar) { - $this->slot = $packet->slot; - } - if(($this->gamemode & 0x01) === SURVIVAL) { + if($this->server->handle("player.equipment.change", $data) !== false){ + if(!Player::$experimentalHotbar) $this->slot = $packet->slot; + if(($this->gamemode & 0x01) === SURVIVAL){ $has = false; $slotPos = 0; $packetSlotPos = 0; - for($i = 0; $i < $this->slotCount; ++$i) { - if($this->slot == $this->hotbar[$i]) { - $slotPos = $i; - } - if($packet->slot == $this->hotbar[$i]) { + for($i = 0; $i < $this->slotCount; ++$i){ + if($this->slot == $this->hotbar[$i]) $slotPos = $i; + if($packet->slot == $this->hotbar[$i]){ $packetSlotPos = $i; $has = true; break; @@ -1890,27 +1855,25 @@ class Player { $this->slot = $packet->slot; $this->curHotbarIndex = $packetSlotPos; } - if(!$has) { + if(!$has){ if(Player::$experimentalHotbar) { $this->slot = $packet->slot; $this->hotbar[$this->curHotbarIndex] = $packet->slot; - } else { + }else{ $this->curHotbarIndex = 0; array_pop($this->hotbar); array_unshift($this->hotbar, $this->slot); } } - if(Player::$experimentalHotbar) { - $this->sendInventory(); - } - } else { + if(Player::$experimentalHotbar) $this->sendInventory(); + }else{ $this->slot = $packet->slot; } - } else { + }else{ //$this->sendInventorySlot($packet->slot); $this->sendInventory(); } - if($this->entity->inAction === true) { + if($this->entity->inAction === true){ $this->entity->inAction = false; $this->entity->inActionCounter = 0; $this->entity->updateMetadata(); @@ -1922,13 +1885,13 @@ class Player { //$this->lastChunk = [$packet->chunkX, $packet->chunkZ]; break; case ProtocolInfo::USE_ITEM_PACKET: - if(!($this->entity instanceof Entity)) { + if(!($this->entity instanceof Entity)){ break; } $blockVector = new Vector3($packet->x, $packet->y, $packet->z); - if(($this->spawned === false or $this->blocked === true) and $packet->face >= 0 and $packet->face <= 5) { + if(($this->spawned === false or $this->blocked === true) and $packet->face >= 0 and $packet->face <= 5){ $target = $this->level->getBlock($blockVector); $block = $target->getSide($packet->face); @@ -1968,18 +1931,18 @@ class Player { $data["posY"] = $packet->posY; $data["posZ"] = $packet->posZ; - if($packet->face >= 0 and $packet->face <= 5) { //Use Block, place - if($this->entity->inAction === true) { + if($packet->face >= 0 and $packet->face <= 5){ //Use Block, place + if($this->entity->inAction === true){ $this->entity->inAction = false; $this->entity->inActionCounter = 0; $this->entity->updateMetadata(); } - if($this->blocked === true or ($this->entity->position instanceof Vector3 and $blockVector->distance($this->entity->position) > 10)) { + if($this->blocked === true or ($this->entity->position instanceof Vector3 and $blockVector->distance($this->entity->position) > 10)){ - } elseif($this->getSlot($this->slot)->getID() !== $packet->item or ($this->getSlot($this->slot)->isTool() === false and $this->getSlot($this->slot)->getMetadata() !== $packet->meta)) { + }elseif($this->getSlot($this->slot)->getID() !== $packet->item or ($this->getSlot($this->slot)->isTool() === false and $this->getSlot($this->slot)->getMetadata() !== $packet->meta)){ $this->sendInventorySlot($this->slot); - } else { + }else{ $this->server->api->block->playerBlockAction($this, $blockVector, $packet->face, $packet->fx, $packet->fy, $packet->fz); break; } @@ -2002,17 +1965,17 @@ class Player { $pk->meta = $block->getMetadata(); $this->dataPacket($pk); break; - } elseif($packet->face === 0xff) { + }elseif($packet->face === 0xff){ $slotItem = $this->getHeldItem(); - if($slotItem->getID() == SNOWBALL || $slotItem->getID() == EGG) { //TODO better way + if($slotItem->getID() == SNOWBALL || $slotItem->getID() == EGG){ //TODO better way $x = $packet->x * 0.000030518; $y = $packet->y * 0.000030518; $z = $packet->z * 0.000030518; $d = sqrt($x * $x + $y * $y + $z * $z); - if($d >= 0.0001) { + if($d >= 0.0001){ $shootX = $x / $d; $shootY = $y / $d; $shootZ = $z / $d; @@ -2029,19 +1992,16 @@ class Player { "shootZ" => $shootZ ]; - if($slotItem->getID() == EGG) { + if($slotItem->getID() == EGG){ $e = $this->server->api->entity->add($this->entity->level, ENTITY_OBJECT, OBJECT_EGG, $data); - } else { + }else{ $e = $this->server->api->entity->add($this->level, ENTITY_OBJECT, OBJECT_SNOWBALL, $data); } if(($this->gamemode & 0x01) == 0x0) { - if($slotItem !== false) { - if($slotItem->count == 1) { - $this->inventory[$this->slot] = BlockAPI::getItem(AIR, 0, 0); - } else { - $slotItem->count -= 1; - } + if($slotItem !== false){ + if($slotItem->count == 1) $this->inventory[$this->slot] = BlockAPI::getItem(AIR, 0, 0); + else $slotItem->count -= 1; //$this->sendInventory(); } } @@ -2049,8 +2009,8 @@ class Player { $this->server->api->entity->spawnToAll($e); } - } else { - if($this->server->handle("player.action", $data) !== false) { + }else{ + if($this->server->handle("player.action", $data) !== false){ $this->entity->inAction = true; $this->entity->inActionCounter = 0; $this->startAction = microtime(true); @@ -2060,26 +2020,24 @@ class Player { } break; case ProtocolInfo::PLAYER_ACTION_PACKET: - if($this->spawned === false or $this->blocked === true) { + if($this->spawned === false or $this->blocked === true){ break; } $packet->eid = $this->eid; $this->craftingItems = []; $this->toCraft = []; - switch($packet->action) { + switch($packet->action){ case 5: //Shot arrow - if($this->entity->inAction) { + if($this->entity->inAction){ $arrowSlot = $this->hasItem(ARROW); - if($this->getSlot($this->slot)->getID() === BOW && (($this->gamemode & 0x01) == 0x1 || $arrowSlot !== false)) { - if($this->startAction !== false) { + if($this->getSlot($this->slot)->getID() === BOW && (($this->gamemode & 0x01) == 0x1 || $arrowSlot !== false)){ + if($this->startAction !== false){ $initalPower = $this->entity->inActionCounter; $power = $initalPower / 20; $power = ($power * $power + $power * 2) / 3; - if($power >= 0.1) { - if($power > 1) { - $power = 1; - } + if($power >= 0.1){ + if($power > 1) $power = 1; $this->server->dhandle("player.shoot", [ "player" => $this, "power" => &$power, @@ -2112,7 +2070,7 @@ class Player { $this->server->api->entity->spawnToAll($e); if(($this->gamemode & 0x01) == 0x0) { $bow = $this->getSlot($this->slot); - if(++$bow->meta >= $bow->getMaxDurability()) { + if(++$bow->meta >= $bow->getMaxDurability()){ $this->inventory[$this->slot] = BlockAPI::getItem(AIR, 0, 0); } $this->removeItem(ARROW, 0, 1, false); @@ -2120,7 +2078,7 @@ class Player { } } } - } else { //inv desynced, resend + }else{ //inv desynced, resend $this->sendInventory(); } } @@ -2135,7 +2093,7 @@ class Player { break; case ProtocolInfo::REMOVE_BLOCK_PACKET: $blockVector = new Vector3($packet->x, $packet->y, $packet->z); - if($this->spawned === false or $this->blocked === true or $this->entity->distance($blockVector) > 8) { + if($this->spawned === false or $this->blocked === true or $this->entity->distance($blockVector) > 8){ $target = $this->level->getBlock($blockVector); $pk = new UpdateBlockPacket; @@ -2152,46 +2110,46 @@ class Player { $this->server->api->block->playerBlockBreak($this, $blockVector); break; case ProtocolInfo::PLAYER_ARMOR_EQUIPMENT_PACKET: - if($this->spawned === false or $this->blocked === true) { + if($this->spawned === false or $this->blocked === true){ break; } $this->craftingItems = []; $this->toCraft = []; $packet->eid = $this->eid; - for($i = 0; $i < 4; ++$i) { + for($i = 0; $i < 4; ++$i){ $s = $packet->slots[$i]; - if($s === 0 or $s === 255) { + if($s === 0 or $s === 255){ $s = BlockAPI::getItem(AIR, 0, 0); - } else { + }else{ $s = BlockAPI::getItem($s + 256, 0, 1); } $slot = $this->armor[$i]; - if($slot->getID() !== AIR and $s->getID() === AIR) { + if($slot->getID() !== AIR and $s->getID() === AIR){ $this->addItem($slot->getID(), $slot->getMetadata(), 1, false); $this->armor[$i] = BlockAPI::getItem(AIR, 0, 0); $packet->slots[$i] = 255; - } elseif($s->getID() !== AIR and $slot->getID() === AIR and ($sl = $this->hasItem($s->getID())) !== false) { + }elseif($s->getID() !== AIR and $slot->getID() === AIR and ($sl = $this->hasItem($s->getID())) !== false){ $this->armor[$i] = $this->getSlot($sl); $this->setSlot($sl, BlockAPI::getItem(AIR, 0, 0), false); - } elseif($s->getID() !== AIR and $slot->getID() !== AIR and ($slot->getID() !== $s->getID() or $slot->getMetadata() !== $s->getMetadata()) and ($sl = $this->hasItem($s->getID())) !== false) { + }elseif($s->getID() !== AIR and $slot->getID() !== AIR and ($slot->getID() !== $s->getID() or $slot->getMetadata() !== $s->getMetadata()) and ($sl = $this->hasItem($s->getID())) !== false){ $item = $this->armor[$i]; $this->armor[$i] = $this->getSlot($sl); $this->setSlot($sl, $item, false); - } else { + }else{ $packet->slots[$i] = 255; } } $this->sendArmor(); - if($this->entity->inAction === true) { + if($this->entity->inAction === true){ $this->entity->inAction = false; $this->entity->inActionCounter = 0; $this->entity->updateMetadata(); } break; case ProtocolInfo::INTERACT_PACKET: - if($this->spawned === false) { + if($this->spawned === false){ break; } $packet->eid = $this->eid; @@ -2202,28 +2160,28 @@ class Player { $this->craftingItems = []; $this->toCraft = []; $target = $this->server->api->entity->get($packet->target); - if($target instanceof Entity and $this->entity instanceof Entity and $this->gamemode !== VIEW and $this->blocked === false and ($target instanceof Entity) and $this->entity->distance($target) <= 8) { + if($target instanceof Entity and $this->entity instanceof Entity and $this->gamemode !== VIEW and $this->blocked === false and ($target instanceof Entity) and $this->entity->distance($target) <= 8){ $data["targetentity"] = $packet->target; $data["entity"] = $this->entity; $data["player"] = $this; - if($this->server->handle("player.interact", $data) !== false) { + if($this->server->handle("player.interact", $data) !== false){ $target->interactWith($this->entity, $packet->action); } } break; case ProtocolInfo::ANIMATE_PACKET: - if($this->spawned === false) { + if($this->spawned === false){ break; } $packet->eid = $this->eid; $this->server->api->dhandle("entity.animate", ["eid" => $packet->eid, "entity" => $this->entity, "action" => $packet->action]); break; case ProtocolInfo::RESPAWN_PACKET: - if($this->spawned === false) { + if($this->spawned === false){ break; } - if(@$this->entity->dead === false) { + if(@$this->entity->dead === false){ break; } $this->craftingItems = []; @@ -2240,18 +2198,18 @@ class Player { $pk->yaw = $this->entity->yaw; $pk->pitch = $this->entity->pitch; $pk->bodyYaw = $this->entity->headYaw; - foreach($this->entity->level->players as $player) { - if($player->entity->eid != $this->entity->eid) { + foreach($this->entity->level->players as $player){ + if($player->entity->eid != $this->entity->eid){ $player->dataPacket(clone $pk); } } - if($this->entity instanceof Entity) { + if($this->entity instanceof Entity){ $this->entity->fire = 0; $this->entity->air = $this->entity->maxAir; $this->entity->setHealth(20, "respawn", true); $this->entity->updateMetadata(); - } else { + }else{ break; } $this->sendInventory(); @@ -2261,22 +2219,22 @@ class Player { case ProtocolInfo::SET_HEALTH_PACKET: //Not used break; case ProtocolInfo::ENTITY_EVENT_PACKET: - if($this->spawned === false or $this->blocked === true) { + if($this->spawned === false or $this->blocked === true){ break; } $this->craftingItems = []; $this->toCraft = []; $packet->eid = $this->eid; - if($this->entity->inAction === true) { + if($this->entity->inAction === true){ $this->entity->inAction = false; $this->entity->inActionCounter = 0; $this->entity->updateMetadata(); } - switch($packet->event) { + switch($packet->event){ case 9: //Eating $slot = $this->getSlot($this->slot); $foodHeal = Item::getFoodHeal($slot->getID()); - if($this->entity->getHealth() < 20 && $foodHeal != 0) { + if($this->entity->getHealth() < 20 && $foodHeal != 0){ $pk = new EntityEventPacket; $pk->eid = 0; $pk->event = 9; @@ -2284,10 +2242,10 @@ class Player { $this->entity->heal($foodHeal, "eating"); --$slot->count; - if($slot->count <= 0) { + if($slot->count <= 0){ $this->setSlot($this->slot, BlockAPI::getItem(AIR, 0, 0), false); } - if($slot->getID() === MUSHROOM_STEW or $slot->getID() === BEETROOT_SOUP) { + if($slot->getID() === MUSHROOM_STEW or $slot->getID() === BEETROOT_SOUP){ $this->addItem(BOWL, 0, 1, false); } } @@ -2295,11 +2253,11 @@ class Player { } break; case ProtocolInfo::DROP_ITEM_PACKET: - if($this->spawned === false or $this->blocked === true) { + if($this->spawned === false or $this->blocked === true){ break; } - if($this->gamemode & 0x01 == 1) { + if($this->gamemode & 0x01 == 1){ ConsoleAPI::warn("{$this->iusername} tried dropping item while in creative!"); return; } @@ -2309,18 +2267,16 @@ class Player { $packet->item = $this->getSlot($this->slot); $sendOnDrop = false; - if($prevItem->getID() != $packet->item->getID() || $prevItem->getMetadata() != $packet->item->getMetadata()) { - if(count($this->inventory) >= 36) { - foreach($this->inventory as $slot => $item) { - if($item->getID() == 0) { - goto inv_desync_on_drop; - } + if($prevItem->getID() != $packet->item->getID() || $prevItem->getMetadata() != $packet->item->getMetadata()){ + if(count($this->inventory) >= 36){ + foreach($this->inventory as $slot => $item){ + if($item->getID() == 0) goto inv_desync_on_drop; } $this->toCraft[] = $prevItem; //vanilla drops only result? $this->lastCraft = microtime(true); break; - } else { + }else{ inv_desync_on_drop: ConsoleAPI::debug("Inventory desync on drop({$this->iusername})"); $sendOnDrop = true; @@ -2333,7 +2289,7 @@ class Player { $data["unknown"] = $packet->unknown; $data["item"] = $packet->item; $data["player"] = $this; - if($this->blocked === false and $this->server->handle("player.drop", $data) !== false) { + if($this->blocked === false and $this->server->handle("player.drop", $data) !== false){ $f1 = 0.3; $sX = -sin(($this->entity->yaw / 180) * M_PI) * cos(($this->entity->pitch / 180) * M_PI) * $f1; $sZ = cos(($this->entity->yaw / 180) * M_PI) * cos(($this->entity->pitch / 180) * M_PI) * $f1; @@ -2346,33 +2302,33 @@ class Player { $sZ += sin($f3) * $f1; $this->server->api->entity->dropRawPos($this->level, $this->entity->x, $this->entity->y - 0.3 + $this->entity->height - 0.12, $this->entity->z, $packet->item, $sX, $sY, $sZ); $this->setSlot($this->slot, BlockAPI::getItem(AIR, 0, 0), $sendOnDrop); - } else { + }else{ $this->sendInventory(); //send if blocked } - if($this->entity->inAction === true) { + if($this->entity->inAction === true){ $this->entity->inAction = false; $this->entity->inActionCounter = 0; $this->entity->updateMetadata(); } break; case ProtocolInfo::MESSAGE_PACKET: - if($this->spawned === false) { + if($this->spawned === false){ break; } $this->craftingItems = []; $this->toCraft = []; - if(trim($packet->message) != "" and strlen($packet->message) <= 255) { + if(trim($packet->message) != "" and strlen($packet->message) <= 255){ $message = $packet->message; - if($message[0] === "/") { //Command - if($this instanceof Player) { + if($message[0] === "/"){ //Command + if($this instanceof Player){ console("[DEBUG] " . FORMAT_AQUA . $this->username . FORMAT_RESET . " issued server command: " . $message); - } else { + }else{ console("[DEBUG] " . FORMAT_YELLOW . "*" . $this . FORMAT_RESET . " issued server command: " . $message); } $this->server->api->console->run(substr($message, 1), $this); - } else { + }else{ $data = ["player" => $this, "message" => $message]; - if(Utils::hasEmoji($data["message"])) { + if(Utils::hasEmoji($data["message"])){ $this->sendChat("Your message contains illegal characters"); break; } @@ -2381,11 +2337,11 @@ class Player { // Living::$pathfind = !Living::$pathfind; //} - if($this->server->api->handle("player.chat", $data) !== false) { + if($this->server->api->handle("player.chat", $data) !== false){ $this->server->send2Discord("<" . $this->username . "> " . $message); - if(isset($data["message"])) { + if(isset($data["message"])){ $this->server->api->chat->send($this, $data["message"]); - } else { + }else{ $this->server->api->chat->send($this, $message); } } @@ -2393,14 +2349,14 @@ class Player { } break; case ProtocolInfo::CONTAINER_CLOSE_PACKET: - if($this->spawned === false) { + if($this->spawned === false){ break; } $this->craftingItems = []; $this->toCraft = []; - if(isset($this->windows[$packet->windowid])) { - if(is_array($this->windows[$packet->windowid])) { - foreach($this->windows[$packet->windowid] as $ob) { + if(isset($this->windows[$packet->windowid])){ + if(is_array($this->windows[$packet->windowid])){ + foreach($this->windows[$packet->windowid] as $ob){ $pk = new TileEventPacket; $pk->x = $ob->x; $pk->y = $ob->y; @@ -2409,7 +2365,7 @@ class Player { $pk->case2 = 0; $this->server->api->player->broadcastPacket($this->level->players, $pk); } - } elseif($this->windows[$packet->windowid]->class === TILE_CHEST) { + }elseif($this->windows[$packet->windowid]->class === TILE_CHEST){ $pk = new TileEventPacket; $pk->x = $this->windows[$packet->windowid]->x; $pk->y = $this->windows[$packet->windowid]->y; @@ -2426,36 +2382,36 @@ class Player { $this->dataPacket($pk); break; case ProtocolInfo::CONTAINER_SET_SLOT_PACKET: - if($this->spawned === false or $this->blocked === true) { + if($this->spawned === false or $this->blocked === true){ break; } - if($this->lastCraft <= (microtime(true) - 1)) { - if(isset($this->toCraft[-1])) { + if($this->lastCraft <= (microtime(true) - 1)){ + if(isset($this->toCraft[-1])){ $this->toCraft = [-1 => $this->toCraft[-1]]; - } else { + }else{ $this->toCraft = []; } $this->craftingItems = []; } - if($packet->windowid === 0) { + if($packet->windowid === 0){ $craft = false; $slot = $this->getSlot($packet->slot); - if($slot->count >= $packet->item->count and (($slot->getID() === $packet->item->getID() and $slot->getMetadata() === $packet->item->getMetadata()) or ($packet->item->getID() === AIR and $packet->item->count === 0)) and !isset($this->craftingItems[$packet->slot])) { //Crafting recipe + if($slot->count >= $packet->item->count and (($slot->getID() === $packet->item->getID() and $slot->getMetadata() === $packet->item->getMetadata()) or ($packet->item->getID() === AIR and $packet->item->count === 0)) and !isset($this->craftingItems[$packet->slot])){ //Crafting recipe $use = BlockAPI::getItem($slot->getID(), $slot->getMetadata(), $slot->count - $packet->item->count); $this->craftingItems[$packet->slot] = $use; $craft = true; - } elseif($slot->count <= $packet->item->count and ($slot->getID() === AIR or ($slot->getID() === $packet->item->getID() and $slot->getMetadata() === $packet->item->getMetadata()))) { //Crafting final + }elseif($slot->count <= $packet->item->count and ($slot->getID() === AIR or ($slot->getID() === $packet->item->getID() and $slot->getMetadata() === $packet->item->getMetadata()))){ //Crafting final $craftItem = BlockAPI::getItem($packet->item->getID(), $packet->item->getMetadata(), $packet->item->count - $slot->count); - if(count($this->toCraft) === 0) { + if(count($this->toCraft) === 0){ $this->toCraft[-1] = 0; } $this->toCraft[$packet->slot] = $craftItem; $craft = true; - } elseif(((count($this->toCraft) === 1 and isset($this->toCraft[-1])) or count($this->toCraft) === 0) and $slot->count > 0 and $slot->getID() > AIR and ($slot->getID() !== $packet->item->getID() or $slot->getMetadata() !== $packet->item->getMetadata())) { //Crafting final + }elseif(((count($this->toCraft) === 1 and isset($this->toCraft[-1])) or count($this->toCraft) === 0) and $slot->count > 0 and $slot->getID() > AIR and ($slot->getID() !== $packet->item->getID() or $slot->getMetadata() !== $packet->item->getMetadata())){ //Crafting final $craftItem = BlockAPI::getItem($packet->item->getID(), $packet->item->getMetadata(), $packet->item->count); - if(count($this->toCraft) === 0) { + if(count($this->toCraft) === 0){ $this->toCraft[-1] = 0; } $use = BlockAPI::getItem($slot->getID(), $slot->getMetadata(), $slot->count); @@ -2464,38 +2420,38 @@ class Player { $craft = true; } - if($craft === true) { + if($craft === true){ $this->lastCraft = microtime(true); } - if($craft === true and count($this->craftingItems) > 0 and count($this->toCraft) > 0 and ($recipe = $this->craftItems($this->toCraft, $this->craftingItems, $this->toCraft[-1])) !== true) { - if($recipe === false) { + if($craft === true and count($this->craftingItems) > 0 and count($this->toCraft) > 0 and ($recipe = $this->craftItems($this->toCraft, $this->craftingItems, $this->toCraft[-1])) !== true){ + if($recipe === false){ $this->sendInventory(); $this->toCraft = []; - } else { + }else{ $this->toCraft = [-1 => $this->toCraft[-1]]; } $this->craftingItems = []; } - } else { + }else{ $this->toCraft = []; $this->craftingItems = []; } - if(!isset($this->windows[$packet->windowid])) { + if(!isset($this->windows[$packet->windowid])){ break; } - if(is_array($this->windows[$packet->windowid])) { + if(is_array($this->windows[$packet->windowid])){ $tiles = $this->windows[$packet->windowid]; - if($packet->slot >= 0 and $packet->slot < CHEST_SLOTS) { + if($packet->slot >= 0 and $packet->slot < CHEST_SLOTS){ $tile = $tiles[0]; $slotn = $packet->slot; $offset = 0; - } elseif($packet->slot >= CHEST_SLOTS and $packet->slot <= (CHEST_SLOTS << 1)) { + }elseif($packet->slot >= CHEST_SLOTS and $packet->slot <= (CHEST_SLOTS << 1)){ $tile = $tiles[1]; $slotn = $packet->slot - CHEST_SLOTS; $offset = CHEST_SLOTS; - } else { + }else{ break; } @@ -2509,7 +2465,7 @@ class Player { "slotdata" => $slot, "itemdata" => $item, "player" => $this - ]) === false) { + ]) === false){ $pk = new ContainerSetSlotPacket; $pk->windowid = $packet->windowid; $pk->slot = $packet->slot; @@ -2518,24 +2474,24 @@ class Player { break; } - if($item->getID() !== AIR and $slot->getID() == $item->getID()) { - if($slot->count < $item->count) { - if($this->removeItem($item->getID(), $item->getMetadata(), $item->count - $slot->count, false) === false) { + if($item->getID() !== AIR and $slot->getID() == $item->getID()){ + if($slot->count < $item->count){ + if($this->removeItem($item->getID(), $item->getMetadata(), $item->count - $slot->count, false) === false){ break; } - } elseif($slot->count > $item->count) { + }elseif($slot->count > $item->count){ $this->addItem($item->getID(), $item->getMetadata(), $slot->count - $item->count, false); } - } else { - if($this->removeItem($item->getID(), $item->getMetadata(), $item->count, false) === false) { + }else{ + if($this->removeItem($item->getID(), $item->getMetadata(), $item->count, false) === false){ break; } $this->addItem($slot->getID(), $slot->getMetadata(), $slot->count, false); } $tile->setSlot($slotn, $item, true, $offset); - } else { + }else{ $tile = $this->windows[$packet->windowid]; - if(($tile->class !== TILE_CHEST and $tile->class !== TILE_FURNACE) or $packet->slot < 0 or ($tile->class === TILE_CHEST and $packet->slot >= CHEST_SLOTS) or ($tile->class === TILE_FURNACE and $packet->slot >= FURNACE_SLOTS)) { + if(($tile->class !== TILE_CHEST and $tile->class !== TILE_FURNACE) or $packet->slot < 0 or ($tile->class === TILE_CHEST and $packet->slot >= CHEST_SLOTS) or ($tile->class === TILE_FURNACE and $packet->slot >= FURNACE_SLOTS)){ break; } $item = BlockAPI::getItem($packet->item->getID(), $packet->item->getMetadata(), $packet->item->count); @@ -2547,7 +2503,7 @@ class Player { "slotdata" => $slot, "itemdata" => $item, "player" => $this, - ]) === false) { + ]) === false){ $pk = new ContainerSetSlotPacket; $pk->windowid = $packet->windowid; $pk->slot = $packet->slot; @@ -2556,24 +2512,24 @@ class Player { break; } - if($tile->class === TILE_FURNACE and $packet->slot == 2) { - switch($slot->getID()) { + if($tile->class === TILE_FURNACE and $packet->slot == 2){ + switch($slot->getID()){ case IRON_INGOT: AchievementAPI::grantAchievement($this, "acquireIron"); break; } } - if($item->getID() !== AIR and $slot->getID() == $item->getID()) { - if($slot->count < $item->count) { - if($this->removeItem($item->getID(), $item->getMetadata(), $item->count - $slot->count, false) === false) { + if($item->getID() !== AIR and $slot->getID() == $item->getID()){ + if($slot->count < $item->count){ + if($this->removeItem($item->getID(), $item->getMetadata(), $item->count - $slot->count, false) === false){ break; } - } elseif($slot->count > $item->count) { + }elseif($slot->count > $item->count){ $this->addItem($item->getID(), $item->getMetadata(), $slot->count - $item->count, false); } - } else { - if($this->removeItem($item->getID(), $item->getMetadata(), $item->count, false) === false) { + }else{ + if($this->removeItem($item->getID(), $item->getMetadata(), $item->count, false) === false){ break; } $this->addItem($slot->getID(), $slot->getMetadata(), $slot->count, false); @@ -2583,27 +2539,27 @@ class Player { } break; case ProtocolInfo::SEND_INVENTORY_PACKET: - if($this->spawned === false) { + if($this->spawned === false){ break; } break; case ProtocolInfo::ENTITY_DATA_PACKET: - if($this->spawned === false or $this->blocked === true) { + if($this->spawned === false or $this->blocked === true){ break; } $this->craftingItems = []; $this->toCraft = []; $t = $this->server->api->tile->get(new Position($packet->x, $packet->y, $packet->z, $this->level)); - if(($t instanceof Tile) and $t->class === TILE_SIGN) { - if($t->data["creator"] !== $this->username) { + if(($t instanceof Tile) and $t->class === TILE_SIGN){ + if($t->data["creator"] !== $this->username){ $t->spawn($this); - } else { + }else{ $nbt = new NBT(); $nbt->load($packet->namedtag); $d = array_shift($nbt->tree); - if($d["id"] !== TILE_SIGN) { + if($d["id"] !== TILE_SIGN){ $t->spawn($this); - } else { + }else{ $t->setText($d["Text1"], $d["Text2"], $d["Text3"], $d["Text4"]); } } @@ -2615,11 +2571,11 @@ class Player { $this->entity->moveForward = $packet->moveForward; $this->entity->moveStrafing = $packet->moveStrafe; - if(strlen(bin2hex($packet->buffer)) === 24 && $this->entity->linkedEntity != 0) { + if(strlen(bin2hex($packet->buffer)) === 24 && $this->entity->linkedEntity != 0){ $this->entity->stopRiding(); break; } - if($this->entity->linkedEntity != 0) { //TODO better riding + if($this->entity->linkedEntity != 0){ //TODO better riding $e = $this->entity->level->entityList[$this->entity->linkedEntity] ?? false; if($e === false) { ConsoleAPI::warn("Player is riding on entity that doesnt exist in world! ({$this->iusername}, {$this->entity->linkedEntity})"); @@ -2652,45 +2608,45 @@ class Player { * @return Item */ - public function getHeldItem() { + public function getHeldItem(){ return $this->getSlot($this->slot); } - public function stopSleep() { + public function stopSleep(){ $this->isSleeping = false; $this->sleepingTime = 0; - if($this->entity instanceof Entity) { + if($this->entity instanceof Entity){ $this->entity->updateMetadata(); } } - public function hasItem($type, $damage = false) { - foreach($this->inventory as $s => $item) { - if($item->getID() === $type and ($item->getMetadata() === $damage or $damage === false) and $item->count > 0) { + public function hasItem($type, $damage = false){ + foreach($this->inventory as $s => $item){ + if($item->getID() === $type and ($item->getMetadata() === $damage or $damage === false) and $item->count > 0){ return $s; } } return false; } - public function removeItem($type, $damage, $count, $send = true) { - while($count > 0) { + public function removeItem($type, $damage, $count, $send = true){ + while($count > 0){ $remove = 0; - foreach($this->inventory as $s => $item) { - if($item->getID() === $type and $item->getMetadata() === $damage) { + foreach($this->inventory as $s => $item){ + if($item->getID() === $type and $item->getMetadata() === $damage){ $remove = min($count, $item->count); - if($remove < $item->count) { + if($remove < $item->count){ $item->count -= $remove; - } else { + }else{ $this->inventory[$s] = BlockAPI::getItem(AIR, 0, 0); } - if($send === true) { + if($send === true){ $this->sendInventorySlot($s); } break; } } - if($remove <= 0) { + if($remove <= 0){ return false; } $count -= $remove; @@ -2702,16 +2658,16 @@ class Player { * * @return array|bool */ - public function craftItems(array $craft, array $recipe, $type) { + public function craftItems(array $craft, array $recipe, $type){ $craftItem = [0, true, 0]; unset($craft[-1]); - foreach($craft as $slot => $item) { - if($item instanceof Item) { + foreach($craft as $slot => $item){ + if($item instanceof Item){ $craftItem[0] = $item->getID(); - if($item->getMetadata() !== $craftItem[1] and $craftItem[1] !== true) { + if($item->getMetadata() !== $craftItem[1] and $craftItem[1] !== true){ $craftItem[1] = false; - } else { + }else{ $craftItem[1] = $item->getMetadata(); } $craftItem[2] += $item->count; @@ -2720,11 +2676,11 @@ class Player { } $recipeItems = []; - foreach($recipe as $slot => $item) { - if(!isset($recipeItems[$item->getID()])) { + foreach($recipe as $slot => $item){ + if(!isset($recipeItems[$item->getID()])){ $recipeItems[$item->getID()] = [$item->getID(), $item->getMetadata(), $item->count]; - } else { - if($item->getMetadata() !== $recipeItems[$item->getID()][1]) { + }else{ + if($item->getMetadata() !== $recipeItems[$item->getID()][1]){ $recipeItems[$item->getID()][1] = false; } $recipeItems[$item->getID()][2] += $item->count; @@ -2733,31 +2689,31 @@ class Player { $res = CraftingRecipes::canCraft($craftItem, $recipeItems, $type); - if(!is_array($res) and $type === 1) { + if(!is_array($res) and $type === 1){ $res2 = CraftingRecipes::canCraft($craftItem, $recipeItems, 0); - if(is_array($res2)) { + if(is_array($res2)){ $res = $res2; } } - if(is_array($res)) { - if($this->server->api->dhandle("player.craft", ["player" => $this, "recipe" => $recipe, "craft" => $craft, "type" => $type]) === false) { + if(is_array($res)){ + if($this->server->api->dhandle("player.craft", ["player" => $this, "recipe" => $recipe, "craft" => $craft, "type" => $type]) === false){ return false; } - foreach($recipe as $slot => $item) { + foreach($recipe as $slot => $item){ $s = $this->getSlot($slot); $s->count -= $item->count; - if($s->count <= 0) { + if($s->count <= 0){ $this->setSlot($slot, BlockAPI::getItem(AIR, 0, 0), false); } } - foreach($craft as $slot => $item) { + foreach($craft as $slot => $item){ $s = $this->getSlot($slot); - if($s->count <= 0 or $s->getID() === AIR) { + if($s->count <= 0 or $s->getID() === AIR){ $this->setSlot($slot, BlockAPI::getItem($item->getID(), $item->getMetadata(), $item->count), false); - } elseif($s->getID() == $item->getID() && $s->getMetadata() == $item->getMetadata() && ($s->count + $item->count) <= $s->getMaxStackSize()) { + }elseif($s->getID() == $item->getID() && $s->getMetadata() == $item->getMetadata() && ($s->count + $item->count) <= $s->getMaxStackSize()){ $this->setSlot($slot, BlockAPI::getItem($item->getID(), $item->getMetadata(), $s->count + $item->count), false); - } else { + }else{ $f1 = 0.3; $sX = -sin(($this->entity->yaw / 180) * M_PI) * cos(($this->entity->pitch / 180) * M_PI) * $f1; $sZ = cos(($this->entity->yaw / 180) * M_PI) * cos(($this->entity->pitch / 180) * M_PI) * $f1; @@ -2773,7 +2729,7 @@ class Player { $this->sendInventory(); //force send on crafting - switch($item->getID()) { + switch($item->getID()){ case WORKBENCH: AchievementAPI::grantAchievement($this, "buildWorkBench"); break; @@ -2812,26 +2768,26 @@ class Player { return $res; } - public function handlePacket(RakNetPacket $packet) { - if($this->connected === true) { + public function handlePacket(RakNetPacket $packet){ + if($this->connected === true){ $time = microtime(true); $this->timeout = $time + 20; - switch($packet->pid()) { + switch($packet->pid()){ case RakNetInfo::NACK: - foreach($packet->packets as $count) { - if(isset($this->recoveryQueue[$count])) { + foreach($packet->packets as $count){ + if(isset($this->recoveryQueue[$count])){ $this->resendQueue[$count] = &$this->recoveryQueue[$count]; $this->lag[] = $time - $this->recoveryQueue[$count]->sendtime; unset($this->recoveryQueue[$count]); - } else { + }else{ ++$this->packetStats[1]; //lost and wont be recovered } } break; case RakNetInfo::ACK: - foreach($packet->packets as $count) { - if(isset($this->recoveryQueue[$count])) { + foreach($packet->packets as $count){ + if(isset($this->recoveryQueue[$count])){ $this->lag[] = $time - $this->recoveryQueue[$count]->sendtime; unset($this->recoveryQueue[$count]); unset($this->resendQueue[$count]); @@ -2858,7 +2814,7 @@ class Player { case RakNetInfo::DATA_PACKET_F: $this->ackQueue[] = $packet->seqNumber; $this->receiveQueue[$packet->seqNumber] = []; - foreach($packet->data as $pk) { + foreach($packet->data as $pk){ $this->receiveQueue[$packet->seqNumber][] = $pk; } break; @@ -2866,9 +2822,9 @@ class Player { } } - public function damageArmorPart($slot, $part) { + public function damageArmorPart($slot, $part){ $part->useOn($this->entity, true); - if($part->getMetadata() >= $part->getMaxDurability()) { + if($part->getMetadata() >= $part->getMaxDurability()){ $this->setArmor($slot, BlockAPI::getItem(AIR, 0, 0), false); return; } @@ -2878,8 +2834,8 @@ class Player { /** * @return string */ - public function __toString() { - if($this->username != "") { + function __toString(){ + if($this->username != ""){ return $this->username; } return $this->clientID; @@ -2887,9 +2843,9 @@ class Player { } -class PlayerNull extends Player { +class PlayerNull extends Player{ public static $INSTANCE; - public function __construct() { + public function __construct(){ } } diff --git a/src/PocketMinecraftServer.php b/src/PocketMinecraftServer.php index ae369d6e..b0ae2dc8 100644 --- a/src/PocketMinecraftServer.php +++ b/src/PocketMinecraftServer.php @@ -1,69 +1,18 @@ port = (int) $port; $this->doTick = true; $this->gamemode = (int) $gamemode; @@ -77,7 +26,7 @@ class PocketMinecraftServer { public static $SAVE_PLAYER_DATA = true; - private function load() { + private function load(){ global $dolog; /*if(defined("DEBUG") and DEBUG >= 0){ @cli_set_process_title("NostalgiaCore ".MAJOR_VERSION); @@ -120,7 +69,7 @@ class PocketMinecraftServer { $this->interface = new MinecraftInterface("255.255.255.255", $this->port, $this->serverip); $this->stop = false; $this->ticks = 0; - if(!defined("NO_THREADS")) { + if(!defined("NO_THREADS")){ $this->asyncThread = new AsyncMultipleQueue(); } console("[INFO] Loading extra.properties..."); @@ -157,24 +106,24 @@ class PocketMinecraftServer { MobController::$ADVANCED = $this->extraprops->get("experimental-mob-ai"); Explosion::$enableExplosions = $this->extraprops->get("enable-explosions"); NetherReactorBlock::$enableReactor = $this->extraprops->get("enable-nether-reactor"); - if(self::$FORCE_20_TPS) { + if(self::$FORCE_20_TPS){ ConsoleAPI::warn("Forcing 20 tps. This may result in higher CPU usage!"); } - if($this->extraprops->get("discord-msg")) { - if($this->extraprops->get("discord-webhook-url") !== "none") { + if($this->extraprops->get("discord-msg")){ + if($this->extraprops->get("discord-webhook-url") !== "none"){ console("[INFO] Discord Logger is enabled."); - } else { + }else{ console("[WARNING] Discord Logger is enabled in extra.properties,"); console("[WARNING] but you didn't put the webhook url, so it won't work."); } - } elseif($this->extraprops->get("version") == null) { + }elseif($this->extraprops->get("version") == null){ console("[WARNING] Your extra.properties file is corrupted!"); console("[WARNING] To fix it - just remove it! Server will generate it again automatically."); } $dolog = $this->extraprops->get("save-console-data"); } - public function onShutdown() { + public function onShutdown(){ console("[INFO] Saving..."); $save = $this->saveEnabled; $this->saveEnabled = true; @@ -182,7 +131,7 @@ class PocketMinecraftServer { $this->saveEnabled = $save; } - public function startDatabase() { + public function startDatabase(){ $this->preparedSQL = new stdClass(); $this->preparedSQL->entity = new stdClass(); $this->database = new SQLite3(":memory:"); @@ -204,16 +153,16 @@ class PocketMinecraftServer { $this->preparedSQL->entity->setLevel = $this->database->prepare("UPDATE entities SET level = :level WHERE EID = :eid ;"); } - public function query($sql, $fetch = false) { + public function query($sql, $fetch = false){ $result = $this->database->query($sql) or console("[ERROR] [SQL Error] " . $this->database->lastErrorMsg() . ". Query: " . $sql, true, true, 0); - if($fetch === true and ($result instanceof SQLite3Result)) { + if($fetch === true and ($result instanceof SQLite3Result)){ $result = $result->fetchArray(SQLITE3_ASSOC); } return $result; } - public function setType($type = "normal") { - switch(trim(strtolower($type))) { + public function setType($type = "normal"){ + switch(trim(strtolower($type))){ case "normal": case "demo": $this->serverType = "MCCPP;Demo;"; @@ -224,9 +173,9 @@ class PocketMinecraftServer { } } - public function titleTick() { + public function titleTick(){ $time = microtime(true); - if(defined("DEBUG") and DEBUG >= 0) { + if(defined("DEBUG") and DEBUG >= 0){ //echo "\x1b]0;NostalgiaCore " . MAJOR_VERSION . " | Online " . count($this->clients) . "/" . $this->maxClients . " | RAM " . round((memory_get_usage() / 1024) / 1024, 2) . "MB | U " . round(($this->interface->bandwidth[1] / max(1, $time - $this->interface->bandwidth[2])) / 1024, 2) . " D " . round(($this->interface->bandwidth[0] / max(1, $time - $this->interface->bandwidth[2])) / 1024, 2) . " kB/s | TPS " . $this->getTPS() . "\x07"; } @@ -236,18 +185,18 @@ class PocketMinecraftServer { /** * @return float */ - public function getTPS() { + public function getTPS(){ $v = array_values($this->tickMeasure); $divval = ($v[39] - $v[0]); - if($divval === 0) { + if($divval === 0){ return 0; } $tps = 40 / $divval; return round($tps, 4); } - public function checkTicks() { - if($this->getTPS() < 12) { + public function checkTicks(){ + if($this->getTPS() < 12){ console("[WARNING] Can't keep up! Is the server overloaded?"); } } @@ -255,14 +204,14 @@ class PocketMinecraftServer { /** * @param string $reason */ - public function close($reason = "server stop") { + public function close($reason = "server stop"){ $this->onShutdown(); - if($this->stop !== true) { - if(is_int($reason)) { + if($this->stop !== true){ + if(is_int($reason)){ $reason = "signal stop"; } - if(($this->api instanceof ServerAPI) === true) { - if(($this->api->chat instanceof ChatAPI) === true) { + if(($this->api instanceof ServerAPI) === true){ + if(($this->api->chat instanceof ChatAPI) === true){ $this->api->chat->send(false, "Stopping server..."); self::$_tmp = new StopMessageThread($this, "[INFO] Stopping server..."); //broadcast didnt want to send message to discord for some reason } @@ -270,8 +219,8 @@ class PocketMinecraftServer { $this->stop = true; $this->trigger("server.close", $reason); $this->interface->close(); - if(!defined("NO_THREADS")) { - $this->asyncThread->synchronized(function ($t) { + if(!defined("NO_THREADS")){ + $this->asyncThread->synchronized(function ($t){ $t->stop = true; $t->notify(); }, $this->asyncThread); @@ -280,8 +229,8 @@ class PocketMinecraftServer { release_lock(); } - public function send2Discord($msg) { - if($this->extraprops->get("discord-msg") and $this->extraprops->get("discord-webhook-url") !== "none") { + public function send2Discord($msg){ + if($this->extraprops->get("discord-msg") and $this->extraprops->get("discord-webhook-url") !== "none"){ $url = $this->extraprops->get("discord-webhook-url"); $name = $this->extraprops->get("discord-bot-name"); $this->asyncOperation(ASYNC_CURL_POST, [ @@ -294,15 +243,15 @@ class PocketMinecraftServer { } } - public function asyncOperation($type, array $data, callable $callable = null) { - if(defined("NO_THREADS")) { + public function asyncOperation($type, array $data, callable $callable = null){ + if(defined("NO_THREADS")){ return false; } $d = ""; $type = (int) $type; - switch($type) { + switch($type){ case ASYNC_CURL_GET: - if(isset($data["headers"])) { + if(isset($data["headers"])){ $jsstr = json_encode($data["headers"]); } $d .= Utils::writeShort(strlen($data["url"])) . $data["url"] . (isset($data["timeout"]) ? Utils::writeShort($data["timeout"]) : Utils::writeShort(10)) . (isset($data["headers"]) ? Utils::writeShort(strlen($jsstr)) . $jsstr : Utils::writeShort(1) . " "); @@ -310,7 +259,7 @@ class PocketMinecraftServer { case ASYNC_CURL_POST: $d .= Utils::writeShort(strlen($data["url"])) . $data["url"] . (isset($data["timeout"]) ? Utils::writeShort($data["timeout"]) : Utils::writeShort(10)); $d .= Utils::writeShort(count($data["data"])); - foreach($data["data"] as $key => $value) { + foreach($data["data"] as $key => $value){ $d .= Utils::writeShort(strlen($key)) . $key . Utils::writeInt(strlen($value)) . $value; } break; @@ -323,55 +272,55 @@ class PocketMinecraftServer { return $ID; } - public function trigger($event, $data = "") { - if(isset($this->events[$event])) { - foreach($this->events[$event] as $evid => $ev) { - if(!is_callable($ev)) { + public function trigger($event, $data = ""){ + if(isset($this->events[$event])){ + foreach($this->events[$event] as $evid => $ev){ + if(!is_callable($ev)){ $this->deleteEvent($evid); continue; } - if(is_array($ev)) { + if(is_array($ev)){ $method = $ev[1]; $ev[0]->$method($data, $event); - } else { + }else{ $ev($data, $event); } } - } elseif(isset(Deprecation::$events[$event])) { + }elseif(isset(Deprecation::$events[$event])){ $sub = ""; - if(Deprecation::$events[$event] !== false) { + if(Deprecation::$events[$event] !== false){ $sub = " Substitute \"" . Deprecation::$events[$event] . "\" found."; } console("[ERROR] Event \"$event\" has been deprecated.$sub [Trigger]"); } } - public function deleteEvent($id) { + public function deleteEvent($id){ $id = (int) $id; - if(isset($this->eventsID[$id])) { + if(isset($this->eventsID[$id])){ $ev = $this->eventsID[$id]; $this->eventsID[$id] = null; unset($this->eventsID[$id]); $this->events[$ev][$id] = null; unset($this->events[$ev][$id]); - if(count($this->events[$ev]) === 0) { + if(count($this->events[$ev]) === 0){ unset($this->events[$ev]); } } } - public function asyncOperationChecker() { - if(defined("NO_THREADS")) { + public function asyncOperationChecker(){ + if(defined("NO_THREADS")){ return false; } - if(isset($this->asyncThread->output[5])) { + if(isset($this->asyncThread->output[5])){ $offset = 0; $ID = Utils::readInt(substr($this->asyncThread->output, $offset, 4)); $offset += 4; $type = Utils::readShort(substr($this->asyncThread->output, $offset, 2)); $offset += 2; $data = []; - switch($type) { + switch($type){ case ASYNC_CURL_GET: case ASYNC_CURL_POST: $len = Utils::readInt(substr($this->asyncThread->output, $offset, 4)); @@ -383,11 +332,11 @@ class PocketMinecraftServer { } $this->asyncThread->output = substr($this->asyncThread->output, $offset); - if(isset($this->async[$ID]) and $this->async[$ID] !== null and is_callable($this->async[$ID])) { - if(is_array($this->async[$ID])) { + if(isset($this->async[$ID]) and $this->async[$ID] !== null and is_callable($this->async[$ID])){ + if(is_array($this->async[$ID])){ $method = $this->async[$ID][1]; $result = $this->async[$ID][0]->$method($data, $type, $ID); - } else { + }else{ $result = $this->async[$ID]($data, $type, $ID); } } @@ -401,12 +350,12 @@ class PocketMinecraftServer { * * @return boolean */ - public function addHandler($event, callable $callable, $priority = 5) { - if(!is_callable($callable)) { + public function addHandler($event, callable $callable, $priority = 5){ + if(!is_callable($callable)){ return false; - } elseif(isset(Deprecation::$events[$event])) { + }elseif(isset(Deprecation::$events[$event])){ $sub = ""; - if(Deprecation::$events[$event] !== false) { + if(Deprecation::$events[$event] !== false){ $sub = " Substitute \"" . Deprecation::$events[$event] . "\" found."; } console("[ERROR] Event \"$event\" has been deprecated.$sub [Adding handle to " . (is_array($callable) ? get_class($callable[0]) . "::" . $callable[1] : $callable) . "]"); @@ -419,64 +368,64 @@ class PocketMinecraftServer { return $hnid; } - public function dhandle($e, $d) { + public function dhandle($e, $d){ return $this->handle($e, $d); } - public function handle($event, &$data) { + public function handle($event, &$data){ $this->preparedSQL->selectHandlers->reset(); $this->preparedSQL->selectHandlers->clear(); $this->preparedSQL->selectHandlers->bindValue(":name", $event, SQLITE3_TEXT); $handlers = $this->preparedSQL->selectHandlers->execute(); $result = null; - if($handlers instanceof SQLite3Result) { + if($handlers instanceof SQLite3Result){ $call = []; - while(($hn = $handlers->fetchArray(SQLITE3_ASSOC)) !== false) { + while(($hn = $handlers->fetchArray(SQLITE3_ASSOC)) !== false){ $call[(int) $hn["ID"]] = true; } $handlers->finalize(); - foreach($call as $hnid => $boolean) { - if($result !== false and $result !== true) { + foreach($call as $hnid => $boolean){ + if($result !== false and $result !== true){ $called[$hnid] = true; $handler = $this->handlers[$hnid]; - if(is_array($handler)) { + if(is_array($handler)){ $method = $handler[1]; $result = $handler[0]->$method($data, $event); - } else { + }else{ $result = $handler($data, $event); } - } else { + }else{ break; } } - } elseif(isset(Deprecation::$events[$event])) { + }elseif(isset(Deprecation::$events[$event])){ $sub = ""; - if(Deprecation::$events[$event] !== false) { + if(Deprecation::$events[$event] !== false){ $sub = " Substitute \"" . Deprecation::$events[$event] . "\" found."; } console("[ERROR] Event \"$event\" has been deprecated.$sub [Handler]"); } - if($result !== false) { + if($result !== false){ $this->trigger($event, $data); } return $result; } - public function eventHandler($data, $event) { - switch($event) { + public function eventHandler($data, $event){ + switch($event){ } } - public function init() { + public function init(){ register_tick_function([$this, "tick"]); declare(ticks=5000); //Minimum TPS for main thread locks $this->loadEvents(); register_shutdown_function([$this, "dumpError"]); register_shutdown_function([$this, "close"]); - if(function_exists("pcntl_signal")) { + if(function_exists("pcntl_signal")){ pcntl_signal(SIGTERM, [$this, "close"]); pcntl_signal(SIGINT, [$this, "close"]); pcntl_signal(SIGHUP, [$this, "close"]); @@ -488,8 +437,8 @@ class PocketMinecraftServer { $this->process(); } - public function loadEvents() { - if(ENABLE_ANSI === true) { + public function loadEvents(){ + if(ENABLE_ANSI === true){ $this->schedule(30, [$this, "titleTick"], [], true); } $this->schedule(20 * 15, [$this, "checkTicks"], [], true); @@ -497,8 +446,8 @@ class PocketMinecraftServer { $this->schedule(20, [$this, "asyncOperationChecker"], [], true); } - public function schedule($ticks, callable $callback, $data = [], $repeat = false, $eventName = "server.schedule") { - if(!is_callable($callback)) { + public function schedule($ticks, callable $callback, $data = [], $repeat = false, $eventName = "server.schedule"){ + if(!is_callable($callback)){ return false; } @@ -511,8 +460,8 @@ class PocketMinecraftServer { /** * @return string */ - public function getGamemode() { - switch($this->gamemode) { + public function getGamemode(){ + switch($this->gamemode){ case SURVIVAL: return "survival"; case CREATIVE: @@ -524,16 +473,17 @@ class PocketMinecraftServer { } } - public function process() { + public function process() + { $lastLoop = 0; - if(self::$FORCE_20_TPS) { - while($this->stop === false) { + if(self::$FORCE_20_TPS){ + while($this->stop === false){ $packetcnt = 0; - while($packet = $this->interface->readPacket()) { + while($packet = $this->interface->readPacket()){ if($packet instanceof Packet) { $this->packetHandler($packet); - if(++$packetcnt > self::$PACKET_READING_LIMIT) { - ConsoleAPI::warn("Reading more than " . self::$PACKET_READING_LIMIT . " packets per tick! Forcing ticking!"); + if(++$packetcnt > self::$PACKET_READING_LIMIT){ + ConsoleAPI::warn("Reading more than ".self::$PACKET_READING_LIMIT." packets per tick! Forcing ticking!"); break; } } @@ -541,30 +491,30 @@ class PocketMinecraftServer { $this->tick(); } - } else { - while($this->stop === false) { + }else{ + while($this->stop === false){ $packetcnt = 0; startReadingAgain: $packet = $this->interface->readPacket(); - if($packet instanceof Packet) { + if($packet instanceof Packet){ $this->packetHandler($packet); $lastLoop = 0; - if(++$packetcnt > self::$PACKET_READING_LIMIT) { - ConsoleAPI::warn("Reading more than " . self::$PACKET_READING_LIMIT . " packets per tick! Forcing ticking!"); - } else { + if(++$packetcnt > self::$PACKET_READING_LIMIT){ + ConsoleAPI::warn("Reading more than ".self::$PACKET_READING_LIMIT." packets per tick! Forcing ticking!"); + }else{ goto startReadingAgain; } - } elseif($this->tick() > 0) { + } elseif($this->tick() > 0){ $lastLoop = 0; - } else { + } else{ ++$lastLoop; - if($lastLoop < 16) { + if($lastLoop < 16){ usleep(1); - } elseif($lastLoop < 128) { + } elseif($lastLoop < 128){ usleep(100); - } elseif($lastLoop < 256) { + } elseif($lastLoop < 256){ usleep(512); - } else { + } else{ usleep(10000); } } @@ -574,19 +524,19 @@ class PocketMinecraftServer { } - public function packetHandler(Packet $packet) { + public function packetHandler(Packet $packet){ $data = &$packet; $CID = PocketMinecraftServer::clientID($packet->ip, $packet->port); - if(isset($this->clients[$CID])) { + if(isset($this->clients[$CID])){ $this->clients[$CID]->handlePacket($packet); - } else { - if($this->handle("server.noauthpacket." . $packet->pid(), $packet) === false) { + }else{ + if($this->handle("server.noauthpacket." . $packet->pid(), $packet) === false){ return; } - switch($packet->pid()) { + switch($packet->pid()){ case RakNetInfo::UNCONNECTED_PING: case RakNetInfo::UNCONNECTED_PING_OPEN_CONNECTIONS: - if($this->invisible === true) { + if($this->invisible === true){ $pk = new RakNetPacket(RakNetInfo::UNCONNECTED_PONG); $pk->pingID = $packet->pingID; $pk->serverID = $this->serverID; @@ -596,11 +546,11 @@ class PocketMinecraftServer { $this->send($pk); break; } - if(!isset($this->custom["times_" . $CID])) { + if(!isset($this->custom["times_" . $CID])){ $this->custom["times_" . $CID] = 0; } $ln = 15; - if($this->description == "" or !str_ends_with($this->description, " ")) { + if($this->description == "" or !str_ends_with($this->description, " ")){ $this->description .= " "; } $txt = substr($this->description, $this->custom["times_" . $CID], $ln); @@ -615,14 +565,14 @@ class PocketMinecraftServer { $this->custom["times_" . $CID] = ($this->custom["times_" . $CID] + 1) % strlen($this->description); break; case RakNetInfo::OPEN_CONNECTION_REQUEST_1: - if($packet->structure !== RakNetInfo::STRUCTURE) { + if($packet->structure !== RakNetInfo::STRUCTURE){ console("[DEBUG] Incorrect structure #" . $packet->structure . " from " . $packet->ip . ":" . $packet->port, true, true, 2); $pk = new RakNetPacket(RakNetInfo::INCOMPATIBLE_PROTOCOL_VERSION); $pk->serverID = $this->serverID; $pk->ip = $packet->ip; $pk->port = $packet->port; $this->send($pk); - } else { + }else{ $pk = new RakNetPacket(RakNetInfo::OPEN_CONNECTION_REPLY_1); $pk->serverID = $this->serverID; $pk->mtuSize = strlen($packet->buffer); @@ -632,7 +582,7 @@ class PocketMinecraftServer { } break; case RakNetInfo::OPEN_CONNECTION_REQUEST_2: - if($this->invisible === true) { + if($this->invisible === true){ break; } @@ -648,30 +598,30 @@ class PocketMinecraftServer { } } - public static function clientID($ip, $port) { + public static function clientID($ip, $port){ return crc32($ip . $port) ^ crc32($port . $ip . BOOTUP_RANDOM); //return $ip . ":" . $port; } - public function send(Packet $packet) { + public function send(Packet $packet){ return $this->interface->writePacket($packet); } - public function tick() { + public function tick(){ $time = microtime(true); - if($this->lastTick <= ($time - 0.05)) { + if($this->lastTick <= ($time - 0.05)){ $this->tickMeasure[] = $this->lastTick = $time; unset($this->tickMeasure[key($this->tickMeasure)]); ++$this->ticks; - foreach($this->clients as $client) { + foreach($this->clients as $client){ $client->handlePacketQueues(); - if($this->ticks % 40 == 0) { //2s + if($this->ticks % 40 == 0){ //2s $client->sendPing(); } } - foreach($this->api->level->levels as $l) { + foreach($this->api->level->levels as $l){ $l->onTick($this, $time); } $r = $this->tickerFunction($time); @@ -680,34 +630,34 @@ class PocketMinecraftServer { return 0; } - public function tickerFunction($time) { + public function tickerFunction($time){ //actions that repeat every x time will go here $this->preparedSQL->selectActions->reset(); $this->preparedSQL->selectActions->bindValue(":time", $time, SQLITE3_FLOAT); $actions = $this->preparedSQL->selectActions->execute(); $actionCount = 0; - if($actions instanceof SQLite3Result) { - while(($action = $actions->fetchArray(SQLITE3_ASSOC)) !== false) { + if($actions instanceof SQLite3Result){ + while(($action = $actions->fetchArray(SQLITE3_ASSOC)) !== false){ $cid = $action["ID"]; $this->preparedSQL->updateAction->reset(); $this->preparedSQL->updateAction->bindValue(":time", $time, SQLITE3_FLOAT); $this->preparedSQL->updateAction->bindValue(":id", $cid, SQLITE3_INTEGER); $this->preparedSQL->updateAction->execute(); - if(isset($this->schedule[$cid]) && is_array($this->schedule[$cid]) && isset($this->schedule[$cid][0]) && is_callable($this->schedule[$cid][0])) { + if(isset($this->schedule[$cid]) && is_array($this->schedule[$cid]) && isset($this->schedule[$cid][0]) && is_callable($this->schedule[$cid][0])){ ++$actionCount; - try { - $return = @call_user_func($this->schedule[$cid][0] ?? function () {}, $this->schedule[$cid][1], $this->schedule[$cid][2]); //somehow args can be null - } catch(TypeError $e) { - $m = $e->getMessage() . "\nStack trace:\n" . $e->getTraceAsString(); + try{ + $return = @call_user_func($this->schedule[$cid][0] ?? function(){}, $this->schedule[$cid][1], $this->schedule[$cid][2]); //somehow args can be null + }catch(TypeError $e){ + $m = $e->getMessage()."\nStack trace:\n".$e->getTraceAsString(); ConsoleAPI::error($m); $return = false; } - } else { + }else{ $return = false; } - if($action["repeat"] == 0 or $return === false) { + if($action["repeat"] == 0 or $return === false){ $this->query("DELETE FROM actions WHERE ID = " . $action["ID"] . ";"); $this->schedule[$cid] = null; unset($this->schedule[$cid]); @@ -718,8 +668,8 @@ class PocketMinecraftServer { return $actionCount; } - public function dumpError() { - if($this->stop === true) { + public function dumpError(){ + if($this->stop === true){ return; } ini_set("memory_limit", "-1"); //Fix error dump not dumped on memory problems @@ -745,18 +695,18 @@ class PocketMinecraftServer { ]; $er["type"] = $errorConversion[$er["type"]] ?? $er["type"]; $dump .= "Error: " . var_export($er, true) . "\r\n\r\n"; - if(stripos($er["file"], "plugin") !== false) { + if(stripos($er["file"], "plugin") !== false){ $dump .= "THIS ERROR WAS CAUSED BY A PLUGIN. REPORT IT TO THE PLUGIN DEVELOPER.\r\n"; } $dump .= "Code: \r\n"; $file = @file($er["file"], FILE_IGNORE_NEW_LINES); - for($l = max(0, $er["line"] - 10); $l < $er["line"] + 10; ++$l) { + for($l = max(0, $er["line"] - 10); $l < $er["line"] + 10; ++$l){ $dump .= "[" . ($l + 1) . "] " . @$file[$l] . "\r\n"; } $dump .= "\r\n\r\n"; $dump .= "Backtrace: \r\n"; - foreach(getTrace() as $line) { + foreach(getTrace() as $line){ $dump .= "$line\r\n"; } $dump .= "\r\n\r\n"; @@ -771,21 +721,21 @@ class PocketMinecraftServer { global $arguments; $dump .= "Parameters: " . var_export($arguments, true) . "\r\n\r\n\r\n"; $p = $this->api->getProperties(); - if($p["rcon.password"] != "") { + if($p["rcon.password"] != ""){ $p["rcon.password"] = "******"; } $dump .= "server.properties: " . var_export($p, true) . "\r\n\r\n\r\n"; - if($this->api->plugin instanceof PluginAPI) { + if($this->api->plugin instanceof PluginAPI){ $plist = $this->api->plugin->getList(); $dump .= "Loaded plugins:\r\n"; - foreach($plist as $p) { + foreach($plist as $p){ $dump .= $p["name"] . " " . $p["version"] . " by " . $p["author"] . "\r\n"; } $dump .= "\r\n\r\n"; } $extensions = []; - foreach(get_loaded_extensions() as $ext) { + foreach(get_loaded_extensions() as $ext){ $extensions[$ext] = phpversion($ext); } @@ -806,7 +756,7 @@ class PocketMinecraftServer { console("[SEVERE] Please submit the \"{$name}.log\" file to the Bug Reporting page. Give as much info as you can.", true, true, 0); } - public function debugInfo($console = false) { + public function debugInfo($console = false){ $info = []; $info["tps"] = $this->getTPS(); $info["memory_usage"] = round((memory_get_usage() / 1024) / 1024, 2) . "MB"; @@ -820,33 +770,33 @@ class PocketMinecraftServer { $info["actions"] = $info["actions"]["count"]; $info["garbage"] = gc_collect_cycles(); $this->handle("server.debug", $info); - if($console === true) { + if($console === true){ console("[INFO] TPS: " . $info["tps"] . ", Memory usage: " . $info["memory_usage"] . " (Peak " . $info["memory_peak_usage"] . "), Entities: " . $info["entities"] . ", Events: " . $info["events"] . ", Handlers: " . $info["handlers"] . ", Actions: " . $info["actions"] . ", Garbage: " . $info["garbage"], true, true); } return $info; } - public function checkMemory() { + public function checkMemory(){ $info = $this->debugInfo(); $data = $info["memory_usage"] . "," . $info["players"] . "," . $info["entities"]; $i = count($this->memoryStats) - 1; - if($i < 0 or $this->memoryStats[$i] !== $data) { + if($i < 0 or $this->memoryStats[$i] !== $data){ $this->memoryStats[] = $data; } } - public function event($event, callable $func) { - if(!is_callable($func)) { + public function event($event, callable $func){ + if(!is_callable($func)){ return false; - } elseif(isset(Deprecation::$events[$event])) { + }elseif(isset(Deprecation::$events[$event])){ $sub = ""; - if(Deprecation::$events[$event] !== false) { + if(Deprecation::$events[$event] !== false){ $sub = " Substitute \"" . Deprecation::$events[$event] . "\" found."; } console("[ERROR] Event \"$event\" has been deprecated.$sub [Attach to " . (is_array($func) ? get_class($func[0]) . "::" . $func[1] : $func) . "]"); } $evid = $this->evCnt++; - if(!isset($this->events[$event])) { + if(!isset($this->events[$event])){ $this->events[$event] = []; } $this->events[$event][$evid] = $func; diff --git a/src/installer/Installer.php b/src/installer/Installer.php index fe4ec2c4..b2697189 100644 --- a/src/installer/Installer.php +++ b/src/installer/Installer.php @@ -25,8 +25,8 @@ } }while($lang == false); $this->lang = new InstallerLang($lang); - echo "[*] " . $this->lang->language_has_been_selected . "\n"; - echo "[?] " . $this->lang->skip_installer . " (y/N): "; + echo "[*] ".$this->lang->language_has_been_selected."\n"; + echo "[?] ".$this->lang->skip_installer." (y/N): "; if(strtolower($this->getInput()) === "y"){ return; } @@ -41,7 +41,7 @@ } private function welcome(){ - echo $this->lang->welcome_to_pocketmine . "\n"; + echo $this->lang->welcome_to_pocketmine."\n"; echo <<lang->accept_license . " (y/N): "; + echo "\n[?] ".$this->lang->accept_license." (y/N): "; if(strtolower($this->getInput("n")) != "y"){ - echo "[!] " . $this->lang->you_have_to_accept_the_license . "\n"; + echo "[!] ".$this->lang->you_have_to_accept_the_license."\n"; sleep(5); exit(0); } - echo "[*] " . $this->lang->setting_up_server_now . "\n"; - echo "[*] " . $this->lang->default_values_info . "\n"; - echo "[*] " . $this->lang->server_properties . "\n"; + echo "[*] ".$this->lang->setting_up_server_now."\n"; + echo "[*] ".$this->lang->default_values_info."\n"; + echo "[*] ".$this->lang->server_properties."\n"; } private function generateBaseConfig(){ $config = new Config(DATA_PATH . "server.properties", CONFIG_PROPERTIES); - echo "[?] " . $this->lang->name_your_server . " (" . self::DEFAULT_NAME . "): "; + echo "[?] ".$this->lang->name_your_server." (".self::DEFAULT_NAME."): "; $config->set("server-name", $this->getInput(self::DEFAULT_NAME)); - echo "[*] " . $this->lang->port_warning . "\n"; + echo "[*] ".$this->lang->port_warning."\n"; do{ - echo "[?] " . $this->lang->server_port . " (" . self::DEFAULT_PORT . "): "; + echo "[?] ".$this->lang->server_port." (".self::DEFAULT_PORT."): "; $port = (int) $this->getInput(self::DEFAULT_PORT); if($port <= 0 or $port > 65535){ - echo "[!] " . $this->lang->invalid_port . "\n"; + echo "[!] ".$this->lang->invalid_port."\n"; } }while($port <= 0 or $port > 65535); $config->set("server-port", $port); - echo "[*] " . $this->lang->ram_warning . "\n"; - echo "[?] " . $this->lang->server_ram . " (" . self::DEFAULT_MEMORY . "): "; - $config->set("memory-limit", ((int) $this->getInput(self::DEFAULT_MEMORY)) . "M"); - echo "[*] " . $this->lang->gamemode_info . "\n"; + echo "[*] ".$this->lang->ram_warning."\n"; + echo "[?] ".$this->lang->server_ram." (".self::DEFAULT_MEMORY."): "; + $config->set("memory-limit", ((int) $this->getInput(self::DEFAULT_MEMORY))."M"); + echo "[*] ".$this->lang->gamemode_info."\n"; do{ - echo "[?] " . $this->lang->default_gamemode . ": (" . self::DEFAULT_GAMEMODE . "): "; + echo "[?] ".$this->lang->default_gamemode.": (".self::DEFAULT_GAMEMODE."): "; $gamemode = (int) $this->getInput(self::DEFAULT_GAMEMODE); }while($gamemode < 0 or $gamemode > 3); $config->set("gamemode", $gamemode); - echo "[?] " . $this->lang->max_players . " (" . self::DEFAULT_PLAYERS . "): "; + echo "[?] ".$this->lang->max_players." (".self::DEFAULT_PLAYERS."): "; $config->set("max-players", (int) $this->getInput(self::DEFAULT_PLAYERS)); - echo "[*] " . $this->lang->spawn_protection_info . "\n"; - echo "[?] " . $this->lang->spawn_protection . " (Y/n): "; + echo "[*] ".$this->lang->spawn_protection_info."\n"; + echo "[?] ".$this->lang->spawn_protection." (Y/n): "; if(strtolower($this->getInput("y")) == "n"){ $config->set("spawn-protection", -1); }else{ @@ -97,21 +97,21 @@ LICENSE; } private function generateUserFiles(){ - echo "[*] " . $this->lang->op_info . "\n"; - echo "[?] " . $this->lang->op_who . ": "; + echo "[*] ".$this->lang->op_info."\n"; + echo "[?] ".$this->lang->op_who.": "; $op = strtolower($this->getInput("")); if($op === ""){ - echo "[!] " . $this->lang->op_warning . "\n"; + echo "[!] ".$this->lang->op_warning."\n"; }else{ - $ops = new Config(DATA_PATH . "ops.txt", CONFIG_LIST); + $ops = new Config(DATA_PATH."ops.txt", CONFIG_LIST); $ops->set($op, true); $ops->save(); } - echo "[*] " . $this->lang->whitelist_info . "\n"; - echo "[?] " . $this->lang->whitelist_enable . " (y/N): "; + echo "[*] ".$this->lang->whitelist_info."\n"; + echo "[?] ".$this->lang->whitelist_enable." (y/N): "; $config = new Config(DATA_PATH . "server.properties", CONFIG_PROPERTIES); if(strtolower($this->getInput("n")) === "y"){ - echo "[!] " . $this->lang->whitelist_warning . "\n"; + echo "[!] ".$this->lang->whitelist_warning."\n"; $config->set("white-list", true); }else{ $config->set("white-list", false); @@ -121,42 +121,42 @@ LICENSE; private function networkFunctions(){ $config = new Config(DATA_PATH . "server.properties", CONFIG_PROPERTIES); - echo "[!] " . $this->lang->query_warning1 . "\n"; - echo "[!] " . $this->lang->query_warning2 . "\n"; - echo "[?] " . $this->lang->query_disable . " (y/N): "; + echo "[!] ".$this->lang->query_warning1."\n"; + echo "[!] ".$this->lang->query_warning2."\n"; + echo "[?] ".$this->lang->query_disable." (y/N): "; if(strtolower($this->getInput("n")) === "y"){ $config->set("enable-query", false); }else{ $config->set("enable-query", true); } - echo "[*] " . $this->lang->rcon_info . "\n"; - echo "[?] " . $this->lang->rcon_enable . " (y/N): "; + echo "[*] ".$this->lang->rcon_info."\n"; + echo "[?] ".$this->lang->rcon_enable." (y/N): "; if(strtolower($this->getInput("n")) === "y"){ $config->set("enable-rcon", true); $password = substr(base64_encode(Utils::getRandomBytes(20, false)), 3, 10); $config->set("rcon.password", $password); - echo "[*] " . $this->lang->rcon_password . ": " . $password . "\n"; + echo "[*] ".$this->lang->rcon_password.": ".$password."\n"; }else{ $config->set("enable-rcon", false); } $config->save(); - echo "[*] " . $this->lang->ip_get . "\n"; + echo "[*] ".$this->lang->ip_get."\n"; $externalIP = Utils::getIP(); $internalIP = gethostbyname(trim(`hostname`)); - echo "[!] " . $this->lang->get("ip_warning", ["{{EXTERNAL_IP}}", "{{INTERNAL_IP}}"], [$externalIP, $internalIP]) . "\n"; - echo "[!] " . $this->lang->ip_confirm; + echo "[!] ".$this->lang->get("ip_warning", ["{{EXTERNAL_IP}}", "{{INTERNAL_IP}}"], [$externalIP, $internalIP])."\n"; + echo "[!] ".$this->lang->ip_confirm; $this->getInput(); } private function endWizard(){ - echo "[*] " . $this->lang->you_have_finished . "\n"; - echo "[*] " . $this->lang->pocketmine_plugins . "\n"; - echo "[*] " . $this->lang->pocketmine_will_start . "\n\n\n"; + echo "[*] ".$this->lang->you_have_finished."\n"; + echo "[*] ".$this->lang->pocketmine_plugins."\n"; + echo "[*] ".$this->lang->pocketmine_will_start."\n\n\n"; sleep(4); } @@ -192,11 +192,11 @@ LICENSE; private $lang; private $langfile; public function __construct($lang = ""){ - if(file_exists(FILE_PATH . "src/lang/Installer/" . $lang . ".ini")){ + if(file_exists(FILE_PATH."src/lang/Installer/".$lang.".ini")){ $this->lang = $lang; - $this->langfile = FILE_PATH . "src/lang/Installer/" . $lang . ".ini"; + $this->langfile = FILE_PATH."src/lang/Installer/".$lang.".ini"; }else{ - $l = glob(FILE_PATH . "src/lang/Installer/" . $lang . "_*.ini"); + $l = glob(FILE_PATH."src/lang/Installer/".$lang."_*.ini"); if(count($l) > 0){ $files = []; foreach($l as $file){ @@ -207,14 +207,14 @@ LICENSE; $l = key($files); $l = substr($l, strrpos($l, "/") + 1, -4); $this->lang = isset(self::$languages[$l]) ? $l:$lang; - $this->langfile = FILE_PATH . "src/lang/Installer/" . $l . ".ini"; + $this->langfile = FILE_PATH."src/lang/Installer/".$l.".ini"; }else{ $this->lang = "en"; - $this->langfile = FILE_PATH . "src/lang/Installer/en.ini"; + $this->langfile = FILE_PATH."src/lang/Installer/en.ini"; } } - $this->loadLang(FILE_PATH . "src/lang/Installer/en.ini", "en"); + $this->loadLang(FILE_PATH."src/lang/Installer/en.ini", "en"); if($this->lang !== "en"){ $this->loadLang($this->langfile, $this->lang); } diff --git a/src/material/Block.php b/src/material/Block.php index e83a913f..f723cb60 100755 --- a/src/material/Block.php +++ b/src/material/Block.php @@ -292,7 +292,7 @@ abstract class Block extends Position{ } final public function __toString(){ - return "Block " . $this->name . " (" . $this->id . ":" . $this->meta . ")"; + return "Block ". $this->name ." (".$this->id.":".$this->meta.")"; } abstract function isBreakable(Item $item, Player $player); diff --git a/src/material/Item.php b/src/material/Item.php index 91aaf975..22e1b392 100755 --- a/src/material/Item.php +++ b/src/material/Item.php @@ -294,7 +294,7 @@ class Item{ } public function __toString(){ - return "Item " . $this->name . " (" . $this->id . ":" . $this->meta . ")"; + return "Item ". $this->name ." (".$this->id.":".$this->meta.")"; } public function getDamageAgainstOf($e){ diff --git a/src/material/block/solid/LeavesBlock.php b/src/material/block/solid/LeavesBlock.php index c4e3dc3e..2862884c 100644 --- a/src/material/block/solid/LeavesBlock.php +++ b/src/material/block/solid/LeavesBlock.php @@ -22,7 +22,7 @@ class LeavesBlock extends TransparentBlock{ } public static function createIndex($x, $y, $z){ - return $x . "." . $y . "." . $z; + return $x.".".$y.".".$z; } public static function findLog(Level $level, $x, $y, $z, array $visited, $distance){ //port from newest pocketmine $index = self::createIndex($x, $y, $z); diff --git a/src/plugin/DummyPlugin.php b/src/plugin/DummyPlugin.php index 6ab9554a..8b5b4e51 100644 --- a/src/plugin/DummyPlugin.php +++ b/src/plugin/DummyPlugin.php @@ -1,13 +1,13 @@ $recipe) { + foreach(CraftingRecipes::$recipes as $id => $recipe){ $server->query("INSERT INTO recipes (id, type, recipe) VALUES (" . $id . ", " . $recipe[3] . ", '" . $recipe[2] . "');"); } } - private static function parseRecipe($recipe) { + private static function parseRecipe($recipe){ $recipe = explode("=>", $recipe); $recipeItems = []; - foreach(explode(",", $recipe[0]) as $item) { + foreach(explode(",", $recipe[0]) as $item){ $item = explode("x", $item); $id = explode(":", $item[0]); $meta = array_pop($id); $id = $id[0]; $it = BlockAPI::fromString($id); - if(!isset($recipeItems[$it->getID()])) { + if(!isset($recipeItems[$it->getID()])){ $recipeItems[$it->getID()] = [$it->getID(), $meta === "?" ? false : intval($meta) & 0xFFFF, intval($item[1])]; - } else { - if($it->getMetadata() !== $recipeItems[$it->getID()][1]) { + }else{ + if($it->getMetadata() !== $recipeItems[$it->getID()][1]){ $recipeItems[$it->getID()][1] = false; } $recipeItems[$it->getID()][2] += $it->count; @@ -256,7 +256,7 @@ class CraftingRecipes { $craftItem = [$it->getID(), intval($meta) & 0xFFFF, intval($item[1])]; $recipeString = ""; - foreach($recipeItems as $item) { + foreach($recipeItems as $item){ $recipeString .= $item[0] . "x" . $item[2] . ","; } $recipeString = substr($recipeString, 0, -1) . "=>" . $craftItem[0] . "x" . $craftItem[2]; @@ -264,11 +264,11 @@ class CraftingRecipes { return [$recipeItems, $craftItem, $recipeString]; } - public static function canCraft(array $craftItem, array $recipeItems, $type) { + public static function canCraft(array $craftItem, array $recipeItems, $type){ ksort($recipeItems); $recipeString = ""; - foreach($recipeItems as $item) { - if($craftItem[0] === CAKE && $item[0] === BUCKET && $item[1] === 1) { //some dark magic with recipe happened in mcpe, pmmp restores it back to normal + foreach($recipeItems as $item){ + if($craftItem[0] === CAKE && $item[0] === BUCKET && $item[1] === 1){ //some dark magic with recipe happened in mcpe, pmmp restores it back to normal $item[2] = 3; } $recipeString .= $item[0] . "x" . $item[2] . ","; @@ -276,33 +276,33 @@ class CraftingRecipes { $recipeString = substr($recipeString, 0, -1) . "=>" . $craftItem[0] . "x" . $craftItem[2]; $server = ServerAPI::request(); $result = $server->query("SELECT id FROM recipes WHERE type == " . $type . " AND recipe == '" . $recipeString . "';"); - if($result instanceof SQLite3Result) { + if($result instanceof SQLite3Result){ $continue = true; - while(($r = $result->fetchArray(SQLITE3_NUM)) !== false) { + while(($r = $result->fetchArray(SQLITE3_NUM)) !== false){ $continue = true; $recipe = CraftingRecipes::$recipes[$r[0]]; - foreach($recipe[0] as $item) { - if(!isset($recipeItems[$item[0]])) { + foreach($recipe[0] as $item){ + if(!isset($recipeItems[$item[0]])){ $continue = false; break; } $oitem = $recipeItems[$item[0]]; - if($craftItem[0] === CAKE && $oitem[0] === BUCKET && $item[1] === 1) { //some dark magic with recipe happened in mcpe, pmmp restores it back to normal x2 + if($craftItem[0] === CAKE && $oitem[0] === BUCKET && $item[1] === 1){ //some dark magic with recipe happened in mcpe, pmmp restores it back to normal x2 $oitem[2] = 3; } - if(($oitem[1] !== $item[1] and $item[1] !== false) or $oitem[2] !== $item[2]) { + if(($oitem[1] !== $item[1] and $item[1] !== false) or $oitem[2] !== $item[2]){ $continue = false; break; } } - if($continue === false or $craftItem[0] !== $recipe[1][0]) { + if($continue === false or $craftItem[0] !== $recipe[1][0]){ $continue = false; continue; } $continue = $recipe; break; } - } else { + }else{ return true; } return $continue; diff --git a/src/recipes/FuelData.php b/src/recipes/FuelData.php index d9025730..e0c61bab 100644 --- a/src/recipes/FuelData.php +++ b/src/recipes/FuelData.php @@ -1,6 +1,6 @@ 80, @@ -27,4 +27,4 @@ class FuelData { BUCKET => 1000, ]; -} +} \ No newline at end of file diff --git a/src/recipes/SmeltingData.php b/src/recipes/SmeltingData.php index 544abd5b..1dd447d3 100644 --- a/src/recipes/SmeltingData.php +++ b/src/recipes/SmeltingData.php @@ -1,6 +1,6 @@ [STONE, 0], @@ -17,4 +17,4 @@ class SmeltingData { RAW_CHICKEN => [COOKED_CHICKEN, 0], POTATO => [BAKED_POTATO, 0], ]; -} +} \ No newline at end of file diff --git a/src/utils/RailLogic.php b/src/utils/RailLogic.php index 1966b7c5..9e8de956 100644 --- a/src/utils/RailLogic.php +++ b/src/utils/RailLogic.php @@ -1,9 +1,8 @@ getID(); $meta = $rail->getMetadata(); $this->level = $rail->level; @@ -22,163 +21,125 @@ class RailLogic { $this->updateConnections($meta); } - public function getRail($v) { - if(($b = $this->level->getBlock($v)) instanceof RailBaseBlock) { //TODO git rid of getBlock + public function getRail($v){ + if(($b = $this->level->getBlock($v)) instanceof RailBaseBlock){ //TODO git rid of getBlock return new RailLogic($b); - } elseif(($b = $this->level->getBlockWithoutVector($v->x, $v->y + 1, $v->z)) instanceof RailBaseBlock) { + }elseif(($b = $this->level->getBlockWithoutVector($v->x, $v->y + 1, $v->z)) instanceof RailBaseBlock){ return new RailLogic($b); - } elseif(($b = $this->level->getBlockWithoutVector($v->x, $v->y - 1, $v->z)) instanceof RailBaseBlock) { + }elseif(($b = $this->level->getBlockWithoutVector($v->x, $v->y - 1, $v->z)) instanceof RailBaseBlock){ return new RailLogic($b); } return null; } - public function hasRail($x, $y, $z) { + public function hasRail($x, $y, $z){ return RailBaseBlock::isRailBlock($this->level, $x, $y, $z) || RailBaseBlock::isRailBlock($this->level, $x, $y + 1, $z) || RailBaseBlock::isRailBlock($this->level, $x, $y - 1, $z); } - public function countPotentialConnections() { + public function countPotentialConnections(){ return $this->hasRail($this->x, $this->y, $this->z - 1) + $this->hasRail($this->x, $this->y, $this->z + 1) + $this->hasRail($this->x - 1, $this->y, $this->z) + $this->hasRail($this->x + 1, $this->y, $this->z); } - public function removeSoftConnections() { - for($ind = 0; $ind < count($this->railPositions); ++$ind) { + public function removeSoftConnections(){ + for($ind = 0; $ind < count($this->railPositions); ++$ind){ $logic = $this->getRail($this->railPositions[$ind]); - if($logic != null && $this->connectsTo($logic)) { + if($logic != null && $this->connectsTo($logic)){ $this->railPositions[$ind] = new Vector3($logic->x, $logic->y, $logic->z); - } else { + }else{ unset($this->railPositions[$ind--]); $this->railPositions = array_values($this->railPositions); //reindexing } } } - public function connectsTo(RailLogic $logic) { - foreach($this->railPositions as $rpos) { - if(($rpos->x === $logic->x) && ($rpos->z === $logic->z)) { + public function connectsTo(RailLogic $logic){ + foreach($this->railPositions as $rpos){ + if(($rpos->x === $logic->x) && ($rpos->z === $logic->z)){ return true; } } return false; } - public function canConnectTo(RailLogic $rail) { + public function canConnectTo(RailLogic $rail){ return $this->connectsTo($rail) || !(count($this->railPositions) == 2); } - public function hasNeighborRail($x, $y, $z) { + public function hasNeighborRail($x, $y, $z){ $logic = $this->getRail(new Vector3($x, $y, $z)); - if($logic === null) { + if($logic === null){ return false; - } else { + }else{ $logic->removeSoftConnections(); //i place $this here and was searching why isnt it working correctly for 2 hours return $logic->canConnectTo($this); } } - public function place($b, $b1) { + public function place($b, $b1){ $hasZneg = $this->hasNeighborRail($this->x, $this->y, $this->z - 1); $hasZpos = $this->hasNeighborRail($this->x, $this->y, $this->z + 1); $hasXneg = $this->hasNeighborRail($this->x - 1, $this->y, $this->z); $hasXpos = $this->hasNeighborRail($this->x + 1, $this->y, $this->z); $state = -1; - if(($hasZneg || $hasZpos) && !($hasXneg && $hasXpos)) { + if(($hasZneg || $hasZpos) && !($hasXneg && $hasXpos)){ $state = 0; } - if(($hasXneg || $hasXpos) && !($hasZneg && $hasZpos)) { + if(($hasXneg || $hasXpos) && !($hasZneg && $hasZpos)){ $state = 1; } - if(!$this->isStraight) { - if($hasZpos && $hasXpos && !($hasZneg && $hasXneg)) { - $state = 6; - } - if($hasZpos && $hasXneg && !($hasZneg && $hasXpos)) { - $state = 7; - } - if($hasZneg && $hasXneg && !($hasZpos && $hasXpos)) { - $state = 8; - } - if($hasZneg && $hasXpos && !($hasZpos && $hasXneg)) { - $state = 9; - } + if(!$this->isStraight){ + if($hasZpos && $hasXpos && !($hasZneg && $hasXneg)) $state = 6; + if($hasZpos && $hasXneg && !($hasZneg && $hasXpos)) $state = 7; + if($hasZneg && $hasXneg && !($hasZpos && $hasXpos)) $state = 8; + if($hasZneg && $hasXpos && !($hasZpos && $hasXneg)) $state = 9; } - if($state === -1) { - if($hasZneg || $hasZpos) { - $state = 0; - } - if($hasXneg || $hasXpos) { - $state = 1; - } + if($state === -1){ + if($hasZneg || $hasZpos) $state = 0; + if($hasXneg || $hasXpos) $state = 1; - if(!$this->isStraight) { - if($b) { - if($hasZpos && $hasXpos) { - $state = 6; - } - if($hasXneg && $hasZpos) { - $state = 7; - } - if($hasXpos && $hasZneg) { - $state = 9; - } - if($hasZneg && $hasXneg) { - $state = 8; - } - } else { - if($hasZneg && $hasXneg) { - $state = 8; - } - if($hasXpos && $hasZneg) { - $state = 9; - } - if($hasXneg && $hasZpos) { - $state = 7; - } - if($hasZpos && $hasXpos) { - $state = 6; - } + if(!$this->isStraight){ + if($b){ + if($hasZpos && $hasXpos) $state = 6; + if($hasXneg && $hasZpos) $state = 7; + if($hasXpos && $hasZneg) $state = 9; + if($hasZneg && $hasXneg) $state = 8; + }else{ + if($hasZneg && $hasXneg) $state = 8; + if($hasXpos && $hasZneg) $state = 9; + if($hasXneg && $hasZpos) $state = 7; + if($hasZpos && $hasXpos) $state = 6; } } } - if($state === 0) { - if(RailBaseBlock::isRailBlock($this->level, $this->x, $this->y + 1, $this->z - 1)) { - $state = 4; - } - if(RailBaseBlock::isRailBlock($this->level, $this->x, $this->y + 1, $this->z + 1)) { - $state = 5; - } - } elseif($state === 1) { - if(RailBaseBlock::isRailBlock($this->level, $this->x + 1, $this->y + 1, $this->z)) { - $state = 2; - } - if(RailBaseBlock::isRailBlock($this->level, $this->x - 1, $this->y + 1, $this->z)) { - $state = 3; - } - } elseif($state < 0) { - $state = 0; - } + if($state === 0){ + if(RailBaseBlock::isRailBlock($this->level, $this->x, $this->y + 1, $this->z - 1)) $state = 4; + if(RailBaseBlock::isRailBlock($this->level, $this->x, $this->y + 1, $this->z + 1)) $state = 5; + }elseif($state === 1){ + if(RailBaseBlock::isRailBlock($this->level, $this->x + 1, $this->y + 1, $this->z)) $state = 2; + if(RailBaseBlock::isRailBlock($this->level, $this->x - 1, $this->y + 1, $this->z)) $state = 3; + }elseif($state < 0) $state = 0; $this->updateConnections($state); $meta = $state; - if($this->isStraight) { + if($this->isStraight){ $meta = $this->level->level->getBlockDamage($this->x, $this->x, $this->z) & 8 | $state; } - if($b1 || $this->level->level->getBlockDamage($this->x, $this->y, $this->z)) { + if($b1 || $this->level->level->getBlockDamage($this->x, $this->y, $this->z)){ //this.logicWorld.setBlockMetadataWithNotify(this.railX, this.railY, this.railZ, var8, 3); $bl = $this->level->getBlockWithoutVector($this->x, $this->y, $this->z); $bl->setMetadata($meta); $this->level->setBlock(new Vector3($this->x, $this->y, $this->z), $bl, true, false, true); - foreach($this->railPositions as $rpos) { + foreach($this->railPositions as $rpos){ $logic = $this->getRail($rpos); - if($logic !== null) { + if($logic !== null){ $logic->removeSoftConnections(); - if($logic->canConnectTo($this)) { + if($logic->canConnectTo($this)){ $logic->connectTo($this); } @@ -189,16 +150,14 @@ class RailLogic { } - public function hasConnection($x, $y, $z) { - foreach($this->railPositions as $rpos) { - if($rpos->x === $x && $rpos->z === $z) { - return true; - } + public function hasConnection($x, $y, $z){ + foreach($this->railPositions as $rpos){ + if($rpos->x === $x && $rpos->z === $z) return true; } return false; } - public function connectTo(RailLogic $logic) { + public function connectTo(RailLogic $logic){ $this->railPositions[] = new Vector3($logic->x, $logic->y, $logic->z); $hasZneg = $this->hasConnection($this->x, $this->y, $this->z - 1); @@ -207,49 +166,27 @@ class RailLogic { $hasXpos = $this->hasConnection($this->x + 1, $this->y, $this->z); $state = -1; - if($hasZneg || $hasZpos) { - $state = 0; - } - if($hasXneg || $hasXpos) { - $state = 1; + if($hasZneg || $hasZpos) $state = 0; + if($hasXneg || $hasXpos) $state = 1; + + if(!$this->isStraight){ + if($hasZpos && $hasXpos && !($hasZneg && $hasXneg)) $state = 6; + if($hasZpos && $hasXneg && !($hasZneg && $hasXpos)) $state = 7; + if($hasZneg && $hasXneg && !($hasZpos && $hasXpos)) $state = 8; + if($hasZneg && $hasXpos && !($hasZpos && $hasXneg)) $state = 9; } - if(!$this->isStraight) { - if($hasZpos && $hasXpos && !($hasZneg && $hasXneg)) { - $state = 6; - } - if($hasZpos && $hasXneg && !($hasZneg && $hasXpos)) { - $state = 7; - } - if($hasZneg && $hasXneg && !($hasZpos && $hasXpos)) { - $state = 8; - } - if($hasZneg && $hasXpos && !($hasZpos && $hasXneg)) { - $state = 9; - } - } - - if($state == 0) { - if(RailBaseBlock::isRailBlock($this->level, $this->x, $this->y + 1, $this->z - 1)) { - $state = 4; - } - if(RailBaseBlock::isRailBlock($this->level, $this->x, $this->y + 1, $this->z + 1)) { - $state = 5; - } - } elseif($state == 1) { - if(RailBaseBlock::isRailBlock($this->level, $this->x + 1, $this->y + 1, $this->z)) { - $state = 2; - } - if(RailBaseBlock::isRailBlock($this->level, $this->x - 1, $this->y + 1, $this->z)) { - $state = 3; - } - } elseif($state < 0) { - $state = 0; - } + if($state == 0){ + if(RailBaseBlock::isRailBlock($this->level, $this->x, $this->y + 1, $this->z - 1)) $state = 4; + if(RailBaseBlock::isRailBlock($this->level, $this->x, $this->y + 1, $this->z + 1)) $state = 5; + }elseif($state == 1){ + if(RailBaseBlock::isRailBlock($this->level, $this->x + 1, $this->y + 1, $this->z)) $state = 2; + if(RailBaseBlock::isRailBlock($this->level, $this->x - 1, $this->y + 1, $this->z)) $state = 3; + }elseif($state < 0) $state = 0; $meta = $state; - if($this->isStraight) { + if($this->isStraight){ $meta = $this->level->level->getBlockDamage($this->x, $this->x, $this->z) & 8 | $state; } @@ -259,11 +196,11 @@ class RailLogic { $this->level->fastSetBlockUpdateMeta($this->x, $this->y, $this->z, $meta, true); } - public function updateConnections($meta) { + public function updateConnections($meta){ $this->railPositions = []; - switch($meta) { + switch($meta){ case 0: $this->railPositions[] = new Vector3($this->x, $this->y, $this->z - 1); $this->railPositions[] = new Vector3($this->x, $this->y, $this->z + 1); @@ -307,3 +244,4 @@ class RailLogic { } } } + diff --git a/src/utils/Utils.php b/src/utils/Utils.php index 42a6f8b0..c3cb47f3 100644 --- a/src/utils/Utils.php +++ b/src/utils/Utils.php @@ -186,7 +186,7 @@ class Utils{ $arr = json_decode($json); $rarr = []; foreach ($arr as $key => $value){ - $rarr[] = $key . ": " . $value; + $rarr[] = $key.": ".$value; } return $rarr; } diff --git a/src/world/Level.php b/src/world/Level.php index 510c3485..200d91a9 100644 --- a/src/world/Level.php +++ b/src/world/Level.php @@ -1,6 +1,6 @@ true ]; - public function __construct(PMFLevel $level, Config $entities, Config $tiles, Config $blockUpdates, $name) { + public function __construct(PMFLevel $level, Config $entities, Config $tiles, Config $blockUpdates, $name){ $this->server = ServerAPI::request(); $this->level = $level; $this->level->level = $this; @@ -89,25 +69,21 @@ class Level { $this->randInt2 = 0x3C6EF35F; } - public function close() { + public function close(){ $this->__destruct(); } - public function isTopSolidBlocking($x, $y, $z) { + public function isTopSolidBlocking($x, $y, $z){ $idmeta = $this->level->getBlock($x, $y, $z); $id = $idmeta[0]; $meta = $idmeta[1]; - if($id == 0) { - return false; - } - if(StaticBlock::getIsTransparent($id)) { - return false; - } + if($id == 0) return false; + if(StaticBlock::getIsTransparent($id)) return false; return true; } - public function rayTraceBlocks(Vector3 $start, Vector3 $end) { + public function rayTraceBlocks(Vector3 $start, Vector3 $end){ $par3 = false; //TODO move to params? $par4 = true; @@ -124,74 +100,54 @@ class Level { //$block::updateShape($this, $xStart, $yStart, $zStart); //TODO better way to do it $aabb = $block::getAABB($this, $xStart, $yStart, $zStart); - if($startID > 0 && $aabb != null) { //TODO also block::canColideCheck + if($startID > 0 && $aabb != null){ //TODO also block::canColideCheck $v14 = $block::clip($this, $xStart, $yStart, $zStart, $start, $end); - if($v14 != null) { - return $v14; - } + if($v14 != null) return $v14; } - for($i = 0; $i <= 200; ++$i) { + for($i = 0; $i <= 200; ++$i){ - if(is_nan($start->x) || is_nan($start->y) || is_nan($start->z) || ($xStart == $xEnd && $yStart == $yEnd && $zStart == $zEnd)) { //also add checks for nan? + if(is_nan($start->x) || is_nan($start->y) || is_nan($start->z) || ($xStart == $xEnd && $yStart == $yEnd && $zStart == $zEnd)){ //also add checks for nan? return null; } $v39 = $v40 = $v41 = true; $v15 = $v17 = $v19 = 999.0; //nice mojang - if($xEnd > $xStart) { - $v15 = $xStart + 1; - } elseif($xEnd < $xStart) { - $v15 = $xStart; - } else { - $v39 = false; - } + if($xEnd > $xStart) $v15 = $xStart + 1; + elseif($xEnd < $xStart) $v15 = $xStart; + else $v39 = false; - if($yEnd > $yStart) { - $v17 = $yStart + 1; - } elseif($yEnd < $yStart) { - $v17 = $yStart; - } else { - $v40 = false; - } + if($yEnd > $yStart) $v17 = $yStart + 1; + elseif($yEnd < $yStart) $v17 = $yStart; + else $v40 = false; - if($zEnd > $zStart) { - $v19 = $zStart + 1; - } elseif($zEnd < $zStart) { - $v19 = $zStart; - } else { - $v41 = false; - } + if($zEnd > $zStart) $v19 = $zStart + 1; + elseif($zEnd < $zStart) $v19 = $zStart; + else $v41 = false; $v21 = $v23 = $v25 = 999.0; //nice mojang x2 $v27 = $end->x - $start->x; $v29 = $end->y - $start->y; $v31 = $end->z - $start->z; - if($v39) { - $v21 = $v27 == 0 ? ($v15 - $start->x) * INF : ($v15 - $start->x) / $v27; - } - if($v40) { - $v23 = $v29 == 0 ? ($v17 - $start->y) * INF : ($v17 - $start->y) / $v29; - } - if($v41) { - $v25 = $v31 == 0 ? ($v19 - $start->z) * INF : ($v19 - $start->z) / $v31; - } + if($v39) $v21 = $v27 == 0 ? ($v15 - $start->x) * INF : ($v15 - $start->x) / $v27; + if($v40) $v23 = $v29 == 0 ? ($v17 - $start->y) * INF : ($v17 - $start->y) / $v29; + if($v41) $v25 = $v31 == 0 ? ($v19 - $start->z) * INF : ($v19 - $start->z) / $v31; - if($v21 < $v23 && $v21 < $v25) { + if($v21 < $v23 && $v21 < $v25){ $v42 = $xEnd > $xStart ? 4 : 5; $start->x = $v15; $start->y += $v29 * $v21; $start->z += $v31 * $v21; - } elseif($v23 < $v25) { + }elseif($v23 < $v25){ $v42 = $yEnd > $yStart ? 0 : 1; $start->x += $v27 * $v23; $start->y = $v17; $start->z += $v31 * $v23; - } else { + }else{ $v42 = $zEnd > $zStart ? 2 : 3; $start->x += $v27 * $v25; @@ -200,36 +156,28 @@ class Level { } $xStart = floor($start->x); - if($v42 == 5) { - --$xStart; - } + if($v42 == 5) --$xStart; $yStart = floor($start->y); - if($v42 == 1) { - --$yStart; - } + if($v42 == 1) --$yStart; $zStart = floor($start->z); - if($v42 == 3) { - --$zStart; - } + if($v42 == 3) --$zStart; [$blockID, $blockMeta] = $this->level->getBlock($xStart, $yStart, $zStart); $block = StaticBlock::getBlock($blockID); $aabb = $block::getAABB($this, $xStart, $yStart, $zStart); - if($blockID > 0 && $aabb != null) { //TODO also block::canColideCheck + if($blockID > 0 && $aabb != null){ //TODO also block::canColideCheck $v38 = $block::clip($this, $xStart, $yStart, $zStart, $start, $end); - if($v38 != null) { - return $v38; - } + if($v38 != null) return $v38; } } return null; } - public function isLavaInBB($aabb) { + public function isLavaInBB($aabb){ $minX = floor($aabb->minX); $maxX = floor($aabb->maxX + 1); $minY = floor($aabb->minY); @@ -237,14 +185,12 @@ class Level { $minZ = floor($aabb->minZ); $maxZ = floor($aabb->maxZ + 1); - for($x = $minX; $x < $maxX; ++$x) { - for($y = $minY; $y < $maxY; ++$y) { - for($z = $minZ; $z < $maxZ; ++$z) { + for($x = $minX; $x < $maxX; ++$x){ + for($y = $minY; $y < $maxY; ++$y){ + for($z = $minZ; $z < $maxZ; ++$z){ $blockId = $this->level->getBlockID($x, $y, $z); - if($blockId == LAVA || $blockId == STILL_LAVA) { - return true; - } + if($blockId == LAVA || $blockId == STILL_LAVA) return true; } } } @@ -252,7 +198,7 @@ class Level { return false; } - public function handleMaterialAcceleration(AxisAlignedBB $aabb, $materialType, Entity $entity) { + public function handleMaterialAcceleration(AxisAlignedBB $aabb, $materialType, Entity $entity){ $minX = floor($aabb->minX); $maxX = ceil($aabb->maxX); $minY = floor($aabb->minY); @@ -264,13 +210,13 @@ class Level { $appliedVelocity = false; $velocityVec = new Vector3(0, 0, 0); - for($x = $minX; $x < $maxX; ++$x) { - for($y = $minY; $y < $maxY; ++$y) { - for($z = $minZ; $z < $maxZ; ++$z) { + for($x = $minX; $x < $maxX; ++$x){ + for($y = $minY; $y < $maxY; ++$y){ + for($z = $minZ; $z < $maxZ; ++$z){ [$block, $meta] = $this->level->getBlock($x, $y, $z); - if(($materialType == 0 && ($block == WATER || $block == STILL_WATER)) || ($materialType == 1 && ($block == LAVA || $block == STILL_LAVA))) { //TODO better material system + if(($materialType == 0 && ($block == WATER || $block == STILL_WATER)) || ($materialType == 1 && ($block == LAVA || $block == STILL_LAVA))){ //TODO better material system $v16 = ($y + 1) - LiquidBlock::getPercentAir($meta); - if($maxY >= $v16) { + if($maxY >= $v16){ $appliedVelocity = true; StaticBlock::$prealloc[$block]::addVelocityToEntity($this, $x, $y, $z, $entity, $velocityVec); } @@ -280,7 +226,7 @@ class Level { } } - if($velocityVec->length() > 0) { //also checks is player flying + if($velocityVec->length() > 0){ //also checks is player flying $velocityVec = $velocityVec->normalize(); //TODO do not use vec methods $v18 = 0.014; $entity->speedX += $velocityVec->x * $v18; @@ -306,13 +252,11 @@ class Level { for($z = $z0; $z < $z1; ++$z) { for($y = $y0 - 1; $y < $y1; ++$y) { $bid = $this->level->getBlockID($x, $y, $z); - if($bid > 0) { + if($bid > 0){ $blockBounds = StaticBlock::$prealloc[$bid]::getCollisionBoundingBoxes($this, $x, $y, $z, $e); //StaticBlock::getBoundingBoxForBlockCoords($b, $x, $y, $z); - foreach($blockBounds as $blockBound) { - if($aABB->intersectsWith($blockBound)) { - $aABBs[] = $blockBound; - } + foreach($blockBounds as $blockBound){ + if($aABB->intersectsWith($blockBound)) $aABBs[] = $blockBound; } } } @@ -322,8 +266,8 @@ class Level { return $aABBs; } - public function __destruct() { - if(isset($this->level)) { + public function __destruct(){ + if(isset($this->level)){ $this->save(false, false, false, false); $this->level->close(); unset($this->level); @@ -331,46 +275,46 @@ class Level { unset($this->mobSpawner->level); } - public function isDay() { + public function isDay(){ return $this->getTime() % 19200 < TimeAPI::$phases["sunset"]; } - public function isNight() { + public function isNight(){ $t = $this->getTime() % 19200; return $t < TimeAPI::$phases["sunrise"] && $t > TimeAPI::$phases["sunset"]; } - public function save($force = false, $entities = true, $tiles = true, $blockupdates = true) { - if(!isset($this->level)) { + public function save($force = false, $entities = true, $tiles = true, $blockupdates = true){ + if(!isset($this->level)){ return false; } - if($this->server->saveEnabled === false and $force === false) { + if($this->server->saveEnabled === false and $force === false){ return; } - if($entities) { + if($entities){ $entities = []; - foreach($this->entityList as $entity) { - if($entity instanceof Entity) { + foreach($this->entityList as $entity){ + if($entity instanceof Entity){ $entities[] = $entity->createSaveData(); } } $this->entities->setAll($entities); $this->entities->save(); } - if($tiles) { + if($tiles){ $tiles = []; - foreach($this->server->api->tile->getAll($this) as $tile) { + foreach($this->server->api->tile->getAll($this) as $tile){ $tiles[] = $tile->data; } $this->tiles->setAll($tiles); $this->tiles->save(); } - if($blockupdates) { + if($blockupdates){ $blockUpdates = []; $updates = $this->server->query("SELECT x,y,z,type,delay FROM blockUpdates WHERE level = '" . $this->getName() . "';"); - if($updates !== false and $updates !== true) { + if($updates !== false and $updates !== true){ $timeu = microtime(true); - while(($bupdate = $updates->fetchArray(SQLITE3_ASSOC)) !== false) { + while(($bupdate = $updates->fetchArray(SQLITE3_ASSOC)) !== false){ $bupdate["delay"] = max(1, ($bupdate["delay"] - $timeu) * 20); $blockUpdates[] = $bupdate; } @@ -386,77 +330,75 @@ class Level { $this->nextSave = microtime(true) + 45; } - public function getName() { + public function getName(){ return $this->name;//return $this->level->getData("name"); } - public function useChunk($X, $Z, Player $player) { - if(!isset($this->usedChunks[$X . "." . $Z])) { + public function useChunk($X, $Z, Player $player){ + if(!isset($this->usedChunks[$X . "." . $Z])){ $this->usedChunks[$X . "." . $Z] = []; } $this->usedChunks[$X . "." . $Z][$player->CID] = true; - if(isset($this->level)) { + if(isset($this->level)){ $this->level->loadChunk($X, $Z); } } - public function freeAllChunks(Player $player) { - foreach($this->usedChunks as $i => $c) { + public function freeAllChunks(Player $player){ + foreach($this->usedChunks as $i => $c){ unset($this->usedChunks[$i][$player->CID]); } } - public function freeChunk($X, $Z, Player $player) { + public function freeChunk($X, $Z, Player $player){ unset($this->usedChunks[$X . "." . $Z][$player->CID]); } - public function checkCollisionsFor(Entity $e) { - if($e->level->getName() != $this->getName()) { + public function checkCollisionsFor(Entity $e){ + if($e->level->getName() != $this->getName()){ return false; //not the same world } - foreach($this->entityList as $e1) { - if($e->boundingBox->intersectsWith($e1->boundingBox) && $e1->isCollidable) { + foreach($this->entityList as $e1){ + if($e->boundingBox->intersectsWith($e1->boundingBox) && $e1->isCollidable){ $e->onCollideWith($e1); $e1->onCollideWith($e); } } } - public function isObstructed($e) { + public function isObstructed($e){ } - public function checkSleep() { //TODO events? - if(count($this->players) == 0) { - return false; - } - if($this->server->api->time->getPhase($this) === "night") { //TODO vanilla - foreach($this->players as $p) { - if(!$p->isSleeping || $p->sleepingTime < 100) { + public function checkSleep(){ //TODO events? + if(count($this->players) == 0) return false; + if($this->server->api->time->getPhase($this) === "night"){ //TODO vanilla + foreach($this->players as $p){ + if(!$p->isSleeping || $p->sleepingTime < 100){ return false; } } $this->server->api->time->set("day", $this); } - foreach($this->players as $p) { + foreach($this->players as $p){ $p->stopSleep(); } } - public function checkThings() { - if(!isset($this->level)) { + public function checkThings(){ + if(!isset($this->level)){ return false; } $now = microtime(true); $this->players = $this->server->api->player->getAll($this); - if(count($this->changedCount) > 0) { + if(count($this->changedCount) > 0){ arsort($this->changedCount); $reorder = false; - foreach($this->changedCount as $index => $count) { - if($count < 582) {//Optimal value, calculated using the relation between minichunks and single packets + foreach($this->changedCount as $index => $count){ + if($count < 582){//Optimal value, calculated using the relation between minichunks and single packets break; } - foreach($this->players as $p) { + foreach($this->players as $p){ unset($p->chunksLoaded[$index]); } $reorder = true; @@ -464,15 +406,15 @@ class Level { } $this->changedCount = []; - if($reorder) { - foreach($this->players as $p) { + if($reorder){ + foreach($this->players as $p){ $p->orderChunks(); } } - if(count($this->changedBlocks) > 0) { - foreach($this->changedBlocks as $i => $blocks) { - foreach($blocks as $b) { + if(count($this->changedBlocks) > 0){ + foreach($this->changedBlocks as $i => $blocks){ + foreach($blocks as $b){ $pk = new UpdateBlockPacket; $pk->x = ($b >> 32) & 0xff; $pk->y = ($b >> 24) & 0xff; @@ -487,33 +429,33 @@ class Level { } } - if($this->nextSave < $now) { + if($this->nextSave < $now){ $this->save(false, true, true, true); } } - public function isSpawnChunk($X, $Z) { + public function isSpawnChunk($X, $Z){ $spawnX = $this->level->getData("spawnX") >> 4; $spawnZ = $this->level->getData("spawnZ") >> 4; return abs($X - $spawnX) <= 1 and abs($Z - $spawnZ) <= 1; } - public function getBlockRaw(Vector3 $pos) { + public function getBlockRaw(Vector3 $pos){ $b = $this->level->getBlock($pos->x, $pos->y, $pos->z); return BlockAPI::get($b[0], $b[1], new Position($pos->x, $pos->y, $pos->z, $this)); } - public function setBlockRaw(Vector3 $pos, Block $block, $direct = true, $send = true) { - if(($ret = $this->level->setBlock($pos->x, $pos->y, $pos->z, $block->getID(), $block->getMetadata())) === true and $send !== false) { - if($direct === true) { + public function setBlockRaw(Vector3 $pos, Block $block, $direct = true, $send = true){ + if(($ret = $this->level->setBlock($pos->x, $pos->y, $pos->z, $block->getID(), $block->getMetadata())) === true and $send !== false){ + if($direct === true){ $this->addBlockToSendQueue($pos->x, $pos->y, $pos->z, $block->id, $block->meta); - } elseif($direct === false) { - if(!($pos instanceof Position)) { + }elseif($direct === false){ + if(!($pos instanceof Position)){ $pos = new Position($pos->x, $pos->y, $pos->z, $this); } $block->position($pos); $i = ($pos->x >> 4) . ":" . ($pos->y >> 4) . ":" . ($pos->z >> 4); - if(!isset($this->changedBlocks[$i])) { + if(!isset($this->changedBlocks[$i])){ $this->changedBlocks[$i] = []; $this->changedCount[$i] = 0; } @@ -523,75 +465,59 @@ class Level { } return $ret; } - public function fastSetBlockUpdateMeta($x, $y, $z, $meta, $updateBlock = false) { + public function fastSetBlockUpdateMeta($x, $y, $z, $meta, $updateBlock = false){ $this->level->setBlockDamage($x, $y, $z, $meta); $id = $this->level->getBlockID($x, $y, $z); $this->addBlockToSendQueue($x, $y, $z, $id, $meta); - if($updateBlock) { + if($updateBlock){ $this->updateNeighborsAt($x, $y, $z, $id); } } - public function updateNeighborsAt($x, $y, $z, $oldID) { + public function updateNeighborsAt($x, $y, $z, $oldID){ $block = $this->level->getBlockID($x - 1, $y, $z); - if($block) { - StaticBlock::getBlock($block)::neighborChanged($this, $x - 1, $y, $z, $x, $y, $z, $oldID); - } + if($block) StaticBlock::getBlock($block)::neighborChanged($this, $x - 1, $y, $z, $x, $y, $z, $oldID); $block = $this->level->getBlockID($x + 1, $y, $z); - if($block) { - StaticBlock::getBlock($block)::neighborChanged($this, $x + 1, $y, $z, $x, $y, $z, $oldID); - } + if($block) StaticBlock::getBlock($block)::neighborChanged($this, $x + 1, $y, $z, $x, $y, $z, $oldID); $block = $this->level->getBlockID($x, $y - 1, $z); - if($block) { - StaticBlock::getBlock($block)::neighborChanged($this, $x, $y - 1, $z, $x, $y, $z, $oldID); - } + if($block) StaticBlock::getBlock($block)::neighborChanged($this, $x, $y - 1, $z, $x, $y, $z, $oldID); $block = $this->level->getBlockID($x, $y + 1, $z); - if($block) { - StaticBlock::getBlock($block)::neighborChanged($this, $x, $y + 1, $z, $x, $y, $z, $oldID); - } + if($block) StaticBlock::getBlock($block)::neighborChanged($this, $x, $y + 1, $z, $x, $y, $z, $oldID); $block = $this->level->getBlockID($x, $y, $z - 1); - if($block) { - StaticBlock::getBlock($block)::neighborChanged($this, $x, $y, $z - 1, $x, $y, $z, $oldID); - } + if($block) StaticBlock::getBlock($block)::neighborChanged($this, $x, $y, $z - 1, $x, $y, $z, $oldID); $block = $this->level->getBlockID($x, $y, $z + 1); - if($block) { - StaticBlock::getBlock($block)::neighborChanged($this, $x, $y, $z + 1, $x, $y, $z, $oldID); - } + if($block) StaticBlock::getBlock($block)::neighborChanged($this, $x, $y, $z + 1, $x, $y, $z, $oldID); } - public function fastSetBlockUpdate($x, $y, $z, $id, $meta, $updateBlocksAround = false, $tiles = false) { + public function fastSetBlockUpdate($x, $y, $z, $id, $meta, $updateBlocksAround = false, $tiles = false){ $oldID = $this->level->getBlockID($x, $y, $z); $this->level->setBlock($x, $y, $z, $id, $meta); - if($tiles) { //TODO rewrite + if($tiles){ //TODO rewrite $this->server->api->tile->invalidateAll($this, $x, $y, $z); } - if($updateBlocksAround) { + if($updateBlocksAround){ self::updateNeighborsAt($x, $y, $z, $oldID); } $this->addBlockToSendQueue($x, $y, $z, $id, $meta); } - public function onTick(PocketMinecraftServer $server, $currentTime) { - if(!$this->stopTime) { - ++$this->time; - } - for($cX = 0; $cX < 16; ++$cX) { - for($cZ = 0; $cZ < 16; ++$cZ) { + public function onTick(PocketMinecraftServer $server, $currentTime){ + if(!$this->stopTime) ++$this->time; + for($cX = 0; $cX < 16; ++$cX){ + for($cZ = 0; $cZ < 16; ++$cZ){ $index = $this->level->getIndex($cX, $cZ); - if(!isset($this->level->chunks[$index]) || $this->level->chunks[$index] === false) { - continue; - } - for($c = 0; $c <= 20; ++$c) { + if(!isset($this->level->chunks[$index]) || $this->level->chunks[$index] === false) continue; + for($c = 0; $c <= 20; ++$c){ $xyz = mt_rand(0, 0xffffffff) >> 2; $x = $xyz & 0xf; $z = ($xyz >> 8) & 0xf; $y = ($xyz >> 16) & 0x7f; $id = $this->level->fastGetBlockID($cX, $y >> 4, $cZ, $x, $y & 0xf, $z, $index); - if(isset(self::$randomUpdateBlocks[$id])) { + if(isset(self::$randomUpdateBlocks[$id])){ $cl = StaticBlock::$prealloc[$id]; $cl::onRandomTick($this, ($cX << 4) + $x, $y, $z + ($cZ << 4)); } @@ -601,8 +527,8 @@ class Level { $this->totalMobsAmount = 0; $post = []; - foreach($this->entityList as $k => $e) { - if(!($e instanceof Entity)) { + foreach($this->entityList as $k => $e){ + if(!($e instanceof Entity)){ unset($this->entityList[$k]); unset($this->server->entities[$k]); //TODO try to remove from $entityListPositioned? @@ -610,7 +536,7 @@ class Level { } $dd = CORRECT_ENTITY_CLASSES[$e->class] ?? false; - if($dd === false || ($dd !== true && !isset($dd[$e->type]))) { + if($dd === false || ($dd !== true && !isset($dd[$e->type]))){ ConsoleAPI::warn("Entity $k has invalid entity! {$e->class} {$e->type}"); $e->close(); @@ -621,7 +547,7 @@ class Level { $curChunkZ = (int) $e->z >> 4; $index = "$curChunkX $curChunkZ"; - if(isset($this->entityListPositioned[$index][$k])) { + if(isset($this->entityListPositioned[$index][$k])){ unset($this->entityListPositioned[$index][$k]); } @@ -629,70 +555,68 @@ class Level { } $curChunkX = (int) $e->x >> 4; $curChunkZ = (int) $e->z >> 4; - if($e->class === ENTITY_MOB && !$e->isPlayer()) { + if($e->class === ENTITY_MOB && !$e->isPlayer()){ ++$this->totalMobsAmount; } - if($e->isPlayer() || $e->needsUpdate) { + if($e->isPlayer() || $e->needsUpdate){ $e->update($currentTime); - if(!$e->isPlayer()) { - $post[] = $k; - } + if(!$e->isPlayer()) $post[] = $k; } - if($e instanceof Entity) { + if($e instanceof Entity){ $newChunkX = (int) $e->x >> 4; $newChunkZ = (int) $e->z >> 4; - if($e->chunkX != $newChunkX || $e->chunkZ != $newChunkZ) { + if($e->chunkX != $newChunkX || $e->chunkZ != $newChunkZ){ $oldIndex = "{$e->chunkX} {$e->chunkZ}"; unset($this->entityListPositioned[$oldIndex][$e->eid]); - if($e->level == $this) { + if($e->level == $this){ $e->chunkX = $newChunkX; $e->chunkZ = $newChunkZ; $newIndex = "$newChunkX $newChunkZ"; $this->entityListPositioned[$newIndex][$e->eid] = $e->eid; } } - if($e->level != $this && isset($this->entityListPositioned["$curChunkX $curChunkZ"])) { + if($e->level != $this && isset($this->entityListPositioned["$curChunkX $curChunkZ"])){ unset($this->entityListPositioned["$curChunkX $curChunkZ"][$e->eid]); - } elseif($curChunkX != $newChunkX || $curChunkZ != $newChunkZ) { + }elseif($curChunkX != $newChunkX || $curChunkZ != $newChunkZ){ $index = "$curChunkX $curChunkZ"; //while creating index like $curChunkX << 32 | $curChunkZ is faster, placing it inside list is slow $newIndex = "$newChunkX $newChunkZ"; unset($this->entityListPositioned[$index][$e->eid]); $this->entityListPositioned[$newIndex][$e->eid] = $e->eid; //set to e->eid to avoid possible memory leaks } - if($e->searchForClosestPlayers) { + if($e->searchForClosestPlayers){ $e->handlePrePlayerSearcher(); - foreach($this->players as $player) { + foreach($this->players as $player){ $dist = ($e->x - $player->entity->x) * ($e->x - $player->entity->x) + ($e->y - $player->entity->y) * ($e->y - $player->entity->y) + ($e->z - $player->entity->z) * ($e->z - $player->entity->z); $e->handlePlayerSearcher($player, $dist); } } - } elseif(isset($this->entityListPositioned["$curChunkX $curChunkZ"])) { + }elseif(isset($this->entityListPositioned["$curChunkX $curChunkZ"])){ unset($this->entityListPositioned["$curChunkX $curChunkZ"][$k]); } } $this->checkSleep(); - if($server->ticks % 100 === 0) { + if($server->ticks % 100 === 0){ $this->mobSpawner->handle(); } - foreach($this->players as $player) { - foreach($post as $eid) { + foreach($this->players as $player){ + foreach($post as $eid){ $e = $this->entityList[$eid] ?? false; - if(!($e instanceof Entity)) { + if(!($e instanceof Entity)){ continue; } $player->addEntityMovementUpdateToQueue($e); } $player->sendEntityMovementUpdateQueue(); - foreach($this->queuedBlockUpdates as $ind => $update) { + foreach($this->queuedBlockUpdates as $ind => $update){ $x = $update[0]; $y = $update[1]; $z = $update[2]; @@ -707,7 +631,7 @@ class Level { $this->queuedBlockUpdates = []; } - public function isBoundingBoxOnFire(AxisAlignedBB $bb) { + public function isBoundingBoxOnFire(AxisAlignedBB $bb){ $minX = floor($bb->minX); $maxX = floor($bb->maxX + 1); $minY = floor($bb->minY); @@ -715,32 +639,30 @@ class Level { $minZ = floor($bb->minZ); $maxZ = floor($bb->maxZ + 1); - for($x = $minX; $x < $maxX; ++$x) { - for($y = $minY; $y < $maxY; ++$y) { - for($z = $minZ; $z < $maxZ; ++$z) { + for($x = $minX; $x < $maxX; ++$x){ + for($y = $minY; $y < $maxY; ++$y){ + for($z = $minZ; $z < $maxZ; ++$z){ $blockAt = $this->level->getBlockID($x, $y, $z); - if($blockAt == FIRE || $blockAt == STILL_LAVA || $blockAt == LAVA) { - return true; - } + if($blockAt == FIRE || $blockAt == STILL_LAVA || $blockAt == LAVA) return true; } } } return false; } - public function getEntitiesInAABBOfType(AxisAlignedBB $bb, $class) { + public function getEntitiesInAABBOfType(AxisAlignedBB $bb, $class){ $minChunkX = ((int) ($bb->minX)) >> 4; $minChunkZ = ((int) ($bb->minZ)) >> 4; $maxChunkX = ((int) ($bb->maxX)) >> 4; $maxChunkZ = ((int) ($bb->maxZ)) >> 4; $ents = []; - for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX) { - for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ) { + for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){ + for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ){ $ind = "$chunkX $chunkZ"; - foreach($this->entityListPositioned[$ind] ?? [] as $ind2 => $entid) { - if(isset($this->entityList[$entid]) && $this->entityList[$entid] instanceof Entity && $this->entityList[$entid]->class === $class && $this->entityList[$entid]->boundingBox->intersectsWith($bb)) { + foreach($this->entityListPositioned[$ind] ?? [] as $ind2 => $entid){ + if(isset($this->entityList[$entid]) && $this->entityList[$entid] instanceof Entity && $this->entityList[$entid]->class === $class && $this->entityList[$entid]->boundingBox->intersectsWith($bb)){ $ents[$entid] = $this->entityList[$entid]; - } elseif(!isset($this->entityList[$entid])) { + }elseif(!isset($this->entityList[$entid])){ ConsoleAPI::debug("Removing entity from level array at index $ind/$ind2: $entid"); unset($this->entityListPositioned[$ind][$ind2]); } @@ -752,20 +674,20 @@ class Level { /** * @return Entity[] */ - public function getEntitiesInAABB(AxisAlignedBB $bb) { + public function getEntitiesInAABB(AxisAlignedBB $bb){ $minChunkX = ((int) ($bb->minX)) >> 4; $minChunkZ = ((int) ($bb->minZ)) >> 4; $maxChunkX = ((int) ($bb->maxX)) >> 4; $maxChunkZ = ((int) ($bb->maxZ)) >> 4; $ents = []; //TODO also index by chunkY? - for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX) { - for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ) { + for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){ + for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ){ $ind = "$chunkX $chunkZ"; - foreach($this->entityListPositioned[$ind] ?? [] as $ind2 => $entid) { - if(isset($this->entityList[$entid]) && $this->entityList[$entid] instanceof Entity && $this->entityList[$entid]->boundingBox->intersectsWith($bb)) { + foreach($this->entityListPositioned[$ind] ?? [] as $ind2 => $entid){ + if(isset($this->entityList[$entid]) && $this->entityList[$entid] instanceof Entity && $this->entityList[$entid]->boundingBox->intersectsWith($bb)){ $ents[$entid] = $this->entityList[$entid]; - } elseif(!isset($this->entityList[$entid])) { + }elseif(!isset($this->entityList[$entid])){ ConsoleAPI::debug("Removing entity from level array at index $ind/$ind2: $entid"); unset($this->entityListPositioned[$ind][$ind2]); } @@ -775,28 +697,28 @@ class Level { return $ents; } - public function addBlockToSendQueue($x, $y, $z, $id, $meta) { - if(!$this->forceDisableBlockQueue) { + public function addBlockToSendQueue($x, $y, $z, $id, $meta){ + if(!$this->forceDisableBlockQueue){ $this->queuedBlockUpdates["$x $y $z"] = [$x, $y, $z, $id, $meta]; } } - public function setBlock(Vector3 $pos, Block $block, $update = true, $tiles = false, $direct = false) { - if(!isset($this->level) or (($pos instanceof Position) and $pos->level !== $this) or $pos->x < 0 or $pos->y < 0 or $pos->z < 0) { + public function setBlock(Vector3 $pos, Block $block, $update = true, $tiles = false, $direct = false){ + if(!isset($this->level) or (($pos instanceof Position) and $pos->level !== $this) or $pos->x < 0 or $pos->y < 0 or $pos->z < 0){ return false; } $oldID = $this->level->getBlockID($pos->x, $pos->y, $pos->z); $ret = $this->level->setBlock($pos->x, $pos->y, $pos->z, $block->getID(), $block->getMetadata()); - if($ret === true) { - if(!($pos instanceof Position)) { + if($ret === true){ + if(!($pos instanceof Position)){ $pos = new Position($pos->x, $pos->y, $pos->z, $this); } $block->position($pos); - if($direct === true) { + if($direct === true){ $this->addBlockToSendQueue($pos->x, $pos->y, $pos->z, $block->id, $block->meta); - } else { + }else{ $i = ($pos->x >> 4) . ":" . ($pos->y >> 4) . ":" . ($pos->z >> 4); - if(!isset($this->changedBlocks[$i])) { + if(!isset($this->changedBlocks[$i])){ $this->changedBlocks[$i] = []; $this->changedCount[$i] = 0; } @@ -804,11 +726,11 @@ class Level { ++$this->changedCount[$i]; } - if($tiles === true) { + if($tiles === true){ $this->server->api->tile->invalidateAll($this, $pos->x, $pos->y, $pos->z); } - if($update === true) { + if($update === true){ $this->updateNeighborsAt($pos->x, $pos->y, $pos->z, $oldID); } @@ -816,105 +738,105 @@ class Level { return $ret; } - public function getMiniChunk($X, $Z, $Y) { - if(!isset($this->level)) { + public function getMiniChunk($X, $Z, $Y){ + if(!isset($this->level)){ return false; } return $this->level->getMiniChunk($X, $Z, $Y); } - public function setMiniChunk($X, $Z, $Y, $data) { - if(!isset($this->level)) { + public function setMiniChunk($X, $Z, $Y, $data){ + if(!isset($this->level)){ return false; } $this->changedCount[$X . ":" . $Y . ":" . $Z] = 4096; return $this->level->setMiniChunk($X, $Z, $Y, $data); } - public function loadChunk($X, $Z) { - if(!isset($this->level)) { + public function loadChunk($X, $Z){ + if(!isset($this->level)){ return false; } return $this->level->loadChunk($X, $Z); } - public function unloadChunk($X, $Z, $force = false) { - if(!isset($this->level)) { + public function unloadChunk($X, $Z, $force = false){ + if(!isset($this->level)){ return false; } - if($force !== true and $this->isSpawnChunk($X, $Z)) { + if($force !== true and $this->isSpawnChunk($X, $Z)){ return false; } return $this->level->unloadChunk($X, $Z, $this->server->saveEnabled); } - public function getOrderedChunk($X, $Z, $Yndex) { - if(!isset($this->level)) { + public function getOrderedChunk($X, $Z, $Yndex){ + if(!isset($this->level)){ return false; } $raw = []; - for($Y = 0; $Y < 8; ++$Y) { - if(($Yndex & (1 << $Y)) > 0) { + for($Y = 0; $Y < 8; ++$Y){ + if(($Yndex & (1 << $Y)) > 0){ $raw[$Y] = $this->level->getMiniChunk($X, $Z, $Y); } } $ordered = ""; $flag = chr($Yndex); - for($j = 0; $j < 256; ++$j) { + for($j = 0; $j < 256; ++$j){ $ordered .= $flag; - foreach($raw as $mini) { + foreach($raw as $mini){ $ordered .= substr($mini, $j << 5, 24); //16 + 8 } } return $ordered; } - public function getOrderedMiniChunk($X, $Z, $Y) { - if(!isset($this->level)) { + public function getOrderedMiniChunk($X, $Z, $Y){ + if(!isset($this->level)){ return false; } $raw = $this->level->getMiniChunk($X, $Z, $Y); $ordered = ""; $flag = chr(1 << $Y); - for($j = 0; $j < 256; ++$j) { + for($j = 0; $j < 256; ++$j){ $ordered .= $flag . substr($raw, $j << 5, 24); //16 + 8 } return $ordered; } - public function getSafeSpawn($spawn = false) { - if($spawn === false) { + public function getSafeSpawn($spawn = false){ + if($spawn === false){ $spawn = $this->getSpawn(); } - if($spawn instanceof Vector3) { + if($spawn instanceof Vector3){ $x = (int) round($spawn->x); $fy = $y = (int) round($spawn->y); $z = (int) round($spawn->z); - if($x < 0 || $x > 255 || $z < 0 || $z > 255) { + if($x < 0 || $x > 255 || $z < 0 || $z > 255){ return new Position($x, 128, $z, $this); } - for(; $y > 0; --$y) { + for(; $y > 0; --$y){ $v = new Vector3($x, $y, $z); $b = $this->getBlock($v->getSide(0)); - if($b === false) { + if($b === false){ return $spawn; - } elseif(!($b instanceof AirBlock)) { + }elseif(!($b instanceof AirBlock)){ break; } } - if($y == 0) { + if($y == 0){ return new Position($x, $fy, $z, $this); //force tp to default if pos is empty } - for(; $y < 128; ++$y) { + for(; $y < 128; ++$y){ $v = new Vector3($x, $y, $z); - if($this->getBlock($v->getSide(1)) instanceof AirBlock) { - if($this->getBlock($v) instanceof AirBlock) { + if($this->getBlock($v->getSide(1)) instanceof AirBlock){ + if($this->getBlock($v) instanceof AirBlock){ return new Position($x, $y, $z, $this); } - } else { + }else{ ++$y; } } @@ -923,8 +845,8 @@ class Level { return false; } - public function getSpawn() { - if(!isset($this->level)) { + public function getSpawn(){ + if(!isset($this->level)){ return false; } return new Position($this->level->getData("spawnX"), $this->level->getData("spawnY"), $this->level->getData("spawnZ"), $this); @@ -938,7 +860,7 @@ class Level { * @return GenericBlock | false if failed */ - public function getBlockWithoutVector($x, $y, $z, $positionfy = true) { + public function getBlockWithoutVector($x, $y, $z, $positionfy = true){ $b = $this->level->getBlock((int) $x, (int) $y, (int) $z); return BlockAPI::get($b[0], $b[1], $positionfy ? new Position($x, $y, $z, $this) : false); } @@ -947,15 +869,15 @@ class Level { * Recommended to use {@link getBlockWithoutVector()} if you dont have the vector * @return Block|false if failed */ - public function getBlock(Vector3 $pos) { - if(!isset($this->level) or ($pos instanceof Position) and $pos->level !== $this) { + public function getBlock(Vector3 $pos){ + if(!isset($this->level) or ($pos instanceof Position) and $pos->level !== $this){ return false; } return $this->getBlockWithoutVector($pos->x, $pos->y, $pos->z); } - public function setSpawn(Vector3 $pos) { - if(!isset($this->level)) { + public function setSpawn(Vector3 $pos){ + if(!isset($this->level)){ return false; } $this->level->setData("spawnX", $pos->x); @@ -963,69 +885,69 @@ class Level { $this->level->setData("spawnZ", $pos->z); } - public function getTime() { + public function getTime(){ return (int) ($this->time); } - public function setTime($time) { + public function setTime($time){ $this->startTime = $this->time = (int) $time; $this->startCheck = microtime(true); $this->checkTime(); } - public function checkTime() { - if(!isset($this->level)) { + public function checkTime(){ + if(!isset($this->level)){ return false; } $now = microtime(true); - if($this->stopTime) { + if($this->stopTime){ $time = $this->startTime; - } else { + }else{ $time = $this->startTime + ($now - $this->startCheck) * 20; } - if($this->server->api->dhandle("time.change", ["level" => $this, "time" => $time]) !== false) { //send time to player every 5 ticks + if($this->server->api->dhandle("time.change", ["level" => $this, "time" => $time]) !== false){ //send time to player every 5 ticks $this->time = $time; $pk = new SetTimePacket; $pk->time = (int) $this->time; $pk->started = $this->stopTime == false; $this->server->api->player->broadcastPacket($this->players, $pk); - } else { + }else{ $this->time -= 20 * 13; } } - public function isTimeStopped() { + public function isTimeStopped(){ return $this->stopTime; } - public function stopTime() { + public function stopTime(){ $this->stopTime = true; $this->startCheck = 0; $this->checkTime(); } - public function startTime() { + public function startTime(){ $this->stopTime = false; $this->startCheck = microtime(true); $this->checkTime(); } - public function getSeed() { - if(!isset($this->level)) { + public function getSeed(){ + if(!isset($this->level)){ return false; } return (int) $this->level->getData("seed"); } - public function setSeed($seed) { - if(!isset($this->level)) { + public function setSeed($seed){ + if(!isset($this->level)){ return false; } $this->level->setData("seed", (int) $seed); } - public function scheduleBlockUpdate(Position $pos, $delay, $type = BLOCK_UPDATE_SCHEDULED) { - if(!isset($this->level)) { + public function scheduleBlockUpdate(Position $pos, $delay, $type = BLOCK_UPDATE_SCHEDULED){ + if(!isset($this->level)){ return false; } return $this->server->api->block->scheduleBlockUpdate($pos, $delay, $type); diff --git a/src/world/LevelImport.php b/src/world/LevelImport.php index b42743dc..49f21773 100644 --- a/src/world/LevelImport.php +++ b/src/world/LevelImport.php @@ -1,33 +1,33 @@ path = $path; } - public function import() { - if(file_exists($this->path . "tileEntities.dat")) { //OldPM + public function import(){ + if(file_exists($this->path . "tileEntities.dat")){ //OldPM $level = unserialize(file_get_contents($this->path . "level.dat")); console("[INFO] Importing OldPM level \"" . $level["LevelName"] . "\" to PMF format"); $entities = new Config($this->path . "entities.yml", CONFIG_YAML, unserialize(file_get_contents($this->path . "entities.dat"))); $entities->save(); $tiles = new Config($this->path . "tiles.yml", CONFIG_YAML, unserialize(file_get_contents($this->path . "tileEntities.dat"))); $tiles->save(); - } elseif(file_exists($this->path . "chunks.dat") and file_exists($this->path . "level.dat")) { //Pocket + }elseif(file_exists($this->path . "chunks.dat") and file_exists($this->path . "level.dat")){ //Pocket $nbt = new NBT(); $nbt->load(substr(file_get_contents($this->path . "level.dat"), 8)); $level = array_shift($nbt->tree); - if($level["LevelName"] == "") { + if($level["LevelName"] == ""){ $level["LevelName"] = "world" . time(); } console("[INFO] Importing Pocket level \"" . $level["LevelName"] . "\" to PMF format"); unset($level["Player"]); $nbt->load(substr(file_get_contents($this->path . "entities.dat"), 12)); $entities = array_shift($nbt->tree); - if(!isset($entities["TileEntities"])) { + if(!isset($entities["TileEntities"])){ $entities["TileEntities"] = []; } $tiles = $entities["TileEntities"]; @@ -36,7 +36,7 @@ class LevelImport { $entities->save(); $tiles = new Config($this->path . "tiles.yml", CONFIG_YAML, $tiles); $tiles->save(); - } else { + }else{ return false; } @@ -54,8 +54,8 @@ class LevelImport { $chunks = new PocketChunkParser(); $chunks->loadFile($this->path . "chunks.dat"); $chunks->loadMap(); - for($Z = 0; $Z < 16; ++$Z) { - for($X = 0; $X < 16; ++$X) { + for($Z = 0; $Z < 16; ++$Z){ + for($X = 0; $X < 16; ++$X){ $chunk = [ 0 => "", 1 => "", @@ -66,18 +66,18 @@ class LevelImport { 6 => "", 7 => "" ]; - for($z = 0; $z < 16; ++$z) { - for($x = 0; $x < 16; ++$x) { + for($z = 0; $z < 16; ++$z){ + for($x = 0; $x < 16; ++$x){ $block = $chunks->getChunkColumn($X, $Z, $x, $z, 0); $meta = $chunks->getChunkColumn($X, $Z, $x, $z, 1); - for($Y = 0; $Y < 8; ++$Y) { + for($Y = 0; $Y < 8; ++$Y){ $chunk[$Y] .= substr($block, $Y << 4, 16); $chunk[$Y] .= substr($meta, $Y << 3, 8); $chunk[$Y] .= "\x00\x00\x00\x00\x00\x00\x00\x00"; } } } - foreach($chunk as $Y => $data) { + foreach($chunk as $Y => $data){ $pmf->setMiniChunk($X, $Z, $Y, $data); } $pmf->saveChunk($X, $Z); @@ -86,29 +86,15 @@ class LevelImport { } $chunks->map = null; $chunks = null; - if(file_exists($this->path . "level.dat")) { - @unlink($this->path . "level.dat"); - } - if(file_exists($this->path . "level.dat_old")) { - @unlink($this->path . "level.dat_old"); - } - if(file_exists($this->path . "player.dat")) { - @unlink($this->path . "player.dat"); - } - if(file_exists($this->path . "entities.dat")) { - @unlink($this->path . "entities.dat"); - } - if(file_exists($this->path . "chunks.dat")) { - @unlink($this->path . "chunks.dat"); - } - if(file_exists($this->path . "chunks.dat.gz")) { - @unlink($this->path . "chunks.dat.gz"); - } - if(file_exists($this->path . "tiles.dat")) { - @unlink($this->path . "tiles.dat"); - } + if(file_exists($this->path . "level.dat")) @unlink($this->path . "level.dat"); + if(file_exists($this->path . "level.dat_old")) @unlink($this->path . "level.dat_old"); + if(file_exists($this->path . "player.dat")) @unlink($this->path . "player.dat"); + if(file_exists($this->path . "entities.dat")) @unlink($this->path . "entities.dat"); + if(file_exists($this->path . "chunks.dat")) @unlink($this->path . "chunks.dat"); + if(file_exists($this->path . "chunks.dat.gz")) @unlink($this->path . "chunks.dat.gz"); + if(file_exists($this->path . "tiles.dat")) @unlink($this->path . "tiles.dat"); unset($chunks, $level, $entities, $tiles, $nbt); return true; } -} +} \ No newline at end of file diff --git a/src/world/MobSpawner.php b/src/world/MobSpawner.php index dd8aa69e..53bf5850 100644 --- a/src/world/MobSpawner.php +++ b/src/world/MobSpawner.php @@ -1,9 +1,7 @@ server = ServerAPI::request(); $this->level = $level; } - public function countEntities() { + public function countEntities(){ return $this->level->totalMobsAmount; } - public function checkDespawn(Living $living) { - if(!isset($this->entityAffectedPlayers[$living->eid])) { + public function checkDespawn(Living $living){ + if(!isset($this->entityAffectedPlayers[$living->eid])){ return false; } $playerID = $this->entityAffectedPlayers[$living->eid]; $player = $this->level->entityList[$playerID] ?? false; - if($player === false) { + if($player === false){ //TODO try retargetting other player? return true; - } else { + }else{ $diffX = $living->x - $player->x; $diffZ = $living->z - $player->z; $dist = $diffX * $diffX + $diffZ * $diffZ; - if($dist <= 512) { + if($dist <= 512){ return false; } @@ -43,35 +41,33 @@ class MobSpawner { } - public function handle() { - if($this->countEntities() > self::$MOB_LIMIT || count($this->level->players) <= 0) { + public function handle(){ + if($this->countEntities() > self::$MOB_LIMIT || count($this->level->players) <= 0){ return false; //not spawning } $svd = $this->totalMobsPerPlayer; $this->totalMobsPerPlayer = min(ceil(self::$MOB_LIMIT / count($this->level->players)), self::$maxMobsNearPlayerAtOnce); - if($svd != $this->totalMobsPerPlayer) { - ConsoleAPI::debug("Changed total mobs per player from $svd to {$this->totalMobsPerPlayer}."); - } + if($svd != $this->totalMobsPerPlayer) ConsoleAPI::debug("Changed total mobs per player from $svd to {$this->totalMobsPerPlayer}."); return $this->spawnMobs(); } - public function spawnMobs() { + public function spawnMobs(){ $phase = $this->server->api->time->getPhase($this->level); - if(self::$spawnAnimals && ($phase == "day" || $phase == "sunrise")) { //Animal + if(self::$spawnAnimals && ($phase == "day" || $phase == "sunrise")){ //Animal $type = mt_rand(10, 13); $baby = false; $grassOnly = true; - } elseif(self::$spawnMobs && ($phase == "night" || $phase == "sunset") && $this->server->difficulty > 0) { //Monster, true night + }elseif(self::$spawnMobs && ($phase == "night" || $phase == "sunset") && $this->server->difficulty > 0){ //Monster, true night $type = mt_rand(32, 35); $grassOnly = false; $baby = 2; - } else { + }else{ return false; } - foreach($this->level->players as $player) { - if(isset($this->playerAffectedEIDS[$player->entity->eid]) && count($this->playerAffectedEIDS[$player->entity->eid]) > $this->totalMobsPerPlayer) { + foreach($this->level->players as $player){ + if(isset($this->playerAffectedEIDS[$player->entity->eid]) && count($this->playerAffectedEIDS[$player->entity->eid]) > $this->totalMobsPerPlayer){ continue; } @@ -80,36 +76,34 @@ class MobSpawner { $diffX = $x - $player->entity->x; $diffZ = $z - $player->entity->z; $dist = $diffX * $diffX + $diffZ * $diffZ; - if($dist < 768) { + if($dist < 768){ continue; } $cnt = mt_rand(1, 3); - for($i = 0; $i < $cnt; ++$i) { + for($i = 0; $i < $cnt; ++$i){ $xMob = $x + mt_rand(-3, 3); $zMob = $z + mt_rand(-3, 3); $y = $this->getSafeY($xMob, $zMob, $grassOnly, $type >= 32 && $type <= 36 && $type != 35); - if(!$y || $y < 0) { + if(!$y || $y < 0){ continue; } $data = $this->genPosData($xMob, $y + 0.5, $zMob); - if($baby != 2) { - $data["IsBaby"] = $baby; - } + if($baby != 2) $data["IsBaby"] = $baby; $e = $this->server->api->entity->add($this->level, 2, $type, $data); - if($e instanceof Entity) { + if($e instanceof Entity){ $this->server->api->entity->spawnToAll($e); ConsoleAPI::debug("$type spawned at $xMob, $y, $zMob"); } - if(!isset($this->playerAffectedEIDS[$player->entity->eid])) { + if(!isset($this->playerAffectedEIDS[$player->entity->eid])){ $this->playerAffectedEIDS[$player->entity->eid] = [$e->eid => true]; - } else { + }else{ $this->playerAffectedEIDS[$player->entity->eid][$e->eid] = true; } @@ -121,7 +115,7 @@ class MobSpawner { return true; } - private function genPosData($x, $y, $z) { + private function genPosData($x, $y, $z){ return [ "x" => $x + 0.5, "y" => $y, @@ -129,9 +123,9 @@ class MobSpawner { ]; } - protected function getSafeY($x, $z, $grassOnly = false, $highMob = false) { //first safe block //TODO check boundingbox + protected function getSafeY($x, $z, $grassOnly = false, $highMob = false){ //first safe block //TODO check boundingbox $allowed = []; - for($y = 0; $y < 128; ++$y) { + for($y = 0; $y < 128; ++$y){ $b = $this->level->level->getBlockID($x, $y, $z); $b2 = $this->level->level->getBlockID($x, $y + 1, $z); $b1 = $this->level->level->getBlockID($x, $y - 1, $z); @@ -139,7 +133,7 @@ class MobSpawner { !StaticBlock::getIsSolid($b) && !StaticBlock::getIsLiquid($b) && (StaticBlock::getIsSolid($b1) && (!$grassOnly || $b1 === GRASS) && (!$highMob || !StaticBlock::getIsSolid($b2) && !StaticBlock::getIsLiquid($b2))) - ) { + ){ $allowed[] = $y; } } @@ -147,3 +141,4 @@ class MobSpawner { return empty($allowed) ? -1 : $allowed[mt_rand(0, count($allowed) - 1)]; } } + diff --git a/src/world/MovingObjectPosition.php b/src/world/MovingObjectPosition.php index a470538d..b3f535f5 100644 --- a/src/world/MovingObjectPosition.php +++ b/src/world/MovingObjectPosition.php @@ -1,6 +1,6 @@ blockX} {$this->blockY} {$this->blockZ}, side: {$this->sideHit} hitVec: {$this->hitVector} entityHit: {$this->entityHit}}"; } @@ -37,7 +37,7 @@ class MovingObjectPosition { * * @return MovingObjectPosition */ - public static function fromBlock($x, $y, $z, $side, Vector3 $hitVector) { + public static function fromBlock($x, $y, $z, $side, Vector3 $hitVector){ $ob = new MovingObjectPosition; $ob->typeOfHit = 0; $ob->blockX = $x; @@ -52,11 +52,11 @@ class MovingObjectPosition { * * @return MovingObjectPosition */ - public static function fromEntity(Entity $entity) { + public static function fromEntity(Entity $entity){ $ob = new MovingObjectPosition; $ob->typeOfHit = 1; $ob->entityHit = $entity; $ob->hitVector = new Vector3($entity->x, $entity->y, $entity->z); return $ob; } -} +} \ No newline at end of file diff --git a/src/world/PocketChunkParser.php b/src/world/PocketChunkParser.php index 0917aa62..2c85bb4a 100644 --- a/src/world/PocketChunkParser.php +++ b/src/world/PocketChunkParser.php @@ -1,26 +1,24 @@ raw = gzinflate(file_get_contents($file . ".gz")); $r = @gzinflate($this->raw); - if($r !== false and $r != "") { + if($r !== false and $r != ""){ $this->raw = $r; } @unlink($file . ".gz"); file_put_contents($file, $this->raw); - } elseif(!file_exists($file)) { + }elseif(!file_exists($file)){ return false; - } else { + }else{ $this->raw = file_get_contents($file); } $this->file = $file; @@ -28,32 +26,32 @@ class PocketChunkParser { return true; } - public function loadRaw($raw, $file) { + public function loadRaw($raw, $file){ $this->file = $file; $this->raw = $raw; $this->chunkLength = $this->sectorLength * ord($this->raw[0]); return true; } - public function getChunk($X, $Z) { + public function getChunk($X, $Z){ $X = (int) $X; $Z = (int) $Z; return substr($this->raw, $this->getOffset($X, $Z), $this->chunkLength); } - private function getOffset($X, $Z) { + private function getOffset($X, $Z){ return $this->location[$X + ($Z << 5)]; } - public function loadMap() { - if($this->raw == "") { + public function loadMap(){ + if($this->raw == ""){ return false; } $this->loadLocationTable(); console("[DEBUG] Loading chunks...", true, true, 2); - for($x = 0; $x < 16; ++$x) { + for($x = 0; $x < 16; ++$x){ $this->map[$x] = []; - for($z = 0; $z < 16; ++$z) { + for($z = 0; $z < 16; ++$z){ $this->map[$x][$z] = $this->parseChunk($x, $z); } } @@ -61,13 +59,13 @@ class PocketChunkParser { console("[DEBUG] Chunks loaded!", true, true, 2); } - private function loadLocationTable() { + private function loadLocationTable(){ $this->location = []; console("[DEBUG] Loading Chunk Location table...", true, true, 2); - for($offset = 0; $offset < 0x1000; $offset += 4) { + for($offset = 0; $offset < 0x1000; $offset += 4){ $data = Utils::readLInt(substr($this->raw, $offset, 4)); $sectors = $data & 0xff; - if($sectors === 0) { + if($sectors === 0){ continue; } $sectorLocation = $data >> 8; @@ -75,7 +73,7 @@ class PocketChunkParser { } } - public function parseChunk($X, $Z) { + public function parseChunk($X, $Z){ $X = (int) $X; $Z = (int) $Z; $offset = $this->getOffset($X, $Z); @@ -87,9 +85,9 @@ class PocketChunkParser { 2 => [], //SkyLight 3 => [], //BlockLight ]; - foreach($chunk as $section => &$data) { + foreach($chunk as $section => &$data){ $l = $section === 0 ? 128 : 64; - for($i = 0; $i < 256; ++$i) { + for($i = 0; $i < 256; ++$i){ $data[$i] = substr($this->raw, $offset, $l); $offset += $l; } @@ -97,13 +95,13 @@ class PocketChunkParser { return $chunk; } - public function saveMap($final = false) { + public function saveMap($final = false){ console("[DEBUG] Saving chunks...", true, true, 2); $fp = fopen($this->file, "r+b"); flock($fp, LOCK_EX); - foreach($this->map as $x => $d) { - foreach($d as $z => $chunk) { + foreach($this->map as $x => $d){ + foreach($d as $z => $chunk){ fseek($fp, $this->getOffset($x, $z)); fwrite($fp, $this->writeChunk($x, $z), $this->chunkLength); } @@ -114,41 +112,41 @@ class PocketChunkParser { file_put_contents($this->file . ".gz", gzdeflate(gzdeflate(file_get_contents($this->file), 9), 9)); //Double compression for flat maps $compressed = filesize($this->file . ".gz"); console("[DEBUG] Saved chunks.dat.gz with " . round(($compressed / $original) * 100, 2) . "% (" . round($compressed / 1024, 2) . "KB) of the original size", true, true, 2); - if($final === true) { + if($final === true){ @unlink($this->file); } } - public function writeChunk($X, $Z) { + public function writeChunk($X, $Z){ $X = (int) $X; $Z = (int) $Z; - if(!isset($this->map[$X][$Z])) { + if(!isset($this->map[$X][$Z])){ return false; } $chunk = ""; - foreach($this->map[$X][$Z] as $section => $data) { - for($i = 0; $i < 256; ++$i) { + foreach($this->map[$X][$Z] as $section => $data){ + for($i = 0; $i < 256; ++$i){ $chunk .= $data[$i]; } } return Utils::writeLInt(strlen($chunk)) . $chunk; } - public function getFloor($x, $z) { + public function getFloor($x, $z){ $X = $x >> 4; $Z = $z >> 4; $aX = $x - ($X << 4); $aZ = $z - ($Z << 4); $index = $aZ + ($aX << 4); - for($y = 127; $y <= 0; --$y) { - if($this->map[$X][$Z][0][$index][$y] !== "\x00") { + for($y = 127; $y <= 0; --$y){ + if($this->map[$X][$Z][0][$index][$y] !== "\x00"){ break; } } return $y; } - public function getBlock($x, $y, $z) { + public function getBlock($x, $y, $z){ $x = (int) $x; $y = (int) $y; $z = (int) $z; @@ -159,20 +157,20 @@ class PocketChunkParser { $index = $aZ + ($aX << 4); $block = ord($this->map[$X][$Z][0][$index][$y]); $meta = ord($this->map[$X][$Z][1][$index][$y >> 1]); - if(($y & 1) === 0) { + if(($y & 1) === 0){ $meta = $meta & 0x0F; - } else { + }else{ $meta = $meta >> 4; } return [$block, $meta]; } - public function getChunkColumn($X, $Z, $x, $z, $type = 0) { + public function getChunkColumn($X, $Z, $x, $z, $type = 0){ $index = $z + ($x << 4); return $this->map[$X][$Z][$type][$index]; } - public function setBlock($x, $y, $z, $block, $meta = 0) { + public function setBlock($x, $y, $z, $block, $meta = 0){ $x = (int) $x; $y = (int) $y; $z = (int) $z; @@ -183,12 +181,12 @@ class PocketChunkParser { $index = $aZ + ($aX << 4); $this->map[$X][$Z][0][$index][$y] = chr($block); $old_meta = ord($this->map[$X][$Z][1][$index][$y >> 1]); - if(($y & 1) === 0) { + if(($y & 1) === 0){ $meta = ($old_meta & 0xF0) | ($meta & 0x0F); - } else { + }else{ $meta = (($meta << 4) & 0xF0) | ($old_meta & 0x0F); } $this->map[$X][$Z][1][$index][$y >> 1] = chr($meta); } -} +} \ No newline at end of file diff --git a/src/world/Position.php b/src/world/Position.php index d7308c2d..dff85467 100644 --- a/src/world/Position.php +++ b/src/world/Position.php @@ -1,13 +1,13 @@ x, $x->y, $x->z); - } else { + }else{ $this->x = $x; $this->y = $y; $this->z = $z; @@ -15,25 +15,25 @@ class Position extends Vector3 { $this->level = $level; } - public function setXYZLevel($x, $y, $z, Level $level) { + public function setXYZLevel($x, $y, $z, Level $level){ $this->x = $x; $this->y = $y; $this->z = $z; $this->level = $level; } - public function getSide($side, $step = 1) { + public function getSide($side, $step = 1){ return new Position(parent::getSide($side, $step), 0, 0, $this->level); } - public function distance($x = 0, $y = 0, $z = 0) { - if(($x instanceof Position) and $x->level !== $this->level) { + public function distance($x = 0, $y = 0, $z = 0){ + if(($x instanceof Position) and $x->level !== $this->level){ return PHP_INT_MAX; } return parent::distance($x, $y, $z); } - public function __toString() { + public function __toString(){ return "Position(level=" . $this->level->getName() . ",x=" . $this->x . ",y=" . $this->y . ",z=" . $this->z . ")"; } -} +} \ No newline at end of file diff --git a/src/world/Tile.php b/src/world/Tile.php index 92cb0f36..2ffefb84 100644 --- a/src/world/Tile.php +++ b/src/world/Tile.php @@ -1,6 +1,6 @@ server = ServerAPI::request(); $this->level = $level; $this->normal = true; $this->class = $class; $this->data = $data; $this->closed = false; - if($class === false) { + if($class === false){ $this->closed = true; } $this->name = ""; @@ -37,83 +35,83 @@ class Tile extends Position { $this->y = (int) $y; $this->z = (int) $z; $this->server->query("INSERT OR REPLACE INTO tiles (ID, level, class, x, y, z) VALUES (" . $this->id . ", '" . $this->level->getName() . "', '" . $this->class . "', " . $this->x . ", " . $this->y . ", " . $this->z . ");"); - switch($this->class) { + switch($this->class){ case TILE_CHEST: case TILE_SIGN: $this->server->query("UPDATE tiles SET spawnable = 1 WHERE ID = " . $this->id . ";"); break; case TILE_FURNACE: - if(!isset($this->data["BurnTime"]) or $this->data["BurnTime"] < 0) { + if(!isset($this->data["BurnTime"]) or $this->data["BurnTime"] < 0){ $this->data["BurnTime"] = 0; } - if(!isset($this->data["CookTime"]) or $this->data["CookTime"] < 0 or ($this->data["BurnTime"] === 0 and $this->data["CookTime"] > 0)) { + if(!isset($this->data["CookTime"]) or $this->data["CookTime"] < 0 or ($this->data["BurnTime"] === 0 and $this->data["CookTime"] > 0)){ $this->data["CookTime"] = 0; } - if(!isset($this->data["MaxTime"])) { + if(!isset($this->data["MaxTime"])){ $this->data["MaxTime"] = $this->data["BurnTime"]; $this->data["BurnTicks"] = 0; } - if($this->data["BurnTime"] > 0) { + if($this->data["BurnTime"] > 0){ $this->update(); } break; } } - public function update() { - if($this->closed === true) { + public function update(){ + if($this->closed === true){ return false; } - if($this->class === TILE_FURNACE) { + if($this->class === TILE_FURNACE){ $fuel = $this->getSlot(1); $raw = $this->getSlot(0); $product = $this->getSlot(2); $smelt = $raw->getSmeltItem(); $canSmelt = ($smelt !== false and $raw->count > 0 and (($product->getID() === $smelt->getID() and $product->getMetadata() === $smelt->getMetadata() and $product->count < $product->getMaxStackSize()) or $product->getID() === AIR)); - if($this->data["BurnTime"] <= 0 and $canSmelt and $fuel->getFuelTime() !== false and $fuel->count > 0) { + if($this->data["BurnTime"] <= 0 and $canSmelt and $fuel->getFuelTime() !== false and $fuel->count > 0){ $this->lastUpdate = microtime(true); $this->data["MaxTime"] = $this->data["BurnTime"] = floor($fuel->getFuelTime() * 20); $this->data["BurnTicks"] = 0; --$fuel->count; - if($fuel->count === 0) { + if($fuel->count === 0){ $fuel = BlockAPI::getItem(AIR, 0, 0); } $this->setSlot(1, $fuel, false); $current = $this->level->getBlock($this); - if($current->getID() === FURNACE) { + if($current->getID() === FURNACE){ $this->level->setBlock($this, BlockAPI::get(BURNING_FURNACE, $current->getMetadata()), true, false, true); } } - if($this->data["BurnTime"] > 0) { + if($this->data["BurnTime"] > 0){ $ticks = (microtime(true) - $this->lastUpdate) * 20; $this->data["BurnTime"] -= $ticks; $this->data["BurnTicks"] = ceil(($this->data["BurnTime"] / $this->data["MaxTime"]) * 200); - if($smelt !== false and $canSmelt) { + if($smelt !== false and $canSmelt){ $this->data["CookTime"] += $ticks; - if($this->data["CookTime"] >= 200) { //10 seconds + if($this->data["CookTime"] >= 200){ //10 seconds $product = BlockAPI::getItem($smelt->getID(), $smelt->getMetadata(), $product->count + 1); $this->setSlot(2, $product, false); --$raw->count; - if($raw->count === 0) { + if($raw->count === 0){ $raw = BlockAPI::getItem(AIR, 0, 0); } $this->setSlot(0, $raw, false); $this->data["CookTime"] -= 200; } - } elseif($this->data["BurnTime"] <= 0) { + }elseif($this->data["BurnTime"] <= 0){ $this->data["BurnTime"] = 0; $this->data["CookTime"] = 0; $this->data["BurnTicks"] = 0; - } else { + }else{ $this->data["CookTime"] = 0; } $this->server->schedule(2, [$this, "update"]); $this->scheduledUpdate = true; - } else { + }else{ $current = $this->level->getBlock($this); - if($current->getID() === BURNING_FURNACE) { + if($current->getID() === BURNING_FURNACE){ $this->level->setBlock($this, BlockAPI::get(FURNACE, $current->getMetadata()), true, false, true); } $this->data["CookTime"] = 0; @@ -126,28 +124,28 @@ class Tile extends Position { $this->lastUpdate = microtime(true); } - public function getSlot($s) { + public function getSlot($s){ $i = $this->getSlotIndex($s); - if($i === false or $i < 0) { + if($i === false or $i < 0){ return BlockAPI::getItem(AIR, 0, 0); - } else { + }else{ return BlockAPI::getItem($this->data["Items"][$i]["id"], $this->data["Items"][$i]["Damage"], $this->data["Items"][$i]["Count"]); } } - public function getSlotIndex($s) { - if($this->class !== TILE_CHEST and $this->class !== TILE_FURNACE) { + public function getSlotIndex($s){ + if($this->class !== TILE_CHEST and $this->class !== TILE_FURNACE){ return false; } - foreach($this->data["Items"] as $i => $slot) { - if($slot["Slot"] === $s) { + foreach($this->data["Items"] as $i => $slot){ + if($slot["Slot"] === $s){ return $i; } } return -1; } - public function setSlot($s, Item $item, $update = true, $offset = 0) { + public function setSlot($s, Item $item, $update = true, $offset = 0){ $i = $this->getSlotIndex($s); $d = [ "Count" => $item->count, @@ -155,15 +153,15 @@ class Tile extends Position { "id" => $item->getID(), "Damage" => $item->getMetadata(), ]; - if($i === false) { + if($i === false){ return false; - } elseif($item->getID() === AIR or $item->count <= 0) { - if($i >= 0) { + }elseif($item->getID() === AIR or $item->count <= 0){ + if($i >= 0){ unset($this->data["Items"][$i]); } - } elseif($i < 0) { + }elseif($i < 0){ $this->data["Items"][] = $d; - } else { + }else{ $this->data["Items"][$i] = $d; } $this->server->api->dhandle("tile.container.slot", [ @@ -173,14 +171,14 @@ class Tile extends Position { "slotdata" => $item, ]); - if($update === true and $this->scheduledUpdate === false) { + if($update === true and $this->scheduledUpdate === false){ $this->update(); } return true; } - public function pairWith(Tile $tile) { - if($this->isPaired() or $tile->isPaired()) { + public function pairWith(Tile $tile){ + if($this->isPaired() or $tile->isPaired()){ return false; } @@ -196,18 +194,18 @@ class Tile extends Position { $this->server->handle("tile.update", $tile); } - public function isPaired() { - if($this->class !== TILE_CHEST) { + public function isPaired(){ + if($this->class !== TILE_CHEST){ return false; } - if(!isset($this->data["pairx"]) or !isset($this->data["pairz"])) { + if(!isset($this->data["pairx"]) or !isset($this->data["pairz"])){ return false; } return true; } - public function unpair() { - if(!$this->isPaired()) { + public function unpair(){ + if(!$this->isPaired()){ return false; } @@ -216,36 +214,36 @@ class Tile extends Position { $this->server->api->tile->spawnToAll($this); $this->server->handle("tile.update", $this); - if($tile instanceof Tile) { + if($tile instanceof Tile){ $this->server->api->tile->spawnToAll($tile); $this->server->handle("tile.update", $tile); } } - public function getPair() { - if($this->isPaired()) { + public function getPair(){ + if($this->isPaired()){ return $this->server->api->tile->get(new Position((int) $this->data["pairx"], $this->y, (int) $this->data["pairz"], $this->level)); } return false; } - public function openInventory(Player $player) { - if($this->class === TILE_CHEST) { + public function openInventory(Player $player){ + if($this->class === TILE_CHEST){ $player->windowCnt++; $player->windowCnt = $id = max(2, $player->windowCnt % 99); - if(($pair = $this->getPair()) !== false) { - if(($pair->x + ($pair->z << 13)) > ($this->x + ($this->z << 13))) { //Order them correctly + if(($pair = $this->getPair()) !== false){ + if(($pair->x + ($pair->z << 13)) > ($this->x + ($this->z << 13))){ //Order them correctly $player->windows[$id] = [ $pair, $this ]; - } else { + }else{ $player->windows[$id] = [ $this, $pair ]; } - } else { + }else{ $player->windows[$id] = $this; } @@ -259,9 +257,9 @@ class Tile extends Position { $player->dataPacket($pk); $slots = []; - if(is_array($player->windows[$id])) { + if(is_array($player->windows[$id])){ $all = $this->server->api->player->getAll($this->level); - foreach($player->windows[$id] as $ob) { + foreach($player->windows[$id] as $ob){ $pk = new TileEventPacket; $pk->x = $ob->x; $pk->y = $ob->y; @@ -269,16 +267,16 @@ class Tile extends Position { $pk->case1 = 1; $pk->case2 = 2; $this->server->api->player->broadcastPacket($all, $pk); - for($s = 0; $s < CHEST_SLOTS; ++$s) { + for($s = 0; $s < CHEST_SLOTS; ++$s){ $slot = $ob->getSlot($s); - if($slot->getID() > AIR and $slot->count > 0) { + if($slot->getID() > AIR and $slot->count > 0){ $slots[] = $slot; - } else { + }else{ $slots[] = BlockAPI::getItem(AIR, 0, 0); } } } - } else { + }else{ $pk = new TileEventPacket; $pk->x = $this->x; $pk->y = $this->y; @@ -286,11 +284,11 @@ class Tile extends Position { $pk->case1 = 1; $pk->case2 = 2; $this->server->api->player->broadcastPacket($this->server->api->player->getAll($this->level), $pk); - for($s = 0; $s < CHEST_SLOTS; ++$s) { + for($s = 0; $s < CHEST_SLOTS; ++$s){ $slot = $this->getSlot($s); - if($slot->getID() > AIR and $slot->count > 0) { + if($slot->getID() > AIR and $slot->count > 0){ $slots[] = $slot; - } else { + }else{ $slots[] = BlockAPI::getItem(AIR, 0, 0); } } @@ -301,7 +299,7 @@ class Tile extends Position { $pk->slots = $slots; $player->dataPacket($pk); return true; - } elseif($this->class === TILE_FURNACE) { + }elseif($this->class === TILE_FURNACE){ $player->windowCnt++; $player->windowCnt = $id = max(2, $player->windowCnt % 99); $player->windows[$id] = $this; @@ -316,11 +314,11 @@ class Tile extends Position { $player->dataPacket($pk); $slots = []; - for($s = 0; $s < FURNACE_SLOTS; ++$s) { + for($s = 0; $s < FURNACE_SLOTS; ++$s){ $slot = $this->getSlot($s); - if($slot->getID() > AIR and $slot->count > 0) { + if($slot->getID() > AIR and $slot->count > 0){ $slots[] = $slot; - } else { + }else{ $slots[] = BlockAPI::getItem(AIR, 0, 0); } } @@ -332,14 +330,14 @@ class Tile extends Position { } } - public function spawn($player) { - if($this->closed) { + public function spawn($player){ + if($this->closed){ return false; } - if(!($player instanceof Player)) { + if(!($player instanceof Player)){ $player = $this->server->api->player->get($player); } - switch($this->class) { + switch($this->class){ case TILE_CHEST: $nbt = new NBT(); $nbt->write(chr(NBT::TAG_COMPOUND) . "\x00\x00"); @@ -360,7 +358,7 @@ class Tile extends Position { $nbt->writeTAG_String("z"); $nbt->writeTAG_Int((int) $this->z); - if($this->isPaired()) { + if($this->isPaired()){ $nbt->write(chr(NBT::TAG_INT)); $nbt->writeTAG_String("pairx"); $nbt->writeTAG_Int((int) $this->data["pairx"]); @@ -427,8 +425,8 @@ class Tile extends Position { } } - public function setText($line1 = "", $line2 = "", $line3 = "", $line4 = "") { - if($this->class !== TILE_SIGN) { + public function setText($line1 = "", $line2 = "", $line3 = "", $line4 = ""){ + if($this->class !== TILE_SIGN){ return false; } $this->data["Text1"] = $line1; @@ -440,7 +438,7 @@ class Tile extends Position { return true; } - public function getText() { + public function getText(){ return [ $this->data["Text1"], $this->data["Text2"], @@ -449,23 +447,23 @@ class Tile extends Position { ]; } - public function __destruct() { + public function __destruct(){ $this->close(); } - public function close() { - if($this->closed === false) { + public function close(){ + if($this->closed === false){ $this->closed = true; $this->server->api->tile->remove($this->id); } } - public function getName() { + public function getName(){ return $this->name; } - public function setPosition(Vector3 $pos) { - if($pos instanceof Position) { + public function setPosition(Vector3 $pos){ + if($pos instanceof Position){ $this->level = $pos->level; $this->server->query("UPDATE tiles SET level = '" . $this->level->getName() . "' WHERE ID = " . $this->id . ";"); } diff --git a/src/world/generator/noise/NoiseGeneratorOctaves.php b/src/world/generator/noise/NoiseGeneratorOctaves.php index 10328dd5..b7ef7323 100644 --- a/src/world/generator/noise/NoiseGeneratorOctaves.php +++ b/src/world/generator/noise/NoiseGeneratorOctaves.php @@ -4,36 +4,36 @@ require_once("NoiseGenerator.php"); /***REM_END***/ -class NoiseGeneratorOctaves extends NoiseGenerator { +class NoiseGeneratorOctaves extends NoiseGenerator{ public $octaves; private $generatorCollection; - public function __construct(MTRandom $random, $octaves) { + public function __construct(MTRandom $random, $octaves){ $this->generatorCollection = []; $this->octaves = (int) $octaves; - for($o = 0; $o < $this->octaves; ++$o) { + for($o = 0; $o < $this->octaves; ++$o){ $this->generatorCollection[$o] = new NoiseGeneratorPerlin($random); } } - public function getValue($x, $y) { + public function getValue($x, $y){ $noise = 0; $scale = 1; - for($i = 0; $i < $this->octaves; ++$i) { + for($i = 0; $i < $this->octaves; ++$i){ $noise += $this->generatorCollection[$i]->getValue($x * $scale, $y * $scale) / $scale; $scale /= 2; } return $noise; } - public function generateNoiseOctaves($int1, $int2, $int3, $int4, $int5, $int6, $par1 = false, $par2 = false, $par3 = false) { - if($par1 === false or $par2 === false or $par3 === false) { + public function generateNoiseOctaves($int1, $int2, $int3, $int4, $int5, $int6, $par1 = false, $par2 = false, $par3 = false){ + if($par1 === false or $par2 === false or $par3 === false){ return $this->generateNoiseOctaves($int1, 10, $int2, $int3, 1, $int4, $int5, 1, $int6); } $floats = array_fill(0, $int4 * $int5 * $int6, 0); $d1 = 1; - for($j = 0; $j < $this->octaves; ++$j) { + for($j = 0; $j < $this->octaves; ++$j){ $d2 = $int1 * $d1 * $par1; $d3 = $int2 * $d1 * $par2; $d4 = $int3 * $d1 * $par3; @@ -51,4 +51,4 @@ class NoiseGeneratorOctaves extends NoiseGenerator { } return $floats; } -} +} \ No newline at end of file diff --git a/src/world/generator/noise/NoiseGeneratorPerlin.php b/src/world/generator/noise/NoiseGeneratorPerlin.php index 85d0435c..2d812a8f 100644 --- a/src/world/generator/noise/NoiseGeneratorPerlin.php +++ b/src/world/generator/noise/NoiseGeneratorPerlin.php @@ -4,23 +4,21 @@ require_once("NoiseGenerator.php"); /***REM_END***/ -class NoiseGeneratorPerlin extends NoiseGenerator { +class NoiseGeneratorPerlin extends NoiseGenerator{ - public $xCoord; - public $yCoord; - public $zCoord; + public $xCoord, $yCoord, $zCoord; private $permutations = []; - public function __construct(MTRandom $random) { + public function __construct(MTRandom $random){ $this->xCoord = $random->nextFloat() * 256; $this->yCoord = $random->nextFloat() * 256; $this->zCoord = $random->nextFloat() * 256; - for($i = 0; $i < 512; ++$i) { + for($i = 0; $i < 512; ++$i){ $this->permutations[$i] = $i < 256 ? $i : 0; } - for($i = 0; $i < 256; ++$i) { + for($i = 0; $i < 256; ++$i){ $j = $random->nextInt(256 - $i) + $i; $k = $this->permutations[$i]; $this->permutations[$i] = $this->permutations[$j]; @@ -30,7 +28,7 @@ class NoiseGeneratorPerlin extends NoiseGenerator { } - public function getValue($d, $d1, $d2 = 0) { + public function getValue($d, $d1, $d2 = 0){ $d3 = $d + $this->xCoord; $d4 = $d1 + $this->yCoord; $d5 = $d2 + $this->zCoord; @@ -66,18 +64,18 @@ class NoiseGeneratorPerlin extends NoiseGenerator { ); } - public function populateNoiseArray(&$floats, $par1, $par2, $par3, $int1, $int2, $int3, $par4, $par5, $par6, $par7) { - if($int2 === 1) { + public function populateNoiseArray(&$floats, $par1, $par2, $par3, $int1, $int2, $int3, $par4, $par5, $par6, $par7){ + if($int2 === 1){ $n = 0; $d3 = 1 / $par7; - for($i1 = 0; $i1 < $int1; ++$i1) { + for($i1 = 0; $i1 < $int1; ++$i1){ $d4 = $par1 + $i1 * $par4 + $this->xCoord; $i2 = floor($d4); $i3 = $i2 & 0xFF; $d4 -= $i2; $d5 = $d4 * $d4 * $d4 * ($d4 * ($d4 * 6 - 15) + 10); - for($i4 = 0; $i4 < $int3; ++$i4) { + for($i4 = 0; $i4 < $int3; ++$i4){ $d6 = $par3 + $i4 * $par6 + $this->zCoord; $i5 = floor($d6); $i6 = $i5 & 0xFF; @@ -103,28 +101,28 @@ class NoiseGeneratorPerlin extends NoiseGenerator { $n = 0; $i = 0; - for($i4 = 0; $i4 < $int1; ++$i4) { + for($i4 = 0; $i4 < $int1; ++$i4){ $d6 = $par1 + $i4 * $par4 + $this->xCoord; $i5 = floor($d6); $i6 = $i5 & 0xFF; $d6 -= $i5; $d7 = $d6 * $d6 * $d6 * ($d6 * ($d6 * 6 - 15) + 10); - for($i12 = 0; $i12 < $int3; ++$i12) { + for($i12 = 0; $i12 < $int3; ++$i12){ $d12 = $par3 + $i12 * $par6 + $this->zCoord; $i13 = floor($d12); $i14 = $i13 & 0xFF; $d12 -= $i13; $d13 = $d12 * $d12 * $d12 * ($d12 * ($d12 * 6 - 15) + 10); - for($i15 = 0; $i15 < $int2; ++$i15) { + for($i15 = 0; $i15 < $int2; ++$i15){ $d14 = $par2 + $i15 * $par5 + $this->yCoord; $i16 = floor($d14); $i17 = $i16 & 0xff; $d14 -= $i16; $d15 = $d14 * $d14 * $d14 * ($d14 * ($d14 * 6 - 15) + 10); - if($i15 == 0 or $i17 != $m) { + if($i15 == 0 or $i17 != $m){ $m = $i17; $i7 = $this->permutations[$i6] + $i17; $i8 = $this->permutations[$i7] + $i14; @@ -147,22 +145,22 @@ class NoiseGeneratorPerlin extends NoiseGenerator { } } - final public static function curve($par1, $par2, $par3) { + public static final function curve($par1, $par2, $par3){ return $par2 + $par1 * ($par3 - $par2); } - public static function grad2D($int, $par1, $par2) { + public static function grad2D($int, $par1, $par2){ $i = $int & 0x0F; $d1 = (1 - (($i & 0x08) >> 3)) * $par1; $d2 = ($i == 12 || $i == 14) ? $par1 : (($i >= 4) * $par2); return (($i & 0x01) ? -$d1 : $d1) + (($i & 0x02) ? -$d2 : $d2); } - public static function grad3D($int, $par1, $par2, $par3) { + public static function grad3D($int, $par1, $par2, $par3){ $i = $int & 0x0F; $d1 = $i < 8 ? $par1 : $par2; $d2 = ($i == 12 or $i == 14) ? $par1 : ($i < 4 ? $par2 : $par3); return (($i & 0x01) ? -$d1 : $d1) + (($i & 0x02) ? -$d2 : $d2); } -} +} \ No newline at end of file diff --git a/src/world/generator/vanilla/VanillaGenerator.php b/src/world/generator/vanilla/VanillaGenerator.php index 4d18f2d6..91289d8f 100644 --- a/src/world/generator/vanilla/VanillaGenerator.php +++ b/src/world/generator/vanilla/VanillaGenerator.php @@ -2,7 +2,8 @@ define("EMPTY_MINI_CHUNK", str_repeat("\x00", 8192)); define("EMPTY_16x16_ARR", array_fill(0, 256, 0)); -class VanillaGenerator implements LevelGenerator { +class VanillaGenerator implements LevelGenerator +{ /** * @var Level */ @@ -22,14 +23,7 @@ class VanillaGenerator implements LevelGenerator { * @var NoiseGeneratorOctaves $depthNoise * @var NoiseGeneratorOctaves $treeNoise */ - private $upperInterpolationNoise; - private $lowerInterpolationNoise; - private $interpolationNoise; - private $beachNoise; - private $surfaceDepthNoise; - private $biomeNoise; - private $depthNoise; - private $treeNoise; + private $upperInterpolationNoise, $lowerInterpolationNoise, $interpolationNoise, $beachNoise, $surfaceDepthNoise, $biomeNoise, $depthNoise, $treeNoise; /** * @var float[] $biomeNoises * @var float[] $depthNoises @@ -42,16 +36,7 @@ class VanillaGenerator implements LevelGenerator { * @var float[] $gravelNoises * @var float[] $surfaceDepthNoises */ - private $biomeNoises; - private $depthNoises; - private $interpolationNoises; - private $upperInterpolationNoises; - private $lowerInterpolationNoises; - private $biomes; - private $heights; - private $sandNoises; - private $gravelNoises; - private $surfaceDepthNoises; + private $biomeNoises, $depthNoises, $interpolationNoises, $upperInterpolationNoises, $lowerInterpolationNoises, $biomes, $heights, $sandNoises, $gravelNoises, $surfaceDepthNoises; /** * @var BiomeSource */ @@ -59,10 +44,12 @@ class VanillaGenerator implements LevelGenerator { private $heightMap = []; - public function __construct(array $options = []) { + public function __construct(array $options = []) + { } - public function init(Level $level, Random $random) { + public function init(Level $level, Random $random) + { $this->level = $level; $this->biomeSource = new BiomeSource($level); $this->rand = new MTRandom($level->getSeed()); @@ -76,11 +63,13 @@ class VanillaGenerator implements LevelGenerator { $this->treeNoise = new NoiseGeneratorOctaves($this->rand, 8); } - public function getSpawn() { + public function getSpawn() + { return new Vector3(128, 64, 128); } - public function populateChunk($chunkX, $chunkZ) { + public function populateChunk($chunkX, $chunkZ) + { $chunkXWorld = $chunkX * 16; $chunkZWorld = $chunkZ * 16; //HeavyTile::instaFall = 1; TODO instant sand/gravel fall @@ -89,7 +78,7 @@ class VanillaGenerator implements LevelGenerator { $i1 = (int) (((int) ($this->rand->nextInt() / 2)) * 2 + 1); //why php integers are so big....??????????????????????????????????????? $j1 = (int) (((int) ($this->rand->nextInt() / 2)) * 2 + 1); $this->rand->setSeed((($chunkX * $i1 + $chunkZ * $j1) & 0xffffffff) ^ $this->level->getSeed()); - for($i2 = 0; $i2 < 10; ++$i2) { + for($i2 = 0; $i2 < 10; ++$i2){ ClayFeature::place($this->level, $this->rand, $chunkXWorld + $this->rand->nextInt(16), $this->rand->nextInt(128), $chunkZWorld + $this->rand->nextInt(16)); } for ($i3 = 0; $i3 < 20; ++$i3) { @@ -101,37 +90,29 @@ class VanillaGenerator implements LevelGenerator { for ($i5 = 0; $i5 < 20; ++$i5) { OreFeature::place($this->level, $this->rand, $chunkXWorld + $this->rand->nextInt(16), $this->rand->nextInt(128), $chunkZWorld + $this->rand->nextInt(16), COAL_ORE, 16); } - for($i6 = 0; $i6 < 20; ++$i6) { + for($i6 = 0; $i6 < 20; ++$i6){ OreFeature::place($this->level, $this->rand, $chunkXWorld + $this->rand->nextInt(16), $this->rand->nextInt(64), $chunkZWorld + $this->rand->nextInt(16), IRON_ORE, 8); } - for($i7 = 0; $i7 < 2; ++$i7) { + for($i7 = 0; $i7 < 2; ++$i7){ OreFeature::place($this->level, $this->rand, $chunkXWorld + $this->rand->nextInt(16), $this->rand->nextInt(32), $chunkZWorld + $this->rand->nextInt(16), GOLD_ORE, 8); } - for($i8 = 0; $i8 < 8; ++$i8) { - OreFeature::place($this->level, $this->rand, $chunkXWorld + $this->rand->nextInt(16), $this->rand->nextInt(16), $chunkZWorld + $this->rand->nextInt(16), REDSTONE_ORE, 7); + for($i8 = 0; $i8 < 8; ++$i8){ + OreFeature::place($this->level, $this->rand, $chunkXWorld + $this->rand->nextInt(16), $this->rand->nextInt(16), $chunkZWorld + $this->rand->nextInt(16), REDSTONE_ORE, 7); } - OreFeature::place($this->level, $this->rand, $chunkXWorld + $this->rand->nextInt(16), $this->rand->nextInt(16), $chunkZWorld + $this->rand->nextInt(16), DIAMOND_ORE, 7); - OreFeature::place($this->level, $this->rand, $chunkXWorld + $this->rand->nextInt(16), $this->rand->nextInt(16) + $this->rand->nextInt(16), $chunkZWorld + $this->rand->nextInt(16), LAPIS_ORE, 6); + OreFeature::place($this->level, $this->rand, $chunkXWorld + $this->rand->nextInt(16), $this->rand->nextInt(16), $chunkZWorld + $this->rand->nextInt(16), DIAMOND_ORE, 7); + OreFeature::place($this->level, $this->rand, $chunkXWorld + $this->rand->nextInt(16), $this->rand->nextInt(16) + $this->rand->nextInt(16), $chunkZWorld + $this->rand->nextInt(16), LAPIS_ORE, 6); $sample = (int) (((($this->treeNoise->getValue($chunkXWorld * 0.5, $chunkZWorld * 0.5) / 8) + ($this->rand->nextFloat() * 4)) + 4) / 3); $treesAmount = $this->rand->nextInt(10) == 0; - if($biome == Biome::$forest) { - $treesAmount += $sample + 2; - } elseif($biome == Biome::$rainForest) { - $treesAmount += $sample + 2; - } elseif($biome == Biome::$seasonalForest) { - $treesAmount += $sample + 1; - } elseif($biome == Biome::$taiga) { - $treesAmount += $sample + 1; - } elseif($biome == Biome::$desert) { - $treesAmount -= 20; - } elseif($biome == Biome::$tundra) { - $treesAmount -= 20; - } elseif($biome == Biome::$plains) { - $treesAmount -= 20; - } - for($l8 = 0; $l8 < $treesAmount; ++$l8) { + if($biome == Biome::$forest) $treesAmount += $sample + 2; + elseif($biome == Biome::$rainForest) $treesAmount += $sample + 2; + elseif($biome == Biome::$seasonalForest) $treesAmount += $sample + 1; + elseif($biome == Biome::$taiga) $treesAmount += $sample + 1; + elseif($biome == Biome::$desert) $treesAmount -= 20; + elseif($biome == Biome::$tundra) $treesAmount -= 20; + elseif($biome == Biome::$plains) $treesAmount -= 20; + for($l8 = 0; $l8 < $treesAmount; ++$l8){ $l12 = $chunkXWorld + $this->rand->nextInt(16) + 8; $j15 = $chunkZWorld + $this->rand->nextInt(16) + 8; /** @@ -140,25 +121,25 @@ class VanillaGenerator implements LevelGenerator { $tree = $biome->getTreeFeature($this->rand); $tree->place($this->level, $this->rand, $l12, $this->getHeightValue($l12, $j15), $j15); } - for($i9 = 0; $i9 < 2; ++$i9) { + for($i9 = 0; $i9 < 2; ++$i9){ $i13 = $chunkXWorld + $this->rand->nextInt(16) + 8; $k15 = $this->rand->nextInt(128); $l17 = $chunkZWorld + $this->rand->nextInt(16) + 8; Feature::$FLOWER_YELLOW->place($this->level, $this->rand, $i13, $k15, $l17); } - if($this->rand->nextInt(2) == 0) { + if($this->rand->nextInt(2) == 0){ $j9 = $chunkXWorld + $this->rand->nextInt(16) + 8; $j13 = $this->rand->nextInt(128); $l15 = $chunkZWorld + $this->rand->nextInt(16) + 8; Feature::$FLOWER_RED->place($this->level, $this->rand, $j9, $j13, $l15); } - if($this->rand->nextInt(4) == 0) { + if($this->rand->nextInt(4) == 0){ $j9 = $chunkXWorld + $this->rand->nextInt(16) + 8; $j13 = $this->rand->nextInt(128); $l15 = $chunkZWorld + $this->rand->nextInt(16) + 8; Feature::$MUSHROOM_BROWN->place($this->level, $this->rand, $j9, $j13, $l15); } - if($this->rand->nextInt(8) == 0) { + if($this->rand->nextInt(8) == 0){ $j9 = $chunkXWorld + $this->rand->nextInt(16) + 8; $j13 = $this->rand->nextInt(128); $l15 = $chunkZWorld + $this->rand->nextInt(16) + 8; @@ -166,7 +147,8 @@ class VanillaGenerator implements LevelGenerator { } } - public function generateChunk($chunkX, $chunkZ) { + public function generateChunk($chunkX, $chunkZ) + { $this->rand->setSeed(341872712 * $chunkX + 132899541 * $chunkZ); $this->biomes = $this->biomeSource->getBiomeBlock($chunkX * 16, $chunkZ * 16, 16, 16); $chunkz = array_fill(0, 8, EMPTY_MINI_CHUNK); //[$blockY >> 4][($blockY & 0xf) + ($blockX << 5) + ($blockZ << 9)]. y&f+x&f+z&f @@ -174,7 +156,7 @@ class VanillaGenerator implements LevelGenerator { $this->buildSurfaces($chunkX, $chunkZ, $chunkz, $this->biomes); $this->generateHeightmap($chunkX, $chunkZ, $chunkz); - for($Y = 0; $Y < 8; ++$Y) { + for($Y = 0; $Y < 8; ++$Y){ $index = ($chunkZ << 4) + $chunkX; $this->level->level->chunks[$index][$Y] = $chunkz[$Y]; $this->level->level->chunkChange[$index][$Y] = 8192; @@ -184,34 +166,30 @@ class VanillaGenerator implements LevelGenerator { } - public function populateLevel() { - } - public function setHeightValue($x, $z, $hv) { - if($x > 255 || $x < 0 || $z > 255 || $z < 0) { - return; - } + public function populateLevel() + {} + public function setHeightValue($x, $z, $hv){ + if($x > 255 || $x < 0 || $z > 255 || $z < 0) return; $cX = $x >> 4; $cZ = $z >> 4; $bX = $x & 0xf; $bZ = $z & 0xf; $this->heightMap[$cX + ($cZ * 16)][$bX + ($bZ * 16)] = $hv; } - public function getHeightValue($x, $z) { - if($x > 255 || $x < 0 || $z > 255 || $z < 0) { - return 0; - } + public function getHeightValue($x, $z){ + if($x > 255 || $x < 0 || $z > 255 || $z < 0) return 0; $cX = $x >> 4; $cZ = $z >> 4; $bX = $x & 0xf; $bZ = $z & 0xf; return $this->heightMap[$cX + ($cZ * 16)][$bX + ($bZ * 16)]; } - public function generateHeightmap($x, $z, &$chunkz) { + public function generateHeightmap($x, $z, &$chunkz){ $heightmapCPtr = EMPTY_16x16_ARR; - for($blockX = 0; $blockX < 16; ++$blockX) { - for($blockZ = 0; $blockZ < 16; ++$blockZ) { - for($Y = 7; $Y >= 0; --$Y) { - for($cY = 15; $cY >= 0; --$cY) { + for($blockX = 0; $blockX < 16; ++$blockX){ + for($blockZ = 0; $blockZ < 16; ++$blockZ){ + for($Y = 7; $Y >= 0; --$Y){ + for($cY = 15; $cY >= 0; --$cY){ $blockY = $Y * 16 + $cY; $blockID = ord($chunkz[$Y][$cY + ($blockX << 5) + ($blockZ << 9)]); if($blockID > 0) { @@ -233,12 +211,12 @@ class VanillaGenerator implements LevelGenerator { * @param array $chunks * @param Biome[] $biomes */ - public function buildSurfaces($chunkX, $chunkZ, &$chunks, $biomes) { + public function buildSurfaces($chunkX, $chunkZ, &$chunks, $biomes){ $this->sandNoises = $this->beachNoise->generateNoiseOctaves($chunkX * 16, $chunkZ * 16, 0, 16, 16, 1, 0.03125, 0.03125, 1); $this->gravelNoises = $this->beachNoise->generateNoiseOctaves($chunkX * 16, 109.01, $chunkZ * 16, 16, 1, 16, 0.03125, 1, 0.03125); $this->surfaceDepthNoises = $this->surfaceDepthNoise->generateNoiseOctaves($chunkX * 16, $chunkZ * 16, 0, 16, 16, 1, 0.0625, 0.0625, 0.0625); - for($blockX = 0; $blockX < 16; ++$blockX) { - for($blockZ = 0; $blockZ < 16; ++$blockZ) { + for($blockX = 0; $blockX < 16; ++$blockX){ + for($blockZ = 0; $blockZ < 16; ++$blockZ){ /** @var Biome $biome **/ $biome = $biomes[$blockX + ($blockZ * 16)]; $z = ($this->sandNoises[$blockX + ($blockZ * 16)] + ($this->rand->nextFloat() * 0.2)) > 0; @@ -247,28 +225,28 @@ class VanillaGenerator implements LevelGenerator { $i = -1; $b = $biome->topBlock; $b2 = $biome->fillerBlock; - for($blockY = 127; $blockY >= 0; --$blockY) { - if($blockY <= $this->rand->nextInt(5)) { + for($blockY = 127; $blockY >= 0; --$blockY){ + if($blockY <= $this->rand->nextInt(5)){ $chunks[$blockY >> 4][($blockY & 0xf) + ($blockZ << 5) + ($blockX << 9)] = "\x07"; - } else { + }else{ $b3 = ord($chunks[$blockY >> 4][($blockY & 0xf) + ($blockZ << 5) + ($blockX << 9)]); - if($b3 == 0) { + if($b3 == 0){ $i = -1; - } elseif($b3 == STONE) { - if($i == -1) { - if($nextFloat > 0) { - if($blockY >= 60 && $blockY <= 65) { - if($z) { + }elseif($b3 == STONE){ + if($i == -1){ + if($nextFloat > 0){ + if($blockY >= 60 && $blockY <= 65){ + if($z){ $b2 = $b = SAND; - } elseif($z2) { + }elseif($z2){ $b = 0; $b2 = GRAVEL; - } else { + }else{ $b = $biome->topBlock; $b2 = $biome->fillerBlock; } } - } else { + }else{ $b = 0; $b2 = STONE; } @@ -276,10 +254,10 @@ class VanillaGenerator implements LevelGenerator { $b = $blockY < 64 && $b == 0 ? STILL_WATER : $b; $i = $nextFloat; $chunks[$blockY >> 4][($blockY & 0xf) + ($blockZ << 5) + ($blockX << 9)] = $blockY >= 63 ? chr($b) : chr($b2); - } elseif($i > 0) { + }elseif($i > 0){ --$i; $chunks[$blockY >> 4][($blockY & 0xf) + ($blockZ << 5) + ($blockX << 9)] = chr($b2); - if($i == 0 && $b2 == SAND) { + if($i == 0 && $b2 == SAND){ $i = $this->rand->nextInt(4); $b2 = SANDSTONE; } @@ -291,12 +269,12 @@ class VanillaGenerator implements LevelGenerator { } } - public function prepareHeights($chunkX, $chunkZ, &$chunks, $biomes, $temperatures) { + public function prepareHeights($chunkX, $chunkZ, &$chunks, $biomes, $temperatures){ $this->heights = $this->getHeights($chunkX * 4, 0, $chunkZ * 4, 5, 17, 5); //if($chunkX == 15 && $chunkZ == 15) var_dump($this->heights); - for($unkX = 0; $unkX < 4; ++$unkX) { - for($unkZ = 0; $unkZ < 4; ++$unkZ) { - for($unkY = 0; $unkY < 16; ++$unkY) { + for($unkX = 0; $unkX < 4; ++$unkX){ + for($unkZ = 0; $unkZ < 4; ++$unkZ){ + for($unkY = 0; $unkY < 16; ++$unkY){ $f = $this->heights[(((($unkX) * 5) + $unkZ) * 17) + $unkY]; $f2 = $this->heights[(((($unkX) * 5) + $unkZ + 1) * 17) + $unkY]; $f3 = $this->heights[(((($unkX + 1) * 5) + $unkZ) * 17) + $unkY]; @@ -307,19 +285,19 @@ class VanillaGenerator implements LevelGenerator { $f7 = ($this->heights[(((($unkX + 1) * 5) + ($unkZ)) * 17) + ($unkY + 1)] - $f3) * 0.125; $f8 = ($this->heights[(((($unkX + 1) * 5) + ($unkZ + 1)) * 17) + ($unkY + 1)] - $f4) * 0.125; - for($unkYY = 0; $unkYY < 8; ++$unkYY) { + for($unkYY = 0; $unkYY < 8; ++$unkYY){ $f9 = $f; $f10 = $f2; $f11 = ($f3 - $f) * 0.25; $f12 = ($f4 - $f2) * 0.25; - for($unkXX = 0; $unkXX < 4; ++$unkXX) { + for($unkXX = 0; $unkXX < 4; ++$unkXX){ $f13 = $f9; $f14 = ($f10 - $f9) * 0.25; - for($unkZZ = 0; $unkZZ < 4; ++$unkZZ) { + for($unkZZ = 0; $unkZZ < 4; ++$unkZZ){ $d15 = $temperatures[((($unkX * 4) + $unkXX) * 16) + ($unkZ * 4) + $unkZZ]; $i3 = $f13 > 0; //true -> STONE, false -> AIR - if(!$i3 && ($unkY * 8) + $unkYY < 64) { + if(!$i3 && ($unkY * 8) + $unkYY < 64){ $i3 = $d15 < 0.5 && (($unkY * 8) + $unkYY) >= 63 ? ICE : STILL_WATER; } @@ -342,7 +320,7 @@ class VanillaGenerator implements LevelGenerator { } } - public function getHeights($chunkX, $chunkY, $chunkZ, $scaleX, $scaleY, $scaleZ) { + public function getHeights($chunkX, $chunkY, $chunkZ, $scaleX, $scaleY, $scaleZ){ $heights = array_fill(0, $scaleX * $scaleY * $scaleZ, 0); $rainNoises = $this->biomeSource->rainfallNoises; $tempNoises = $this->biomeSource->temperatureNoises; @@ -353,9 +331,9 @@ class VanillaGenerator implements LevelGenerator { $this->lowerInterpolationNoises = $this->lowerInterpolationNoise->generateNoiseOctaves($chunkX, $chunkY, $chunkZ, $scaleX, $scaleY, $scaleZ, 684.41, 684.41, 684.41); $k1 = $l1 = 0; $i2 = ((int) (16 / $scaleX)); - for($j2 = 0; $j2 < $scaleX; ++$j2) { + for($j2 = 0; $j2 < $scaleX; ++$j2){ $k2 = (int) ($j2 * $i2 + $i2 / 2); - for($l2 = 0; $l2 < $scaleZ; ++$l2) { + for($l2 = 0; $l2 < $scaleZ; ++$l2){ $i3 = (int) ($l2 * $i2 + $i2 / 2); $d2 = $tempNoises[$k2 * 16 + $i3]; $d3 = $rainNoises[$k2 * 16 + $i3] * $d2; @@ -366,58 +344,42 @@ class VanillaGenerator implements LevelGenerator { $d5 = (($this->biomeNoises[$l1] + 256) / 512); $d5 *= $d4; - if($d5 > 1) { - $d5 = 1; - } + if($d5 > 1) $d5 = 1; $d6 = $this->depthNoises[$l1] / 8000; - if($d6 < 0) { - $d6 = -$d6 * 0.3; - } + if($d6 < 0) $d6 = -$d6 * 0.3; $d6 = $d6 * 3 - 2; - if($d6 < 0) { + if($d6 < 0){ $d6 /= 2; - if($d6 < -1) { - $d6 = -1; - } + if($d6 < -1) $d6 = -1; $d6 /= 1.4; $d6 /= 2; $d5 = 0; - } else { - if($d6 > 1) { - $d6 = 1; - } + }else{ + if($d6 > 1) $d6 = 1; $d6 /= 8; } - if($d5 < 0) { - $d5 = 0; - } + if($d5 < 0) $d5 = 0; $d5 += 0.5; $d6 = ($d6 * $scaleY) / 16; $d7 = ($scaleY / 2 + $d6 * 4); ++$l1; - for($j3 = 0; $j3 < $scaleY; ++$j3) { + for($j3 = 0; $j3 < $scaleY; ++$j3){ $d8 = 0; $d9 = (((float) $j3 - $d7) * 12) / $d5; - if($d9 < 0) { - $d9 *= 4; - } + if($d9 < 0) $d9 *= 4; $d10 = $this->upperInterpolationNoises[$k1] / 512; $d11 = $this->lowerInterpolationNoises[$k1] / 512; $d12 = ($this->interpolationNoises[$k1] / 10 + 1) / 2; - if($d12 < 0) { - $d8 = $d10; - } elseif($d12 > 1) { - $d8 = $d11; - } else { - $d8 = $d10 + ($d11 - $d10) * $d12; - } + if($d12 < 0) $d8 = $d10; + elseif($d12 > 1) $d8 = $d11; + else $d8 = $d10 + ($d11 - $d10) * $d12; $d8 -= $d9; - if($j3 > $scaleY - 4) { + if($j3 > $scaleY - 4){ $d13 = ($j3 - ($scaleY - 4)) / 3; $d8 = $d8 * (1 - $d13) + -10 * $d13; } @@ -431,3 +393,4 @@ class VanillaGenerator implements LevelGenerator { } } + diff --git a/src/world/generator/vanilla/feature/TreeFeature.php b/src/world/generator/vanilla/feature/TreeFeature.php index b30b45ea..3ffd91fd 100644 --- a/src/world/generator/vanilla/feature/TreeFeature.php +++ b/src/world/generator/vanilla/feature/TreeFeature.php @@ -1,42 +1,39 @@ nextInt(3) + 4; $z2 = true; - if($y < 1 || $y + $nextInt + 1 > 128) { - return false; - } - for($i = $y; $i <= $y + 1 + $nextInt; ++$i) { + if($y < 1 || $y + $nextInt + 1 > 128) return false; + for($i = $y; $i <= $y + 1 + $nextInt; ++$i){ $i2 = ($i == $y) ? 0 : 1; - if($i >= (($y + 1) + $nextInt) - 2) { - $i2 = 2; - } + if($i >= (($y + 1) + $nextInt) - 2) $i2 = 2; - for($i3 = $x - $i2; $i3 <= $x + $i2 && $z2; ++$i3) { - for($i4 = $z - $i2; $i4 <= $z + $i2 && $z2; ++$i4) { - if($i >= 0 && $i < 128) { + for($i3 = $x - $i2; $i3 <= $x + $i2 && $z2; ++$i3){ + for($i4 = $z - $i2; $i4 <= $z + $i2 && $z2; ++$i4){ + if($i >= 0 && $i < 128){ $tileID = $level->level->getBlockID($i3, $i, $i4); - if($tileID != 0 && $tileID != LEAVES) { + if($tileID != 0 && $tileID != LEAVES){ return; } - } else { + }else{ return; } } } } - if($z2) { + if($z2){ $tileID = $level->level->getBlockID($x, $y - 1, $z); - if(($tileID == GRASS || $tileID == DIRT) && $y < (128 - $nextInt) - 1) { + if(($tileID == GRASS || $tileID == DIRT) && $y < (128 - $nextInt) - 1){ $level->level->setBlockID($x, $y - 1, $z, DIRT); } - for($i5 = ($y - 3) + $nextInt; $i5 <= $y + $nextInt; ++$i5) { + for($i5 = ($y - 3) + $nextInt; $i5 <= $y + $nextInt; ++$i5){ $i6 = $i5 - ($y + $nextInt); $i7 = (int) (1 - ($i6 / 2)); - for($i8 = $x - $i7; $i8 <= $x + $i7; ++$i8) { + for($i8 = $x - $i7; $i8 <= $x + $i7; ++$i8){ $i9 = $i8 - $x; - for($i10 = $z - $i7; $i10 <= $z + $i7; ++$i10) { + for($i10 = $z - $i7; $i10 <= $z + $i7; ++$i10){ $i11 = $i10 - $z; if((abs($i9) != $i7 || abs($i11) != $i7 || ($rand->nextInt(2) != 0 && $i6 != 0))/* && !Block.FULL_OPAQUE[world.getBlockIDAt(i8, i5, i10)]TODO opaque?*/) { $level->level->setBlockID($i8, $i5, $i10, LEAVES); @@ -44,12 +41,13 @@ class TreeFeature extends Feature { } } } - for($i12 = 0; $i12 < $nextInt; ++$i12) { + for($i12 = 0; $i12 < $nextInt; ++$i12){ $tileID = $level->level->getBlockID($x, $y + $i12, $z); - if($tileID == 0 || $tileID == LEAVES) { + if($tileID == 0 || $tileID == LEAVES){ $level->level->setBlockID($x, $y + $i12, $z, WOOD); } } } } } +