diff --git a/README.md b/README.md index ffbe02f9..7cbb57a5 100644 --- a/README.md +++ b/README.md @@ -10,22 +10,24 @@ Supported MCPE versions: 0.3.0 ~ 0.8.1 (maybe 0.8.2)

Why should you use NostalgiaCore to run a Minecraft Pocket Edition 0.8.1 server?

+• PHP 8 Support, PHAR plugins + +• Crafting system was rewritten to hopefully have less problems + • Items are dropping normally. -• Dupes, that were in PocketMine by mistake are fixed. - • Player hotbar is saved. +• Working Nether Reactor. + +• Mob AI + +• Dupes, that were in PocketMine by mistake are fixed. + • Extra options (like in-game messages to discord) • Vector2 is fixed. -• Working Nether Reactor. - -• PHAR plugins support - -• Mob AI - ...and etc.

Download Stable NostalgiaCore

diff --git a/src/API/AchievementAPI.php b/src/API/AchievementAPI.php index be89f3b7..9f5d6e0d 100644 --- a/src/API/AchievementAPI.php +++ b/src/API/AchievementAPI.php @@ -1,7 +1,7 @@ array( "name" => "Taking Inventory", @@ -79,20 +79,21 @@ class AchievementAPI{ "buildSword", ], ], - + ]; - + /** @var PocketMinecraftServer */ private $server; - + function __construct(){ $this->server = ServerAPI::request(); } - + /** * Add an achievement * @param string $achievementId - * @param string $achievementName - * @return boolean + * @param string $achievementName display name + * @param array $requires a list of achievement ids, optional + * @return boolean true if the achievement was added. false if the achievement with this id already exists. */ public static function addAchievement($achievementId, $achievementName, array $requires = []){ if(!isset(self::$achievements[$achievementId])){ @@ -104,7 +105,13 @@ class AchievementAPI{ } return false; } - + + /** + * Gives the achievement to player + * @param Player $player + * @param string $achievementId + * @return boolean + */ public static function grantAchievement(Player $player, $achievementId){ if(isset(self::$achievements[$achievementId]) and !self::hasAchievement($player, $achievementId)){ foreach(self::$achievements[$achievementId]["requires"] as $requerimentId){ @@ -122,19 +129,29 @@ class AchievementAPI{ } return false; } - + + /** + * @param Player $player + * @param string $achievementId + * @return boolean + */ public static function hasAchievement(Player $player, $achievementId){ if(!isset(self::$achievements[$achievementId]) or !isset($player->achievements)){ $player->achievements = []; return false; } - + if(!isset($player->achievements[$achievementId]) or !$player->achievements[$achievementId]){ return false; } return true; } - + + /** + * @param Player $player + * @param string $achievementId + * @return boolean + */ public static function broadcastAchievement(Player $player, $achievementId){ if(isset(self::$achievements[$achievementId])){ $result = ServerAPI::request()->api->dhandle("achievement.broadcast", ["player" => $player, "achievementId" => $achievementId]); @@ -149,13 +166,18 @@ class AchievementAPI{ } return false; } - + + /** + * Removes achievement from player. + * @param Player $player + * @param string $achievementId + */ public static function removeAchievement(Player $player, $achievementId){ if(self::hasAchievement($player, $achievementId)){ $player->achievements[$achievementId] = false; } } - + public function viewAchievements($cmd, $params, $issuer, $alias) { if(!isset($params[0])){ @@ -170,17 +192,17 @@ class AchievementAPI{ }else{ return false; } - + if(!$data){ return "Player is not found."; } - + if($data instanceof Config){ $achs = $data->get("achievements"); }else{ $achs = $data; } - + if(count($achs) <= 0){ return "Player {$params[0]} unlocked 0 achievements"; } @@ -191,9 +213,9 @@ class AchievementAPI{ $output .= "{$info["name"]}, "; } } - return substr($output, 0, -2); + return substr($output, 0, - 2); } - + public function init(){ $this->server->api->console->register("ach", "", [$this, "viewAchievements"]); $this->server->api->console->alias("getplayerachievements", "ach"); diff --git a/src/API/BanAPI.php b/src/API/BanAPI.php index bab63ec3..ecd2f7be 100644 --- a/src/API/BanAPI.php +++ b/src/API/BanAPI.php @@ -1,11 +1,8 @@ server = ServerAPI::request(); } @@ -56,7 +57,6 @@ class BanAPI{ /** * @param mixed $data * @param string $event - * * @return boolean */ public function permissionsCheck($data, $event){ @@ -106,11 +106,11 @@ class BanAPI{ } /** + * Checks is player op or not * @param string $username - * * @return boolean */ - public function isOp($username){//Is a player op? + public function isOp($username){ $username = strtolower($username); if($this->server->api->dhandle("op.check", $username) === true){ return true; @@ -121,6 +121,7 @@ class BanAPI{ } /** + * Bans a player. * @param string $username */ public function ban($username){ @@ -316,14 +317,16 @@ class BanAPI{ } /** - * @param string $username - * @param string $reason + * Kicks a player + * @param string $username - player's username + * @param string $reason - kick reason, optional */ public function kick($username, $reason = "No Reason"){ $this->commandHandler("kick", [$username, $reason], "console", ""); } /** + * Unbans a player * @param string $username */ public function pardon($username){ @@ -331,6 +334,7 @@ class BanAPI{ } /** + * Bans some ip * @param string $ip */ public function banIP($ip){ @@ -338,12 +342,16 @@ class BanAPI{ } /** + * Unbans some ip * @param string $ip */ public function pardonIP($ip){ $this->commandHandler("banip", ["pardon", $ip], "console", ""); } + /** + * Rereads ban list, kick list and banip list + */ public function reload(){ $this->commandHandler("ban", ["reload"], "console", ""); $this->commandHandler("banip", ["reload"], "console", ""); @@ -351,8 +359,8 @@ class BanAPI{ } /** + * Checks is ip banned or not * @param string $ip - * * @return boolean */ public function isIPBanned($ip){ @@ -366,8 +374,8 @@ class BanAPI{ } /** + * Checks is username banned or not. * @param string $username - * * @return boolean */ public function isBanned($username){ @@ -382,8 +390,8 @@ class BanAPI{ } /** + * Checks is username in the whitelist or not * @param string $username - * * @return boolean */ public function inWhitelist($username){ diff --git a/src/API/BlockAPI.php b/src/API/BlockAPI.php index 951e05da..dcf00cc1 100755 --- a/src/API/BlockAPI.php +++ b/src/API/BlockAPI.php @@ -1,9 +1,9 @@ server = ServerAPI::request(); + foreach(static::$creative as $slot => [$id, $meta]){ + $rind = ($id << 24) | ($meta); + static::$reverseCreativeLookup[$rind] = $slot; + } + + self::$creativeHotbarSlots[0] = static::hasCreativeItem(STONE, 0); + self::$creativeHotbarSlots[1] = static::hasCreativeItem(COBBLESTONE, 0); + self::$creativeHotbarSlots[2] = static::hasCreativeItem(DIRT, 0); + self::$creativeHotbarSlots[3] = static::hasCreativeItem(PLANKS, 0); + self::$creativeHotbarSlots[4] = static::hasCreativeItem(PLANKS, 1); + self::$creativeHotbarSlots[5] = static::hasCreativeItem(TORCH, 0); + self::$creativeHotbarSlots[6] = static::hasCreativeItem(BRICK_STAIRS, 0); + self::$creativeHotbarSlots[7] = static::hasCreativeItem(COBBLE_WALL, 0); + self::$creativeHotbarSlots[8] = static::hasCreativeItem(SAPLING, 0); + } public static function get($id, $meta = 0, $v = false){ @@ -259,7 +284,7 @@ class BlockAPI{ $output .= "Usage: /setblock "; break; } - + $level = $issuer->entity->level; $block = self::fromString($args[3])->getBlock(); } @@ -294,8 +319,8 @@ class BlockAPI{ break; case "give": $player = $this->server->api->player->get($args[0] ?? ""); - - if($player instanceof Player){ + + if($player instanceof Player){ $item = self::fromString($args[1] ?? ""); if(($player->gamemode & 0x01) === 0x01){ return "Player is in creative mode."; @@ -303,18 +328,18 @@ class BlockAPI{ if($item->getID() === 0){ return "You cannot give an air block to a player."; } - + if(!isset($args[2])){ $item->count = $item->getMaxStackSize(); }else{ $item->count = (int) $args[2]; } - + $player->addItem($item->getID(), $item->getMetadata(), $item->count); $output .= "Giving ".$item->count." of ".$item->getName()." (".$item->getID().":".$item->getMetadata().") to ".$player->username; break; }else{ - $item = self::fromString($args[0] ?? ""); + $item = self::fromString($args[0] ?? ""); if(!($issuer instanceof Player)){ return "You cant give an item to a non-player."; } @@ -341,6 +366,16 @@ class BlockAPI{ return $output; } + public static function blockIDFromString($str){ + if(defined(strtoupper($str))){ + $ida = explode(":", constant(strtoupper($str))); + if(count($ida) === 2){} + return (int) $ida[0]; + }else if(is_numeric($str)){ + return (int) $str; + } + } + public static function fromString($str, $multiple = false){ if($multiple === true){ $blocks = []; @@ -392,26 +427,50 @@ class BlockAPI{ return $this->cancelAction($target, $player, false); } } - - if((!$target->isBreakable($item, $player) and $this->server->api->dhandle("player.block.break.invalid", ["player" => $player, "target" => $target, "item" => $item]) !== true) or ($player->gamemode & 0x02) === 0x02 or (($player->lastBreak - $player->getLag() / 1000) + $target->getBreakTime($item, $player) - 0.2) >= microtime(true)){ + + $currentTime = microtime(true); + $isIndestructible = (!$target->isBreakable($item, $player) && $this->server->api->dhandle("player.block.break.invalid", ["player" => $player, "target" => $target, "item" => $item]) !== true); + $isAdventure = ($player->gamemode & 0x02) === 0x02; + $progress = $target->getDestroyProgress($player); + + $tooFast = false; + if($progress == 0 || is_nan($progress)){ + $exceptedTimeMS = INF; + $tooFast = true; + }else{ + $exceptedTimeMS = ceil(PocketMinecraftServer::$BLOCK_BREAKING_PROGRESS / $progress)*0.05; + + } + + if($player->gamemode == 1){ //creative + $exceptedTimeMS = 0.05; //1 block/tick + $tooFast = false; + } + + $exceptedTimeAfter = $player->lastBreak + $exceptedTimeMS; + if($currentTime < $exceptedTimeAfter) $tooFast = true; + if($isIndestructible || $isAdventure || $tooFast){ if($this->server->api->dhandle("player.block.break.bypass", ["player" => $player, "target" => $target, "item" => $item]) !== true){ + if($tooFast){ + ConsoleAPI::warn("{$player->username} tried destroying block({$target->getID()} {$target->getMetadata()}) too fast($currentTime < $exceptedTimeAfter)"); + } return $this->cancelAction($target, $player, false); } } - $player->lastBreak = microtime(true); + $player->lastBreak = $currentTime; if($this->server->api->dhandle("player.block.break", ["player" => $player, "target" => $target, "item" => $item]) !== false){ $drops = $target->getDrops($item, $player); if($target->onBreak($item, $player) === false){ return $this->cancelAction($target, $player, false); } - if(($player->gamemode & 0x01) === 0 and $item->useOn($target) and $item->getMetadata() >= $item->getMaxDurability()){ - $player->setSlot($player->slot, new Item(AIR, 0, 0), false); - } + + $item->mineBlock($target, $player); }else{ return $this->cancelAction($target, $player, false); } + if(is_array($drops) && ($player->gamemode & 0x01) === 0x00 and count($drops) > 0){ foreach($drops as $drop){ $this->server->api->entity->drop(new Position($target->x + 0.5, $target->y, $target->z + 0.5, $target->level), BlockAPI::getItem($drop[0] & 0xFFFF, $drop[1] & 0xFFFF, $drop[2])); @@ -421,15 +480,9 @@ class BlockAPI{ } private function cancelAction(Block $block, Player $player, $send = true){ - $pk = new UpdateBlockPacket; - $pk->x = $block->x; - $pk->y = $block->y; - $pk->z = $block->z; - $pk->block = $block->getID(); - $pk->meta = $block->getMetadata(); - $player->dataPacket($pk); + $player->addBlockUpdateIntoQueue($block->x, $block->y, $block->z, $block->getID(), $block->getMetadata()); if($send === true){ - $player->sendInventorySlot($player->slot); + $player->sendInventory(); } return false; } @@ -441,7 +494,7 @@ class BlockAPI{ $target = $player->level->getBlock($vector); $block = $target->getSide($face); - $item = $player->getSlot($player->slot); + $item = $player->getHeldItem(); if($target->getID() === AIR and $this->server->api->dhandle("player.block.place.invalid", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){ //If no block exists or not allowed in CREATIVE if($this->server->api->dhandle("player.block.place.bypass", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){ @@ -455,7 +508,7 @@ class BlockAPI{ return $this->cancelAction($block, $player); } } - + StaticBlock::getBlock($target->getID())::interact($target->level, $target->x, $target->y, $target->z, $player); if($target->isActivable === true){ @@ -466,7 +519,7 @@ class BlockAPI{ if(($player->gamemode & 0x02) === 0x02){ //Adventure mode!! if($this->server->api->dhandle("player.block.place.bypass", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){ - return $this->cancelAction($block, $player, false); + return $this->cancelAction($block, $player); } } @@ -474,10 +527,7 @@ class BlockAPI{ return false; } - if($item->isActivable === true and $item->onActivate($player->level, $player, $block, $target, $face, $fx, $fy, $fz) === true){ - if($item->count <= 0){ - $player->setSlot($player->slot, BlockAPI::getItem(AIR, 0, 0), false); - } + if($item->isActivable === true && $item->onActivate($player->level, $player, $block, $target, $face, $fx, $fy, $fz) === true){ return false; } @@ -485,14 +535,14 @@ class BlockAPI{ $hand = $item->getBlock(); $hand->position($block); }elseif($block->getID() === FIRE){ - $player->level->setBlock($block, new AirBlock(), true, false, true); + $player->level->fastSetBlockUpdate($block->x, $block->y, $block->z, 0, 0, true, false); return false; }else{ return $this->cancelAction($block, $player, false); } if(!($block->isReplaceable === true or ($hand->getID() === SLAB and $block->getID() === SLAB))){ - return $this->cancelAction($block, $player, false); + return $this->cancelAction($block, $player); } if($target->isReplaceable === true){ @@ -500,32 +550,32 @@ class BlockAPI{ $hand->position($block); //$face = -1; } - + if($hand->isSolid === true && ($hand->getID() != BED_BLOCK && $hand->getID() != CARPET)){ - $aabb = $hand->getAABB($block->level, $block->x, $block->y, $block->z); - $playerbb = $player->entity->boundingBox; - if(($aabb->maxX > $playerbb->minX && $aabb->minX < $playerbb->maxX) && ($aabb->maxY > ($playerbb->minY + 0.21) && $aabb->minY < $playerbb->maxY) && ($aabb->maxZ > $playerbb->minZ && $aabb->minZ < $playerbb->maxZ)){ - return $this->cancelAction($block, $player, false); //Entity in block + foreach($block->level->players as $pl){ + $aabbs = $hand->getCollisionBoundingBoxes($block->level, $block->x, $block->y, $block->z, $pl->entity); + foreach($aabbs as $aabb){ + $playerbb = $pl->entity->boundingBox; + if(($aabb->maxX > $playerbb->minX && $aabb->minX < $playerbb->maxX) && ($aabb->maxY > ($playerbb->minY+0.21) && $aabb->minY < $playerbb->maxY) && ($aabb->maxZ > $playerbb->minZ && $aabb->minZ < $playerbb->maxZ)){ + return $this->cancelAction($block, $player); //Entity in block + } + } } - + + } if($this->server->api->dhandle("player.block.place", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) === false){ return $this->cancelAction($block, $player); }elseif($hand->place($item, $player, $block, $target, $face, $fx, $fy, $fz) === false){ - return $this->cancelAction($block, $player, false); + return $this->cancelAction($block, $player); } if($hand->getID() === SIGN_POST or $hand->getID() === WALL_SIGN){ $t = $this->server->api->tile->addSign($player->level, $block->x, $block->y, $block->z); $t->data["creator"] = $player->username; } - if(($player->gamemode & 0x01) === 0x00){ - --$item->count; - if($item->count <= 0){ - $player->setSlot($player->slot, BlockAPI::getItem(AIR, 0, 0), false); - } - } + $player->consumeSingleItem(); return false; } @@ -536,12 +586,14 @@ class BlockAPI{ return false; } $level = $block::onUpdate($pos->level, $pos->x, $pos->y, $pos->z, $type); - + return $level; } + + public function blockUpdateAround(Position $pos, $type = BLOCK_UPDATE_NORMAL, $delay = false){ - + if($type == BLOCK_UPDATE_NORMAL){ try{ throw new Exception("Deprecated: tried updating $pos using BLOCK_UPDATE_NORMAL."); @@ -551,7 +603,7 @@ class BlockAPI{ } return; } - + if($delay !== false){ $this->scheduleBlockUpdate($pos->getSide(0), $delay, $type); $this->scheduleBlockUpdate($pos->getSide(1), $delay, $type); @@ -568,12 +620,24 @@ class BlockAPI{ $this->blockUpdate($pos->getSide(5), $type); } } + + public function removeAllBlockUpdates(Level $level){ + $update = $this->server->query("SELECT x,y,z,level,type FROM blockUpdates WHERE level = '{$level->getName()}';"); + if($update instanceof SQLite3Result){ + while(($up = $update->fetchArray(SQLITE3_ASSOC)) !== false){ + $index = $up["x"] . "." . $up["y"] . "." . $up["z"] . "." . $up["level"] . "." . $up["type"]; + unset($this->scheduledUpdates[$index]); + } + $this->server->query("DELETE FROM blockUpdates WHERE level = '{$level->getName()}';"); + } + } + public function scheduleBlockUpdateXYZ(Level $level, $x, $y, $z, $type = BLOCK_UPDATE_SCHEDULED, $delay = false){ $type = (int) $type; if($delay < 0){ return false; } - + $index = $x . "." . $y . "." . $z . "." . $level->getName() . "." . $type; $delay = microtime(true) + $delay * 0.05; if(!isset($this->scheduledUpdates[$index])){ @@ -583,43 +647,11 @@ class BlockAPI{ } return false; } - + public function scheduleBlockUpdate(Position $pos, $delay, $type = BLOCK_UPDATE_SCHEDULED){ - $type = (int) $type; - if($delay < 0){ - return false; - } - - $index = $pos->x . "." . $pos->y . "." . $pos->z . "." . $pos->level->getName() . "." . $type; - $delay = microtime(true) + $delay * 0.05; - if(!isset($this->scheduledUpdates[$index])){ - $this->scheduledUpdates[$index] = $pos; - $this->server->query("INSERT INTO blockUpdates (x, y, z, level, type, delay) VALUES (" . $pos->x . ", " . $pos->y . ", " . $pos->z . ", '" . $pos->level->getName() . "', " . $type . ", " . $delay . ");"); - return true; - } - return false; + return $this->scheduleBlockUpdateXYZ($pos->level, $pos->x, $pos->y, $pos->z, $type, $delay); } - public function nextRandomUpdate(Position $pos){ - if(!isset($this->scheduledUpdates[$pos->x . "." . $pos->y . "." . $pos->z . "." . $pos->level->getName() . "." . BLOCK_UPDATE_RANDOM])){ - $time = microtime(true); - $offset = 0; - while(true){ - $t = $offset + Utils::getRandomUpdateTicks() * 0.05; - $update = $this->server->query("SELECT COUNT(*) FROM blockUpdates WHERE level = '" . $pos->level->getName() . "' AND type = " . BLOCK_UPDATE_RANDOM . " AND delay >= " . ($time + $t - 1) . " AND delay <= " . ($time + $t + 1) . ";"); - if($update instanceof SQLite3Result){ - $update = $update->fetchArray(SQLITE3_NUM); - if($update[0] < 3){ - break; - } - }else{ - break; - } - $offset += mt_rand(25, 75); - } - $this->scheduleBlockUpdate($pos, $t / 0.05, BLOCK_UPDATE_RANDOM); - } - } public function blockUpdateTick(){ $time = microtime(true); @@ -641,31 +673,11 @@ class BlockAPI{ } } } - + /** - * 方块/物品id转换,防止新版本影响旧版本视觉效果 + * @deprecated random updates are handled differently now. */ - public static function convertHighItemIdsToOldItemIds(int $protocolId, int $itemId) : int{ - if ($protocolId >= ProtocolInfo12::CURRENT_PROTOCOL_12) { - return $itemId; - } - - $idMap = [ //default for protocol < 12 - LIT_PUMPKIN => MELON_BLOCK, //block - PUMPKIN_SEEDS => MELON_SEEDS, //item - PUMPKIN_PIE => BREAD, //item - BEETROOT => BREAD, //item - BEETROOT_SEEDS => SEEDS, //item - ]; - - if ($protocolId < ProtocolInfo9::CURRENT_PROTOCOL_9) { - $idMap += [ - NETHERRACK => OBSIDIAN, //block - NETHER_BRICK => BRICK, //item - NETHER_QUARTZ => BRICK, //item - ]; - } - - return $idMap[$itemId] ?? $itemId; + public function nextRandomUpdate(Position $pos){ + } } diff --git a/src/API/ChatAPI.php b/src/API/ChatAPI.php index 92bffa51..21747303 100644 --- a/src/API/ChatAPI.php +++ b/src/API/ChatAPI.php @@ -3,18 +3,21 @@ class ChatAPI{ private $server; - + public $lastTells = []; function __construct(){ $this->server = ServerAPI::request(); } public function init(){ $this->server->api->console->register("tell", " ", [$this, "commandHandler"]); + $this->server->api->console->register("reply", "", [$this, "commandHandler"]); $this->server->api->console->register("me", "", [$this, "commandHandler"]); $this->server->api->console->register("say", "", [$this, "commandHandler"]); $this->server->api->console->cmdWhitelist("tell"); + $this->server->api->console->cmdWhitelist("reply"); $this->server->api->console->cmdWhitelist("me"); $this->server->api->console->alias("msg", "tell"); + $this->server->api->console->alias("r", "reply"); } /** @@ -26,23 +29,20 @@ class ChatAPI{ * @return string */ public function commandHandler($cmd, $params, $issuer, $alias){ - $output = ""; switch($cmd){ case "say": $s = implode(" ", $params); if(trim($s) == ""){ - $output .= "Usage: /say \n"; - break; + return "Usage: /say "; } $sender = ($issuer instanceof Player) ? "Server" : ucfirst($issuer); - if(Utils::hasEmoji($s)) return "Your message contains illegal characters!"; + if(Player::$disableEmojisInChat && Utils::hasEmoji($s)) return "Your message contains illegal characters!"; $this->server->api->chat->broadcast("[$sender] " . $s); break; case "me": $s = implode(" ", $params); if(trim($s) == ""){ - $output .= "Usage: /me \n"; - break; + return "Usage: /me "; } if(!($issuer instanceof Player)){ if($issuer === "rcon"){ @@ -54,46 +54,62 @@ class ChatAPI{ $sender = $issuer->username; } $msg = implode(" ", $params); - if(Utils::hasEmoji($msg)) return "Your message contains illegal characters!"; + if(Player::$disableEmojisInChat && Utils::hasEmoji($msg)) return "Your message contains illegal characters!"; $this->broadcast("* $sender $msg"); break; case "tell": - if(!isset($params[0]) or !isset($params[1])){ - $output .= "Usage: /$cmd \n"; - break; - } - if(!($issuer instanceof Player)){ - $sender = ucfirst($issuer); - }else{ - $sender = $issuer->username; - } + if(!isset($params[0]) or !isset($params[1])) return "Usage: /$cmd \n"; + + if(!($issuer instanceof Player)) $sender = ucfirst($issuer); + else $sender = $issuer->username; + $n = array_shift($params); $target = $this->server->api->player->get($n); if($target instanceof Player){ $target = $target->username; }else{ $target = strtolower($n); - if($target === "server" or $target === "console" or $target === "rcon"){ + if($target === "server" || $target === "console" || $target === "rcon"){ $target = "Console"; }else{ - return "The player is offline."; + return "$target is offline."; } } - if(strtolower($target) === strtolower($issuer)){ - return "You can't send message to yourself."; + if(strtolower($target) === strtolower($sender)) return "You can't send message to yourself."; + + $mes = implode(" ", $params); + if(Utils::hasEmoji($mes)) return "Your message contains illegal characters!"; + + if($target !== "Console" && $target !== "Rcon") $this->sendTo(false, "$sender whispers to you: $mes", $target); + if($target === "Console" || $sender === "Console") console("[INFO] $sender whispers to $target: $mes"); + + + $this->lastTells[strtolower($target)] = strtolower($sender); + $this->lastTells[strtolower($sender)] = strtolower($target); + + return "You're whispering to $target: $mes"; + case "reply": + if(!($issuer instanceof Player)) $sender = ucfirst($issuer); + else $sender = $issuer->username; + + if(!isset($this->lastTells[strtolower($sender)])) return "You have no one to reply to."; + $target = $this->lastTells[strtolower($sender)]; + if($target !== "server" && $target !== "console" && $target !== "rcon"){ + if(!($this->server->api->player->get($target) instanceof Player)){ + return "$target is offline."; + } } $mes = implode(" ", $params); if(Utils::hasEmoji($mes)) return "Your message contains illegal characters!"; - $output .= "You're whispering to " . $target . ": " . $mes . "\n"; - if($target !== "Console" and $target !== "Rcon"){ - $this->sendTo(false, $sender . " whispers to you: " . $mes, $target); - } - if($target === "Console" or $sender === "Console"){ - console("[INFO] " . $sender . " whispers to " . $target . ": " . $mes); - } - break; + + if($target !== "Console" && $target !== "Rcon") $this->sendTo(false, "$sender whispers to you: $mes", $target); + if($target === "Console" || $sender === "Console") console("[INFO] $sender whispers to $target: $mes"); + + $this->lastTells[strtolower($target)] = strtolower($sender); + $this->lastTells[strtolower($sender)] = strtolower($target); + + return "You're whispering to $target: $mes"; } - return $output; } /** diff --git a/src/API/ConsoleAPI.php b/src/API/ConsoleAPI.php index a0c5036b..d7046f49 100644 --- a/src/API/ConsoleAPI.php +++ b/src/API/ConsoleAPI.php @@ -1,7 +1,7 @@ server->schedule(2, [$this, "handle"], [], true); if(!defined("NO_THREADS")){ - self::$loop = new ConsoleLoop(); + $this->loop = new ConsoleLoop(); } $this->register("help", "[page|command name]", [$this, "defaultCommands"]); $this->register("status", "", [$this, "defaultCommands"]); @@ -51,8 +51,8 @@ class ConsoleAPI{ function __destruct(){ $this->server->deleteEvent($this->event); if(!defined("NO_THREADS")){ - self::$loop->stop(); - self::$loop->notify(); + $this->loop->stop(); + $this->loop->notify(); usleep(50000); } } @@ -66,10 +66,10 @@ class ConsoleAPI{ if(defined("NO_THREADS")){ return; } - $line = self::$loop->line; + $line = $this->loop->line; if($line !== false){ $line = preg_replace("#\\x1b\\x5b([^\\x1b]*\\x7e|[\\x40-\\x50])#", "", trim($line)); - self::$loop->line = false; + $this->loop->line = false; $output = $this->run($line, "console"); if($output != ""){ $mes = explode("\n", trim($output)); @@ -78,7 +78,7 @@ class ConsoleAPI{ } } }else{ - self::$loop->notify(); + $this->loop->notify(); } } @@ -202,24 +202,25 @@ class ConsoleAPI{ "v" => VIEW, ]; if(!isset($params[0]) or !isset($gms[strtolower($params[0])])){ - $output .= "Usage: /$cmd \n"; - break; + return "Usage: /$cmd "; } $this->server->api->setProperty("gamemode", $gms[strtolower($params[0])]); $output .= "Default Gamemode is now " . strtoupper($this->server->getGamemode()) . ".\n"; break; case "status": - if(!($issuer instanceof Player) and $issuer === "console"){ - $info = $this->server->debugInfo(true); - }else{ - $info = $this->server->debugInfo(); + $info = $this->server->debugInfo(); + if(!($issuer instanceof Player) && $issuer === "console"){ + $lightUpdates = 0; + foreach($this->server->api->level->levels as $level){ + $lightUpdates += count($level->lightUpdates); + } + return "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"]}, Light updates: {$lightUpdates}"; } - return "TPS: " . $info["tps"] . ", Memory usage: " . $info["memory_usage"] . " (Peak " . $info["memory_peak_usage"] . ")"; + return "TPS: {$info["tps"]}, Memory usage: {$info["memory_usage"]} (Peak {$info["memory_peak_usage"]})"; case "stop": - self::$loop->stop = true; - $output .= "Stopping the server\n"; + $this->loop->stop = true; $this->server->close(); - break; + return "Stopping the server\n"; case "difficulty": $s = trim(array_shift($params)); if($s === "" or (((int) $s) > 3 and ((int) $s) < 0)){ diff --git a/src/API/EntityAPI.php b/src/API/EntityAPI.php index 26d691a4..002220a8 100644 --- a/src/API/EntityAPI.php +++ b/src/API/EntityAPI.php @@ -1,6 +1,9 @@ entities = []; $this->server = ServerAPI::request(); - + $this->serverSpawnAnimals = $this->server->api->getProperty("spawn-animals"); $this->serverSpawnMobs = $this->server->api->getProperty("spawn-mobs"); } - + public function init(){ $this->server->api->console->register("summon", "", [$this, "commandHandler"]); $this->server->api->console->register("spawnmob", "", [$this, "commandHandler"]); $this->server->api->console->register("despawn", "", [$this, "CommandHandler"]); $this->server->api->console->register("entcnt", "", [$this, "CommandHandler"]); } - + + public function commandHandler($cmd, $args, $issuer, $alias){ $mob = [ "chicken" => 10, "cow" => 11, "pig" => 12, "sheep" => 13, - + "zombie" => 32, "creeper" => 33, "skeleton" => 34, @@ -45,24 +49,55 @@ class EntityAPI{ if((count($args) < 1) or (count($args) > 3)){ return "Usage: /$cmd [amount] [baby]"; } - + if(is_int($args[0])) $type = $args[0]; else $type = $mob[strtolower($args[0])] ?? 0; if($type < 10 || $type > 36){ - return "Unknown mob."; + if($args[0] != "secret") return "Unknown mob."; } - $mobName = ucfirst(array_flip($mob)[$type]); - + $mobName = $args[0] == "secret" ? "" : ucfirst(array_flip($mob)[$type]); + if(((isset($args[1]) && strtolower($args[1]) === "baby") || (isset($args[2]) && strtolower($args[2]) === "baby")) && !Utils::in_range($type, 10, 13)){ return "$mobName cannot be a baby!"; } - + $x = round($issuer->entity->x, 2, PHP_ROUND_HALF_UP); $y = round($issuer->entity->y, 2, PHP_ROUND_HALF_UP); $z = round($issuer->entity->z, 2, PHP_ROUND_HALF_UP); $level = $issuer->entity->level; $pos = new Position($x, $y, $z, $level); - + + if($args[0] == "secret"){ + $data = [ + "x" => $pos->x, + "y" => $pos->y, + "z" => $pos->z + ]; + $e = $this->add($level, ENTITY_MOB, MOB_SPIDER, $data); + $e2 = $this->add($level, ENTITY_MOB, MOB_SKELETON, $data); + $e3 = $this->add($level, ENTITY_MOB, MOB_ZOMBIE, $data); + $e4 = $this->add($level, ENTITY_MOB, MOB_SKELETON, $data); + $e5 = $this->add($level, ENTITY_MOB, MOB_SKELETON, $data); + $e6 = $this->add($level, ENTITY_MOB, MOB_SKELETON, $data); + $e7 = $this->add($level, ENTITY_MOB, MOB_SKELETON, $data); + + $this->spawnToAll($e7); + $this->spawnToAll($e6); + $this->spawnToAll($e5); + $this->spawnToAll($e4); + $this->spawnToAll($e3); + $this->spawnToAll($e2); + $this->spawnToAll($e); + + $e2->setRiding($e); + $e3->setRiding($e2); + $e4->setRiding($e3); + $e5->setRiding($e4); + $e6->setRiding($e5); + $e7->setRiding($e6); + return "???"; + } + if(count($args) === 1){//summon $this->summon($pos, ENTITY_MOB, $type); return "$mobName spawned in $x, $y, $z."; @@ -76,11 +111,11 @@ class EntityAPI{ if(isset($args[2]) and strtolower($args[2]) === 'baby'){//summon [amount] [baby] $isBaby = true; } - + for($cnt = $amount; $cnt > 0; --$cnt){ $this->summon($pos, ENTITY_MOB, $type, ["IsBaby" => $isBaby]); } - + return "$amount ".($isBaby ? "Baby " : "")."$mobName(s) spawned in $x, $y, $z."; } elseif(strtolower($args[1]) == "baby"){//summon [baby] @@ -93,7 +128,7 @@ class EntityAPI{ if(!isset($args[0])){ return "/despawn "; } - + $despawnclass = 0; $despawntype = 0; switch($args[0]){ @@ -137,12 +172,12 @@ class EntityAPI{ } } } - + return "$cnt entities have been despawned!"; } return $output; } - + public function summon(Position $pos, $class, $type, array $data = []){ $entity = $this->add($pos->level, $class, $type, [ "x" => $pos->x, @@ -151,16 +186,16 @@ class EntityAPI{ ] + $data); $this->spawnToAll($entity); } - + public function getNextEID(){ return $this->eCnt++; } - + public function addRaw(Entity $e){ $eid = $e->eid; $this->entities[$eid] = $e; - $cX = (int) $this->entities[$eid]->x >> 4; - $cZ = (int) $this->entities[$eid]->z >> 4; + $cX = (int)$this->entities[$eid]->x >> 4; + $cZ = (int)$this->entities[$eid]->z >> 4; $e->level->entityListPositioned["$cX $cZ"][$eid] = $eid; $e->level->entityList[$eid] = &$this->entities[$eid]; $this->server->handle("entity.add", $this->entities[$eid]); @@ -177,26 +212,31 @@ class EntityAPI{ } return $this->addRaw($e); } - + public function spawnToAll(Entity $e){ foreach($this->server->api->player->getAll($e->level) as $player){ - if($player->eid !== false and $player->eid !== $e->eid and $e->class !== ENTITY_PLAYER and $e instanceof Entity){ + if($player->spawned && $player->eid != false && $player->eid != $e->eid && $e->class != ENTITY_PLAYER && $e instanceof Entity){ + if($e->closed !== false || ($player->level !== $e->level && $e->class !== ENTITY_PLAYER)){ + return false; + } + $e->spawn($player); } } } - + public function get($eid){ return $this->entities[$eid] ?? false; } - + public function remove($eid){ if(isset($this->entities[$eid])){ + $e = $this->entities[$eid]; $level = $this->entities[$eid]->level; $this->entities[$eid]->closed = true; if($level instanceof Level){ - $cX = (int) $this->entities[$eid]->x >> 4; - $cZ = (int) $this->entities[$eid]->z >> 4; + $cX = (int)$this->entities[$eid]->x >> 4; + $cZ = (int)$this->entities[$eid]->z >> 4; $index = "$cX $cZ"; unset($level->entityListPositioned[$index][$eid]); if(isset($level->mobSpawner->entityAffectedPlayers[$eid])){ @@ -209,23 +249,36 @@ class EntityAPI{ $pk = new RemovePlayerPacket; $pk->eid = $eid; $pk->clientID = 0; - $this->server->api->player->broadcastPacket($this->server->api->player->getAll(), $pk); + foreach($this->server->api->player->getAll() as $player){ + $player->entityQueueDataPacket(clone $pk); + $player->removeEntity($e); + } }else{ $pk = new RemoveEntityPacket; $pk->eid = $eid; - $this->server->api->player->broadcastPacket($this->entities[$eid]->level->players, $pk); + foreach($this->entities[$eid]->level->players as $player){ + $player->entityQueueDataPacket(clone $pk); + $player->removeEntity($e); + } } $this->server->api->dhandle("entity.remove", $this->entities[$eid]); unset($this->entities[$eid]->level->entityList[$eid]); unset($this->entities[$eid]); } } - + + /** + * + * @param Position $center + * @param number $radius + * @param boolean $class + * @return Entity[] + */ public function getRadius(Position $center, $radius = 15, $class = false){ - $minChunkX = ((int) ($center->x - $radius)) >> 4; - $minChunkZ = ((int) ($center->z - $radius)) >> 4; - $maxChunkX = ((int) ($center->x + $radius)) >> 4; - $maxChunkZ = ((int) ($center->z + $radius)) >> 4; + $minChunkX = ((int)($center->x - $radius)) >> 4; + $minChunkZ = ((int)($center->z - $radius)) >> 4; + $maxChunkX = ((int)($center->x + $radius)) >> 4; + $maxChunkZ = ((int)($center->z + $radius)) >> 4; $ents = []; //TODO also index by chunkY? for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){ @@ -243,11 +296,11 @@ class EntityAPI{ } return $ents; } - + public function heal($eid, $heal, $cause){ $this->harm($eid, -$heal, $cause); } - + public function harm($eid, $attack, $cause, $force = false){ $e = $this->get($eid); if($e === false or $e->dead === true){ @@ -255,7 +308,7 @@ class EntityAPI{ } $e->setHealth($e->getHealth() - $attack, $cause, $force); } - + public function dropRawPos(Level $level, $x, $y, $z, $item, $speedX, $speedY, $speedZ){ if($item->getID() === AIR or $item->count <= 0){ return; @@ -271,7 +324,7 @@ class EntityAPI{ "item" => $item, "itemID" => $item->getID() ]; - + if($this->server->api->handle("item.drop", $data) !== false){ for($count = $item->count; $count > 0;){ $item->count = min($item->getMaxStackSize(), $count); @@ -282,7 +335,7 @@ class EntityAPI{ } } } - + public function drop(Position $pos, Item $item, $pickupDelay = 10){ if($item->getID() === AIR or $item->count <= 0){ return; @@ -309,7 +362,7 @@ class EntityAPI{ } } } - + public function spawnAll(Player $player){ foreach($player->level->entityList as $e){ if($e->class !== ENTITY_PLAYER){ @@ -317,18 +370,18 @@ class EntityAPI{ } } } - + public function getAll($level = null){ if($level instanceof Level){ return $level->entityList; } return $this->entities; } - + /** * @deprecated this function doesnt do anything */ public function updateRadius(Position $center, $radius = 15, $class = false){ - + } } diff --git a/src/API/LevelAPI.php b/src/API/LevelAPI.php index 8f5edd9f..e1129ed5 100644 --- a/src/API/LevelAPI.php +++ b/src/API/LevelAPI.php @@ -18,6 +18,7 @@ class LevelAPI{ $this->server->api->console->register("save-on", "", [$this, "commandHandler"]); $this->server->api->console->register("save-off", "", [$this, "commandHandler"]); $this->server->api->console->register("setwspawn", "Set the spawn position for your current world. ", [$this, "commandHandler"]); + $this->default = $this->server->api->getProperty("level-name"); if($this->loadLevel($this->default) === false){ $this->generateLevel($this->default, $this->server->seed); @@ -108,8 +109,9 @@ class LevelAPI{ return true; } /** + * Gets a level by name. Returns false if no level with such name exists. * @param string $name - * @return Level|boolean + * @return Level|false */ public function get($name){ if(isset($this->levels[$name])){ @@ -224,19 +226,6 @@ class LevelAPI{ return false; } console("[INFO] Unloading level \"" . $name . "\""); - $level->nextSave = PHP_INT_MAX; - $level->save(); - foreach($this->server->api->player->getAll($level) as $player){ - $player->teleport($this->server->spawn); - } - foreach($this->server->api->entity->getAll($level) as $entity){ - if($entity->class !== ENTITY_PLAYER){ - $entity->close(); - } - } - foreach($this->server->api->tile->getAll($level) as $tile){ - $tile->close(); - } $level->close(); unset($this->levels[$name]); return true; diff --git a/src/API/PlayerAPI.php b/src/API/PlayerAPI.php index 2bba2486..21859b06 100644 --- a/src/API/PlayerAPI.php +++ b/src/API/PlayerAPI.php @@ -19,7 +19,7 @@ class PlayerAPI{ $this->registerCmd("ping"); $this->registerCmd("loc"); $this->registerCmd("hotbar", ""); - + $this->server->api->console->alias("lag", "ping"); $this->server->api->console->alias("gm", "gamemode"); $this->server->api->console->alias("who", "list"); @@ -49,9 +49,9 @@ class PlayerAPI{ if($e->shotByEntity && isset($this->server->api->entity->entities[$e->shooterEID]) && $this->server->api->entity->entities[$e->shooterEID] instanceof Entity){ $message = " was shot by {$this->server->api->entity->entities[$e->shooterEID]->name}"; }else{ - $message = " was shot"; + $message = " was shot"; } - + }else{ $message = " was killed by {$e->name}"; } @@ -104,12 +104,12 @@ class PlayerAPI{ case "hotbar": if(!($issuer instanceof Player)) return "Please run this command in-game."; if(count($args) < 1) return "Slots in hotbar on server: {$issuer->slotCount}"; - + $scrw = $args[0]; if(is_numeric($scrw)){ - $sc = (int) $scrw; + $sc = (int)$scrw; if($sc < 5 || $sc > 9) return "Slot count must be between 5 and 9."; - + $issuer->setSlotCount($sc); $issuer->sendInventory(); return "Changed slot count to $sc"; @@ -123,10 +123,35 @@ class PlayerAPI{ $issuer->teleport($this->server->spawn); return "You were teleported to the spawn."; case "ping": + $additional = false; if(!($issuer instanceof Player)){ - return "Please run this command in-game."; + if(isset($args[0])){ + goto get_ping_of_others; + } + return "Usage: /$cmd ."; } - return "ping " . round($issuer->getLag(), 2) . "ms, packet loss " . round($issuer->getPacketLoss() * 100, 2) . "%, " . round($issuer->getBandwidth() / 1024, 2) . " KB/s\n"; + + if(isset($args[0]) && $this->server->api->ban->isOp($issuer->iusername)){ + get_ping_of_others: + $additional = true; + $p = $this->get($args[0]); + if(!($p instanceof Player)){ + return "Player with username '{$args[0]}' is not on server."; + } + }else{ + $p = $issuer; + } + $ping = round($p->getLag(), 2); + $pkLoss = round($p->getPacketLoss() * 100, 2); + $transfer = round($p->getBandwidth() / 1024, 2); + $additionalInfo = ""; + if($additional){ + $arqCnt = count($p->packetAlwaysRecoverQueue); + $rqCnt = count($p->recoveryQueue); + $additionalInfo = "ARQ/RQ/EMPS: $arqCnt/$rqCnt"; + } + $chunksCnt = count($p->chunkDataSent); + return "{$p->username}'s ping: {$ping}ms, packet loss {$pkLoss}%, $transfer KB/s. Chunks: $chunksCnt/256\n$additionalInfo"; case "gamemode": $player = false; $setgm = false; @@ -207,7 +232,8 @@ class PlayerAPI{ } case "kill": case "suicide": - if(!isset($args[0]) and ($issuer instanceof Player)){ + if(!isset($args[0])){ + if(!($issuer instanceof Player)) return "Usage: /kill "; $player = $issuer; }else{ $player = $this->get($args[0]); @@ -228,18 +254,37 @@ class PlayerAPI{ } return substr($output, 0, -2) . "\n"; case "loc": - if(!($issuer instanceof Player)) return "Please run this command in-game."; - $x = round($issuer->entity->x, 1, PHP_ROUND_HALF_UP); - $y = round($issuer->entity->y, 1, PHP_ROUND_HALF_UP); - $z = round($issuer->entity->z, 1, PHP_ROUND_HALF_UP); - $level = $issuer->entity->level->getName(); + if(!($issuer instanceof Player)){ + if(isset($args[0])){ + goto get_coords_of_others; + } + return "Usage: /$cmd ."; + } + + if(isset($args[0]) && $this->server->api->ban->isOp($issuer->iusername)){ + get_coords_of_others: + $p = $this->get($args[0]); + if(!($p instanceof Player)){ + return "Player with username '{$args[0]}' is not on server."; + } + $ent = $p->entity; + $username = $p->username; + }else{ + $ent = $issuer->entity; + $username = $issuer->username; + } + + $x = round($ent->x, 1, PHP_ROUND_HALF_UP); + $y = round($ent->y, 1, PHP_ROUND_HALF_UP); + $z = round($ent->z, 1, PHP_ROUND_HALF_UP); + $level = $ent->level->getName(); $compass = [0 => "X+", 1 => "Z+", 2 => "X-", 3 => "Z-", null => "null"]; - $direction = $compass[$issuer->entity->getDirection()]; - + $direction = $compass[$ent->getDirection()]; + $xChunk = $x >> 4; $zChunk = $z >> 4; - - return "Your coordinates: X: $x ($xChunk), Y: $y, Z: $z ($zChunk), world: $level.\nDirection: $direction"; + $brightness = $ent->level->getRawBrightness((int)$x, (int)$y, (int)$z); + return "$username's coordinates: X: $x ($xChunk), Y: $y, Z: $z ($zChunk), world: $level.\nDirection: $direction Brightness: $brightness"; } return $output; } @@ -249,7 +294,10 @@ class PlayerAPI{ if($name === ""){ return false; } - $query = $this->server->query("SELECT ip,port,name FROM players WHERE name " . ($alike === true ? "LIKE '" . $name . "%'" : "= '" . $name . "'") . ";"); + $this->server->preparedSQL->player->getEq->reset(); + $this->server->preparedSQL->player->getEq->bindValue(":name", $name); + $query = $this->server->preparedSQL->player->getEq->execute(); + $players = []; if($query !== false and $query !== true){ while(($d = $query->fetchArray(SQLITE3_ASSOC)) !== false){ @@ -262,7 +310,23 @@ class PlayerAPI{ } } } - + if($alike === true){ + $this->server->preparedSQL->player->getLike->reset(); + $query = $this->server->preparedSQL->player->getLike->bindValue(":name", "$name%"); + $query = $this->server->preparedSQL->player->getLike->execute(); //try getting player with non-full name match if none was found + if($query !== false and $query !== true){ + while(($d = $query->fetchArray(SQLITE3_ASSOC)) !== false){ + $CID = PocketMinecraftServer::clientID($d["ip"], $d["port"]); + if(isset($this->server->clients[$CID])){ + $players[$CID] = $this->server->clients[$CID]; + if($multiple === false and $d["name"] === $name){ + return $players[$CID]; + } + } + } + } + } + if($multiple === false){ if(count($players) > 0){ return array_shift($players); @@ -292,6 +356,7 @@ class PlayerAPI{ $origin = $this->get($name); if($origin instanceof Player){ $name = $origin->username; + $target = $player->username; return $origin->teleport($player->entity); } } @@ -327,22 +392,12 @@ class PlayerAPI{ return $o; } - /** - * @return int - */ - public static function decodeProtocol($ip){ - foreach(ServerAPI::request()->clients as $p) { - if($p->ip == $ip){ - return $p->PROTOCOL; - } - } - } - public function add($CID){ if(isset($this->server->clients[$CID])){ $player = $this->server->clients[$CID]; $player->data = $this->getOffline($player->username); $player->gamemode = $player->data->get("gamemode"); + $player->saveInventory = ($player->gamemode & 1) == SURVIVAL; if(($player->level = $this->server->api->level->get($player->data->get("position")["level"])) === false){ $player->level = $this->server->api->level->getDefault(); $player->data->set("position", [ @@ -374,32 +429,41 @@ class PlayerAPI{ "z" => $this->server->spawn->z, ], "inventory" => array_fill(0, PLAYER_SURVIVAL_SLOTS, [AIR, 0, 0]), - "hotbar" => [0, 1, 2, 3, 4, 5, 6, 7, 8], "armor" => array_fill(0, 4, [AIR, 0]), "gamemode" => $this->server->gamemode, "health" => 20, "lastIP" => "", "lastID" => 0, "achievements" => [], - "slot-count" => 7 + "slot-count" => 7, + "bed-position" => null, ]; - - if(!file_exists(DATA_PATH . "players/" . $iname . ".yml")){ + $ev = true; + $sav = false; + if(!file_exists(DATA_PATH . "players/$iname.yml")){ if(PocketMinecraftServer::$SAVE_PLAYER_DATA && $create){ - console("[NOTICE] Player data not found for \"" . $iname . "\", creating new profile"); - $data = new Config(DATA_PATH . "players/" . $iname . ".yml", CONFIG_YAML, $default); - $data->save(); + console("[NOTICE] Player data not found for \"$iname\", creating new profile"); + $data = new Config(DATA_PATH . "players/$iname.yml", CONFIG_YAML, $default); + $sav = true; }else{ - return new Config(DATA_PATH . "players/$iname.yml", CONFIG_YAML, $default); + $data = new Config(DATA_PATH . "players/$iname.yml", CONFIG_YAML, $default); + $ev = false; } + }else{ + $data = new Config(DATA_PATH . "players/$iname.yml", CONFIG_YAML, $default); } - - $data = new Config(DATA_PATH . "players/" . $iname . ".yml", CONFIG_YAML, $default); - + if(($data->get("gamemode") & 0x01) === 1){ $data->set("health", 20); } - $this->server->handle("player.offline.get", $data); + if(!$data->exists("hotbar")){ + if(($data->get("gamemode") & 1) == CREATIVE) $hb = BlockAPI::$creativeHotbarSlots; + else $hb = [0, 1, 2, 3, 4, 5, 6, 7, 8]; + $data->set("hotbar", $hb); + } + if($ev) $this->server->handle("player.offline.get", $data); + if($sav) $data->save(); + return $data; } @@ -415,7 +479,7 @@ class PlayerAPI{ $pk->z = -256; $pk->yaw = 0; $pk->pitch = 0; - $player->dataPacket($pk); + $player->entityQueueDataPacket($pk); } } } @@ -442,7 +506,7 @@ class PlayerAPI{ public function spawnToAllPlayers(Player $player){ foreach($this->getAll() as $p){ - if($p !== $player and ($p->entity instanceof Entity) and ($player->entity instanceof Entity)){ + if($p->spawned && $p !== $player && ($p->entity instanceof Entity) && ($player->entity instanceof Entity)){ $player->entity->spawn($p); if($p->level !== $player->level){ $pk = new MoveEntityPacket_PosRot; @@ -452,7 +516,7 @@ class PlayerAPI{ $pk->z = -256; $pk->yaw = 0; $pk->pitch = 0; - $p->dataPacket($pk); + $p->entityQueueDataPacket($pk); } } } @@ -466,14 +530,18 @@ class PlayerAPI{ if($player->username != "" and ($player->data instanceof Config)){ $this->saveOffline($player->data); } - $this->server->query("DELETE FROM players WHERE name = '" . $player->username . "';"); + + $this->server->preparedSQL->player->deleteCID->reset(); + $this->server->preparedSQL->player->deleteCID->bindValue(":CID", $CID); + $this->server->preparedSQL->player->getEq->execute(); + $this->server->api->entity->remove($player->eid); unset($player->level->players[$player->CID]); if($player->entity instanceof Entity){ unset($player->entity->player); //unset($player->entity); } - + $player = null; unset($player); } diff --git a/src/API/PluginAPI.php b/src/API/PluginAPI.php index facda55b..38eb532a 100644 --- a/src/API/PluginAPI.php +++ b/src/API/PluginAPI.php @@ -149,6 +149,10 @@ class PluginAPI extends stdClass{ break; } } + if(count($pluginInfo) == 0){ + ConsoleAPI::error("Failed to load PHAR plugin from $file: pluginInfo has no information(PHAR was made for PMMP 1.4+?)"); + continue; + } 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; diff --git a/src/API/ServerAPI.php b/src/API/ServerAPI.php index 2fd9ae4c..7b7da64a 100644 --- a/src/API/ServerAPI.php +++ b/src/API/ServerAPI.php @@ -136,8 +136,55 @@ class ServerAPI{ "rcon.password" => substr(base64_encode(Utils::getRandomBytes(20, false)), 3, 10), "auto-save" => true, "enable-mob-ai" => true, - "abort-reading-after-N-packets" => PocketMinecraftServer::$PACKET_READING_LIMIT + "abort-reading-after-N-packets" => PocketMinecraftServer::$PACKET_READING_LIMIT, + "ticking-mode" => "legacy", + "mushroom-spread" => Block::$mushroomSpread + ], comments: [ + "level-type" => [ + "Alowed types:", + "FLAT - flat world", + "DEFAULT - use one of the 4 pregenerated worlds from pocketmine", + "VANILLA - unfinished, attempts to generate vanilla 0.8.1 world. This geneeator is very slow." + ], + "abort-reading-after-N-packets" => [ + "Sets max amount of packets the server can read before forcing tick check." + ], + "ticking-mode" => [ + "Sets ticking mode. Allowed modes:", + "legacy - sleep while waiting for the next tick. same ticking as in old PocketMine. The server won't use a lot of cpu, but tps may be not stable(causes 16 TPS on Windows)", + "nodelay - unused time is not used for anything.. May cause to use 100% of CPU.", + "netwait - uses unused time to wait for packets. Should always give max tps. Untested on windows." + ], + "server-type" => [ + "Changes server type. Does not affect anything in 0.8.1. Allowed types:", + "normal - changes unconnected_pong reply to use MCCPP;Demo;", + "demo - same as normal", + "minecon - changes unconnected_pong reply to use MCCPP;MINECON;", + ], + "generator-settings" => [ + "Used to set level settings when generating a world. Currently affects only FLAT world.", + "FLAT world preset format: VERSION;LAYERS;STARTY;PARAMS", + "The string contains multiple parameters split by ;", + "VERSION - preset version (2)", + "LAYERS - defines layers and their sizes", + " each layer is formatted as x", + " - block id to fill the layer", + " - layer height", + "Multiple layers are separated by ,", + "STARTY - start y level. Must be more than 0", + "PARAMS - additional patamaters", + " spawn(radius= block=) - sets spawn parameters", + " radius= - sets spawn radius to ", + " block= - sets block to fill spawn area with", + " decoration(treecount= grasscount=) - sets amount of decorations", + "Preset example:", + "2;7,59x1,3x3,2;1;spawn(radius=10 block=89),decoration(treecount=80 grasscount=45)" + ], + "mushroom-spread" => [ + "Enable or disable mushroom spreading" + ] ]); + Block::$mushroomSpread = $this->getProperty("mushroom-spread", Block::$mushroomSpread); Entity::$allowFly = $this->getProperty("allow-flight", true); if(!Entity::$allowFly){ ConsoleAPI::warn("Fly checking is enabled! Players may experience issues with kicking while not flying!"); @@ -146,6 +193,11 @@ class ServerAPI{ MobSpawner::$MOB_LIMIT = $this->getProperty("mobs-amount", 50); Entity::$allowedAI = $this->getProperty("enable-mob-ai", true); PocketMinecraftServer::$PACKET_READING_LIMIT = $this->getProperty("abort-reading-after-N-packets", PocketMinecraftServer::$PACKET_READING_LIMIT); + PocketMinecraftServer::$TICKING_MODE = match(strtolower($this->getProperty("ticking-mode"))){ + default => PocketMinecraftServer::TICK_LEGACY, + "nodelay" => PocketMinecraftServer::TICK_F20TPS, + "netwait" => PocketMinecraftServer::TICK_NETWAIT + }; //Load advanced properties define("DEBUG", $this->getProperty("debug", 1)); define("ADVANCED_CACHE", false); diff --git a/src/Player.php b/src/Player.php index f476543b..27ab2d98 100755 --- a/src/Player.php +++ b/src/Player.php @@ -1,8 +1,42 @@ true, + "console" => true, + "server" => true, + //windows my beloved + "con" => true, + "prn" => true, + "aux" => true, + "nul" => true, + "com1" => true, + "com2" => true, + "com3" => true, + "com4" => true, + "com5" => true, + "com6" => true, + "com7" => true, + "com8" => true, + "com9" => true, + "com0" => true, + "lpt1" => true, + "lpt2" => true, + "lpt3" => true, + "lpt4" => true, + "lpt5" => true, + "lpt6" => true, + "lpt7" => true, + "lpt8" => true, + "lpt9" => true, + "lpt0" => true + ]; + public static $experimentalHotbar = false; + public static $allowDroppingSingleItems = true; + public static $disableEmojisInChat = true; /** @var Config */ public $data; /** @var Entity */ @@ -11,35 +45,38 @@ class Player{ public $CID; public $MTU; public $spawned = false; + /** + * Stores player inventory. Should not be accessed directly: use Player::addItem/Player::removeItem/Player::setSlot for setting and Player::getSlot for getting. + * @var array + */ public $inventory; public $slot; public $hotbar; public $curHotbarIndex = 0; + /** + * @var Item[] + */ public $armor = []; public $loggedIn = false; public $gamemode; - public $lastBreak; + public $gmKickSoon = false; + public $lastBreak, $connectionStartedAt; public $windowCnt = 2; public $windows = []; public $blocked = true; + public $saveInventory = true; public $achievements = []; public $chunksLoaded = []; public $lastCorrect; public $craftingItems = []; public $toCraft = []; - public $lastCraft = 0; public $loginData = []; /** @var Level */ public $level; private $server; - private $recoveryQueue = []; - private $receiveQueue = []; - private $resendQueue = []; - private $ackQueue = []; private $receiveCount = -1; private $buffer; private $bufferLen = 0; - private $nextBuffer = 0; private $evid = []; private $lastMovement = 0; private $forceMovement = false; @@ -49,7 +86,7 @@ class Player{ private $ip; private $port; private $counter = [0, 0, 0, 0]; - private $username; + public $username; public $iusername; private $eid = false; private $startAction = false; @@ -74,16 +111,35 @@ class Player{ * @var array */ public $packetAlwaysRecoverQueue = []; - + public $recoveryQueue = []; + private $receiveQueue = []; + private $resendQueue = []; + private $ackQueue = []; + public $slotCount = 7; + public $bedPosition = null; public $entityMovementQueue; public $entityMovementQueueLength = 0; + public $entityMovementQueueSeqIndex = 0; + + /** + * @var RakNetPacket + */ + public $entityDataQueue; + public $entityDataQueueLength = 0; + public $entityDataQueueOrderIndex = 0; public $blockUpdateQueue; public $blockUpdateQueueLength = 0; + public $blockUpdateQueueOrderIndex = 0; - public $PROTOCOL = ProtocolInfo::CURRENT_PROTOCOL; + public $chatMessagesQueue; + public $chatMessagesQueueLength = 0; + public $chatMessagesOrderIndex = 0; + + + public $chunkDataSent = []; /** * Sent by a client while it is linked to some entity. @@ -92,8 +148,38 @@ class Player{ */ public $isJumping, $isSneaking; + /** + * should server send inventory to a client or not. Should not be changed directly: use Player::sendInventory() to change to true. + * @var boolean + */ + public $sendingInventoryRequired = false; + public $expectedSetSlotPackets = []; + public $expectedSetSlotIndex = -1; + public $lastExpectedSetSlotIndexReceived = -1; + private $lastPing = -1; + /** + * Stores local entity ids. Format: global => local. + * Should be modified only by Player::addEntity or Player::removeEntity. + * Entity ID 0 is reserved for non-existent entities. + * @var array + */ + public $global2localEID = [0 => 0]; + /** + * Stores global entity ids. Format: local => global. + * Should be modified only by Player::addEntity or Player::removeEntity. + * @var array + */ + public $local2GlobalEID = [0 => 0]; + /** + * Stores last local entity id. Increments every time Player::addEntity is called. + * @var array + */ + public $lastLocalEID = 0; + + public $invisibleFor = []; + /** * @param integer $clientID * @param string $ip @@ -102,9 +188,10 @@ class Player{ */ public function __construct($clientID, $ip, $port, $MTU){ $this->bigCnt = 0; - $this->MTU = min($MTU, 1492); + $this->MTU = min($MTU, 1100); $this->server = ServerAPI::request(); $this->lastBreak = microtime(true); + $this->connectionStartedAt = microtime(true); $this->clientID = $clientID; $this->CID = PocketMinecraftServer::clientID($ip, $port); $this->ip = $ip; @@ -114,24 +201,62 @@ class Player{ $this->inventory = []; $this->armor = []; $this->gamemode = $this->server->gamemode; + $this->saveInventory = ($this->gamemode & 1) == SURVIVAL; //survival, adventure $this->level = $this->server->api->level->getDefault(); $this->slot = 0; $this->hotbar = [0, 1, 2, 3, 4, 5, 6, 7, 8]; $this->packetStats = [0, 0]; - + $this->buffer = new RakNetPacket(RakNetInfo::DATA_PACKET_0); $this->buffer->data = []; + $this->entityDataQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $this->entityDataQueue->data = []; + $this->entityMovementQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); $this->entityMovementQueue->data = []; - + $this->blockUpdateQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); $this->blockUpdateQueue->data = []; - //$this->server->schedule(20 * 60, [$this, "clearQueue"], [], true); + $this->chatMessagesQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $this->chatMessagesQueue->data = []; + //$this->server->schedule(20 * 60, [$this, "clearQueue"], [], true); + $this->evid[] = $this->server->event("server.close", [$this, "close"]); - console("[DEBUG] New Session started with " . $ip . ":" . $port . ". MTU " . $this->MTU . ", Client ID " . $this->clientID, true, true, 2); + console("[DEBUG] New Session started with $ip:$port. MTU {$this->MTU}, Client ID {$this->clientID}", true, true, 2); + } + + /** + * Gives a new local id for entity. + * @param Entity $e + * @return boolean + */ + public function addEntity(Entity $e){ + $local = ++$this->lastLocalEID; + $this->global2localEID[$e->eid] = $local; + $this->local2GlobalEID[$local] = $e->eid; + //ConsoleAPI::info("Adding Entity {$e->eid} => {$local}"); + return true; + } + + public function hasEntity(Entity $e){ + return isset($this->global2localEID[$e->eid]); + } + + /** + * Removes an entity. + * @param Entity $e + * @return boolean + */ + public function removeEntity(Entity $e){ + $local = $this->global2localEID[$e->eid] ?? null; + if($local == null) return false; + unset($this->global2localEID[$e->eid]); + unset($this->local2GlobalEID[$local]); + //ConsoleAPI::info("Removing Entity {$e->eid} => {$local}"); + return true; } public function __get($name){ @@ -141,15 +266,50 @@ class Player{ return null; } + /** + * @param int $slot inventory slot. -1 - drop + * @param int $id + * @param int $meta + * @param int $count + */ + public function addExpectedSetSlotPacket(int $slot, int $id, int $meta, int $count){ + ConsoleAPI::debug("Adding expected set slot: $slot $id $meta $count"); + $this->expectedSetSlotPackets[++$this->expectedSetSlotIndex]["$slot $id $meta $count"] = $this->server->ticks; + } + + public function isExpectedSetSlot(int $slot, Item $item){ + $index = "$slot {$item->getID()} {$item->getMetadata()} {$item->count}"; + foreach($this->expectedSetSlotPackets as $i => $stuff){ + $a = key($stuff); + + if($index == $a){ + return $i; + } + } + return false; + } + + public function removeExpectedSetSlot(int $index){ + unset($this->expectedSetSlotPackets[$index]); + } + public function getSpawn(){ return $this->spawnPosition; } + public function setBedPosition(?Position $bedPos){ + if($bedPos != null) $this->bedPosition = [$bedPos->level->getName(), (int)$bedPos->x, (int)$bedPos->y, (int)$bedPos->z]; + else $this->bedPosition = null; + $this->data->set("bed-position", $this->bedPosition); + } + + /** + * @param Vector3 $pos position of the top block of the bed * * @return boolean */ - public function sleepOn(Vector3 $pos){ + public function sleepOn(Position $pos){ foreach($this->server->api->player->getAll($this->level) as $p){ if($p->isSleeping instanceof Vector3){ if($pos->distance($p->isSleeping) <= 0.1){ @@ -157,30 +317,31 @@ class Player{ } } } + + $this->setBedPosition($pos); $this->isSleeping = $pos; $this->sleepingTime = 0; - $this->teleport(new Position($pos->x + 0.5, $pos->y + 1, $pos->z + 0.5, $this->level), false, false, false, false); + $meta = $this->level->level->getBlockDamage($pos->x, $pos->y, $pos->z); + $xoff = BedBlock::PLAYER_BED_OFFS_X[$meta & 3]; + $zoff = BedBlock::PLAYER_BED_OFFS_Z[$meta & 3]; + $this->teleport(new Position($pos->x + $xoff, $pos->y + 0.9375, $pos->z + $zoff, $this->level), false, false, false, false); //TODO change player hitbox size after he starts sleeping if($this->entity instanceof Entity){ + $this->entity->forceUpdateMovement = true; + $this->entity->updateMovement(); $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{ - $spawnPoint->x += 0.5; - $spawnPoint->z += 0.5; - } - $this->setSpawn($spawnPoint); return true; } - + public function setSlotCount($cnt){ $this->slotCount = $cnt; $this->data->set("slot-count", $this->slotCount); } - + /** + * @param Vector3 $pos * @param float|boolean $yaw * @param float|boolean $pitch * @param float|boolean $terrain @@ -211,35 +372,13 @@ class Player{ 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; - $pk->y = 128; - $pk->z = -256; - $pk->yaw = 0; - $pk->pitch = 0; - $pk->bodyYaw = 0; - $e->player->dataPacket($pk); - - $pk = new MovePlayerPacket(); - $pk->eid = $e->eid; - $pk->x = -256; - $pk->y = 128; - $pk->z = -256; - $pk->yaw = 0; - $pk->pitch = 0; - $pk->bodyYaw = 0; - $this->dataPacket($pk); - + $this->setInvisibleFor($e->player, true); + $e->player->setInvisibleFor($this, true); }else{ - $pk = new MoveEntityPacket_PosRot(); + $pk = new RemoveEntityPacket(); $pk->eid = $e->eid; - $pk->x = -256; - $pk->y = 128; - $pk->z = -256; - $pk->yaw = 0; - $pk->pitch = 0; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); + $this->removeEntity($e); } } } @@ -254,43 +393,29 @@ class Player{ $this->level->players[$this->CID] = $this; $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()){ - $pk = new MoveEntityPacket_PosRot(); - $pk->eid = $e->eid; - $pk->x = $e->x; - $pk->y = $e->y; - $pk->z = $e->z; - $pk->yaw = $e->yaw; - $pk->pitch = $e->pitch; - $this->dataPacket($pk); + $e->spawn($this); } } } - + $pk = new SetTimePacket; $pk->time = $this->level->getTime(); $this->dataPacket($pk); $terrain = true; 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; - $pk->y = $player->entity->y; - $pk->z = $player->entity->z; - $pk->yaw = $player->entity->yaw; - $pk->pitch = $player->entity->pitch; - $this->dataPacket($pk); + $player->setInvisibleFor($this, false); + $this->setInvisibleFor($player, false); $pk = new PlayerEquipmentPacket; $pk->eid = $this->eid; $pk->item = $this->getSlot($this->slot)->getID(); $pk->meta = $this->getSlot($this->slot)->getMetadata(); $pk->slot = 0; - $player->dataPacket($pk); + $player->entityQueueDataPacket($pk); $this->sendArmor($player); $pk = new PlayerEquipmentPacket; @@ -298,16 +423,16 @@ class Player{ $pk->item = $player->getSlot($player->slot)->getID(); $pk->meta = $player->getSlot($player->slot)->getMetadata(); $pk->slot = 0; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); $player->sendArmor($this); } } - + $resyncpos = new Position($pos->x, $pos->y, $pos->z, $pos->level); }else{ $resyncpos = new Vector3($pos->x, $pos->y, $pos->z); } - + $this->lastCorrect = $resyncpos; $this->entity->fallY = false; $this->entity->fallStart = false; @@ -325,37 +450,58 @@ class Player{ $this->forceMovement = $resyncpos; } } - + $pk = new SetEntityMotionPacket(); - $pk->eid = 0; + $pk->eid = $this->eid; $pk->speedX = 0; $pk->speedY = 0; $pk->speedZ = 0; - $this->dataPacket($pk); - + $this->dataPacketAlwaysRecover($pk); + $pk = new MovePlayerPacket; - $pk->eid = 0; + $pk->eid = $this->eid; $pk->x = $pos->x; $pk->y = $pos->y; $pk->z = $pos->z; $pk->bodyYaw = $yaw; $pk->pitch = $pitch; $pk->yaw = $yaw; - $this->dataPacket($pk); + $this->dataPacketAlwaysRecover($pk); } /** - * - * @return array|bool + * Sends data packet that wont be buffered. Packets are not ordered. + * @param RakNetDataPacket $packet + * @param int $reliability=0 unused + * @param bool $recover=true can the packet be recovered or not. If true the packet will be recovered only once. Otherwise, it won't be recovered at all. + * @returns int[]|false - array with seqNumber of the packet. false if player is not connected. empty array if cancelled by DataPacketSendEvent. */ - public function dataPacket(RakNetDataPacket $packet){ - if($this->connected === false){ - return 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) return []; + if(!$this->convertToLocalEIDPacket($packet)) return false; + + $packet->encode(); + $pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $pk->data[] = $packet; + $pk->seqNumber = $this->counter[0]++; + $pk->sendtime = microtime(true); + if($recover !== false){ + $this->recoveryQueue[$pk->seqNumber] = $pk; } - if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY){ - return; - } + $this->send($pk); + return [$pk->seqNumber]; + } + + /** + * Sends data packet that will be recovered only once. Packet MAY not arrive at all or arrive out of order. + * @param RakNetDataPacket $packet + */ + public function dataPacket(RakNetDataPacket $packet){ + if($this->connected === false) return false; + if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return; + if(!$this->convertToLocalEIDPacket($packet)) return false; if(PacketPool::isPacketExist($packet->pid(), $this->PROTOCOL) != true){ return; @@ -364,27 +510,165 @@ class Player{ $packet->PROTOCOL = $this->PROTOCOL; $packet->encode(); - if($packet->pid() == 163 or $packet->pid() == 164 && $this->PROTOCOL < ProtocolInfo8::CURRENT_PROTOCOL_8){ - return; - } $len = strlen($packet->buffer) + 1; $MTU = $this->MTU - 24; if($len > $MTU){ return $this->directBigRawPacket($packet); } - + if(($this->bufferLen + $len) >= $MTU){ $this->sendBuffer(); } $packet->messageIndex = $this->counter[3]++; - $packet->reliability = 2; + $packet->reliability = RakNetInfo::RELIABILITY_RELIABLE; @$this->buffer->data[] = $packet; $this->bufferLen += 6 + $len; return []; } - public function sendChunkDataPacket(RakNetDataPacket $pk){ + /** + * Sends data packet that will always be recovered. Packets MAY arrive out of order. + * @param RakNetDataPacket $packet + */ + public function dataPacketAlwaysRecover(RakNetDataPacket $packet){ + if($this->connected === false) return false; + if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return false; + if(!$this->convertToLocalEIDPacket($packet)) return false; + + $pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $pk->data[] = $packet; + $pk->seqNumber = $this->counter[0]++; + $pk->sendtime = microtime(true); + + $packet->encode(); + $len = strlen($packet->buffer) + 1; + $MTU = $this->MTU - 24; + if($len > $MTU){ + return $this->sendBigPacketAlwaysRecover($packet); //TODO fix + } + + $packet->messageIndex = $this->counter[3]++; + $packet->reliability = RakNetInfo::RELIABILITY_RELIABLE; + + $this->send($pk); + $this->packetAlwaysRecoverQueue[$pk->seqNumber] = $pk; + return [$pk->seqNumber]; + } + public function sendChatMessagePacket_big(RakNetDataPacket $pk){ + $sendtime = microtime(true); + $size = $this->MTU - 34; + if($size <= 0) return false; + $buffer = str_split($pk->buffer, $size); + $bigCnt = $this->bigCnt; + $this->bigCnt = ($this->bigCnt + 1) % 0x10000; + $cnts = []; + $bufCount = count($buffer); + + $orderIndex = $this->chatMessagesOrderIndex++; + foreach($buffer as $i => $buf){ + $cnts[] = $count = $this->counter[0]++; + + $pk = new UnknownPacket; + $pk->packetID = $pk->pid(); + $pk->reliability = RakNetInfo::RELIABILITY_RELIABLE_ORDERED; + + $pk->orderChannel = Player::CHATMESSAGE_ORDER_CHANNEL; + $pk->orderIndex = $orderIndex; + + $pk->hasSplit = true; + $pk->splitCount = $bufCount; + $pk->splitID = $bigCnt; + $pk->splitIndex = $i; + $pk->buffer = $buf; + $pk->messageIndex = $this->counter[3]++; + + $rk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $rk->data[] = $pk; + $rk->seqNumber = $count; + $rk->sendtime = $sendtime; + $this->packetAlwaysRecoverQueue[$count] = $rk; + $this->send($rk); + } + return $cnts; + } + public function blockQueueDataPacket_big(RakNetDataPacket $pk){ + $sendtime = microtime(true); + $size = $this->MTU - 34; + if($size <= 0) return false; + $buffer = str_split($pk->buffer, $size); + $bigCnt = $this->bigCnt; + $this->bigCnt = ($this->bigCnt + 1) % 0x10000; + $cnts = []; + $bufCount = count($buffer); + + $orderIndex = $this->blockUpdateQueueOrderIndex++; + foreach($buffer as $i => $buf){ + $cnts[] = $count = $this->counter[0]++; + + $pk = new UnknownPacket; + $pk->packetID = $pk->pid(); + $pk->reliability = RakNetInfo::RELIABILITY_RELIABLE_ORDERED; + + $pk->orderChannel = Player::BLOCKUPDATE_ORDER_CHANNEL; + $pk->orderIndex = $orderIndex; + + $pk->hasSplit = true; + $pk->splitCount = $bufCount; + $pk->splitID = $bigCnt; + $pk->splitIndex = $i; + $pk->buffer = $buf; + $pk->messageIndex = $this->counter[3]++; + + $rk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $rk->data[] = $pk; + $rk->seqNumber = $count; + $rk->sendtime = $sendtime; + $this->packetAlwaysRecoverQueue[$count] = $rk; + $this->send($rk); + } + return $cnts; + } + + public function entityQueueDataPacket_big(RakNetDataPacket $pk){ + $sendtime = microtime(true); + $size = $this->MTU - 34; + if($size <= 0) return false; + $buffer = str_split($pk->buffer, $size); + $bigCnt = $this->bigCnt; + $this->bigCnt = ($this->bigCnt + 1) % 0x10000; + $cnts = []; + $bufCount = count($buffer); + + $orderIndex = $this->entityDataQueueOrderIndex++; + foreach($buffer as $i => $buf){ + $cnts[] = $count = $this->counter[0]++; + + $pk = new UnknownPacket; + $pk->packetID = $pk->pid(); + $pk->reliability = RakNetInfo::RELIABILITY_RELIABLE_ORDERED; + + $pk->orderChannel = Player::ENTITY_ORDER_CHANNEL; + $pk->orderIndex = $orderIndex; + + $pk->hasSplit = true; + $pk->splitCount = $bufCount; + $pk->splitID = $bigCnt; + $pk->splitIndex = $i; + $pk->buffer = $buf; + $pk->messageIndex = $this->counter[3]++; + + $rk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $rk->data[] = $pk; + $rk->seqNumber = $count; + $rk->sendtime = $sendtime; + $this->packetAlwaysRecoverQueue[$count] = $rk; + $this->send($rk); + } + return $cnts; + } + + public function sendBigPacketAlwaysRecover(RakNetDataPacket $pk){ if($this->connected === false) return false; if(EventHandler::callEvent(new DataPacketSendEvent($this, $pk)) === BaseEvent::DENY) return; @@ -402,7 +686,7 @@ class Player{ $pk = new UnknownPacket; $pk->packetID = $pk->pid(); - $pk->reliability = 2; + $pk->reliability = RakNetInfo::RELIABILITY_RELIABLE; $pk->hasSplit = true; $pk->splitCount = $bufCount; $pk->splitID = $bigCnt; @@ -439,7 +723,7 @@ class Player{ $pk = new UnknownPacket; $pk->packetID = $packet->pid(); - $pk->reliability = 2; + $pk->reliability = RakNetInfo::RELIABILITY_RELIABLE; $pk->hasSplit = true; $pk->splitCount = $bufCount; $pk->splitID = $bigCnt; @@ -461,7 +745,11 @@ class Player{ if($this->connected === true){ $packet->ip = $this->ip; $packet->port = $this->port; - $this->bandwidthRaw += $this->server->send($packet); + $len = $this->server->send($packet); + if($len > $this->MTU){ + ConsoleAPI::warn("Packet length is more than {$this->iusername}'s mtu!($len > {$this->MTU})"); + } + $this->bandwidthRaw += $len; } } @@ -475,7 +763,6 @@ class Player{ $this->bufferLen = 0; $this->buffer = new RakNetPacket(RakNetInfo::DATA_PACKET_0); $this->buffer->data = []; - $this->nextBuffer = microtime(true) + 0.05; } /** @@ -484,20 +771,30 @@ class Player{ * @return Item */ public function getSlot($slot){ - return $this->inventory[(int) $slot] ?? BlockAPI::getItem(AIR, 0, 0); + return $this->inventory[(int)$slot] ?? BlockAPI::getItem(AIR, 0, 0); } /** * @param integer $slot + * @param Item $item * @param boolean $send * * @return boolean */ - public function setSlot($slot, Item $item, $send = true){ - $this->inventory[(int) $slot] = $item; + public function setSlot($slot, Item $item, $send = true, $addexpected = true){ + $slot = (int) $slot; + $old = $this->getSlot($slot); + + $this->inventory[$slot] = $item; + if($send === true){ - $this->sendInventorySlot((int) $slot); + $this->sendInventorySlot($slot); } + + if($addexpected){ + $this->addExpectedSetSlotPacket($slot, $item->getID(), $item->getMetadata(), $item->count); + } + return true; } @@ -523,12 +820,12 @@ class Player{ $pk = new ContainerSetContentPacket; $pk->windowid = 0x78; //Armor window id $pk->slots = $this->armor; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); }else{ $pk = new PlayerArmorEquipmentPacket; $pk->eid = $this->eid; $pk->slots = $data["slots"]; - $player->dataPacket($pk); + $player->entityQueueDataPacket($pk); } }else{ $this->server->api->dhandle("player.armor", $data); @@ -536,48 +833,33 @@ class Player{ } public $lastOrderX = 0; public $lastOrderZ = 0; - + public function orderChunks(){ if(!($this->entity instanceof Entity) or $this->connected === false){ return false; } - $X = ((int) $this->entity->x) >> 4; - $Z = ((int) $this->entity->z) >> 4; + $X = ((int)$this->entity->x) >> 4; + $Z = ((int)$this->entity->z) >> 4; $this->chunksOrder = []; $this->lastOrderX = $X; $this->lastOrderZ = $Z; - 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){ - $dist = $v->distance(new Vector3($x, $y, $z)); - $d = $x . ":" . $y . ":" . $z; - if(!isset($this->chunksLoaded[$d])){ - $this->chunksOrder[$d] = $dist; - } - } - } - } - }else{ - $v = new Vector2($X, $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){ - $d = $x . ":" . $y . ":" . $z; - if(!isset($this->chunksLoaded[$d])){ - $this->chunksOrder[$d] = $dist; - } + + $v = new Vector2($X, $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){ + $d = $x . ":" . $y . ":" . $z; + if(!isset($this->chunksLoaded[$d])){ + $this->chunksOrder[$d] = $dist; } } } } - + asort($this->chunksOrder); } - + public function loaddAllChunks(){ for($x = 0; $x < 16; $x++){ for($z = 0; $z < 16; $z++){ @@ -585,7 +867,7 @@ class Player{ } } } - + public function useChunk($X, $Z){ $Yndex = 0; for($iY = 0; $iY < 8; ++$iY){ @@ -599,12 +881,13 @@ class Player{ $maxX = (($X << 4) + 15); $minZ = ($Z << 4); $maxZ = (($Z << 4) + 15); - + $pk = new ChunkDataPacket; $pk->chunkX = $X; $pk->chunkZ = $Z; $pk->data = $this->level->getOrderedChunk($X, $Z, $Yndex); - $cnt = $this->sendChunkDataPacket($pk); + $cnt = $this->blockQueueDataPacket($pk); + $this->chunkDataSent["$X:$Z"] = true; $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; @@ -616,12 +899,42 @@ class Player{ } } } - + if($cnt === false){ return false; } } + public $currentChunk = false; + + public function getDestroySpeed($id, $meta){ + return $this->getHeldItem()->getDestroySpeed($id, $meta); + } + + public function canDestroy($id, $meta){ + $mat = StaticBlock::getMaterial($id); + if($mat->alwaysDestroyable) return true; + + return $this->getHeldItem()->canDestroySpecial($id, $meta); + } + + public function onChunkReceived($blockX, $blockZ){ + $minX = $blockX; + $maxX = $blockX + 15; + $minZ = $blockZ; + $maxZ = $blockZ + 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){ + $tile = $this->server->api->tile->getByID($tile["ID"]); + if($tile instanceof Tile){ + $tile->spawn($this); + } + } + } + } + public function getNextChunk($world){ if($this->connected === false or $world != $this->level){ return false; @@ -637,20 +950,8 @@ class Player{ } 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->onChunkReceived($this->lastChunk[0], $this->lastChunk[1]); $this->lastChunk = 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){ - $tile->spawn($this); - } - } - } } $c = key($this->chunksOrder); @@ -682,29 +983,35 @@ class Player{ $pk->chunkX = $X; $pk->chunkZ = $Z; $pk->data = $this->level->getOrderedChunk($X, $Z, $Yndex); - $cnt = $this->sendChunkDataPacket($pk); + $cnt = $this->blockQueueDataPacket($pk); + $this->chunkDataSent["$X:$Z"] = true; + if($cnt === false){ return false; } + $this->chunkCount = []; 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 != ((int)$this->entity->x >> 4) || $this->lastOrderZ != ((int)$this->entity->z >> 4)){ $this->orderChunks(); } $this->server->schedule(MAX_CHUNK_RATE, [$this, "getNextChunk"], $world); } + /** + * @param Vector3 $pos + */ public function setSpawn(Vector3 $pos){ if(!($pos instanceof Position)){ $level = $this->entity->level; }else{ $level = $pos->level; } - $this->spawnPosition = new Position($pos->x, $pos->y, $pos->z, $level); + $this->spawnPosition = new Position($pos->x, $pos->y + 1, $pos->z, $level); $pk = new SetSpawnPositionPacket; $pk->x = (int) $this->spawnPosition->x; $pk->y = (int) $this->spawnPosition->y; @@ -718,21 +1025,13 @@ class Player{ } public function sendInventory(){ - if(($this->gamemode & 0x01) === CREATIVE){ - return; - } - $hotbar = []; - foreach($this->hotbar as $slot){ - $hotbar[] = $slot <= -1 ? -1 : $slot + 9; - } - $pk = new ContainerSetContentPacket; - $pk->windowid = 0; - $pk->slots = $this->inventory; - $pk->hotbar = $hotbar; - $this->dataPacket($pk); + $this->sendingInventoryRequired = true; } /** + * @param $type + * @param $damage + * @param $count * * @return boolean */ @@ -747,7 +1046,7 @@ class Player{ break; }elseif($item->getID() === $type and $item->getMetadata() === $damage){ $add = min($item->getMaxStackSize() - $item->count, $count); - + if($add <= 0){ continue; } @@ -769,7 +1068,7 @@ class Player{ * @return Item */ public function getArmor($slot){ - return $this->armor[(int) $slot] ?? BlockAPI::getItem(AIR, 0, 0); + return $this->armor[(int)$slot] ?? BlockAPI::getItem(AIR, 0, 0); } public function setArmor($slot, Item $armor, $send = true){ @@ -780,18 +1079,28 @@ class Player{ return true; } + public function invisibilityHandler(&$data, $event){ + $target = $data["target"]; + if($target == $this){ + $for = $data["for"]; + if($target->level != $for->level || $target->gamemode == SPECTATOR) { + $data["status"] = true; + } + } + } + /** - * @param mixed $data + * @param mixed &$data * @param string $event */ public function eventHandler($data, $event){ switch($event){ case "entity.link": $pk = new SetEntityLinkPacket(); - $pk->rider = $data["rider"] == $this->entity->eid ? 0 : $data["rider"]; - $pk->riding = $data["riding"] == $this->entity->eid ? 0 : $data["riding"]; + $pk->rider = $data["rider"]; + $pk->riding = $data["riding"]; $pk->type = 0; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); break; case "tile.update": if($data->level === $this->level){ @@ -802,13 +1111,13 @@ class Player{ $pk->windowid = $id; $pk->property = 0; //Smelting $pk->value = floor($data->data["CookTime"]); - $this->dataPacket($pk); + $this->blockQueueDataPacket($pk); $pk = new ContainerSetDataPacket; $pk->windowid = $id; $pk->property = 1; //Fire icon $pk->value = $data->data["BurnTicks"]; - $this->dataPacket($pk); + $this->blockQueueDataPacket($pk); } } } @@ -822,7 +1131,7 @@ class Player{ $pk->windowid = $id; $pk->slot = $data["slot"] + ($data["offset"] ?? 0); $pk->item = $data["slotdata"]; - $this->dataPacket($pk); + $this->blockQueueDataPacket($pk); } } } @@ -836,16 +1145,16 @@ class Player{ $pk = new PlayerArmorEquipmentPacket; $pk->eid = $data["eid"]; $pk->slots = $data["slots"]; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); } break; case "player.pickup": if($data["eid"] === $this->eid){ - $data["eid"] = 0; $pk = new TakeItemEntityPacket; - $pk->eid = 0; + $pk->eid = $data["eid"]; $pk->target = $data["entity"]->eid; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); + if(($this->gamemode & 0x01) === 0x00){ $this->addItem($data["entity"]->itemID, $data["entity"]->meta, $data["entity"]->stack, false); } @@ -864,7 +1173,7 @@ class Player{ $pk = new TakeItemEntityPacket; $pk->eid = $data["eid"]; $pk->target = $data["entity"]->eid; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); } break; case "player.equipment.change": @@ -878,11 +1187,11 @@ class Player{ $pk->item = $data["item"]->getID(); $pk->meta = $data["item"]->getMetadata(); $pk->slot = $data["slot"]; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); break; case "entity.motion": - if($data->eid === $this->eid or $data->level !== $this->level){ + if($data->eid === $this->eid || $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)){ @@ -893,39 +1202,31 @@ class Player{ $pk->speedX = $data->speedX; $pk->speedY = $data->speedY; $pk->speedZ = $data->speedZ; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); break; case "entity.animate": - $pk = new AnimatePacket; $pk->eid = $data["eid"]; $pk->action = $data["action"]; //1 swing arm, - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); break; case "entity.metadata": - if($data->eid === $this->eid){ - $eid = 0; - }else{ - $eid = $data->eid; - } + if(!$this->hasEntity($data)) break; + $eid = $data->eid; if($data->level === $this->level){ $pk = new SetEntityDataPacket; $pk->eid = $eid; $pk->metadata = $data->getMetadata(); - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); } break; case "entity.event": - if($data["entity"]->eid === $this->eid){ - $eid = 0; - }else{ - $eid = $data["entity"]->eid; - } + $eid = $data["entity"]->eid; if($data["entity"]->level === $this->level){ $pk = new EntityEventPacket; $pk->eid = $eid; $pk->event = $data["event"]; - $this->dataPacket($pk); + $this->entityQueueDataPacket($pk); } break; case "server.chat": @@ -945,39 +1246,64 @@ class Player{ } /** + * @param $type + * @param $damage * @param integer $count * @param boolean $send * * @return boolean */ - public function addItem($type, $damage, $count, $send = true){ - + public function addItem($type, $damage, $count, $send = true, $addexpected = true, $drop=true){ + $toadd = BlockAPI::getItem($type, $damage, $count); 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); - + $add = min($toadd->getMaxStackSize() - $item->count, $count); + if($add <= 0){ continue; } $item->count += $add; if($send) $this->sendInventorySlot($s); + if($addexpected) $this->addExpectedSetSlotPacket($s, $item->getID(), $item->getMetadata(), $item->count); $count -= $add; if($count <= 0) return true; } } - $toadd = BlockAPI::getItem($type, $damage, $count); + 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($addexpected) $this->addExpectedSetSlotPacket($s, $type, $damage, $add); $count -= $add; if($count <= 0) return true; } } if($count <= 0) return true; - return false; + if(!$drop) return false; + + while($count > 0){ + $stacksz = min($toadd->getMaxStackSize(), $count); + $count -= $stacksz; + + $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; + $sY = -sin(($this->entity->pitch / 180) * M_PI) * $f1 + 0.1; + $f1 = 0.02; + $f3 = $this->entity->random->nextFloat() * M_PI * 2.0; + $f1 *= $this->entity->random->nextFloat(); + $sX += cos($f3) * $f1; + $sY += ($this->entity->random->nextFloat() - $this->entity->random->nextFloat()) * 0.1; + $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, BlockAPI::getItem($type, $damage, $stacksz), $sX, $sY, $sZ); + if($addexpected) $this->addExpectedSetSlotPacket(-1, $type, $damage, $stacksz); + } + return true; } /** @@ -1009,19 +1335,59 @@ class Player{ $pk = new MessagePacket; $pk->source = ($author instanceof Player) ? $author->username : $author; $pk->message = TextFormat::clean($m); //Colors not implemented :( - $this->dataPacket($pk); + $this->sendChatMessagePacket($pk); } } } - public function makeInvisibleForOnePlayer(Player $player){ - $pk = new RemoveEntityPacket; - $pk->eid = $this->entity->eid; - $player->dataPacket($pk); + + + public function isInvisibleFor(Player $player){ + return isset($this->invisibleFor[$player->CID]); } + + public function setInvisibleFor(Player $player, $b, $send=true){ + $data = [ + "target" => $this, + "for" => $player, + "status" => $b + ]; + + $this->server->handle("player.invisible", $data); + $b = $data["status"]; + if(!($this->entity instanceof Entity)) $send = false; + if($b){ + $this->invisibleFor[$player->CID] = $b; + if($send){ + $pk = new MovePlayerPacket(); + $pk->x = -256; + $pk->y = 128; + $pk->z = -256; + $pk->eid = $this->eid; + $pk->yaw = 0; + $pk->pitch = 0; + $pk->headYaw = 0; + $player->entityQueueDataPacket($pk); + } + }else{ + unset($this->invisibleFor[$player->CID]); + if($send){ + $pk = new MovePlayerPacket(); + $pk->eid = $this->entity->eid; + $pk->x = $this->entity->x; + $pk->y = $this->entity->y; + $pk->z = $this->entity->z; + $pk->yaw = $this->entity->yaw; + $pk->pitch = $this->entity->pitch; + $pk->bodyYaw = $this->entity->headYaw; + $player->entityQueueDataPacket($pk); + } + } + } + public function makeInvisibleForAllPlayers(){ - $pk = new RemoveEntityPacket; - $pk->eid = $this->entity->eid; - $this->server->api->player->broadcastPacket($this->server->api->player->getAll($this->level), $pk); + foreach($this->server->api->player->getA as $player){ + if($player->CID != $this->CID) $this->setInvisibleFor($player, true); + } } public function getGamemode(){ switch($this->gamemode){ @@ -1035,7 +1401,7 @@ class Player{ return "view"; } } - + public function checkSpawnPosition(){ if($this->server->api->dhandle("player.checkspawnpos", ["player" => $this]) === false) return; $level = $this->spawnPosition->level; @@ -1044,20 +1410,20 @@ class Player{ $level = $this->server->api->level->getDefault(); $this->spawnPosition = $level->getSpawn(); }else{ - $x0 = floor($this->spawnPosition->x - $this->entity->width / 2); - $x1 = floor($this->spawnPosition->x + $this->entity->width / 2 + 1); + $x0 = floor($this->spawnPosition->x - $this->entity->width/2); + $x1 = floor($this->spawnPosition->x + $this->entity->width/2 + 1); $y0 = floor($this->spawnPosition->y); $y1 = floor($this->spawnPosition->y + $this->entity->height + 1); - $z0 = floor($this->spawnPosition->z - $this->entity->width / 2); - $z1 = floor($this->spawnPosition->z + $this->entity->width / 2 + 1); - + $z0 = floor($this->spawnPosition->z - $this->entity->width/2); + $z1 = floor($this->spawnPosition->z + $this->entity->width/2 + 1); + for($x = $x0; $x < $x1; ++$x) { 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)){ $blockBounds = StaticBlock::$prealloc[$bid]::getCollisionBoundingBoxes($this->entity->level, $x, $y, $z, $this->entity); - + foreach($blockBounds as $blockBound){ if($this->entity->boundingBox->intersectsWith($blockBound)){ $this->sendChat("Your spawn positon is obstructed."); @@ -1073,7 +1439,7 @@ class Player{ $this->spawnPosition = $this->server->api->level->getDefault()->getSpawn(); } } - + public function setGamemode($gm){ if($gm < 0 or $gm > 3 or $this->gamemode === $gm){ return false; @@ -1083,13 +1449,14 @@ class Player{ return false; } + $this->save(); $inv = &$this->inventory; if($gm === VIEW){ $this->armor = []; $this->sendArmor(); } if(($this->gamemode & 0x01) === ($gm & 0x01)){ - if(($gm & 0x01) === 0x01 and ($gm & 0x02) === 0x02){ + if(($gm & 0x01) === 0x01 && ($gm & 0x02) === 0x02){ //gm == VIEW $inv = []; foreach(BlockAPI::$creative as $item){ $inv[] = BlockAPI::getItem(0, 0, 1); @@ -1101,26 +1468,36 @@ class Player{ } } $this->gamemode = $gm; + $this->saveInventory = ($this->gamemode & 1) == SURVIVAL; $this->sendChat("Your gamemode has been changed to " . $this->getGamemode() . ".\n"); }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]; + $this->hotbar = $gm == CREATIVE ? BlockAPI::$creativeHotbarSlots : [0, 1, 2, 3, 4, 5, 6, 7, 8]; $this->lastCorrect = $this->entity->copy(); $this->blocked = true; + if(($this->gamemode & 1) != ($gm & 1)){ + $this->saveInventory = false; + } $this->gamemode = $gm; $this->sendChat("Your gamemode has been changed to " . $this->getGamemode() . ", you've to do a forced reconnect.\n"); + $this->gmKickSoon = true; $this->server->schedule(30, [$this, "close"], "gamemode change", false, true); //Forces a kick - } + } + if($this->gamemode === SPECTATOR){ - $this->makeInvisibleForAllPlayers(); + foreach($this->server->api->player->getAll() as $player){ + if($player->CID != $this->CID) $this->setInvisibleFor($player, true); + } } if($this->gamemode === CREATIVE){ - $this->server->api->player->spawnToAllPlayers($this); + foreach($this->server->api->player->getAll() as $player){ + if($player->CID != $this->CID) $this->setInvisibleFor($player, false); + } } - + $this->inventory = $inv; $this->sendSettings(); $this->sendInventory(); @@ -1147,10 +1524,10 @@ class Player{ if($nametags !== false){ $flags |= 0x20; //Show Nametags } - + //$flags |= 0x2; //pvp //$flags |= 0x4; //pve - + $pk = new AdventureSettingsPacket; $pk->flags = $flags; $this->dataPacket($pk); @@ -1204,10 +1581,20 @@ class Player{ } public function handlePacketQueues(){ + if($this->server->ticks % 40 == 0){ //2s + $this->sendPing(); + } + if($this->connected === false){ return false; } $time = microtime(true); + + if($this->loggedIn === false && ($time - $this->connectionStartedAt) >= 20){ + $this->close("timeout"); + return false; + } + if($time > $this->timeout){ $this->close("timeout"); return false; @@ -1231,6 +1618,35 @@ class Player{ $this->ackQueue = []; } + if($this->sendingInventoryRequired){ + + $pk = new ContainerSetContentPacket; + $pk->windowid = 0; + if($this->gmKickSoon){ + $pk->slots = []; + $hotbar = []; + }else if($this->gamemode !== CREATIVE){ + $hotbar = []; + foreach($this->hotbar as $slot){ + $hotbar[] = $slot <= -1 ? -1 : $slot + 9; + } + $pk->slots = $this->inventory; + }else{ + $pk->slots = []; + for($i = 0; $i < 9; ++$i){ + if(!isset($this->hotbar[$i])) [$id, $meta] = [0, 0]; + else [$id, $meta] = BlockAPI::$creative[$this->hotbar[$i]] ?? [0, 0]; + $pk->slots[$i] = BlockAPI::getItem($id, $meta, 1); + } + $hotbar = [9, 10, 11, 12, 13, 14, 15, 16, 17]; + + } + $pk->hotbar = $hotbar; + $this->dataPacket($pk); + + $this->sendingInventoryRequired = false; + } + if(($receiveCnt = count($this->receiveQueue)) > 0){ ksort($this->receiveQueue); foreach($this->receiveQueue as $count => $packets){ @@ -1265,10 +1681,26 @@ class Player{ } } + if($this->chatMessagesQueueLength > 0 && $this->server->ticks % 5 == 0){ //send 4 times/second + $this->sendChatBuffer(); + } + if($this->bufferLen > 0){ $this->sendBuffer(); } + if($this->blockUpdateQueueLength > 0){ + $this->sendBlockUpdateQueue(); + } + + if($this->entityDataQueueLength > 0){ + $this->sendEntityDataQueue(); + } + + if($this->entityMovementQueueLength > 0){ + $this->sendEntityMovementUpdateQueue(); + } + $limit = $time - 5; //max lag foreach($this->recoveryQueue as $count => $data){ if($data->sendtime > $limit){ @@ -1279,13 +1711,16 @@ class Player{ } foreach($this->packetAlwaysRecoverQueue as $cnt => $data){ - if($time - $data->sendtime >= 5){ + $maxDelay = (isset($this->chunkCount[$cnt])) ? 1 : 5; + if($time - $data->sendtime >= $maxDelay){ $this->resendQueue[$cnt] = $data; } } if(($resendCnt = count($this->resendQueue)) > 0){ + $limit = 25; foreach($this->resendQueue as $count => $data){ + if(!--$limit) break; unset($this->resendQueue[$count]); $this->packetStats[1]++; $this->lag[] = $time - $data->sendtime; @@ -1294,9 +1729,24 @@ class Player{ } } } + + public function sendChatBuffer(){ + if($this->chatMessagesQueueLength > 0 && $this->chatMessagesQueue instanceof RakNetPacket){ + $this->chatMessagesQueue->seqNumber = $this->counter[0]++; + $this->packetAlwaysRecoverQueue[$this->chatMessagesQueue->seqNumber] = $this->chatMessagesQueue; + $this->chatMessagesQueue->sendtime = microtime(true); + $this->send($this->chatMessagesQueue); + } + + $this->chatMessagesQueueLength = 0; + $this->chatMessagesQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $this->chatMessagesQueue->data = []; + } + public function sendEntityMovementUpdateQueue(){ if($this->entityMovementQueueLength > 0 && $this->entityMovementQueue instanceof RakNetPacket){ $this->entityMovementQueue->seqNumber = $this->counter[0]++; + $this->entityMovementQueue->sendtime = microtime(true); $this->send($this->entityMovementQueue); } $this->entityMovementQueueLength = 0; @@ -1304,10 +1754,22 @@ class Player{ $this->entityMovementQueue->data = []; } + public function sendEntityDataQueue(){ + if($this->entityDataQueueLength > 0 && $this->entityDataQueue instanceof RakNetPacket){ + $this->entityDataQueue->seqNumber = $this->counter[0]++; + $this->packetAlwaysRecoverQueue[$this->entityDataQueue->seqNumber] = $this->entityDataQueue; + $this->entityDataQueue->sendtime = microtime(true); + $this->send($this->entityDataQueue); + } + $this->entityDataQueueLength = 0; + $this->entityDataQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $this->entityDataQueue->data = []; + } + 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->packetAlwaysRecoverQueue[$this->blockUpdateQueue->seqNumber] = $this->blockUpdateQueue; $this->blockUpdateQueue->sendtime = microtime(true); $this->send($this->blockUpdateQueue); } @@ -1316,35 +1778,116 @@ class Player{ $this->blockUpdateQueue->data = []; } + /** + * Sends packet in block order channel. Packets are always delivered and ordered. + * Used for sending tileentity data, chunk data, updateblock packets. + * @param RakNetPacket $pk + */ + public function blockQueueDataPacket(RakNetDataPacket $pk){ + if($this->connected === false) return false; + if(EventHandler::callEvent(new DataPacketSendEvent($this, $pk)) === BaseEvent::DENY) return; + if(!$this->convertToLocalEIDPacket($pk)) return false; + + $pk->encode(); + + $len = 1 + strlen($pk->buffer); + $MTU = $this->MTU - 24; + if($len > $MTU) return $this->blockQueueDataPacket_big($pk); + if(($this->blockUpdateQueueLength + $len+10) >= $MTU){ + $this->sendBlockUpdateQueue(); + } + + $pk->messageIndex = $this->counter[3]++; + $pk->reliability = RakNetInfo::RELIABILITY_RELIABLE_ORDERED; + $pk->orderChannel = Player::BLOCKUPDATE_ORDER_CHANNEL; + $pk->orderIndex = $this->blockUpdateQueueOrderIndex++; + @$this->blockUpdateQueue->data[] = $pk; + $this->blockUpdateQueueLength += 10 + $len; + } + + public function convertToGlobalEIDPacket(RakNetDataPacket $pk){ + if(!$pk->eidsToGlobal($this)){ + //ConsoleAPI::warn("Failed to convert eids to global in {$pk->pid()}! (Player: {$this->ip}:{$this->port}). Stacktrace: "); + //foreach(explode("\n", (new Exception())->getTraceAsString()) as $s) ConsoleAPI::warn($s); + return false; + } + return true; + } + public function convertToLocalEIDPacket(RakNetDataPacket $pk){ + if(!$pk->eidsToLocal($this)){ + //ConsoleAPI::debug("Failed to convert eids to local in {$pk->pid()}! (Player: {$this->ip}:{$this->port}). Stacktrace: "); + //foreach(explode("\n", (new Exception())->getTraceAsString()) as $s) ConsoleAPI::debug($s); + return false; + } + return true; + } + + /** + * Sends a packet in entity order channel. Packets are always delivered and ordered. + * @param RakNetDataPacket $pk + * @return void|boolean|boolean|number[] + */ + public function entityQueueDataPacket(RakNetDataPacket $pk){ + if($this->connected === false) return false; + if(EventHandler::callEvent(new DataPacketSendEvent($this, $pk)) === BaseEvent::DENY) return; + if(!$this->convertToLocalEIDPacket($pk)) return false; + $pk->encode(); + + $len = 1 + strlen($pk->buffer); + $MTU = $this->MTU - 24; + if($len > $MTU) return $this->entityQueueDataPacket_big($pk); + + if(($this->entityDataQueueLength + $len+10) >= $MTU){ + $this->sendEntityDataQueue(); + } + + $pk->messageIndex = $this->counter[3]++; + + $pk->reliability = RakNetInfo::RELIABILITY_RELIABLE_ORDERED; + $pk->orderChannel = Player::ENTITY_ORDER_CHANNEL; + $pk->orderIndex = $this->entityDataQueueOrderIndex++; + @$this->entityDataQueue->data[] = $pk; + $this->entityDataQueueLength += 10 + $len; + } + + /** + * Adds block update into queue. Does nothing if chunk wasnt loaded. + * @param int $x + * @param int $y + * @param int $z + * @param int $id + * @param int $meta + * @return boolean + */ public function addBlockUpdateIntoQueue($x, $y, $z, $id, $meta){ + $xC = $x >> 4; + $zC = $z >> 4; + if(!isset($this->chunkDataSent["$xC:$zC"])){ + ConsoleAPI::debug("Ignoring block update $x $y $z $id $meta: chunk data was not sent."); + return false; //dont send updateblockpacket as it will be buffered and updated only after all chunks will load + } $packet = new UpdateBlockPacket(); $packet->x = $x; $packet->y = $y; $packet->z = $z; $packet->block = $id; $packet->meta = $meta; - $packet->PROTOCOL = $this->PROTOCOL; - $packet->encode(); - - $len = 1 + strlen($packet->buffer); - $MTU = $this->MTU - 24; - - if(($this->blockUpdateQueueLength + $len) >= $MTU){ - $this->sendBlockUpdateQueue(); - } - - $packet->messageIndex = $this->counter[3]++; - $packet->reliability = 2; - @$this->blockUpdateQueue->data[] = $packet; - $this->blockUpdateQueueLength += 6 + $len; + $this->blockQueueDataPacket($packet); } - + public function addEntityMovementUpdateToQueue(Entity $e){ $len = 0; $packets = 0; $motionSent = false; $moveSent = false; $headSent = false; + $localeid = $this->global2localEID[$e->eid] ?? false; + if($localeid === false){ + ConsoleAPI::warn("Attempt to convert global eid to local failed! (Global: {$e->eid}, Player: {$this->ip}:{$this->port}). Stacktrace: "); + foreach(explode("\n", (new Exception())->getTraceAsString()) as $s) ConsoleAPI::warn($s); + return false; + } + $svdYSpeed = $e->speedY; if($e->modifySpeedY){ $e->speedY = $e->modifedSpeedY; @@ -1352,13 +1895,13 @@ class Player{ 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->eid = $localeid; $motion->speedX = $e->speedX; $motion->speedY = $e->speedY; $motion->speedZ = $e->speedZ; $motion->PROTOCOL = $this->PROTOCOL; $motion->encode(); - $len += 1 + strlen($motion->buffer); + $len += 10 + strlen($motion->buffer); ++$packets; $motionSent = true; } @@ -1367,11 +1910,11 @@ class Player{ $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){ $move = new MovePlayerPacket(); - $move->eid = $e->eid; + $move->eid = $localeid; $move->x = $e->x; $move->y = $e->y + $e->yOffset; $move->z = $e->z; @@ -1382,7 +1925,7 @@ class Player{ $move->encode(); }else{ $move = new MoveEntityPacket_PosRot(); - $move->eid = $e->eid; + $move->eid = $localeid; $move->x = $e->x; $move->y = $e->y + $e->yOffset; $move->z = $e->z; @@ -1391,18 +1934,18 @@ class Player{ $move->PROTOCOL = $this->PROTOCOL; $move->encode(); } - - $len += strlen($move->buffer) + 1; + + $len += strlen($move->buffer) + 10; ++$packets; $moveSent = true; }elseif($this->PROTOCOL > ProtocolInfo12::CURRENT_PROTOCOL_12 && $e->headYaw != $e->lastHeadYaw){ $headyaw = new RotateHeadPacket(); - $headyaw->eid = $e->eid; + $headyaw->eid = $localeid; $headyaw->yaw = $e->headYaw; $headyaw->PROTOCOL = $this->PROTOCOL; $headyaw->encode(); - $len += strlen($headyaw->buffer) + 1; + $len += strlen($headyaw->buffer) + 10; ++$packets; $headSent = true; } @@ -1414,23 +1957,32 @@ class Player{ } if($motionSent){ $motion->messageIndex = 0; //force 0 cuz reliability 0 - $motion->reliability = 0; + $motion->reliability = RakNetInfo::RELIABILITY_UNRELIABLE_SEQUENCED; + $motion->orderIndex = $this->entityDataQueueOrderIndex; + $motion->orderChannel = self::ENTITY_ORDER_CHANNEL; + $motion->seqIndex = $this->entityMovementQueueSeqIndex++; $this->entityMovementQueue->data[] = $motion; } if($moveSent){ $move->messageIndex = 0; - $move->reliability = 0; + $move->reliability = RakNetInfo::RELIABILITY_UNRELIABLE_SEQUENCED; + $move->orderIndex = $this->entityDataQueueOrderIndex; + $move->orderChannel = self::ENTITY_ORDER_CHANNEL; + $move->seqIndex = $this->entityMovementQueueSeqIndex++; $this->entityMovementQueue->data[] = $move; } if($headSent){ $headyaw->messageIndex = 0; - $headyaw->reliability = 0; + $headyaw->reliability = RakNetInfo::RELIABILITY_UNRELIABLE_SEQUENCED; + $headyaw->orderIndex = $this->entityDataQueueOrderIndex; + $headyaw->orderChannel = self::ENTITY_ORDER_CHANNEL; + $headyaw->seqIndex = $this->entityMovementQueueSeqIndex++; $this->entityMovementQueue->data[] = $headyaw; } - - $this->entityMovementQueueLength += 6 * $packets + $len; + + $this->entityMovementQueueLength += $len; } - + /** * @param string $reason Reason for closing connection * @param boolean $msg Set to false to silently disconnect player. No broadcast. @@ -1461,6 +2013,11 @@ class Player{ if($msg === true and $this->username != "" and $this->spawned !== false){ $this->server->api->chat->broadcast($this->username . " left the game: " . $reason); } + + foreach($this->server->api->player->getAll() as $player){ + $player->setInvisibleFor($this, false); + } + $this->spawned = false; console("[INFO] " . FORMAT_AQUA . $this->username . FORMAT_RESET . "[/" . $this->ip . ":" . $this->port . "] logged out due to " . $reason); $this->windows = []; @@ -1471,6 +2028,7 @@ class Player{ $this->chunkCount = []; $this->craftingItems = []; $this->received = []; + unset($this->server->api->chat->lastTells[$this->iusername]); //$this->entity->close(); } } @@ -1492,24 +2050,31 @@ class Player{ "y" => $this->spawnPosition->y, "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)){ - $inv[$slot] = [$item->getID(), $item->getMetadata(), $item->count]; + + if($this->saveInventory){ + $inv = []; + 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]; + } } } + $this->data->set("inventory", $inv); } - $this->data->set("inventory", $inv); + $this->data->set("hotbar", $this->hotbar); - $armor = []; - foreach($this->armor as $slot => $item){ - if($item instanceof Item){ - $armor[$slot] = [$item->getID(), $item->getMetadata()]; + if($this->saveInventory){ + $armor = []; + foreach($this->armor as $slot => $item){ + if($item instanceof Item){ + $armor[$slot] = [$item->getID(), $item->getMetadata()]; + } } + $this->data->set("armor", $armor); } - $this->data->set("armor", $armor); + if($this->entity instanceof Entity){ $this->data->set("health", $this->entity->getHealth()); } @@ -1517,36 +2082,45 @@ class Player{ } } - public function directDataPacket(RakNetDataPacket $packet, $reliability = 0, $recover = true){ - if($this->connected === false){ - return false; - } + public function sendChatMessagePacket(RakNetDataPacket $packet){ + if($this->connected === false) return false; + if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY) return false; + if(!$this->convertToLocalEIDPacket($packet)) return false; - if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY){ - return []; - } - - $packet->PROTOCOL = $this->PROTOCOL; $packet->encode(); - $pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); - $pk->data[] = $packet; - $pk->seqNumber = $this->counter[0]++; - $pk->sendtime = microtime(true); - if($recover !== false){ - $this->recoveryQueue[$pk->seqNumber] = $pk; - } + $len = strlen($packet->buffer) + 1; + $MTU = $this->MTU - 24; + if($len > $MTU) return $this->sendChatMessagePacket_big($packet); - $this->send($pk); - return [$pk->seqNumber]; + if(($this->chatMessagesQueueLength + $len+10) >= $MTU) $this->sendChatBuffer(); + + $packet->reliability = RakNetInfo::RELIABILITY_RELIABLE_ORDERED; + $packet->messageIndex = $this->counter[3]++; + $packet->orderChannel = Player::CHATMESSAGE_ORDER_CHANNEL; + $packet->orderIndex = $this->chatMessagesOrderIndex++; + $this->chatMessagesQueue->data[] = $packet; + $this->chatMessagesQueueLength += 10+$len; //reliability(1)+lenbits(2)+messageindex(3)+orderChannel(1)+orderIndex(3) = 10 + return true; } - 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){ $this->entity->setHealth(min(20, $this->entity->health + 1), "regeneration"); } } + + $cnt = 0; + foreach($this->expectedSetSlotPackets as $s => $stuff){ + $b = current($stuff); + if(($this->server->ticks - $b) > 10*20){ //keep slot as expected for 10 seconds, no idea how good will it work + ++$cnt; + $this->removeExpectedSetSlot($s); + } + } + if($cnt > 0) ConsoleAPI::debug("$cnt slots were removed from {$this->iusername}'s expected queue due to timeout"); } public function sendPing() { @@ -1559,13 +2133,13 @@ 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(!$this->convertToGlobalEIDPacket($packet)) return; - if (EventHandler::callEvent(new DataPacketReceiveEvent($this, $packet)) === BaseEvent::DENY) { + if(EventHandler::callEvent(new DataPacketReceiveEvent($this, $packet)) === BaseEvent::DENY){ return; } @@ -1751,7 +2325,7 @@ class Player{ 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; @@ -1765,7 +2339,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; @@ -1775,28 +2349,28 @@ 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]; - $this->PROTOCOL = $packet->PROTOCOL; - if (count($this->server->clients) > $this->server->maxClients and !$this->server->api->ban->isOp($this->iusername)) { + $this->PROTOCOL = $packet->PROTOCOL; + 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); @@ -1804,74 +2378,82 @@ 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 === "" || isset(Player::$blacklistedUsernames[$this->iusername]) || 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) { - $u = $this->server->clients[$this->CID]; - $u->close("this player already in game"); + if($u !== false){ + $this->close("this player already in game"); + return; } $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) { - $inv = []; - if (($this->gamemode & 0x02) === 0x02) { - foreach (BlockAPI::$creative as $item) { + + $inv = []; + if(!$this->data->exists("inventory") || ($this->gamemode & 0x01) === 0x01){ + if(($this->gamemode & 0x01) === 0x01){ + 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]; } } } - $this->data->set("inventory", $inv); + }else{ + $inv = []; + foreach($this->data->get("inventory") as $slot => $item){ + $inv[$slot] = [$item[0], $item[1], $item[2]]; + } } + $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($inv 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) { - $this->armor[$slot] = BlockAPI::getItem($item[0], $item[1], $item[0] === 0 ? 0 : 1); + if(($this->gamemode & 0x01) == 0){ + foreach($this->data->get("armor") as $slot => $item){ + $this->armor[$slot] = BlockAPI::getItem($item[0], $item[1], $item[0] === 0 ? 0 : 1); + } } $this->data->set("lastIP", $this->ip); @@ -1879,47 +2461,63 @@ class Player{ $this->server->api->player->saveOffline($this->data); + $pk = new LoginStatusPacket; $pk->status = 0; $this->dataPacket($pk); - $pk = new StartGamePacket; - $pk->seed = $this->level->getSeed(); - $pk->x = $this->data->get("position")["x"]; - $pk->y = ceil($this->data->get("position")["y"]); - $pk->z = $this->data->get("position")["z"]; - $pk->generator = 0; - $pk->gamemode = $this->gamemode & 0x01; - $pk->eid = 0; - $this->dataPacket($pk); - - if (($this->gamemode & 0x01) === 0x01) { - - $this->slot = 0; - $this->hotbar = []; - } elseif ($this->data->exists("hotbar")) { + if($this->data->exists("hotbar")){ $this->hotbar = $this->data->get("hotbar"); - $this->slot = $this->hotbar[0]; - } else { - $this->slot = 0; - $this->hotbar = [0, 1, 2, 3, 4, 5, 6, 7, 8]; + }else{ + if(($this->gamemode & 0x01) === 0x01) $this->hotbar = BlockAPI::$creativeHotbarSlots; + else $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; + + $this->slot = $this->hotbar[0]; + + for($i = 0; $i < count($this->hotbar); ++$i){ + if($this->hotbar[$i] > (($this->gamemode & 1) == 0 ? 36 : count(BlockAPI::$creative))) $this->hotbar[$i] = -1; + 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); } + if($this->data->exists("bed-position")){ + $this->bedPosition = $this->data->get("bed-position"); + }else{ + $this->setBedPosition(null); + } + $this->entity = $this->server->api->entity->add($this->level, ENTITY_PLAYER, 0, ["player" => $this]); $this->eid = $this->entity->eid; $this->server->query("UPDATE players SET EID = " . $this->eid . " WHERE CID = " . $this->CID . ";"); + + $this->addEntity($this->entity); + + $pk = new StartGamePacket; + $pk->seed = $this->level->getSeed(); + $pk->x = $this->data->get("position")["x"]; + $pk->y = ceil($this->data->get("position")["y"])+1; + $pk->z = $this->data->get("position")["z"]; + $pk->generator = 0; + $pk->gamemode = $this->gamemode & 0x01; + $pk->eid = $this->entity->eid; + $this->entity->x = $pk->x; - $this->entity->y = $pk->y; + $this->entity->y = $pk->y-0.9; $this->entity->z = $pk->z; + $this->dataPacket($pk); + + //should cache it for client(unless the queue was full and startgamepacket was sent without settime + //and client receives time before startgame - TODO maybe make it ordered?) + $pk = new SetTimePacket; + $pk->time = $this->level->getTime(); + $pk->started = !$this->level->isTimeStopped(); + $this->dataPacket($pk); + 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); @@ -1943,29 +2541,32 @@ class Player{ $this->evid[] = $this->server->event("player.pickup", [$this, "eventHandler"]); $this->evid[] = $this->server->event("tile.container.slot", [$this, "eventHandler"]); $this->evid[] = $this->server->event("tile.update", [$this, "eventHandler"]); + $this->evid[] = $this->server->event("player.invisible", [$this, "invisibilityHandler"]); $this->lastMeasure = microtime(true); $this->server->schedule(50, [$this, "measureLag"], [], true); + - $pk = new SetTimePacket; - $pk->time = $this->level->getTime(); - $pk->started = !$this->level->isTimeStopped(); - $this->dataPacket($pk); - - 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) . ")"); + 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) . ") MTU: {$this->MTU}"); 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; } + $pk = new SetTimePacket; + $pk->time = $this->level->getTime(); + $pk->started = !$this->level->isTimeStopped(); + $this->dataPacketAlwaysRecover($pk); + $pos = new Position($this->entity->x, $this->entity->y, $this->entity->z, $this->level); $pData = $this->data->get("position"); - $this->entity->setHealth($this->data->get("health"), "spawn", true, false); + $this->entity->setHealth($this->data->get("health"), "spawn", true, allowHarm: false); $this->spawned = true; $this->teleport($pos, $pData["yaw"] ?? false, $pData["pitch"] ?? false, true, true); $this->server->api->player->spawnAllPlayers($this); @@ -1976,9 +2577,9 @@ class Player{ //$this->server->schedule(5, [$this->entity, "update"], [], true); //$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"); + $array = explode("@n", (string)$this->server->motd); + foreach($array as $msg){ + $this->sendChat($msg."\n"); } $this->sendInventory(); @@ -1994,48 +2595,49 @@ 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) && $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; @@ -2044,78 +2646,85 @@ 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) { + }else if($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->gamemode == VIEW && $packet->item != AIR){ + $this->sendInventory(); + break; + } + + 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; } } - - if (Player::$experimentalHotbar && $has) { + + if(Player::$experimentalHotbar && $has) { $this->slot = $packet->slot; $this->curHotbarIndex = $packetSlotPos; } - if (!$has) { - if (Player::$experimentalHotbar) { + 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(); @@ -2127,31 +2736,17 @@ 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); - - $pk = new UpdateBlockPacket; - $pk->x = $target->x; - $pk->y = $target->y; - $pk->z = $target->z; - $pk->block = $target->getID(); - $pk->meta = $target->getMetadata(); - $this->dataPacket($pk); - - $pk = new UpdateBlockPacket; - $pk->x = $block->x; - $pk->y = $block->y; - $pk->z = $block->z; - $pk->block = $block->getID(); - $pk->meta = $block->getMetadata(); - $this->dataPacket($pk); + $this->addBlockUpdateIntoQueue($target->x, $target->y, $target->z, $target->getID(), $target->getMetadata()); + $this->addBlockUpdateIntoQueue($block->x, $block->y, $block->z, $block->getID(), $block->getMetadata()); break; } $this->craftingItems = []; @@ -2173,12 +2768,19 @@ class Player{ $data["posX"] = $packet->posX; $data["posY"] = $packet->posY; $data["posZ"] = $packet->posZ; - + //nc: check item desync $heldItem = $this->getHeldItem(); - if($heldItem->getID() != $packet->item || $heldItem->getMetadata() != $packet->meta){ - ConsoleAPI::warn("{$this->username}'s heldItem doesnt match on clientside and serverside when using item. Resending inventory."); + $pmeta = ($packet->meta & 0xff); + $hmeta = ($heldItem->getMetadata() & 0xff); //in 0.8.1 useitempacket uses byte for meta + + if($heldItem->getID() != $packet->item || $hmeta != $pmeta){ $this->sendInventory(); + if($heldItem->getID() == $packet->item && $heldItem->getMaxDurability() != false){ //id matches, meta is used as durability -> allow to perform whatever action the player wants to do + goto allow_use_item; + } + ConsoleAPI::warn("{$this->username}'s heldItem doesnt match on clientside({$packet->item} {$pmeta}) and serverside({$heldItem->getID()} {$hmeta}) when using item. Resending inventory."); + if($packet->face >= 0 && $packet->face <= 5){ $target = $this->level->getBlock($blockVector); $block = $target->getSide($packet->face); @@ -2187,6 +2789,7 @@ class Player{ } break; } + allow_use_item: if($packet->face >= 0 and $packet->face <= 5){ //Use Block, place if($this->entity->inAction === true){ @@ -2195,48 +2798,35 @@ class Player{ $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; } $target = $this->level->getBlock($blockVector); $block = $target->getSide($packet->face); - $pk = new UpdateBlockPacket; - $pk->x = $target->x; - $pk->y = $target->y; - $pk->z = $target->z; - $pk->block = $target->getID(); - $pk->meta = $target->getMetadata(); - $this->dataPacket($pk); - - $pk = new UpdateBlockPacket; - $pk->x = $block->x; - $pk->y = $block->y; - $pk->z = $block->z; - $pk->block = $block->getID(); - $pk->meta = $block->getMetadata(); - $this->dataPacket($pk); + $this->addBlockUpdateIntoQueue($target->x, $target->y, $target->z, $target->getID(), $target->getMetadata()); + $this->addBlockUpdateIntoQueue($block->x, $block->y, $block->z, $block->getID(), $block->getMetadata()); 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) { + + $d = sqrt($x*$x + $y*$y + $z*$z); + + if($d >= 0.0001){ $shootX = $x / $d; $shootY = $y / $d; $shootZ = $z / $d; - + $data = [ "x" => $this->entity->x, "y" => $this->entity->y + $this->entity->getEyeHeight(), @@ -2248,26 +2838,25 @@ class Player{ "shootY" => $shootY, "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); + + 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; - //$this->sendInventory(); } } - + $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); @@ -2344,7 +2933,7 @@ 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; @@ -2354,20 +2943,20 @@ class Player{ 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, ]); - + $d = [ "x" => $this->entity->x, "y" => $this->entity->y + 1.6, @@ -2391,19 +2980,15 @@ class Player{ * args: xvel, yvel, zvel, (power+power)*1.5, 1.0 */ $e->critical = ($power == 1); - $e->shoot($e->speedX, $e->speedY, $e->speedZ, ($power + $power) * 1.5, 1.0); + $e->shoot($e->speedX, $e->speedY, $e->speedZ, ($power+$power) * 1.5, 1.0); $this->server->api->entity->spawnToAll($e); - if (($this->gamemode & 0x01) == 0x0) { - $bow = $this->getSlot($this->slot); - if (++$bow->meta >= $bow->getMaxDurability()) { - $this->inventory[$this->slot] = BlockAPI::getItem(AIR, 0, 0); - } - $this->removeItem(ARROW, 0, 1, false); - $this->sendInventory(); + if(($this->gamemode & 0x01) == 0x0) { + $this->getHeldItem()->hurtAndBreak(1, $this); + $this->removeItem(ARROW, 0, 1, send: true); } } } - } else { //inv desynced, resend + }else{ //inv desynced, resend $this->sendInventory(); } } @@ -2418,16 +3003,9 @@ 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) { - $target = $this->level->getBlock($blockVector); - - $pk = new UpdateBlockPacket; - $pk->x = $target->x; - $pk->y = $target->y; - $pk->z = $target->z; - $pk->block = $target->getID(); - $pk->meta = $target->getMetadata(); - $this->dataPacket($pk); + if($this->spawned === false or $this->blocked === true or $this->entity->distance($blockVector) > 8){ + [$id, $meta] = $this->level->level->getBlock($blockVector->x, $blockVector->y, $blockVector->z); + $this->addBlockUpdateIntoQueue($blockVector->x, $blockVector->y, $blockVector->z, $id, $meta); break; } $this->craftingItems = []; @@ -2436,47 +3014,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 = []; $this->craftingType = CraftingRecipes::TYPE_INVENTORY; - $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) { - $this->addItem($slot->getID(), $slot->getMetadata(), 1, false); + + if($slot->getID() !== AIR && $s->getID() === AIR){ + $this->addItem($slot->getID(), $slot->getMetadata(), $slot->count, 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 && $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; @@ -2488,36 +3065,53 @@ class Player{ $this->toCraft = []; $this->craftingType = CraftingRecipes::TYPE_INVENTORY; $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 = []; $this->toCraft = []; $this->craftingType = CraftingRecipes::TYPE_INVENTORY; + $this->checkSpawnPosition(); - $this->teleport($this->spawnPosition, false, false, true, false); + $tpTarget = $this->level->getSpawn(); + if($this->bedPosition != null){ + [$levelname, $x, $y, $z] = $this->bedPosition; + $level = $this->server->api->level->get($levelname); + if($level === false || $level->level->getBlockID($x, $y, $z) != BED_BLOCK){ + remove_bed: + $this->sendChat("The bed is missing or cannot be accessed."); + $this->setBedPosition(null); + }else{ + $spawnPoint = BedBlock::findStandUpPosition($level, $x, $y, $z); + if($spawnPoint == null) goto remove_bed; + $spawnPoint->x += 0.5; + $spawnPoint->z += 0.5; + $tpTarget = $spawnPoint; + } + } + $this->teleport($tpTarget, false, false, true, false); $pk = new MovePlayerPacket(); $pk->eid = $this->entity->eid; $pk->x = $this->entity->x; @@ -2526,18 +3120,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) { - $player->dataPacket(clone $pk); + foreach($this->entity->level->players as $player){ + if($player->entity->eid != $this->entity->eid && !$this->isInvisibleFor($player)){ + $player->entityQueueDataPacket(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(); @@ -2547,34 +3141,34 @@ 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 = []; $this->craftingType = CraftingRecipes::TYPE_INVENTORY; $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; - $this->dataPacket($pk); + $pk->eid = $this->eid; + $pk->event = EntityEventPacket::ENTITY_COMPLETE_USING_ITEM; + $this->entityQueueDataPacket($pk); $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); } } @@ -2582,42 +3176,62 @@ 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; } - + $packet->eid = $this->eid; $prevItem = $packet->item; - $packet->item = $this->getSlot($this->slot); - $sendOnDrop = false; + $newItem = $this->getHeldItem(); - 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(($n = $this->isExpectedSetSlot(-1, $prevItem))){ + ConsoleAPI::debug("{$this->username}: Expected drop slot dropped"); + $this->removeExpectedSetSlot($n); + return; + } + + if($newItem->getID() != $prevItem->getID() || $newItem->getMetadata() != $prevItem->getMetadata()){ + + if(count($this->inventory) >= 36){ + foreach($this->inventory as $slot => $item){ + if($item->getID() == 0) goto inv_desync_on_drop; + } + $this->addCraftingResult(-1, $prevItem->getID(), $prevItem->getMetadata(), $prevItem->count); break; } - } else { inv_desync_on_drop: - ConsoleAPI::debug("Inventory desync on drop({$this->iusername})"); - $sendOnDrop = true; + + ConsoleAPI::debug("{$this->username} tried dropping item from non-held slot or inventory desynchronized."); + $this->sendInventory(); + break; + } + + if($newItem->count < $prevItem->count){ + ConsoleAPI::warn("{$this->username} tried dropping too many items(serverside stack has {$newItem->count}, tried dropping {$prevItem->count}."); + $this->sendInventory(); + return; + } + if(Player::$allowDroppingSingleItems){ + $packet->item = BlockAPI::getItem($newItem->getID(), $newItem->getMetadata(), $prevItem->count); + }else{ + $packet->item = $newItem; } $this->craftingItems = []; $this->toCraft = []; $this->craftingType = CraftingRecipes::TYPE_INVENTORY; $data["eid"] = $packet->eid; - $data["unknown"] = $packet->unknown; + $data["unknown"] = $packet->randomly; + $data["randomly"] = $packet->randomly; $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; @@ -2629,18 +3243,21 @@ class Player{ $sY += ($this->entity->random->nextFloat() - $this->entity->random->nextFloat()) * 0.1; $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 { + $newItem->count -= $packet->item->count; + if($newItem->count <= 0){ + $this->setSlot($this->slot, BlockAPI::getItem(0, 0, 0), false); + } + }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 = []; @@ -2648,29 +3265,29 @@ class Player{ $this->craftingType = CraftingRecipes::TYPE_INVENTORY; 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(Player::$disableEmojisInChat && Utils::hasEmoji($data["message"])){ $this->sendChat("Your message contains illegal characters"); break; } - + //if($message == "pf"){ // 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); } } @@ -2678,7 +3295,7 @@ class Player{ } break; case ProtocolInfo::CONTAINER_CLOSE_PACKET: - if ($this->spawned === false) { + if($this->spawned === false){ break; } $this->craftingItems = []; @@ -2695,7 +3312,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; @@ -2712,14 +3329,34 @@ 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($packet->windowid === 0){ //crafting + if(($this->gamemode & 1) == CREATIVE){ //sets hotbar item - works only in creative(-based) mode + if($this->gamemode == VIEW) break; //TODO maybe send inventory? + if($packet->slot < 0 || $packet->slot > 8) break; + $it = $packet->item; + $yes = BlockAPI::hasCreativeItem($it->getID(), $it->getMetadata()); + if($yes === false){ //TODO maybe send inventory + break; + } + $this->hotbar[$packet->slot] = $yes; + return; + } + $slot = $this->getSlot($packet->slot); $citem = $packet->item; + + if(($n = $this->isExpectedSetSlot($packet->slot, $packet->item)) !== false){ + //ConsoleAPI::debug("Expected setslot at $n found {$packet->item}"); + $this->removeExpectedSetSlot($n); + break; + }else{ + //ConsoleAPI::info("unexpected setslot, assuming caused by crafting {$packet->slot} {$packet->item}"); + } + if($slot->getID() == $citem->getID() && $slot->getMetadata() == $citem->getMetadata()){ if($citem->count > $slot->count){ //item added, result $this->addCraftingResult($packet->slot, $slot->getID(), $slot->getMetadata(), $citem->count - $slot->count); @@ -2741,98 +3378,100 @@ class Player{ $this->craftingItems = []; $this->craftingType = CraftingRecipes::TYPE_INVENTORY; } - 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; } $item = BlockAPI::getItem($packet->item->getID(), $packet->item->getMetadata(), $packet->item->count); $slot = $tile->getSlot($slotn); - if ($this->server->api->dhandle("player.container.slot", [ + if($this->server->api->dhandle("player.container.slot", [ "tile" => $tile, "slot" => $packet->slot, "offset" => $offset, "slotdata" => $slot, "itemdata" => $item, "player" => $this - ]) === false) { + ]) === false){ $pk = new ContainerSetSlotPacket; $pk->windowid = $packet->windowid; $pk->slot = $packet->slot; $pk->item = $slot; - $this->dataPacket($pk); + $this->blockQueueDataPacket($pk); 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); $slot = $tile->getSlot($packet->slot); - if ($this->server->api->dhandle("player.container.slot", [ + if($this->server->api->dhandle("player.container.slot", [ "tile" => $tile, "slot" => $packet->slot, "slotdata" => $slot, "itemdata" => $item, "player" => $this, - ]) === false) { + ]) === false){ $pk = new ContainerSetSlotPacket; $pk->windowid = $packet->windowid; $pk->slot = $packet->slot; $pk->item = $slot; - $this->dataPacket($pk); + $this->blockQueueDataPacket($pk); 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); @@ -2842,80 +3481,70 @@ 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 = []; $this->craftingType = CraftingRecipes::TYPE_INVENTORY; $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"]); } } } break; + case ProtocolInfo::SET_ENTITY_LINK_PACKET: + if($this->entity->riding != 0){ + $this->entity->setRiding(null); + } + break; case ProtocolInfo::PLAYER_INPUT_PACKET: $this->isJumping = $packet->isJumping; $this->isSneaking = $packet->isSneaking; $this->entity->moveForward = $packet->moveForward; $this->entity->moveStrafing = $packet->moveStrafe; - - if (strlen(bin2hex($packet->buffer)) === 24 && $this->entity->linkedEntity != 0) { - $this->entity->stopRiding(); - break; - } - 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})"); - $this->entity->stopRiding(); + + if($this->entity->riding != 0){ + $e = $this->entity->level->entityList[$this->entity->riding] ?? false; + if($e === false) { + ConsoleAPI::warn("Player is riding on entity that doesnt exist in world! ({$this->iusername}, {$this->entity->riding})"); + $this->entity->setRiding(null); break; } - /*$pk = new SetEntityMotionPacket; - $pk->eid = $e->eid; - $pk->speedX = ($this->entity->x - $e->x)*1.2; - $pk->speedY = ($this->entity->y - $e->y)*1.2; - $pk->speedZ = ($this->entity->z - $e->z)*1.2; - foreach($this->level->players as $p){ - if($p->entity->eid != $this->entity->eid){ - $p->dataPacket(clone $pk); - } - } - console("{$e} {$this->entity}"); - //$this->entity->linkedEntity->moveFlying($packet->moveStrafe, $packet->moveForward, 1);*/ } - + break; default: console("[DEBUG] Unhandled 0x" . dechex($packet->pid()) . " data packet for " . $this->username . " (" . $this->clientID . "): " . print_r($packet, true), true, true, 2); break; } } - - /** + + /** * Get an Item which is currently held by player * @return Item */ - + public function getHeldItem(){ return $this->getSlot($this->slot); } - + public function stopSleep(){ $this->isSleeping = false; $this->sleepingTime = 0; @@ -2965,20 +3594,22 @@ class Player{ $results = []; foreach($this->toCraft as $i => $slotz){ - $results[$i >> 16] = [$i >> 16, $i & 0xffff, array_sum($slotz)]; + $results[$i] = [$i >> 16, $i & 0xffff, array_sum($slotz)]; } $ingridients = []; foreach($this->craftingItems as $i => $slotz){ - $ingridients[$i >> 16] = [$i >> 16, $i & 0xffff, array_sum($slotz)]; + $ingridients[$i] = [$i >> 16, $i & 0xffff, array_sum($slotz)]; } $cc = CraftingRecipes::canCraft($results, $ingridients, $this->craftingType); - if(!is_array($cc) && $this->craftingType == CraftingRecipes::TYPE_CRAFTIGTABLE){ - $cc = CraftingRecipes::canCraft($results, $ingridients, CraftingRecipes::TYPE_INVENTORY); - if(!is_array($cc)){ - return; //recipe not found + if(!is_array($cc)){ + if(!$cc){ + $this->toCraft = []; + $this->craftingItems = []; + return false; } + return; } if($this->server->api->dhandle("player.craft", ["player" => $this, "ingridients" => $this->craftingItems, "results" => $this->toCraft, "type" => $this->craftingType]) === false){ @@ -2987,6 +3618,7 @@ class Player{ return false; } + //ConsoleAPI::debug("crafted successfully"); foreach($this->craftingItems as $i => $slotz){ $id = $i >> 16; $meta = $i & 0xffff; @@ -2994,7 +3626,7 @@ class Player{ $slt = $this->getSlot($slot); if($slt->getID() == $id && $slt->getMetadata() == $meta){ $slt->count -= $count; - if($slt->count <= 0) $this->setSlot($slot, BlockAPI::getItem(0, 0, 0), false); + if($slt->count <= 0) $this->setSlot($slot, BlockAPI::getItem(0, 0, 0), false, addexpected: false); }else{ ConsoleAPI::warn("{$slt->getID()} != $id && {$slt->getMetadata()} != $meta!!!"); } @@ -3024,15 +3656,14 @@ class Player{ if($slt->getID() == $id && $slt->getMetadata() == $meta){ $slt->count += $count; }else if($slt->getID() == 0){ - $this->setSlot($slot, BlockAPI::getItem($id, $meta, $count), false); + $this->setSlot($slot, BlockAPI::getItem($id, $meta, $count), false, addexpected: false); }else{ ConsoleAPI::warn("{$slt->getID()} != $id || 0 !!!"); } } } } - - $this->sendInventory(); + $this->toCraft = []; $this->craftingItems = []; } @@ -3077,20 +3708,40 @@ class Player{ return false; } - public function removeItem($type, $damage, $count, $send = true){ + /** + * Removes a single item from whatever player is holding. + * @param boolean $send Force send inventory to player. + */ + public function consumeSingleItem($send = false){ + $it = $this->getHeldItem(); + if(($this->gamemode & 0x01) === 0x00) --$it->count; + + if($it->count <= 0){ + $this->setSlot($this->slot, BlockAPI::getItem(0, 0, 0), false); + } + + if($send) $this->sendInventory(); + } + + public function removeItem($type, $damage, $count, $send = true, $addexpected = true){ while($count > 0){ $remove = 0; foreach($this->inventory as $s => $item){ if($item->getID() === $type and $item->getMetadata() === $damage){ $remove = min($count, $item->count); + if($remove < $item->count){ $item->count -= $remove; + $exid = $item->getID(); + $exmeta = $item->getMetadata(); + $excnt = $item->count; }else{ $this->inventory[$s] = BlockAPI::getItem(AIR, 0, 0); + $exid = $exmeta = $excnt = 0; } - if($send === true){ - $this->sendInventorySlot($s); - } + if($send === true) $this->sendInventorySlot($s); + + if($addexpected) $this->addExpectedSetSlotPacket($s, $exid, $exmeta, $excnt); break; } } @@ -3101,7 +3752,7 @@ class Player{ } return true; } - + public function handlePacket(RakNetPacket $packet){ if($this->connected === true){ $time = microtime(true); @@ -3110,21 +3761,23 @@ class Player{ case RakNetInfo::NACK: foreach($packet->packets as $count){ if(isset($this->packetAlwaysRecoverQueue[$count])){ - $this->packetAlwaysRecoverQueue[$count]->sendtime = 0; //forces resend next time it will be checked + $this->resendQueue[$count] = $this->packetAlwaysRecoverQueue[$count]; }else if(isset($this->recoveryQueue[$count])){ $this->resendQueue[$count] =& $this->recoveryQueue[$count]; $this->lag[] = $time - $this->recoveryQueue[$count]->sendtime; unset($this->recoveryQueue[$count]); - }else{ - ++$this->packetStats[1]; //lost and wont be recovered + }else{ //lost and wont be recovered + ++$this->packetStats[1]; } } break; case RakNetInfo::ACK: + //if(mt_rand(0, 99) > 50) break; foreach($packet->packets as $count){ if(isset($this->packetAlwaysRecoverQueue[$count])){ $this->lag[] = $time - $this->packetAlwaysRecoverQueue[$count]->sendtime; + unset($this->packetAlwaysRecoverQueue[$count]); unset($this->chunkCount[$count]); }else if(isset($this->recoveryQueue[$count])){ @@ -3162,15 +3815,6 @@ class Player{ } } - public function damageArmorPart($slot, $part){ - $part->useOn($this->entity, true); - if($part->getMetadata() >= $part->getMaxDurability()){ - $this->setArmor($slot, BlockAPI::getItem(AIR, 0, 0), false); - return; - } - $this->setArmor($slot, $part, false); - } - /** * @return string */ @@ -3182,6 +3826,14 @@ class Player{ } + /** + * @deprecated use Player::setInvisibleFor + * @param Player $player + */ + public function makeInvisibleForOnePlayer(Player $player){ + $this->setInvisibleFor($player, true); + } + /** * @deprecated craft system changed * @param array $craft @@ -3194,6 +3846,15 @@ class Player{ return false; } + /** + * @deprecated armor is damaged by Entity::hurtArmor and cant be damaged by singular pieces + */ + public function damageArmorPart($slot, $part){} + + /** + * @deprecated 16x16x16 chunk sending was removed + */ + public static $smallChunks = false; } class PlayerNull extends Player{ diff --git a/src/PocketMinecraftServer.php b/src/PocketMinecraftServer.php index 5e3db110..150e3e90 100644 --- a/src/PocketMinecraftServer.php +++ b/src/PocketMinecraftServer.php @@ -1,18 +1,28 @@ port = (int) $port; $this->doTick = true; @@ -24,15 +34,17 @@ class PocketMinecraftServer{ $this->serverip = $serverip; $this->load(); } - + public static $SAVE_PLAYER_DATA = true; - + + private function load(){ global $dolog; /*if(defined("DEBUG") and DEBUG >= 0){ @cli_set_process_title("NostalgiaCore ".MAJOR_VERSION); }*/ console("[INFO] Starting Minecraft PE server on " . ($this->serverip === "0.0.0.0" ? "*" : $this->serverip) . ":" . $this->port); + Material::init(); EntityRegistry::registerEntities(); PlayerNull::$INSTANCE = new PlayerNull(); Feature::init(); @@ -67,7 +79,6 @@ class PocketMinecraftServer{ $this->saveEnabled = true; $this->tickMeasure = array_fill(0, 40, 0); $this->setType("normal"); - PacketPool::init(); $this->interface = new MinecraftInterface("255.255.255.255", $this->port, $this->serverip); $this->stop = false; $this->ticks = 0; @@ -86,31 +97,75 @@ class PocketMinecraftServer{ "discord-ru-smiles" => false, "discord-webhook-url" => "none", "discord-bot-name" => "NostalgiaCore Logger", - "despawn-mobs" => true, + "despawn-mobs" => true, "mob-despawn-ticks" => 18000, - "16x16x16_chunk_sending" => false, - "experimental-mob-ai" => false, - "force-20-tps" => false, "enable-mob-pushing" => Living::$entityPushing, "keep-chunks-loaded" => self::$KEEP_CHUNKS_LOADED, "use-experimental-hotbar" => Player::$experimentalHotbar, - "keep-items-on-death" => Entity::$keepInventory + "keep-items-on-death" => Entity::$keepInventory, + "disable-emojis-in-chat" => Player::$disableEmojisInChat, + "disable-emojis-on-signs" => Level::$disableEmojisOnSigns, + "allow-dropping-single-items" => Player::$allowDroppingSingleItems, + "enable-light-updates" => self::$ENABLE_LIGHT_UPDATES, + "min-block-breaking-progress" => self::$BLOCK_BREAKING_PROGRESS, + ], comments: [ + "min-block-breaking-progress" => [ + "Affects how strict block breaking speed check is.", + "0 - allow blocks to be mined instantly", + "0.8 - allow breaking blocks after 80% of vanilla block break time.", + "The value should be in range from 0 to 1." + ], + "enable-light-updates" => [ + "Enabling light updates may affects performance and will increase world generation time.", + "Disabling light updates will disable all light-related features(like light-based mob spawning)" + ], + "allow-dropping-single-items" => [ + "Allows players to drop any amount of items from stack in the slot.", + "While it is not possible using vanilla client, some custom clients(like Ninecraft) have this feature" + ], + "disable-emojis-in-chat" => [ + "Disallows players to send certain symbols in chat to prevent client lags" + ], + "use-experimental-hotbar" => [ + "Changes serverside hotbar behavior to be more like in 0.8 rather than 0.7(when disabled)", + "May cause more problems than old hotbar" + ], + "enable-mob-pushing" => [ + "Enables or disables serverside mob pushing", + "If enabled it may cause performance issues when there are a lot of mobs in a small enclosed area", + "If disabled it will cause small entity position desync(that should be fixed every time a server sends a new movement packet to the client)" + ], + "discord-ru-smiles" => [ + "Replaces cyrillic symbols Ы Ь Ъ Ё with emojis when sending a message using discord webhook(as it is done in some custom clients)" + ], + "keep-chunks-loaded" => [ + "If disabled chunks won't be loaded into memory until the player(or something else) loads them" + ] ]); + self::$BLOCK_BREAKING_PROGRESS = $this->extraprops->get("min-block-breaking-progress"); + Player::$disableEmojisInChat = $this->extraprops->get("disable-emojis-in-chat"); + Level::$disableEmojisOnSigns = $this->extraprops->get("disable-emojis-on-signs"); Entity::$keepInventory = $this->extraprops->get("keep-items-on-death"); Player::$experimentalHotbar = $this->extraprops->get("use-experimental-hotbar"); - Player::$smallChunks = $this->extraprops->get("16x16x16_chunk_sending"); + Player::$allowDroppingSingleItems = $this->extraprops->get("allow-dropping-single-items"); Living::$despawnMobs = $this->extraprops->get("despawn-mobs"); Living::$despawnTimer = $this->extraprops->get("mob-despawn-ticks"); Living::$entityPushing = $this->extraprops->get("enable-mob-pushing"); - self::$FORCE_20_TPS = $this->extraprops->get("force-20-tps"); + self::$KEEP_CHUNKS_LOADED = $this->extraprops->get("keep-chunks-loaded"); + self::$ENABLE_LIGHT_UPDATES = $this->extraprops->get("enable-light-updates"); PocketMinecraftServer::$SAVE_PLAYER_DATA = $this->extraprops->get("save-player-data"); - 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::$TICKING_MODE == self::TICK_F20TPS){ ConsoleAPI::warn("Forcing 20 tps. This may result in higher CPU usage!"); } + if(self::$BLOCK_BREAKING_PROGRESS > 1){ + ConsoleAPI::warn("Minimal block breaking progress is more than 1, may cause ghost blocks to appear even for players with extremely low ping!"); + } + if(!self::$ENABLE_LIGHT_UPDATES){ + ConsoleAPI::warn("Light updates are disabled: this should decrease memory consumption and increase performance, but will prevent all existing light from updating and disable some light-dependant features."); + } if($this->extraprops->get("discord-msg")){ if($this->extraprops->get("discord-webhook-url") !== "none"){ console("[INFO] Discord Logger is enabled."); @@ -136,6 +191,8 @@ class PocketMinecraftServer{ public function startDatabase(){ $this->preparedSQL = new stdClass(); $this->preparedSQL->entity = new stdClass(); + $this->preparedSQL->player = new stdClass(); + $this->database = new SQLite3(":memory:"); $this->query("PRAGMA journal_mode = OFF;"); $this->query("PRAGMA encoding = \"UTF-8\";"); @@ -146,13 +203,17 @@ class PocketMinecraftServer{ $this->query("CREATE TABLE actions (ID INTEGER PRIMARY KEY, interval NUMERIC, last NUMERIC, code TEXT, repeat NUMERIC);"); $this->query("CREATE TABLE handlers (ID INTEGER PRIMARY KEY, name TEXT, priority NUMERIC);"); $this->query("CREATE TABLE blockUpdates (level TEXT, x INTEGER, y INTEGER, z INTEGER, type INTEGER, delay NUMERIC);"); - $this->query("CREATE TABLE recipes (id INTEGER PRIMARY KEY, type NUMERIC, recipe TEXT);"); $this->query("PRAGMA synchronous = OFF;"); $this->preparedSQL->selectHandlers = $this->database->prepare("SELECT DISTINCT ID FROM handlers WHERE name = :name ORDER BY priority DESC;"); $this->preparedSQL->selectActions = $this->database->prepare("SELECT ID,code,repeat FROM actions WHERE last <= (:time - interval);"); $this->preparedSQL->updateAction = $this->database->prepare("UPDATE actions SET last = :time WHERE ID = :id;"); $this->preparedSQL->entity->setPosition = $this->database->prepare("UPDATE entities SET x = :x, y = :y, z = :z, pitch = :pitch, yaw = :yaw WHERE EID = :eid ;"); $this->preparedSQL->entity->setLevel = $this->database->prepare("UPDATE entities SET level = :level WHERE EID = :eid ;"); + + $this->preparedSQL->player->deleteCID = $this->database->prepare("DELETE FROM players WHERE CID = :CID;"); + $this->preparedSQL->player->getEq = $this->database->prepare("SELECT ip,port,name FROM players WHERE name = :name;"); //'$name' + $this->preparedSQL->player->getLike = $this->database->prepare("SELECT ip,port,name FROM players WHERE name LIKE :name;"); //'$name' + } public function query($sql, $fetch = false){ @@ -230,7 +291,7 @@ class PocketMinecraftServer{ } release_lock(); } - + 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"); @@ -244,7 +305,7 @@ class PocketMinecraftServer{ ], null); } } - + public function asyncOperation($type, array $data, callable $callable = null){ if(defined("NO_THREADS")){ return false; @@ -348,6 +409,7 @@ class PocketMinecraftServer{ /** * @param string $event + * @param callable $callable * @param integer $priority * * @return boolean @@ -432,7 +494,7 @@ class PocketMinecraftServer{ pcntl_signal(SIGINT, [$this, "close"]); pcntl_signal(SIGHUP, [$this, "close"]); } - + console("[INFO] Default game type: " . strtoupper($this->getGamemode())); $this->trigger("server.start", microtime(true)); console('[INFO] Done (' . round(microtime(true) - START_TIME, 3) . 's)! For help, type "help" or "?"'); @@ -452,7 +514,7 @@ class PocketMinecraftServer{ if(!is_callable($callback)){ return false; } - + $chcnt = $this->scheduleCnt++; $this->schedule[$chcnt] = [$callback, $data, $eventName]; $this->query("INSERT INTO actions (ID, interval, last, repeat) VALUES(" . $chcnt . ", " . ($ticks / 20) . ", " . microtime(true) . ", " . (((bool) $repeat) === true ? 1 : 0) . ");"); @@ -478,7 +540,7 @@ class PocketMinecraftServer{ public function process() { $lastLoop = 0; - if(self::$FORCE_20_TPS){ + if(self::$TICKING_MODE != self::TICK_LEGACY){ while($this->stop === false){ $packetcnt = 0; while($packet = $this->interface->readPacket()){ @@ -490,7 +552,7 @@ class PocketMinecraftServer{ } } } - + $this->tick(); } }else{ @@ -523,11 +585,12 @@ class PocketMinecraftServer{ $this->tick(); } } - + + } public function packetHandler(Packet $packet){ - $data = &$packet; + $data =& $packet; $CID = PocketMinecraftServer::clientID($packet->ip, $packet->port); if(isset($this->clients[$CID])){ $this->clients[$CID]->handlePacket($packet); @@ -587,7 +650,10 @@ class PocketMinecraftServer{ if($this->invisible === true){ break; } - + + if($packet->mtuSize > 2048) $packet->mtuSize = 2048; + if($packet->mtuSize <= 512) $packet->mtuSize = 512; + $this->clients[$CID] = $c = new Player($packet->clientID, $packet->ip, $packet->port, $packet->mtuSize); //New Session! $pk = new RakNetPacket(RakNetInfo::OPEN_CONNECTION_REPLY_2); $pk->serverID = $this->serverID; @@ -602,7 +668,6 @@ class PocketMinecraftServer{ public static function clientID($ip, $port){ return crc32($ip . $port) ^ crc32($port . $ip . BOOTUP_RANDOM); - //return $ip . ":" . $port; } public function send(Packet $packet){ @@ -615,14 +680,11 @@ class PocketMinecraftServer{ $this->tickMeasure[] = $this->lastTick = $time; unset($this->tickMeasure[key($this->tickMeasure)]); ++$this->ticks; - + foreach($this->clients as $client){ $client->handlePacketQueues(); - if($this->ticks % 40 == 0){ //2s - $client->sendPing(); - } } - + foreach($this->api->level->levels as $l){ $l->onTick($this, $time); } @@ -773,7 +835,7 @@ class PocketMinecraftServer{ $info["garbage"] = gc_collect_cycles(); $this->handle("server.debug", $info); 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); + 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; } diff --git a/src/config.php b/src/config.php index 8352e431..d29cb707 100644 --- a/src/config.php +++ b/src/config.php @@ -1,117 +1,10 @@ 0){ + echo "[ERROR] Use PHP >= 8.0.0 to launch this server software.\n"; + exit(1); } -if(ini_get("date.timezone") == ""){ //No Timezone set - date_default_timezone_set("GMT"); - if(str_contains(" " . strtoupper(php_uname("s")), " WIN")){ - - $regex = '/(UTC)(\+*\-*\d*\d*\:*\d*\d*)/'; - - /* - * wmic timezone get Caption - * Get the timezone offset - * - * Sample Output var_dump - * array(3) { - * [0] => - * string(7) "Caption" - * [1] => - * string(20) "(UTC+09:30) Adelaide" - * [2] => - * string(0) "" - * } - */ - exec("wmic timezone get Caption", $output); - - $string = trim(implode("\n", $output)); - - //Detect the Time Zone string - preg_match($regex, $string, $matches); - - if(!isset($matches[2]) or ($timezone = parseOffset($matches[2])) === false){ - $timezone = 'UTC'; - } - if(date_default_timezone_set($timezone)){ - ini_set("date.timezone", $timezone); - } - }else{ - exec("date +%s", $t); - $offset = round((intval(trim($t[0])) - time()) / 60) * 60; - $daylight = (int) date("I"); - $d = timezone_name_from_abbr("", $offset, $daylight); - @ini_set("date.timezone", $d); - date_default_timezone_set($d); - } -}else{ - $d = @date_default_timezone_get(); - if(!str_contains($d, "/")){ - $d = timezone_name_from_abbr($d); - @ini_set("date.timezone", $d); - date_default_timezone_set($d); - } -} - -gc_enable(); -error_reporting(E_ALL | E_STRICT); -ini_set("allow_url_fopen", 1); -ini_set("display_errors", 1); -ini_set("display_startup_errors", 1); -ini_set("default_charset", "utf-8"); -if(defined("POCKETMINE_COMPILE") and POCKETMINE_COMPILE === true){ - define("FILE_PATH", realpath(dirname(__FILE__)) . "/"); -}else{ - define("FILE_PATH", realpath(dirname(__FILE__) . "/../") . "/"); -} -set_include_path(get_include_path() . PATH_SEPARATOR . FILE_PATH); - -ini_set("memory_limit", "256M"); //Default -define("LOG", true); -define("START_TIME", microtime(true)); -define("MAJOR_VERSION", "1.1.0dev"); -define("CODENAME", "懐かしさ (Nostalgia)"); //i'm not very creative - kotyaralih -define("CURRENT_MINECRAFT_VERSION", "v0.8.1 alpha"); -define("CURRENT_API_VERSION", "12.2"); -define("CURRENT_PHP_VERSION", "8.0"); -$gitsha1 = false; -if(file_exists(FILE_PATH . ".git/refs/heads/master")){ //Found Git information! - define("GIT_COMMIT", strtolower(trim(file_get_contents(FILE_PATH . ".git/refs/heads/master")))); -}else{ //Unknown :( - define("GIT_COMMIT", str_repeat("00", 20)); -} +require_once(dirname(__FILE__)."/config_post.php"); //that config uses modern php features which may cause errors before php version check has been completed \ No newline at end of file diff --git a/src/config_post.php b/src/config_post.php new file mode 100644 index 00000000..879a941a --- /dev/null +++ b/src/config_post.php @@ -0,0 +1,116 @@ + + * string(7) "Caption" + * [1] => + * string(20) "(UTC+09:30) Adelaide" + * [2] => + * string(0) "" + * } + */ + exec("wmic timezone get Caption", $output); + + $string = trim(implode("\n", $output)); + + //Detect the Time Zone string + preg_match($regex, $string, $matches); + + if(!isset($matches[2]) or ($timezone = parseOffset($matches[2])) === false){ + $timezone = 'UTC'; + } + if(date_default_timezone_set($timezone)){ + ini_set("date.timezone", $timezone); + } + }else{ + exec("date +%s", $t); + $offset = round((intval(trim($t[0])) - time()) / 60) * 60; + $daylight = (int) date("I"); + $d = timezone_name_from_abbr("", $offset, $daylight); + @ini_set("date.timezone", $d); + date_default_timezone_set($d); + } +}else{ + $d = @date_default_timezone_get(); + if(!str_contains($d, "/")){ + $d = timezone_name_from_abbr($d); + @ini_set("date.timezone", $d); + date_default_timezone_set($d); + } +} + +gc_enable(); +error_reporting(E_ALL | E_STRICT); +ini_set("allow_url_fopen", 1); +ini_set("display_errors", 1); +ini_set("display_startup_errors", 1); +ini_set("default_charset", "utf-8"); +if(defined("POCKETMINE_COMPILE") and POCKETMINE_COMPILE === true){ + define("FILE_PATH", realpath(dirname(__FILE__)) . "/"); +}else{ + define("FILE_PATH", realpath(dirname(__FILE__) . "/../") . "/"); +} +set_include_path(get_include_path() . PATH_SEPARATOR . FILE_PATH); + +ini_set("memory_limit", "256M"); //Default +define("LOG", true); +define("START_TIME", microtime(true)); +define("MAJOR_VERSION", "1.1.1dev"); +define("CODENAME", "Nostalgia"); //i\'m not very creative - kotyaralih, yeah - tema1d. +define("CURRENT_MINECRAFT_VERSION", "v0.8.1 alpha"); +define("CURRENT_API_VERSION", "12.2"); +define("CURRENT_PHP_VERSION", "8.0"); +$gitsha1 = false; +if(file_exists(FILE_PATH . ".git/refs/heads/master")){ //Found Git information! + define("GIT_COMMIT", strtolower(trim(file_get_contents(FILE_PATH . ".git/refs/heads/master")))); +}else{ //Unknown :( + define("GIT_COMMIT", str_repeat("00", 20)); +} \ No newline at end of file diff --git a/src/constants/BlockIDs.php b/src/constants/BlockIDs.php index cdbcc01b..7db0855f 100755 --- a/src/constants/BlockIDs.php +++ b/src/constants/BlockIDs.php @@ -105,7 +105,7 @@ define("SUGARCANE_BLOCK", 83); define("FENCE", 85); define("PUMPKIN", 86); define("NETHERRACK", 87); -define("SOUL_SAND", 88); +define("SOUL_SAND", 88); //doesnt exist define("GLOWSTONE", 89); define("GLOWSTONE_BLOCK", 89); @@ -135,7 +135,7 @@ define("NETHER_BRICKS", 112); define("NETHER_BRICK_BLOCK", 112); define("NETHER_BRICKS_STAIRS", 114); - +//TODO missing tile: 126 dt 0.500000 h 2.500000 b CakeTile n activatorRail, mat cake define("SANDSTONE_STAIRS", 128); define("SPRUCE_WOOD_STAIRS", 134); diff --git a/src/dependencies.php b/src/dependencies.php index 54260b95..6c3bc9bc 100644 --- a/src/dependencies.php +++ b/src/dependencies.php @@ -17,11 +17,6 @@ set_error_handler("error_handler", E_ALL); $errors = 0; -if(version_compare("8.0.0", PHP_VERSION) > 0){ - console("[ERROR] Use PHP >= 8.0.0", true, true, 0); - ++$errors; -} - if(php_sapi_name() !== "cli"){ console("[ERROR] You must run NostalgiaCore using the CLI.", true, true, 0); ++$errors; diff --git a/src/entity/Animal.php b/src/entity/Animal.php index f9ccf9be..f4098922 100644 --- a/src/entity/Animal.php +++ b/src/entity/Animal.php @@ -1,15 +1,17 @@ setAge($data["Age"] ?? 0); @@ -18,11 +20,11 @@ abstract class Animal extends Creature implements Ageable, Breedable{ } $this->searchForClosestPlayers = true; } - + public function isPlayerValid(Player $player){ return $player->spawned && $this->isFood($player->getHeldItem()->id) && !$player->entity->dead; } - + public function handlePrePlayerSearcher(){ parent::handlePrePlayerSearcher(); if($this->closestPlayerThatCanFeedEID !== false){ @@ -31,15 +33,15 @@ abstract class Animal extends Creature implements Ageable, Breedable{ $this->closestPlayerThatCanFeedEID = false; $this->closestPlayerThatCanFeedDist = INF; }else{ - $dist = ($this->x - $player->x) * ($this->x - $player->x) + ($this->y - $player->y) * ($this->y - $player->y) + ($this->z - $player->z) * ($this->z - $player->z); + $dist = ($this->x - $player->x)*($this->x - $player->x) + ($this->y - $player->y)*($this->y - $player->y) + ($this->z - $player->z)*($this->z - $player->z); $this->closestPlayerThatCanFeedDist = $dist; } } } - + public function handlePlayerSearcher(Player $player, $dist){ parent::handlePlayerSearcher($player, $dist); - + if($this->closestPlayerThatCanFeedDist >= $dist){ if($this->isPlayerValid($player)){ $this->closestPlayerThatCanFeedDist = $dist; @@ -47,43 +49,43 @@ abstract class Animal extends Creature implements Ageable, Breedable{ } } } - + public function harm($dmg, $cause = "generic", $force = false){ $ret = parent::harm($dmg, $cause, $force); $this->inPanic |= ($ret && is_numeric($cause)); $this->inLove = false; return $ret; } - + public function isBaby(){ return $this->getAge() < 0; } - - public function breed(){ - if($this->server->dhandle("entity.animal.breed", ["parent" => $this]) !== false){ - $c = $this->spawnChild(); + + public function breed($mate){ + if($this->server->dhandle("entity.animal.breed", ["parent" => $this, "parent2" => $mate]) !== false){ + $c = $this->spawnChild($mate); $c->parent = $this; //TODO save eid to avoid memory leaks? $this->server->api->entity->spawnToAll($c); return $c; } return false; } - + public function resetInLove(){ $this->inLove = 0; } - + public function canMate($ent){ return $ent->eid != $this->eid && $this->type === $ent->type && $this->isInLove() && $ent->isInLove(); } - + public function update($now){ parent::update($now); - + if($this->loveTimeout > 0){ --$this->loveTimeout; } - + $age = $this->getAge() + 1; //100 - fast. debug, 1 - normal if($age >= 0 && $this->isBaby()){ $this->setAge($age); @@ -97,16 +99,16 @@ abstract class Animal extends Creature implements Ageable, Breedable{ unset($this->level->entitiesInLove[$this->eid]); } } - + public function getAge(){ return $this->age; } - + public function setAge($i){ $this->age = $i; } - - public function spawnChild() + + public function spawnChild($mate) { return $this->server->api->entity->add($this->level, $this->class, $this->type, [ "x" => $this->x + lcg_value() * mt_rand(-1, 1), @@ -116,45 +118,43 @@ abstract class Animal extends Creature implements Ageable, Breedable{ "Age" => -24000, ]); } - + public function getMetadata(){ $d = parent::getMetadata(); $d[14]["value"] = $this->isBaby(); return $d; } - + public function createSaveData(){ $data = parent::createSaveData(); $data["IsBaby"] = $this->isBaby(); $data["Age"] = $this->getAge(); return $data; } - + public function isInLove(){ return $this->inLove > 0; } - + public function interactWith(Entity $e, $action){ if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){ $slot = $e->player->getHeldItem(); if($this->isFood($slot->getID()) && $this->inLove <= 0 && !$this->isBaby() && $this->loveTimeout <= 0){ - if(($e->player->gamemode & 0x01) === SURVIVAL){ - $e->player->removeItem($slot->getID(), $slot->getMetadata(), 1); - } + $e->player->consumeSingleItem(); $this->inLove = 600; return true; } } parent::interactWith($e, $action); } - + public function counterUpdate(){ parent::counterUpdate(); if($this->isInLove()){ --$this->inLove; } } - + public function getDrops(){ if($this->isBaby()){ return []; diff --git a/src/entity/Breedable.php b/src/entity/Breedable.php index 211c6c7e..39c1ae6b 100644 --- a/src/entity/Breedable.php +++ b/src/entity/Breedable.php @@ -2,8 +2,8 @@ interface Breedable{ public function isFood($id); //original name - - public function spawnChild(); - + + public function spawnChild($mate); + public function isInLove(); } \ No newline at end of file diff --git a/src/entity/Creature.php b/src/entity/Creature.php index be41e0e5..61ee671b 100644 --- a/src/entity/Creature.php +++ b/src/entity/Creature.php @@ -2,24 +2,26 @@ abstract class Creature extends Living{ const CLASS_TYPE = ENTITY_MOB; - + public $inPanic; public $closestPlayerEID = false; public $closestPlayerDist = INF; - + + public function __construct(Level $level, $eid, $class, $type = 0, $data = []){ $this->inPanic = false; //force for now parent::__construct($level, $eid, $class, $type, $data); - $this->setHealth($this->data["Health"] ?? 1, "generic"); + $this->setHealth($this->data["Health"] ?? 1, "generic", allowHarm: false); $this->enableAutojump = true; $this->searchForClosestPlayers = true; } - + public function update($now){ $this->handlePrePlayerSearcher(); return parent::update($now); } - + + public function handlePrePlayerSearcher(){ parent::handlePrePlayerSearcher(); if($this->closestPlayerEID !== false){ @@ -28,12 +30,12 @@ abstract class Creature extends Living{ $this->closestPlayerEID = false; $this->closestPlayerDist = INF; }else{ - $dist = ($this->x - $player->x) * ($this->x - $player->x) + ($this->y - $player->y) * ($this->y - $player->y) + ($this->z - $player->z) * ($this->z - $player->z); + $dist = ($this->x - $player->x)*($this->x - $player->x) + ($this->y - $player->y)*($this->y - $player->y) + ($this->z - $player->z)*($this->z - $player->z); $this->closestPlayerDist = $dist; } } } - + public function handlePlayerSearcher(Player $player, $dist){ parent::handlePlayerSearcher($player, $dist); if($this->closestPlayerDist >= $dist){ @@ -41,47 +43,46 @@ abstract class Creature extends Living{ $this->closestPlayerDist = $dist; } } - + public function createSaveData(){ $data = parent::createSaveData(); $data["State"] = @$this->getState(); return $data; } - + public function getSpeedModifer(){ return 0.7; } public function getArmorValue(){ return 0; } - public function spawn($player){ - if(!($player instanceof Player)){ - $player = $this->server->api->player->get($player); - } + public function spawn(Player $player){ if($player->eid === $this->eid or $this->closed !== false or ($player->level !== $this->level and $this->class !== ENTITY_PLAYER)){ return false; } - $pk = new AddMobPacket; - $pk->eid = $this->eid; - $pk->type = $this->type; - $pk->x = $this->x; - $pk->y = $this->y; - $pk->z = $this->z; - $pk->yaw = $this->yaw; - $pk->pitch = $this->pitch; - $pk->metadata = $this->getMetadata(); - $player->dataPacket($pk); - - $pk = new SetEntityMotionPacket; - $pk->eid = $this->eid; - $pk->speedX = $this->speedX; - $pk->speedY = $this->speedY; - $pk->speedZ = $this->speedZ; - $player->dataPacket($pk); - - if($this->linkedEntity != 0 && $this->isRider){ - $player->eventHandler(["rider" => $this->eid, "riding" => $this->linkedEntity, "type" => 0], "entity.link"); + if(!$player->hasEntity($this)){ + $player->addEntity($this); + $pk = new AddMobPacket; + $pk->eid = $this->eid; + $pk->type = $this->type; + $pk->x = $this->x; + $pk->y = $this->y; + $pk->z = $this->z; + $pk->yaw = $this->yaw; + $pk->pitch = $this->pitch; + $pk->metadata = $this->getMetadata(); + $player->entityQueueDataPacket($pk); + + $pk = new SetEntityMotionPacket; + $pk->eid = $this->eid; + $pk->speedX = $this->speedX; + $pk->speedY = $this->speedY; + $pk->speedZ = $this->speedZ; + $player->entityQueueDataPacket($pk); + $this->sendLinkPackets($player); + return true; } + return false; } - + } diff --git a/src/entity/Entity.php b/src/entity/Entity.php index 82678e6f..bfb6a2b1 100644 --- a/src/entity/Entity.php +++ b/src/entity/Entity.php @@ -3,10 +3,11 @@ class Entity extends Position { - const TYPE = -1; - const CLASS_TYPE = -1; - const MIN_POSSIBLE_SPEED = 1 / 8000; //anything below will send 0 to player - + const TYPE = - 1; + const CLASS_TYPE = - 1; + const MIN_POSSIBLE_SPEED = 1/8000; //anything below will send 0 to player + + public $forceUpdateMovement = false; public $searchForClosestPlayers = false; public $modifySpeedY = false; public $modifedSpeedY = 0.0; @@ -18,6 +19,10 @@ class Entity extends Position public $canBeAttacked; public $moveTime, $lookTime, $idleTime, $knockbackTime = 0; public $attackTimeout = 0; + /** + * @deprecated always true + * @var boolean + */ public $needsUpdate = true; public $speedModifer; public $hasGravity; @@ -36,17 +41,17 @@ class Entity extends Position public $delayBeforePickup; public $x, $y, $z; public $speedX, $speedY, $speedZ, $speed; - public $lastX = 0, $lastY = 0, $lastZ = 0, $lastYaw = 0, $lastPitch = 0, $lastTime = 0, $lastHeadYaw = 0, $lastSpeedX = 0, $lastSpeedY = 0, $lastSpeedZ = 0; + public $lastX = 0, $lastY = 0, $lastZ = 0, $lastYaw = 0, $lastPitch = 0, $lastTime = 0, $lastHeadYaw = 0, $lastSpeedX = 0, $lastSpeedY = 0, $lastSpeedZ = 0; /** - * 0 = lastX, - * 1 = lastY, - * 2 = lastZ, - * 3 = lastYaw, - * 4 = lastPitch, - * 5 = lastTime. - * + * 0 = lastX, + * 1 = lastY, + * 2 = lastZ, + * 3 = lastYaw, + * 4 = lastPitch, + * 5 = lastTime. + * * It is not recommended to use this and it is left as a backwards compability. - * + * * @var array */ public $last; @@ -65,17 +70,18 @@ class Entity extends Position public $fallStart; private $state; private $tickCounter; - private $speedMeasure = [0, 0, 0, 0, 0, 0, 0]; + private $speedMeasure = array(0, 0, 0, 0, 0, 0, 0); public $server; private $isStatic; public $level; - public $isRiding = false; public $lastUpdate; - public $linkedEntity = 0; - public $isRider = false; + public $check = true; public $width = 1; public $height = 1; + /** + * @var XorShift128Random + */ public $random; public $radius; public $inAction = false; @@ -87,33 +93,45 @@ class Entity extends Position public $onGround, $inWater; public $carryoverDamage; public $gravity; - + public $stepHeight = 0.5; public $enableAutojump = false; public $yOffset = 0.0; public $noClip = false; - + public $chunkX = 0; public $chunkZ = 0; - + public $isCollidedHorizontally, $isCollidedVertically, $isCollided; /** * Amount of ticks you can be in fire until you start receiving damage * @var integer */ public $fireResistance = 1; - + public $isImmuneToFire = false; - + public $inWeb; public $inLava; public $notOnGroundTicks = 0; - + public $moveStrafing, $moveForward; - - function __construct(Level $level, $eid, $class, $type = 0, $data = []) + + + /** + * Stores EID of the entity that is riding on this entity. + * @var integer + */ + public $rider = 0; + /** + * Stores EID of the entity that is being ridden by this entity. + * @var integer + */ + public $riding = 0; + + public function __construct(Level $level, $eid, $class, $type = 0, $data = []) { - $this->random = new Random(); + $this->random = new XorShift128Random(); $this->last = [&$this->lastX, &$this->lastY, &$this->lastZ, &$this->lastYaw, &$this->lastPitch, &$this->lastTime]; //pointers to variables $this->canBeAttacked = false; $this->hasKnockback = false; @@ -131,7 +149,7 @@ class Entity extends Position $this->status = 0; $this->health = 20; $this->hasGravity = false; - $this->dmgcounter = [0, 0, 0]; + $this->dmgcounter = array(0, 0, 0); $this->air = $this->maxAir; $this->fire = 0; $this->crouched = false; @@ -143,7 +161,6 @@ class Entity extends Position $this->name = ""; $this->gravity = 0.08; $this->state = $this->data["State"] = $this->data["State"] ?? 0; - $this->tickCounter = 0; $this->x = isset($this->data["x"]) ? (float) $this->data["x"] : 0; $this->y = isset($this->data["y"]) ? (float) $this->data["y"] : 0; $this->z = isset($this->data["z"]) ? (float) $this->data["z"] : 0; @@ -154,21 +171,21 @@ class Entity extends Position $this->yaw = isset($this->data["yaw"]) ? (float) $this->data["yaw"] : 0; $this->headYaw = $this->data["headYaw"] ?? $this->yaw; $this->pitch = isset($this->data["pitch"]) ? (float) $this->data["pitch"] : 0; - $this->position = [ + $this->position = array( "level" => $this->level, "x" => &$this->x, "y" => &$this->y, "z" => &$this->z, "yaw" => &$this->yaw, "pitch" => &$this->pitch - ]; + ); $this->moveTime = 0; $this->lookTime = 0; $this->onGround = false; switch($this->class) { case ENTITY_PLAYER: $this->player = $this->data["player"]; - $this->setHealth($this->health, "generic"); + $this->setHealth($this->health, "generic", allowHarm: false); $this->speedModifer = 1; $this->width = 0.6; $this->height = 1.8; @@ -176,14 +193,14 @@ class Entity extends Position $this->hasGravity = true; $this->canBeAttacked = true; $this->fireResistance = 20; - + break; case ENTITY_OBJECT: if($this->type == OBJECT_PAINTING) break; $this->x = $this->data["TileX"] ?? $this->x; $this->y = $this->data["TileY"] ?? $this->y; $this->z = $this->data["TileZ"] ?? $this->z; - $this->setHealth(1, "generic"); + $this->setHealth(1, "generic", allowHarm: false); $this->stepHeight = false; $this->setSize(1, 1); break; @@ -196,8 +213,9 @@ class Entity extends Position $this->outOfWorld(); } } + public function handlePrePlayerSearcher(){ - + } public function isType(){ return in_array($this->type, func_get_args()); @@ -210,12 +228,12 @@ class Entity extends Position public function attackEntity($entity, $distance){ return false; } - + public function setInWeb(){ $this->inWeb = true; $this->fallDistance = 0; } - + public function addVelocity($vX, $vY = 0, $vZ = 0) { if($vX instanceof Vector3){ @@ -225,11 +243,11 @@ class Entity extends Position $this->speedY += $vY; $this->speedZ += $vZ; } - + public function isPushable(){ return $this->isPlayer(); } - + public function applyCollision(Entity $collided){ if(!($this->isPlayer() && $collided->isPlayer()) && $this->eid != $collided->eid){ $diffX = $collided->x - $this->x; @@ -239,7 +257,7 @@ class Entity extends Position $sqrtMax = sqrt($maxDiff); $diffX /= $sqrtMax; $diffZ /= $sqrtMax; - + $col = (($v = 1 / $sqrtMax) > 1 ? 1 : $v); $diffX *= $col; $diffZ *= $col; @@ -250,7 +268,7 @@ class Entity extends Position } } } - + public function isMovingHorizontally() { return ($this->speedX >= self::MIN_POSSIBLE_SPEED || $this->speedX <= -self::MIN_POSSIBLE_SPEED) || ($this->speedZ >= self::MIN_POSSIBLE_SPEED || $this->speedZ <= -self::MIN_POSSIBLE_SPEED); @@ -345,26 +363,26 @@ class Entity extends Position if(self::$keepInventory){ return []; } - for($i = 0; $i < PLAYER_SURVIVAL_SLOTS; ++$i){ + for($i = 0; $i < PLAYER_SURVIVAL_SLOTS; ++ $i){ $slot = $this->player->getSlot($i); $this->player->setSlot($i, BlockAPI::getItem(AIR, 0, 0)); if($slot->getID() !== AIR and $slot->count > 0){ - $inv[] = [ + $inv[] = array( $slot->getID(), $slot->getMetadata(), $slot->count - ]; + ); } } - for($re = 0; $re < 4; $re++){ + for($re = 0; $re < 4; $re ++){ $slot = $this->player->getArmor($re); $this->player->setArmor($re, BlockAPI::getItem(AIR, 0, 0)); if($slot->getID() !== AIR and $slot->count > 0){ - $inv[] = [ + $inv[] = array( $slot->getID(), $slot->getMetadata(), $slot->count - ]; + ); } } return $inv; @@ -378,11 +396,11 @@ class Entity extends Position $this->server->api->entity->drop($this, BlockAPI::getItem($drop[0] & 0xFFFF, $drop[1] & 0xFFFF, $drop[2] & 0xFF)); } } - + public function canSee(Entity $e){ return $this->level->rayTraceBlocks(new Vector3($this->x, $this->y + $this->getEyeHeight(), $this->z), new Vector3($e->x, $e->y + $e->getEyeHeight(), $e->z)) == null; } - + /** * Can entity be collided with or not * @return boolean @@ -390,14 +408,14 @@ class Entity extends Position public function isPickable(){ return $this->isPlayer() && !$this->dead; } - + public function handleLavaMovement(){ //TODO maybe try merging with water? $this->inLava = $this->level->isLavaInBB($this->boundingBox->expand(-0.1, -0.4, -0.1)); return $this->inLava; } - + public function handleWaterMovement(){ - if($this->level->handleMaterialAcceleration($this->boundingBox->expand(0, -0.4, 0)->contract(0.001, 0.001, 0.001), 0, $this)){ + if($this->level->handleMaterialAcceleration($this->boundingBox->expand(0, -0.4, 0)->contract(0.001, 0.001, 0.001), Material::$water, $this)){ $this->fallDistance = 0; $this->inWater = true; if($this->fire > 0){ @@ -406,39 +424,37 @@ class Entity extends Position }else{ $this->fire = 0; } - + }else{ $this->inWater = false; } - + return $this->inWater; } - + public function environmentUpdate($time) { - $hasUpdate = $this->class === ENTITY_MOB; // force true for mobs - $tickDiff = ($time - $this->lastUpdate) / 0.05; if($this->attackTimeout > 0) $this->attackTimeout -= $tickDiff; if($this->attackTimeout < 0) $this->attackTimeout = 0; - + if($this->isPlayer() && $this->player->spawned === true && $this->player->blocked !== true && !$this->dead){ $myBB = $this->boundingBox->grow(1, 0.5, 1); foreach($this->server->api->entity->getRadius($this, 2, false) as $item){ if($item->class === ENTITY_ITEM && !$item->closed && $item->spawntime > 0 && $item->delayBeforePickup <= 0){ - if($item->boundingBox->intersectsWith($myBB)){ - if((($this->player->gamemode & 0x01) === 1 || $this->player->hasSpace($item->itemID, $item->meta, $item->stack) === true) && $this->server->api->dhandle("player.pickup", [ + if($item->boundingBox->intersectsWith($myBB)){ + if((($this->player->gamemode & 0x01) === 1 || $this->player->hasSpace($item->itemID, $item->meta, $item->stack) === true) && $this->server->api->dhandle("player.pickup", array( "eid" => $this->player->eid, "player" => $this->player, "entity" => $item, "block" => $item->itemID, "meta" => $item->meta, "target" => $item->eid - ]) !== false){ + )) !== false){ $item->close(); } } - }elseif($item->class == ENTITY_OBJECT && !$item->closed && $item->type == OBJECT_ARROW && $item->shotByPlayer && $item->inGround && $item->shake <= 0 && $item->boundingBox->intersectsWith($myBB)){ + }else if($item->class == ENTITY_OBJECT && !$item->closed && $item->type == OBJECT_ARROW && $item->shotByPlayer && $item->inGround && $item->shake <= 0 && $item->boundingBox->intersectsWith($myBB)){ if(($this->player->gamemode & 0x01) == 1 || $this->player->hasSpace(ARROW, 0, 1)){ $this->player->addItem(ARROW, 0, 1); $item->close(); @@ -463,7 +479,7 @@ class Entity extends Position $this->air = $this->maxAir; return false; } - + $this->handleWaterMovement(); if($this->fire > 0){ //TODO move somewhere if(!$this->isImmuneToFire){ @@ -475,11 +491,9 @@ class Entity extends Position $this->fire -= 4; if($this->fire <= 0) $this->fire = 0; } - + if($this->fire <= 0){ $this->updateMetadata(); - } else{ - $hasUpdate = true; } } @@ -487,16 +501,15 @@ class Entity extends Position if(!$this->isImmuneToFire){ $this->harm(4, "fire"); $oldOnFire = $this->fire; - if($oldOnFire < 20 * 30) $this->fire = 20 * 30; //30 seconds + if($oldOnFire < 20*30) $this->fire = 20*30; //30 seconds } } - + if($this->isInVoid()){ $this->outOfWorld(); - $hasUpdate = true; } - - if(!($this instanceof Painting) && !($this->isPlayer() && $this->player->isSleeping !== false)){ //TODO better way to fix + + if(!($this instanceof Painting) && !($this->isPlayer() && $this->player->isSleeping !== false)){ //TODO better way to fix $x = floor($this->x); $y = floor($this->y + $this->getEyeHeight()); $z = floor($this->z); @@ -504,14 +517,14 @@ class Entity extends Position $this->harm(1, "suffocation"); } } - + //air damage if($this->isPlayer() || $this instanceof Living){ $d = $this->y + $this->getEyeHeight(); $x = floor($this->x); $y = floor($d); $z = floor($this->z); - + $id = $this->level->level->getBlockID($x, $y, $z); if($id == WATER || $id == STILL_WATER){ $f = LiquidBlock::getPercentAir($this->level->level->getBlockDamage($x, $y, $z)) - 0.1111111; @@ -529,30 +542,30 @@ class Entity extends Position $this->air = $this->maxAir; } } - return $hasUpdate; + return true; } - + public function moveFlying($strafe, $forward, $speed){ //TODO rename? - $v4 = $strafe * $strafe + $forward * $forward; - + $v4 = $strafe*$strafe + $forward*$forward; + if($v4 >= 0.0001){ $v4 = sqrt($v4); if($v4 < 1) $v4 = 1; - + $v4 = $speed / $v4; $strafe *= $v4; $forward *= $v4; - - $v5 = sin($this->yaw * M_PI / 180); - $v6 = cos($this->yaw * M_PI / 180); - - $this->speedX += $strafe * $v6 - $forward * $v5; - $this->speedZ += $forward * $v6 + $strafe * $v5; + + $v5 = sin($this->yaw * M_PI/180); + $v6 = cos($this->yaw * M_PI/180); + + $this->speedX += $strafe*$v6 - $forward*$v5; + $this->speedZ += $forward*$v6 + $strafe*$v5; } } - + public function updateEntityMovement(){} - + public function doBlocksCollision(){ $minY = floor($this->boundingBox->minY + 0.001); $maxY = floor($this->boundingBox->maxY - 0.001); @@ -560,88 +573,91 @@ class Entity extends Position $minZ = floor($this->boundingBox->minZ + 0.001); $maxX = floor($this->boundingBox->maxX - 0.001); $maxZ = floor($this->boundingBox->maxZ - 0.001); - + for($x = $minX; $x <= $maxX; ++$x){ for($y = $minY; $y <= $maxY; ++$y){ for($z = $minZ; $z <= $maxZ; ++$z){ $id = $this->level->level->getBlockID($x, $y, $z); - + if($id > 0){ StaticBlock::$prealloc[$id]::onEntityCollidedWithBlock($this->level, $x, $y, $z, $this); } } } } - + } - + public function move($dx, $dy, $dz){ $movX = $this->x; $movY = $this->y; $movZ = $this->z; - + if($this->inWeb){ $this->inWeb = false; $dx *= 0.25; $dy *= 0.05; $dz *= 0.25; - + $this->speedX = $this->speedY = $this->speedZ = 0; } - + + $savedDX = $dx; $savedDY = $dy; $savedDZ = $dz; - + $oldBB = clone $this->boundingBox; - + + $aaBBs = $this->level->getCubes($this, $this->boundingBox->addCoord($dx, $dy, $dz)); + foreach($aaBBs as $bb){ $dy = $bb->calculateYOffset($this->boundingBox, $dy); } $this->boundingBox->offset(0, $dy, 0); - + foreach($aaBBs as $bb){ $dx = $bb->calculateXOffset($this->boundingBox, $dx); } - $this->boundingBox->offset($dx, 0, 0); - + $this->boundingBox->offset($dx, 0, 0); + foreach($aaBBs as $bb){ $dz = $bb->calculateZOffset($this->boundingBox, $dz); } $this->boundingBox->offset(0, 0, $dz); - + $fallingFlag = $this->onGround || $savedDY != $dy && $savedDY < 0; - + if($this->stepHeight > 0 && $fallingFlag && ($savedDX != $dx || $savedDZ != $dz)){ $cx = $dx; $cy = $dy; $cz = $dz; - + $dx = $savedDX; $dy = $this->stepHeight; $dz = $savedDZ; $aabb1 = clone $this->boundingBox; $this->boundingBox->setBB($oldBB); - + $aaBBs = $this->level->getCubes($this, $this->boundingBox->addCoord($dx, $dy, $dz)); - + foreach($aaBBs as $bb){ $dy = $bb->calculateYOffset($this->boundingBox, $dy); } $this->boundingBox->offset(0, $dy, 0); - + foreach($aaBBs as $bb){ $dx = $bb->calculateXOffset($this->boundingBox, $dx); } $this->boundingBox->offset($dx, 0, 0); - + foreach($aaBBs as $bb){ $dz = $bb->calculateZOffset($this->boundingBox, $dz); } $this->boundingBox->offset(0, 0, $dz); - - if ($cx * $cx + $cz * $cz >= $dx * $dx + $dz * $dz) + + if ($cx*$cx + $cz*$cz >= $dx*$dx + $dz*$dz) { $dx = $cx; $dy = $cy; @@ -651,8 +667,9 @@ class Entity extends Position $this->modifySpeedY = true; $this->modifedSpeedY = 0.5; } + } - + $this->x = ($this->boundingBox->minX + $this->boundingBox->maxX) / 2; $this->y = $this->boundingBox->minY + $this->yOffset; $this->z = ($this->boundingBox->minZ + $this->boundingBox->maxZ) / 2; @@ -661,46 +678,48 @@ class Entity extends Position $this->onGround = $savedDY != $dy && $savedDY < 0.0; $this->isCollided = $this->isCollidedHorizontally || $this->isCollidedVertically; $this->updateFallState($this->speedY); - + if($savedDX != $dx) $this->speedX = 0; if($savedDY != $dy) $this->speedY = 0; if($savedDZ != $dz) $this->speedZ = 0; - + + + //TODO more stuff -> onEntityWalking - + $this->doBlocksCollision(); - + $oldFire = $this->fire; if($this->level->isBoundingBoxOnFire($this->boundingBox->contract(0.001, 0.001, 0.001))){ $this->harm(1, "fire"); if(!$this->inWater){ ++$this->fire; - if($this->fire == 0) $this->fire = 8 * 20; + if($this->fire == 0) $this->fire = 8*20; } }elseif($this->fire <= 0){ $this->fire = -$this->fireResistance; } - + if($this->inWater && $this->fire > 0){ $this->fire = -$this->fireResistance; } - + if(($oldFire > 0 && $this->fire <= 0) || ($oldFire <= 0 && $this->fire > 0)){ $this->updateMetadata(); //TODO rewrite metadata } } - + //in MCP it is called isOffsetPositionInLiquid, in 0.8 - isFree public function isFree($offsetX, $offsetY, $offsetZ){ $offsetBB = $this->boundingBox->getOffsetBoundingBox($offsetX, $offsetY, $offsetZ); - + $minX = floor($offsetBB->minX); $minY = floor($offsetBB->minY); $minZ = floor($offsetBB->minZ); $maxX = floor($offsetBB->maxX + 1); $maxY = floor($offsetBB->maxY + 1); $maxZ = floor($offsetBB->maxZ + 1); - + $hasLiquid = false; $result = false; for($x = $minX; $x < $maxX; ++$x){ @@ -718,55 +737,82 @@ class Entity extends Position if($result) return !$hasLiquid; return false; } - + + public function getRidingHeight(){ + return $this->yOffset; + } + + public function getRideHeight(){ + return $this->height * 0.75; + } + public function isInVoid(){ return $this->y < -1.6; } - + public function handlePlayerSearcher(Player $player, $dist){ - + } - + + public function positionRider($dead){ + if($this->rider != 0){ + $e = $this->level->entityList[$this->rider]; + if($e === false) return; + + $v3 = $this->getRideHeight(); + if($dead || $this->dead) $v3 = 0.01; + $v4 = $e->getRidingHeight(); + $e->setPos($this->x, $this->y + $v3+$v4, $this->z); + } + } + + public function handleRiding(){ + if($this->riding != 0){ + $e = $this->server->api->entity->get($this->riding); + if($e instanceof Entity){ + $this->speedX = $this->speedY = $this->speedZ = 0; + + $e->positionRider($e->dead); + + $this->fallDistance = 0; + }else{ + ConsoleAPI::warn("$this is riding invalid entity({$this->riding})"); + } + } + } + public function update($now){ if($this->closed === true){ return false; } - + if($this->check === false){ $this->lastUpdate = $now; return; } - $hasUpdate = $this->environmentUpdate($now); + $this->environmentUpdate($now); if($this->closed === true){ return false; } ++$this->counter; - + + if($this->riding != 0){ + $this->handleRiding(); + } + if($this->isStatic === false){ if(!$this->isPlayer()){ $this->updateLast(); $this->updatePosition(); //TODO shouldnt be called in Entity $this->updateEntityMovement(); - $update = false; - if($this->lastX != $this->x || $this->lastZ != $this->z || $this->lastY != $this->z){ - //$this->server->api->handle("entity.move", $this); - $update = true; - }elseif ($this->lastYaw != $this->yaw || $this->lastPitch != $this->pitch || $this->lastHeadYaw != $this->headYaw) { - $update = true; - } - - if($update === true){ - $hasUpdate = true; - } - } else{ $prevGroundState = $this->onGround; $this->onGround = false; $this->speedX = -($this->lastX - $this->x); $this->speedY = -($this->lastY - $this->y); $this->speedZ = -($this->lastZ - $this->z); - + $contractedCollisionBB = $this->boundingBox->contract(0.001, 0.001, 0.001); $fireMinX = floor($contractedCollisionBB->minX); $fireMinY = floor($contractedCollisionBB->minY); @@ -774,58 +820,110 @@ class Entity extends Position $fireMaxX = floor($contractedCollisionBB->maxX + 1); $fireMaxY = floor($contractedCollisionBB->maxY + 1); $fireMaxZ = floor($contractedCollisionBB->maxZ + 1); - + $bbbottom = $this->boundingBox->addCoord(0, -0.05, 0); $bbbottom->minX = round($this->x, 3) - $this->radius; $bbbottom->maxX = round($this->x, 3) + $this->radius; $bbbottom->minZ = round($this->z, 3) - $this->radius; $bbbottom->maxZ = round($this->z, 3) + $this->radius; - - $handleFire = false; - $handleCactus = false; - for($x = floor($this->boundingBox->minX); $x < ceil($this->boundingBox->maxX); ++$x){ - for($z = floor($this->boundingBox->minZ); $z < ceil($this->boundingBox->maxZ); ++$z){ - for($y = floor($this->boundingBox->minY - 1); $y < ceil($this->boundingBox->maxY); ++$y){ - $intersects = 0; + + $maxx = $this->x; + $minx = $this->lastX; + $maxy = $this->y; + $miny = $this->lastY; + $maxz = $this->z; + $minz = $this->lastZ; + + if($this->x < $this->lastX){ + $minx = $this->x; + $maxx = $this->lastX; + } + + if($this->y < $this->lastY){ + $miny = $this->y; + $maxy = $this->lastY; + } + + if($this->z < $this->lastZ){ + $minz = $this->z; + $maxz = $this->lastZ; + } + + $useOldGroundCheck = false; + $distBetweenLastAndCurrent = sqrt(($this->lastX-$this->x)*($this->lastX-$this->x) + ($this->lastY-$this->y)*($this->lastY-$this->y) + ($this->lastZ-$this->z)*($this->lastZ-$this->z)); + if($distBetweenLastAndCurrent > 10){ + ConsoleAPI::warn("{$this->player} is moving too fast! (Old: {$this->lastX} {$this->lastY} {$this->lastZ}, New: {$this->x} {$this->y} {$this->z}). Skipping new onground check!"); + $useOldGroundCheck = true; + goto skip_new_onground_check; + } + $bbGround = new AxisAlignedBB($minx - $this->radius, $miny, $minz - $this->radius, $maxx + $this->radius, $maxy, $maxz + $this->radius); + + for($x = floor($bbGround->minX); $x <= ceil($bbGround->maxX); ++$x){ + for($z = floor($bbGround->minZ); $z <= ceil($bbGround->maxZ); ++$z){ + for($y = floor($bbGround->minY-1); $y <= ceil($bbGround->maxY); ++$y){ $id = $this->level->level->getBlockID($x, $y, $z); $bounds = StaticBlock::$prealloc[$id]::getCollisionBoundingBoxes($this->level, $x, $y, $z, $this); foreach($bounds as $bb){ - if($bbbottom->intersectsWith($bb)){ - ++$intersects; + if($bbGround->intersectsWith($bb)){ + $this->onGround = true; } } - - if($id == WATER || $id === STILL_WATER || $id === COBWEB || $id == LAVA || $id === STILL_LAVA){ + } + } + } + + skip_new_onground_check: + + $handleFire = false; + $handleCactus = false; + + for($x = floor($this->boundingBox->minX); $x < ceil($this->boundingBox->maxX); ++$x){ + for($z = floor($this->boundingBox->minZ); $z < ceil($this->boundingBox->maxZ); ++$z){ + for($y = floor($this->boundingBox->minY - 1); $y < ceil($this->boundingBox->maxY); ++$y){ + [$id, $meta] = $this->level->level->getBlock($x, $y, $z); + + if($useOldGroundCheck){ + $intersects = 0; + $bounds = StaticBlock::$prealloc[$id]::getCollisionBoundingBoxes($this->level, $x, $y, $z, $this); + foreach($bounds as $bb){ + if($bbbottom->intersectsWith($bb)){ + ++$intersects; + } + } + } + + + if($id == WATER || $id === STILL_WATER || $id === COBWEB || $id == LAVA || $id === STILL_LAVA){ $this->notOnGroundTicks = 0; } - - intersects: - if($y <= floor($this->boundingBox->minY) && !$this->onGround){ - if($intersects > 0) $this->onGround = count($bounds) > 0; + + if($useOldGroundCheck){ + intersects: + if($y <= floor($this->boundingBox->minY) && !$this->onGround){ + if($intersects > 0) $this->onGround = count($bounds) > 0; + } } + if($y >= floor($this->boundingBox->minY)){ - $block = $this->level->level->getBlock($x, $y, $z); - $id = $block[0]; - $meta = $block[1]; $handleFire = $handleFire || (($id == FIRE || $id == STILL_LAVA || $id == LAVA) && $x >= $fireMinX && $x < $fireMaxX && $y >= $fireMinY && $y < $fireMaxY && $z >= $fireMinZ && $z < $fireMaxZ); $handleCactus = $handleCactus || ($id == CACTUS && $x >= $fireMinX && $x < $fireMaxX && $y >= $fireMinY && $y < $fireMaxY && $z >= $fireMinZ && $z < $fireMaxZ); - + if($id === WATER || $id === STILL_WATER || $id === COBWEB){ $this->fallDistance = 0; $this->fallStart = $this->y; } } - + } } } - + if($prevGroundState == $this->onGround && !$this->onGround && $this->player->isSleeping == false && !$this->dead){ //isSleeping may be a vector ++$this->notOnGroundTicks; - }elseif($this->onGround){ + }else if($this->onGround){ $this->notOnGroundTicks = 0; } - + if($this->notOnGroundTicks > 80){ //~70 ticks is needed to reach from 127 to 0 if(($this->player->gamemode & 1) != CREATIVE && !$this->player->blocked && $this->player->spawned){ //survival(0), adventure(2) if(!Entity::$allowFly){ @@ -833,20 +931,21 @@ class Entity extends Position } } } - + + if($this->isOnLadder()){ $this->fallDistance = 0; $this->notOnGroundTicks = 0; $this->fallStart = $this->y; } - + if(!$this->onGround && $prevGroundState){ $this->fallStart = $this->y; } - - $this->updateFallState(($this->speedY <=> 0) * 0.1); + + $this->updateFallState(($this->speedY <=> 0)*0.1); if($this->onGround) $this->fallDistance = 0; - + if($handleCactus){ $this->harm(1, "cactus"); } @@ -855,67 +954,66 @@ class Entity extends Position $this->harm(1, "fire"); if(!$this->inWater){ ++$this->fire; - if($this->fire == 0) $this->fire = 8 * 20; + if($this->fire == 0) $this->fire = 8*20; } }elseif($this->fire <= 0){ $this->fire = -$this->fireResistance; } - + if($this->inWater && $this->fire > 0){ $this->fire = -$this->fireResistance; } - + if(($oldFire > 0 && $this->fire <= 0) || ($oldFire <= 0 && $this->fire > 0)){ $this->updateMetadata(); //TODO rewrite metadata } - - $hasUpdate = true; } } - + + $this->counterUpdate(); - + if($this->isPlayer()){ $this->updateMovement(); } - + if($this->isPlayer()){ $this->player->entityTick(); } - - $this->needsUpdate = $hasUpdate; + + $this->needsUpdate = true; $this->lastUpdate = $now; } public function isOnLadder(){ - $x = (int) $this->x; - $y = (int) $this->boundingBox->minY; - $z = (int) $this->z; + $x = (int)$this->x; + $y = (int)$this->boundingBox->minY; + $z = (int)$this->z; return $this->level->level->getBlockID($x, $y, $z) === LADDER; } - + public function fall(){ if($this->isPlayer()){ - + $x = floor($this->x); $y = floor($this->y - 1); //TODO not 1 $z = floor($this->z); $bid = $this->level->level->getBlockID($x, $y, $z); if($bid > 0){ $clz = StaticBlock::getBlock($bid); - $clz::fallOn($this->level, $x, $y, $z, $this, ceil($this->fallStart - $this->y)); + $clz::fallOn($this->level, $x, $y, $z, $this, $this->fallStart - $this->y); } - + $dmg = ceil($this->fallStart - $this->y - 3); if($dmg > 0){ $this->harm($dmg, "fall"); } } } - + public function canBeShot(){ return $this->isPlayer(); } - + public function updateFallState($fallTick){ if($this->onGround && $this->fallDistance > 0){ $this->fall(); @@ -923,16 +1021,17 @@ class Entity extends Position }elseif($fallTick < 0){ $this->fallDistance -= $fallTick; } - + } - + public function updateMovement() { if($this->closed === true){ return false; } $now = microtime(true); - if($this->isStatic === false and ($this->lastX != $this->x or $this->lastY != $this->y or $this->lastZ != $this->z or $this->lastYaw != $this->yaw or $this->lastPitch != $this->pitch or $this->lastHeadYaw != $this->headYaw)){ + if($this->isStatic === false && ($this->lastX != $this->x || $this->lastY != $this->y || $this->lastZ != $this->z || $this->lastYaw != $this->yaw || $this->lastPitch != $this->pitch || $this->lastHeadYaw != $this->headYaw || $this->forceUpdateMovement)){ + $this->forceUpdateMovement = false; if($this->class === ENTITY_PLAYER){ if($this->server->api->handle("entity.move", $this) === false){ if($this->class === ENTITY_PLAYER){ @@ -946,19 +1045,21 @@ class Entity extends Position $pk = new MovePlayerPacket(); $pk->eid = $this->eid; $pk->x = $this->x; - $pk->y = $this->y; + $pk->y = $this->y - ($this->player->isSleeping ? 1.7375 : 0); $pk->z = $this->z; $pk->yaw = $this->yaw; $pk->pitch = $this->pitch; - $pk->bodyYaw = $this->yaw; - $this->server->api->player->broadcastPacket($players, $pk); + $pk->bodyYaw = $this->headYaw; + foreach($players as $player){ + if($player->hasEntity($this) && !$this->player->isInvisibleFor($player)) $player->entityQueueDataPacket(clone $pk); + } } } } } $this->lastUpdate = $now; } - + /** * Handle fall out of world */ @@ -970,11 +1071,11 @@ class Entity extends Position $this->close(); } } - + public function getEyeHeight(){ //TODO in vanilla player's eyeHeight is 0.12 return $this->isPlayer() ? $this->height - 0.12 : $this->height * 0.85; } - + public function interactWith(Entity $e, $action) { if($this->isPlayer() and ($this->server->api->getProperty("pvp") == false or $this->server->difficulty <= 0 or ($this->player->gamemode & 0x01) === 0x01)){ @@ -985,11 +1086,7 @@ class Entity extends Position $slot = $e->player->getHeldItem(); $damage = $slot->getDamageAgainstOf($this); $this->harm($damage, $e->eid); - if($slot->isTool() && (!$this->isPlayer() || ($this->player->gamemode & 0x01) === 0)){ - if($slot->useOn($this) and $slot->getMetadata() >= $slot->getMaxDurability()){ - $e->player->removeItem($slot->getID(), $slot->getMetadata(), 1, true); - } - } + $slot->hurtEnemy($this, $e->player); //TODO dont try destroying if harm was cancelled? return true; } return false; @@ -1051,7 +1148,7 @@ class Entity extends Position ], 1 => [ "type" => 1, - "value" => (int) $this->air + "value" => (int)$this->air ], 14 => [ "type" => 0, @@ -1089,78 +1186,87 @@ class Entity extends Position $this->server->api->dhandle("entity.metadata", $this); } - public function spawn($player) - { - if(!($player instanceof Player)){ - $player = $this->server->api->player->get($player); + public function sendLinkPackets(Player $player){ + if($this->rider != 0){ + $e = $this->level->entityList[$this->rider] ?? false; + + if($e != false) { + $e->spawn($player); + $player->eventHandler(["rider" => $this->rider, "riding" => $this->eid, "type" => 0], "entity.link"); + } } + if($this->riding != 0){ + $e = $this->level->entityList[$this->riding] ?? false; + + if($e != false) { + $e->spawn($player); + $player->eventHandler(["rider" => $this->eid, "riding" => $this->riding, "type" => 0], "entity.link"); + } + } + } + + /** + * @param Player $player + * @return boolean + */ + public function spawn(Player $player) + { if($player->eid === $this->eid or $this->closed !== false or ($player->level !== $this->level and $this->class !== ENTITY_PLAYER)){ return false; } - switch($this->class) { - case ENTITY_PLAYER: - if($this->player->connected !== true or $this->player->spawned === false){ - return false; - } - if($this->player->gamemode === SPECTATOR){ - break; - } - $pk = new AddPlayerPacket(); - $pk->clientID = 0; // $this->player->clientID; - $pk->username = $this->player->username; - $pk->eid = $this->eid; - $pk->x = $this->x; - $pk->y = $this->y; - $pk->z = $this->z; - $pk->yaw = 0; - $pk->pitch = 0; - $pk->itemID = 0; - $pk->itemAuxValue = 0; - $pk->metadata = $this->getMetadata(); - $player->directDataPacket($pk, 2, true); - - $pk = new SetEntityMotionPacket(); - $pk->eid = $this->eid; - $pk->speedX = $this->speedX; - $pk->speedY = $this->speedY; - $pk->speedZ = $this->speedZ; - $player->dataPacket($pk); - - $pk = new PlayerEquipmentPacket(); - $pk->eid = $this->eid; - $pk->item = $this->player->getSlot($this->player->slot)->getID(); - $pk->meta = $this->player->getSlot($this->player->slot)->getMetadata(); - $pk->slot = 0; - $player->dataPacket($pk); - $this->player->sendArmor($player); - break; - case ENTITY_FALLING: - $pk = new AddEntityPacket(); - $pk->eid = $this->eid; - $pk->type = $this->type; - $pk->x = $this->x; - $pk->y = $this->y; - $pk->z = $this->z; - $pk->speedX = $this->speedX; - $pk->speedY = $this->speedY; - $pk->speedZ = $this->speedZ; - $pk->did = -$this->data["Tile"]; - $player->dataPacket($pk); + if($this->class != ENTITY_PLAYER) return false; + if($this->player->connected !== true or $this->player->spawned === false) return false; + if(!$player->hasEntity($this)){ + $player->addEntity($this); + if($this->level != $player->entity->level || $this->player->gamemode === SPECTATOR) $this->player->setInvisibleFor($player, true, send:false); + $pk = new AddPlayerPacket(); + $pkm = new MovePlayerPacket(); + $pk->clientID = 0; // $this->player->clientID; + $pk->username = $this->player->username; + $pkm->eid = $pk->eid = $this->eid; + + if($this->player->isInvisibleFor($player)){ + $pkm->x = $pk->x = -256; + $pkm->y = $pk->y = 128; + $pkm->z = $pk->z = -256; + $pkm->yaw = $pk->yaw = 0; + $pkm->pitch = $pk->pitch = 0; + $pkm->bodyYaw = 0; + }else{ + $pkm->x = $pk->x = $this->x; + $pkm->y = $pk->y = $this->y; + $pkm->z = $pk->z = $this->z; + $pkm->yaw = $pk->yaw = $this->yaw; + $pkm->pitch = $pk->pitch = $this->pitch; + $pkm->bodyYaw = $this->headYaw; + } + + $pk->itemID = 0; + $pk->itemAuxValue = 0; + $pk->metadata = $this->getMetadata(); + $player->entityQueueDataPacket($pk); + //AddPlayerPacket doesnt read yaw correctly in vanilla(uses PacketUtil::Rot_degreesToChar instead of PacketUtil::Rot_charToDegrees) + $player->entityQueueDataPacket($pkm); + + $pk = new PlayerEquipmentPacket(); + $pk->eid = $this->eid; + $pk->item = $this->player->getSlot($this->player->slot)->getID(); + $pk->meta = $this->player->getSlot($this->player->slot)->getMetadata(); + $pk->slot = 0; + $player->entityQueueDataPacket($pk); + $this->player->sendArmor($player); + + $this->sendLinkPackets($player); + return true; } - - if($this->linkedEntity != 0 && $this->isRider){ - $player->eventHandler(["rider" => $this->eid, "riding" => $this->linkedEntity, "type" => 0], "entity.link"); //TODO fix it - } - + return false; } - + public function counterUpdate(){ if($this->knockbackTime > 0){ --$this->knockbackTime; } - if($this->delayBeforePickup > 0){ - --$this->delayBeforePickup; - } + if($this->moveTime > 0){ --$this->moveTime; } @@ -1170,16 +1276,23 @@ class Entity extends Position if($this->idleTime > 0){ --$this->idleTime; } - + + if($this->inAction){ ++$this->inActionCounter; } } - + public function close() { if($this->closed === false){ $this->closed = true; + + + $rider = $this->level->entityList[$this->rider] ?? false; + if($rider != false) $rider->setRiding(null); + $this->setRiding(null); + $this->server->api->entity->remove($this->eid); } } @@ -1215,7 +1328,7 @@ class Entity extends Position public function updateAABB() { $this->boundingBox->setBounds( - $this->x - $this->radius, $this->y - $this->yOffset, $this->z - $this->radius, + $this->x - $this->radius, $this->y - $this->yOffset, $this->z - $this->radius, $this->x + $this->radius, $this->y + $this->height - $this->yOffset, $this->z + $this->radius ); } @@ -1225,7 +1338,7 @@ class Entity extends Position $this->sendMoveUpdate(); $this->updateAABB(); } - + public function setPosition(Vector3 $pos, $yaw = false, $pitch = false, $headYaw = false) { $this->x = $pos->x; @@ -1237,12 +1350,12 @@ class Entity extends Position if($pitch !== false){ $this->pitch = $pitch; } - + if($headYaw !== false) $this->headYaw = $headYaw; } public function inBlockNonVector($x, $y, $z, $radius = 0.8) { - return $y == ceil($this->y) || $y == (ceil($this->y) + 1) && max(abs($x - ($this->x - 0.5)), abs($z - ($this->z - 0.5))); + return $y == ceil($this->y) || $y == (ceil($this->y)+1) && max(abs($x - ($this->x-0.5)), abs($z - ($this->z-0.5))); } public function inBlock(Vector3 $block, $radius = 0.8) { @@ -1266,7 +1379,7 @@ class Entity extends Position { $me = new Vector2($this->x - 0.5, $this->z - 0.5); $diff = $this->y - $pos->y; - if($me->distance(new Vector2($pos->x, $pos->z)) < $radius and $diff > -0.7 and $diff < 1.6){ + if($me->distance(new Vector2($pos->x, $pos->z)) < $radius and $diff > - 0.7 and $diff < 1.6){ return true; } return false; @@ -1274,7 +1387,7 @@ class Entity extends Position public function resetSpeed() { - $this->speedMeasure = [0, 0, 0, 0, 0, 0, 0]; + $this->speedMeasure = array(0, 0, 0, 0, 0, 0, 0); } public function getSpeed() @@ -1324,7 +1437,7 @@ class Entity extends Position "speedX" => $this->speedX, "speedY" => $this->speedY, "speedZ" => $this->speedZ, - + ]; if($this->class === ENTITY_OBJECT){ $data["TileX"] = $this->x; @@ -1340,12 +1453,12 @@ class Entity extends Position "Damage" => $this->meta, "Count" => $this->stack, ]; - + $data["id"] = 64; //ty shoghicp } return $data; } - + public function updateLast() { $this->lastX = $this->x; @@ -1378,30 +1491,30 @@ class Entity extends Position // $dmg = 0; // break; case 1: - $dmg = (int) ($dmg / 3) + 1; + $dmg = (int)($dmg / 3) + 1; break; case 3: - $dmg = 3 * (int) ($dmg / 2); + $dmg = 3 * (int)($dmg / 2); break; } } } - + $dmg = $this->applyArmor($dmg, $cause); - $ret = $this->setHealth(max(-128, $this->getHealth() - ((int) $dmg)), $cause, $force); - + $ret = $this->setHealth(max(- 128, $this->getHealth() - ((int) $dmg)), $cause, $force); + if($ret && is_numeric($cause) && ($entity = $this->server->api->entity->get($cause)) != false){ //TODO simplify $this->attackTimeout = 10; } - + if ($ret != false && $this->hasKnockback && is_numeric($cause) && ($entity = $this->server->api->entity->get($cause)) != false) { - + $d = $entity->x - $this->x; for ($d1 = $entity->z - $this->z; $d * $d + $d1 * $d1 < 0.0001; $d1 = (lcg_value() - lcg_value()) * 0.01) { $d = (lcg_value() - lcg_value()) * 0.01; } - + $this->knockBack($d, $d1); if($this->isPlayer()){ $pk = new SetEntityMotionPacket(); @@ -1431,56 +1544,49 @@ class Entity extends Position public function heal($health, $cause = "generic") { - return $this->setHealth(min(20, $this->getHealth() + ((int) $health)), $cause); + return $this->setHealth(min(20, $this->getHealth() + ((int) $health)), $cause, allowHarm: false); } - - public function stopRiding(){ - if(isset($this->level->entityList[$this->linkedEntity])){ - $e = $this->level->entityList[$this->linkedEntity]; - if(!$e->dead && !$e->closed){ - $this->linkedEntity = 0; - $e->linkedEntity = 0; - $this->server->api->dhandle("entity.link", ["rider" => $this->eid, "riding" => -1, "type" => 1]); - $this->server->api->dhandle("entity.link", ["rider" => $this->linkedEntity, "riding" => -1, "type" => 1]); - $this->isRider = false; - } - }else{ - $this->linkedEntity = 0; - } - } - + public function setPos($x, $y, $z){ $this->x = $x; $this->y = $y; $this->z = $z; - + $this->boundingBox->minX = $x - $this->radius; $this->boundingBox->minY = ($y - $this->yOffset); //TODO what is this + $this->ySize; $this->boundingBox->minZ = $z - $this->radius; - + $this->boundingBox->maxX = $x + $this->radius; $this->boundingBox->maxY = $this->boundingBox->minY + $this->height; $this->boundingBox->maxZ = $z + $this->radius; } - - public function setRiding(Entity $e, $type = 0) + + /** + * Sets entity that is being ridden by this entity. + * @param ?Entity $riding + */ + public function setRiding(?Entity $riding) { - if(!isset($this->level->entityList[$e->eid])){ - ConsoleAPI::warn("Tried linking $this with $e that doesnt exist in the world!"); - return; - } - - if($this->linkedEntity == $e->eid || $e->eid == $this->eid){ - $this->linkedEntity = 0; - $e->linkedEntity = 0; - $this->server->api->dhandle("entity.link", ["rider" => $this->eid, "riding" => $e->eid, "type" => $type]); + if($riding == null){ + if($this->riding != 0){ + $riding = $this->server->api->entity->get($this->riding); + if($riding instanceof Entity){ + $riding->rider = 0; + }else{ + ConsoleAPI::warn("SR Failed to get entity that is being ridden by $this"); + } + } + $this->riding = 0; }else{ - $this->linkedEntity = $e->eid; - $e->linkedEntity = $this->eid; - $this->isRider = true; - $this->server->api->dhandle("entity.link", ["rider" => $this->eid, "riding" => $e->eid, "type" => 0]); + if(!isset($this->level->entityList[$riding->eid])){ + ConsoleAPI::warn("Tried linking $this with $riding that doesnt exist in the world!"); + return; + } + $this->riding = $riding->eid; + $riding->rider = $this->eid; + } - + $this->server->api->dhandle("entity.link", ["rider" => $this->eid, "riding" => $this->riding, "type" => 0]); } public function isPlayer() @@ -1491,7 +1597,7 @@ class Entity extends Position public function sendMoveUpdate() { if($this->class === ENTITY_PLAYER){ - $this->player->teleport(new Vector3($this->x, $this->y, $this->z), false, false, true, false); + //$this->player->teleport(new Vector3($this->x, $this->y, $this->z), false, false, true, false); } } @@ -1513,23 +1619,36 @@ class Entity extends Position foreach($this->player->armor as $slot => $part){ if($part instanceof ArmorItem){ $pnts += $part->getDamageReduceAmount(); - $this->player->damageArmorPart($slot, $part); } } - $this->player->sendArmor($this->player); } return $pnts; } + + public function hurtArmor($dmg){ + if($this->isPlayer()){ + $v2 = (int)($dmg / 4); + if($v2 < 1) $v2 = 1; + + foreach($this->player->armor as $slot => $part){ + $part->hurtAndBreak($v2, $this->player, helditem: false); + if($part->count <= 0) $this->player->setArmor($slot, BlockAPI::getItem(0, 0, 0), send: false); + } + $this->player->sendArmor(); + } + } + public function applyArmor($damage, $cause){ if(is_numeric($cause) || $cause === "explosion"){ $var3 = 25 - $this->getArmorValue(); + $this->hurtArmor($damage); //uses damage without armor affection $var4 = $damage * $var3 + $this->carryoverDamage; $damage = $var4 / 25; $this->carryoverDamage = $var4 % 25; } return $damage; } - + public function setHealth($health, $cause = "generic", $force = false, $allowHarm = true) { $health = (int) $health; @@ -1546,32 +1665,28 @@ class Entity extends Position }elseif($health === $this->health and !$this->dead){ $harm = true; } - - if($this->server->api->dhandle("entity.health.change", [ + + if($this->server->api->dhandle("entity.health.change", array( "entity" => $this, "eid" => $this->eid, "health" => $health, "cause" => $cause - ]) !== false or $force === true){ - $this->health = min(127, max(-127, $health)); + )) !== false or $force === true){ + + $this->health = min(127, max(- 127, $health)); if($harm === true && $allowHarm){ $pk = new EntityEventPacket; $pk->eid = $this->eid; $pk->event = EntityEventPacket::ENTITY_DAMAGE; foreach($this->level->players as $p){ - if(($p->entity instanceof Entity) && $p->entity->eid == $this->eid){ - $pk2 = clone $pk; - $pk2->eid = 0; - $p->dataPacket($pk2); - }else{ - $p->dataPacket(clone $pk); - } + if($p->hasEntity($this)) $p->entityQueueDataPacket(clone $pk); } } + if($this->player instanceof Player){ $pk = new SetHealthPacket(); $pk->health = $this->health; - $this->player->dataPacket($pk); + if($this->player->hasEntity($this)) $this->player->entityQueueDataPacket($pk); } if($this->health <= 0 and $this->dead === false){ $this->makeDead($cause); @@ -1589,7 +1704,7 @@ class Entity extends Position $this->height = $h; $this->radius = $w / 2; } - + public function makeDead($cause){ if($this->server->api->dhandle("entity.death", ["entity" => $this, "cause" => $cause]) === false) return false; $this->spawnDrops(); @@ -1608,12 +1723,16 @@ class Entity extends Position $pk->z = -256; $pk->yaw = 0; $pk->pitch = 0; - $this->server->api->player->broadcastPacket($this->level->players, $pk); + foreach($this->level->players as $player){ + if($player->hasEntity($this) && $player != $this->player) $player->entityQueueDataPacket(clone $pk); + } }else{ $pk = new EntityEventPacket; $pk->eid = $this->eid; $pk->event = EntityEventPacket::ENTITY_DEAD; - $this->server->api->player->broadcastPacket($this->level->players, $pk); + foreach($this->level->players as $player){ + if($player->hasEntity($this)) $player->entityQueueDataPacket(clone $pk); + } } if($this->player instanceof Player){ @@ -1634,11 +1753,11 @@ class Entity extends Position } } } - + public function getAttackDamage(){ return 0; } - + public function setSpeed($s) { $this->speed = $s; @@ -1669,37 +1788,44 @@ class Entity extends Position public function __toString() { - return "Entity(x={$this->x},y={$this->y},z={$this->z},level=" . $this->level->getName() . ",class={$this->class},type={$this->type})"; + return "Entity(eid={$this->eid},x={$this->x},y={$this->y},z={$this->z},level=" . $this->level->getName() . ",class={$this->class},type={$this->type})"; } - + /** * Debug */ public function printSpeed($add = ""){ ConsoleAPI::debug("$add {$this->speedX}:{$this->speedY}:{$this->speedZ}"); } - + /* * Deprecated methods. * Those methods were left only for compability with older plugins */ /** * - * @deprecated Use {@link getHeightOf} or {@link getWidthOf} instead + * @deprecated Use {@link Entity::getHeightOf} or {@link Entity::getWidthOf} instead * @throws Exception */ public static function getSizeOf($e) { throw new Exception("Use getHeightOf or getWidthOf method instead of this."); } - + + /** - * - * @deprecated Use {@link getHeight} or {@link getWidth} instead + * @deprecated Use {@link Entity::getHeight} or {@link Entity::getWidth} instead * @throws Exception */ public function getSize() { throw new Exception("Use getHeight or getWidth method instead of this."); } + + /** + * @deprecated use {@link Entity::setRiding} instead + */ + public function stopRiding(){ + $this->setRiding(null); + } } diff --git a/src/entity/Projectile.php b/src/entity/Projectile.php index ed9df100..52817b89 100644 --- a/src/entity/Projectile.php +++ b/src/entity/Projectile.php @@ -78,7 +78,7 @@ abstract class Projectile extends Entity{ $this->lastSpeedY = $this->speedY; $this->lastSpeedZ = $this->speedZ; $this->needsUpdate = true; - $this->handleWaterMovement(); //TODO: maybe just call parent::update(); ? + $this->handleWaterMovement(); if($this->fire > 0){ if(!$this->isImmuneToFire){ if(($this->fire % 20) == 0){ @@ -199,19 +199,26 @@ abstract class Projectile extends Entity{ return $data; } - public function spawn($player) + + public function spawn(Player $player) { - $pk = new AddEntityPacket(); - $pk->eid = $this->eid; - $pk->type = $this->type; - $pk->x = $this->x; - $pk->y = $this->y; - $pk->z = $this->z; - $pk->speedX = $this->speedX; - $pk->speedY = $this->speedY; - $pk->speedZ = $this->speedZ; - $pk->did = 0; - $player->dataPacket($pk); + if(!$player->hasEntity($this)){ + $player->addEntity($this); + $pk = new AddEntityPacket(); + $pk->eid = $this->eid; + $pk->type = $this->type; + $pk->x = $this->x; + $pk->y = $this->y; + $pk->z = $this->z; + $pk->speedX = $this->speedX; + $pk->speedY = $this->speedY; + $pk->speedZ = $this->speedZ; + $pk->did = 0; + $player->entityQueueDataPacket($pk); + $this->sendLinkPackets($player); + return true; + } + return false; } } \ No newline at end of file diff --git a/src/entity/ai/MobController.php b/src/entity/ai/MobController.php index 586d93fe..6c0e4c52 100644 --- a/src/entity/ai/MobController.php +++ b/src/entity/ai/MobController.php @@ -2,7 +2,6 @@ class MobController { - public static $ADVANCED = false; public static $AUTOJUMP = false; public static $landed = false; public static $DANGEROUS_BLOCKS = [ @@ -92,6 +91,7 @@ class MobController public function movementTick(){ $this->entity->moveForward = 0; + if($this->updateMove){ $this->updateMove = false; $v1 = floor($this->entity->boundingBox->minY + 0.5); diff --git a/src/entity/ai/tasks/TaskEatTileGoal.php b/src/entity/ai/tasks/TaskEatTileGoal.php index 4f69a7a8..a81ef6ca 100644 --- a/src/entity/ai/tasks/TaskEatTileGoal.php +++ b/src/entity/ai/tasks/TaskEatTileGoal.php @@ -5,7 +5,9 @@ class TaskEatTileGoal extends TaskBase public function onStart(EntityAI $ai) { $this->selfCounter = 40; - $ai->entity->server->api->player->broadcastPacket($ai->entity->level->players, new EntityEventPacket($ai->entity->eid, EntityEventPacket::ENTITY_ANIM_10)); + foreach($ai->entity->level->players as $player){ + if($player->hasEntity($ai->entity)) $player->entityQueueDataPacket(new EntityEventPacket($ai->entity->eid, EntityEventPacket::ENTITY_ANIM_10)); + } } public function onEnd(EntityAI $ai) diff --git a/src/entity/ai/tasks/TaskFollowParent.php b/src/entity/ai/tasks/TaskFollowParent.php index 9c5a989d..dcb0bcf4 100644 --- a/src/entity/ai/tasks/TaskFollowParent.php +++ b/src/entity/ai/tasks/TaskFollowParent.php @@ -2,6 +2,7 @@ class TaskFollowParent extends TaskBase { + public $speedMultiplier; public function __construct($speed){ $this->speedMultiplier = $speed; } diff --git a/src/entity/ai/tasks/TaskMate.php b/src/entity/ai/tasks/TaskMate.php index d073bd1a..6b39692d 100644 --- a/src/entity/ai/tasks/TaskMate.php +++ b/src/entity/ai/tasks/TaskMate.php @@ -2,6 +2,7 @@ class TaskMate extends TaskBase { + public $speedMultiplier; public function __construct($speed){ $this->speedMultiplier = $speed; } @@ -41,7 +42,7 @@ class TaskMate extends TaskBase /** * @var Animal $baby */ - $baby = $ai->entity->breed(); + $baby = $ai->entity->breed($entpar2); //this.theAnimal.setGrowingAge(6000); TODO growing age? //this.targetMate.setGrowingAge(6000); diff --git a/src/entity/ai/tasks/TaskRangedAttack.php b/src/entity/ai/tasks/TaskRangedAttack.php index dfe2dee1..ab1f3d42 100644 --- a/src/entity/ai/tasks/TaskRangedAttack.php +++ b/src/entity/ai/tasks/TaskRangedAttack.php @@ -5,6 +5,7 @@ class TaskRangedAttack extends \TaskBase public $server; public $attackCounter = 0; public $seenTicks = 0; + public $rangeSquared = 0; public function __construct($speed, $range){ $this->speedMultiplier = $speed; $this->rangeSquared = $range * $range; @@ -14,7 +15,6 @@ class TaskRangedAttack extends \TaskBase public function onStart(EntityAI $ai) { $this->selfCounter = 1; - $this->ticksNoSeen = 0; } public function onEnd(EntityAI $ai) @@ -67,7 +67,7 @@ class TaskRangedAttack extends \TaskBase $arrow = $this->server->api->entity->add($selfEntity->level, ENTITY_OBJECT, OBJECT_ARROW, $d); $arrow->shotByEntity = true; $arrow->shooterEID = $selfEntity->eid; - $posY = ($target->y + $target->getEyeHeight() - 0.1); + $posY = ($selfEntity->y + $selfEntity->getEyeHeight() - 0.1); $diffX = $target->x - $selfEntity->x; $diffY = ($target->boundingBox->minY + ($target->height / 3)) - $posY; $diffZ = $target->z - $selfEntity->z; diff --git a/src/entity/ai/tasks/TaskTempt.php b/src/entity/ai/tasks/TaskTempt.php index 5dd67c66..9bec4858 100644 --- a/src/entity/ai/tasks/TaskTempt.php +++ b/src/entity/ai/tasks/TaskTempt.php @@ -2,6 +2,8 @@ class TaskTempt extends TaskBase { + public $speedMultiplier; + public $targetDistance; public function __construct($speed){ $this->speedMultiplier = $speed; $this->targetDistance = 10 * 10; diff --git a/src/entity/animal/Chicken.php b/src/entity/animal/Chicken.php index 8f66e5f8..52ae5227 100644 --- a/src/entity/animal/Chicken.php +++ b/src/entity/animal/Chicken.php @@ -7,7 +7,7 @@ class Chicken extends Animal{ $this->timeUntilEgg = mt_rand(0,6000) + 6000; $this->setSize(0.4, 0.7); parent::__construct($level, $eid, $class, $type, $data); - $this->setHealth($this->data["Health"] ?? 4, "generic"); + $this->setHealth($this->data["Health"] ?? 4, "generic", allowHarm: false); $this->setName('Chicken'); $this->setSpeed(0.25); diff --git a/src/entity/animal/Cow.php b/src/entity/animal/Cow.php index 86a5358a..151d7a4b 100644 --- a/src/entity/animal/Cow.php +++ b/src/entity/animal/Cow.php @@ -5,7 +5,7 @@ class Cow extends Animal{ function __construct(Level $level, $eid, $class, $type = 0, $data = []){ $this->setSize(0.9, 1.3); parent::__construct($level, $eid, $class, $type, $data); - $this->setHealth($this->data["Health"] ?? 10, "generic"); + $this->setHealth($this->data["Health"] ?? 10, "generic", allowHarm: false); $this->setName("Cow"); $this->setSpeed(0.2); $this->ai->addTask(new TaskRandomWalk(0.8)); @@ -26,7 +26,7 @@ class Cow extends Animal{ if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){ $slot = $e->player->getHeldItem(); if($slot->getID() === BUCKET && $slot->getMetadata() === 0){ - $e->player->removeItem($slot->getID(), $slot->getMetadata(), 1, true); //remove only 1 bucket + $e->player->consumeSingleItem(); $e->player->addItem(BUCKET, 1, 1, true); return true; } diff --git a/src/entity/animal/Pig.php b/src/entity/animal/Pig.php index 9b48b6f8..bc564beb 100644 --- a/src/entity/animal/Pig.php +++ b/src/entity/animal/Pig.php @@ -6,7 +6,7 @@ class Pig extends Animal implements Rideable{ public function __construct(Level $level, $eid, $class, $type = 0, $data = []){ $this->setSize(0.9, 0.9); parent::__construct($level, $eid, $class, $type, $data); - $this->setHealth($this->data["Health"] ?? 10, "generic"); + $this->setHealth($this->data["Health"] ?? 10, "generic", allowHarm: false); $this->server = ServerAPI::request(); $this->setName("Pig"); $this->setSpeed(0.25); @@ -35,7 +35,7 @@ class Pig extends Animal implements Rideable{ } public function canRide($e){ - return $this->isSaddled() && $this->linkedEntity == 0 && $e->linkedEntity == 0; + return $this->isSaddled() && $this->rider == 0; } public function updateEntityMovement(){ @@ -63,7 +63,7 @@ class Pig extends Animal implements Rideable{ if($slot->getID() === SADDLE){ if(!$this->isSaddled()){ - $e->player->removeItem($slot->getID(), 0, 1); + $e->player->consumeSingleItem(send: true); $this->setSaddled(1); } return true; //avoid further interactions diff --git a/src/entity/animal/Sheep.php b/src/entity/animal/Sheep.php index 5cd80c1b..f651bcd7 100644 --- a/src/entity/animal/Sheep.php +++ b/src/entity/animal/Sheep.php @@ -3,16 +3,16 @@ class Sheep extends Animal{ public $color; const TYPE = MOB_SHEEP; - + function __construct(Level $level, $eid, $class, $type = 0, $data = []){ $this->setSize(0.9, 1.3); parent::__construct($level, $eid, $class, $type, $data); - $this->setHealth($this->data["Health"] ?? 8, "generic"); + $this->setHealth($this->data["Health"] ?? 8, "generic", allowHarm: false); $this->setName("Sheep"); $this->data["Sheared"] = $this->data["Sheared"] ?? 0; $this->data["Color"] = $this->data["Color"] ?? $this->sheepColor(); $this->setSpeed(0.25); - + $this->ai->addTask(new TaskRandomWalk(1.0)); $this->ai->addTask(new TaskLookAtPlayer(6)); $this->ai->addTask(new TaskPanic(1.5)); @@ -23,14 +23,27 @@ class Sheep extends Animal{ $this->ai->addTask(new TaskMate(1.0)); $this->ai->addTask(new TaskFollowParent(1.0)); } - + + public function spawnChild($mate) + { + $child = parent::spawnChild($mate); + if($child instanceof Sheep){ + if($mate instanceof Sheep){ + $child->setColor(mt_rand(0, 1) == 0 ? $this->getColor() : $mate->getColor()); + }else{ + $child->setColor($this->getColor()); + } + } + return $child; + } + public function createSaveData(){ $data = parent::createSaveData(); $data["Color"] = @$this->data["Color"]; $data["Sheared"] = @$this->data["Sheared"]; return $data; } - + public function eatGrass(){ $this->setSheared(0); if($this->isBaby()){ @@ -39,24 +52,24 @@ class Sheep extends Animal{ $this->setAge($age); } } - + public function setSheared($v = null){ $this->data["Sheared"] = $v === null ? !$this->isSheared() : $v; $this->updateMetadata(); } - + public function isSheared(){ return $this->data["Sheared"]; } - + public function getColor(){ return $this->data["Color"]; //color === 16 -> color = 0, color === 17 -> color = 1 ... } - + public function switchColorMeta($meta){ return abs($meta - 15); } - + public function setColor($meta){ $this->data["Color"] = $meta; } @@ -65,40 +78,33 @@ class Sheep extends Animal{ [WOOL, $this->getColor(), 1] ]; } - + public function isFood($id){ return $id === WHEAT; } - + public function interactWith(Entity $e, $action){ if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){ $slot = $e->player->getHeldItem(); if($slot->getID() === SHEARS){ if(!$this->isSheared() && !$this->isBaby()){ - if($e->player->gamemode != 1) $slot->useOn($this); $this->setSheared(1); $speedX = (lcg_value() * 0.2 - 0.1) + (lcg_value() - lcg_value()) * 0.1; $speedZ = (lcg_value() * 0.2 - 0.1) + (lcg_value() - lcg_value()) * 0.1; - $speedY = 0.2 + (lcg_value()) * 0.05; + $speedY = 0.2 + (lcg_value()) * 0.05; $this->server->api->entity->dropRawPos($this->level, $this->x, $this->y + 1, $this->z, BlockAPI::getItem(WOOL, $this->getColor(), mt_rand(1, 3)), $speedX, $speedY, $speedZ); - if($slot->getMetadata() >= $slot->getMaxDurability()){ - $e->player->removeItem($slot->getID(), $slot->getMetadata(), $slot->count, true); - }else{ - $e->player->setSlot($e->player->slot, $slot); - } + $slot->hurtAndBreak(1, $e->player); } return true; }elseif($slot->getID() === DYE){ $this->setColor($this->switchColorMeta($slot->getMetadata())); - - if(($e->player->gamemode & 0x01) === SURVIVAL){ - $e->player->removeItem($slot->getID(), $slot->getMetadata(), 1, true); - } + + $e->player->consumeSingleItem(); } } return parent::interactWith($e, $action); } - + public function getMetadata(){ $d = parent::getMetadata(); if(!isset($this->data["Sheared"])){ @@ -107,7 +113,7 @@ class Sheep extends Animal{ $d[16]["value"] = ($this->data["Sheared"] << 4) | ($this->getColor() & 0x0F); return $d; } - + public function sheepColor(){ //a method from 0.8.1 $c = mt_rand(0,100); if($c <= 4){ diff --git a/src/entity/monster/Creeper.php b/src/entity/monster/Creeper.php index a8539b11..d3da8f38 100644 --- a/src/entity/monster/Creeper.php +++ b/src/entity/monster/Creeper.php @@ -1,5 +1,4 @@ setSize(0.6, 1.7); parent::__construct($level, $eid, $class, $type, $data); - $this->setHealth($this->data["Health"] ?? 16, "generic"); + $this->setHealth($this->data["Health"] ?? 16, "generic", allowHarm: false); $this->setName("Creeper"); $this->ignited = 0; $this->setSpeed(0.25); $this->timeUntilExplode = $this->isIgnited() ? self::EXPL_TIME : 0; - + $this->ai->addTask(new TaskRandomWalk(1.0)); $this->ai->addTask(new TaskAttackPlayer(1.25, 16)); $this->ai->addTask(new TaskLookAround()); $this->ai->addTask(new TaskSwimming()); } - + public function getAttackDamage(){ return 0; } - + public function setIgnited($v = null){ - $this->setState($v === null ? !$this->getState() : $v); + $this->setState($v === null ? !$this->getState() : $v); } - + /** * @return boolean */ public function isIgnited(){ return $this->getState() > 0; } - + public function interactWith(Entity $e, $action){ if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){ $slot = $e->player->getHeldItem(); if($slot->getID() === FLINT_AND_STEEL && !$this->isIgnited()){ - if($slot->useOn($this) && $slot->getMetadata() >= $slot->getMaxDurability()){ - $e->player->removeItem($slot->getID(), $slot->getMetadata(), $slot->count, true); - }else{ - $e->player->setSlot($e->player->slot, $slot); - } + $slot->hurtAndBreak(1, $e->player); $this->ignite(); return true; } } return parent::interactWith($e, $action); } - + public function ignite(){ $this->setIgnited(1); $this->timeUntilExplode = self::EXPL_TIME; } - + public function attackEntity($entity, $distance){ if(Utils::distance_noroot($entity, $this) <= 49 && !$this->isIgnited() && $this->ai->canSee($entity)){ $this->ignite(); @@ -87,7 +82,7 @@ class Creeper extends Monster{ $this->close(); $explosion->explode(); } - + public function getDrops(){ return [ [GUNPOWDER, 0, mt_rand(0,2)] diff --git a/src/entity/monster/PigZombie.php b/src/entity/monster/PigZombie.php index c508d1a8..0b3381b2 100644 --- a/src/entity/monster/PigZombie.php +++ b/src/entity/monster/PigZombie.php @@ -5,7 +5,7 @@ class PigZombie extends Monster{ //TODO extends zombie function __construct(Level $level, $eid, $class, $type = 0, $data = []){ $this->setSize(0.3, 1.95); parent::__construct($level, $eid, $class, $type, $data); - $this->setHealth($this->data["Health"] ?? 12, "generic"); + $this->setHealth($this->data["Health"] ?? 12, "generic", allowHarm: false); $this->setName("Pigman"); $this->setSpeed(0.25); $this->isImmuneToFire = true; diff --git a/src/entity/monster/Skeleton.php b/src/entity/monster/Skeleton.php index c5956075..e5d67b51 100644 --- a/src/entity/monster/Skeleton.php +++ b/src/entity/monster/Skeleton.php @@ -5,7 +5,7 @@ class Skeleton extends Monster{ function __construct(Level $level, $eid, $class, $type = 0, $data = []){ $this->setSize(0.6, 1.99); parent::__construct($level, $eid, $class, $type, $data); - $this->setHealth($this->data["Health"] ?? 10, "generic"); + $this->setHealth($this->data["Health"] ?? 10, "generic", allowHarm: false); $this->setName("Skeleton"); $this->ai->removeTask("TaskAttackPlayer"); $this->setSpeed(0.25); diff --git a/src/entity/monster/Spider.php b/src/entity/monster/Spider.php index 081187fb..6cb57c98 100644 --- a/src/entity/monster/Spider.php +++ b/src/entity/monster/Spider.php @@ -6,7 +6,7 @@ class Spider extends Monster{ function __construct(Level $level, $eid, $class, $type = 0, $data = []){ $this->setSize(1.4, 0.9); parent::__construct($level, $eid, $class, $type, $data); - $this->setHealth($this->data["Health"] ?? 8, "generic"); + $this->setHealth($this->data["Health"] ?? 8, "generic", allowHarm: false); $this->setName("Spider"); $this->setSpeed(0.3); $this->ai->addTask(new TaskRandomWalk(1.2)); diff --git a/src/entity/monster/Zombie.php b/src/entity/monster/Zombie.php index 7cfb4885..f53d7248 100644 --- a/src/entity/monster/Zombie.php +++ b/src/entity/monster/Zombie.php @@ -1,39 +1,38 @@ setSize(0.6, 1.85); parent::__construct($level, $eid, $class, $type, $data); - $this->setHealth($this->data["Health"] ?? 12, "generic"); + $this->setHealth($this->data["Health"] ?? 12, "generic", allowHarm: false); $this->setName("Zombie"); $this->setSpeed(0.23); - + $this->ai->addTask(new TaskRandomWalk(1.0)); $this->ai->addTask(new TaskLookAround()); $this->ai->addTask(new TaskSwimming()); $this->ai->addTask(new TaskAttackPlayer(1.0, 16)); } - + public function getArmorValue(){ return 2; } - + public function updateBurning(){ if($this->fire > 0 || !$this->level->isDay() || $this->inWater){ return false; } //bad fix for burning in water - [$block, $meta] = $this->level->level->getBlock((int) $this->x, (int) $this->y, (int) $this->z); + [$block, $meta] = $this->level->level->getBlock((int)$this->x, (int)$this->y, (int)$this->z); if($block == WATER || $block == STILL_WATER){ - $v16 = ((int) $this->y + 1) - LiquidBlock::getPercentAir($meta); - if($this->boundingBox->intersectsWith(new AxisAlignedBB((int) $this->x, (int) $this->y, (int) $this->z, (int) $this->x + 1, $v16, (int) $this->z + 1))){ + $v16 = ((int)$this->y + 1) - LiquidBlock::getPercentAir($meta); + if($this->boundingBox->intersectsWith(new AxisAlignedBB((int)$this->x, (int)$this->y, (int)$this->z, (int)$this->x + 1, $v16, (int)$this->z + 1))){ return false; } } - - for($y = (int) $this->y; $y < 129; $y++){ - $block = $this->level->level->getBlockID($this->x, $y, $this->z); + + for($y = (int)$this->y; $y < 129; $y++){ + $block = $this->level->level->getBlockID(floor($this->x), $y, floor($this->z)); if(StaticBlock::getIsSolid($block)){ return false; } @@ -49,7 +48,7 @@ class Zombie extends Monster{ return false; } } - + public function getAttackDamage(){ return 4; } @@ -58,7 +57,7 @@ class Zombie extends Monster{ $this->updateBurning(); return parent::updateEntityMovement(); } - + public function getDrops(){ return [ [CARROT, 0, Utils::chance(0.83) ? 1 : 0], diff --git a/src/entity/object/Arrow.php b/src/entity/object/Arrow.php index cac786cf..3175b23b 100644 --- a/src/entity/object/Arrow.php +++ b/src/entity/object/Arrow.php @@ -3,7 +3,7 @@ class Arrow extends Entity{ const TYPE = OBJECT_ARROW; const CLASS_TYPE = ENTITY_OBJECT; - + public $shooterEID = 0; public $xTile, $yTile, $zTile; public $inTile, $inData; @@ -13,7 +13,8 @@ class Arrow extends Entity{ public $criticial = false; public $groundTicks = 0; public $shotByPlayer = false; - + public $shotByEntity = false; + function __construct(Level $level, $eid, $class, $type = 0, $data = []){ parent::__construct($level, $eid, $class, $type, $data); $this->gravity = 0.05; @@ -32,12 +33,12 @@ class Arrow extends Entity{ $this->yTile = $data["yTile"] ?? $this->yTile; $this->zTile = $data["zTile"] ?? $this->zTile; $this->shotByPlayer = $data["shotByPlayer"] ?? $this->shotByPlayer; - + //$this->server->schedule(1210, array($this, "update")); //Despawn } public function createSaveData(){ $data = parent::createSaveData(); - + $data["inTile"] = $this->inTile; $data["inData"] = $this->inData; $data["inGround"] = $this->inGround; @@ -47,17 +48,7 @@ class Arrow extends Entity{ $data["shotByPlayer"] = $this->shotByPlayer; return $data; } - public function handleUpdate(){ - $pk = new MoveEntityPacket_PosRot; - $pk->eid = $this->eid; - $pk->x = $this->x; - $pk->y = $this->y; - $pk->z = $this->z; - $pk->yaw = $this->yaw; - $pk->pitch = $this->pitch; - $this->server->api->player->broadcastPacket($this->level->players, $pk); - } - + public function shoot($d, $d1, $d2, $f, $f1){ //original name from 0.8.1 IDA decompilation, var names are taken from b1.7.3 $f2 = sqrt($d * $d + $d1 * $d1 + $d2 * $d2); $d /= $f2; @@ -79,7 +70,7 @@ class Arrow extends Entity{ //$this->update(); $this->groundTicks = 0; } - + public function update($now){ $this->lastX = $this->x; $this->lastY = $this->y; @@ -101,39 +92,40 @@ class Arrow extends Entity{ $this->fire -= 4; if($this->fire <= 0) $this->fire = 0; } - + if($this->fire <= 0){ $this->updateMetadata(); } } - + if($this->handleLavaMovement()){ if(!$this->isImmuneToFire){ $this->harm(4, "fire"); $oldOnFire = $this->fire; - if($oldOnFire < 20 * 30) $this->fire = 20 * 30; //30 seconds + if($oldOnFire < 20*30) $this->fire = 20*30; //30 seconds } } - + if($this->isInVoid()){ $this->outOfWorld(); } //Entity::update end - + + if($this->lastPitch == $this->lastYaw && $this->lastYaw == 0){ - $v1 = sqrt($this->speedX * $this->speedX + $this->speedZ * $this->speedZ); + $v1 = sqrt($this->speedX*$this->speedX + $this->speedZ*$this->speedZ); $this->lastYaw = $this->yaw = atan2($this->speedX, $this->speedZ) * 180 / M_PI; $this->lastPitch = $this->pitch = atan2($this->speedY, $v1) * 180 / M_PI; } - + if($this->shake > 0){ --$this->shake; } - + if($this->inGround){ [$blockID, $blockMeta] = $this->level->level->getBlock($this->xTile, $this->yTile, $this->zTile); $this->speedZ = $this->speedX = $this->speedY = 0; - + if($blockID == $this->inTile && $blockMeta == $this->inData){ ++$this->groundTicks; if($this->groundTicks >= 1200){ //TODO customizeable? @@ -146,7 +138,7 @@ class Arrow extends Entity{ $this->speedZ *= lcg_value() * 0.2; $this->groundTicks = $this->airTicks = 0; } - + }else{ ++$this->airTicks; $start = new Vector3($this->x, $this->y, $this->z); @@ -161,40 +153,42 @@ class Arrow extends Entity{ }else{ $end = new Vector3($this->x + $this->speedX, $this->y + $this->speedY, $this->z + $this->speedZ); } - + + $entities = $this->level->getEntitiesInAABB($this->boundingBox->addCoord($this->speedX, $this->speedY, $this->speedZ)->expand(1, 1, 1)); $bestDist = 0; $bestEnt = null; - + foreach($entities as $eid => $ent){ if($eid != $this->eid && $ent->isPickable() && ($eid != $this->shooterEID || $this->airTicks >= 5)){ - + $v12 = $ent->boundingBox->expand(0.3, 0.3, 0.3); $v13 = $v12->calculateIntercept($start, $end); - + if($v13 != null){ $dist = $start->distance($v13->hitVector); - + if($dist < $bestDist || $bestDist == 0){ $bestEnt = $ent; } } } } - + if($bestEnt != null){ $v4 = MovingObjectPosition::fromEntity($bestEnt); } - + if($v4 != null){ if($v4->entityHit != null){ - $v49 = sqrt($this->speedY * $this->speedY + $this->speedX * $this->speedX + $this->speedZ * $this->speedZ); - $damage = ceil($v49 + $v49); - + $v49 = sqrt($this->speedY*$this->speedY + $this->speedX*$this->speedX + $this->speedZ*$this->speedZ); + $damage = ceil($v49+$v49); + if($this->criticial){ $damage += mt_rand(0, $damage / 2 + 1); } - + + if($v4->entityHit->harm($damage, $this->eid)){ //vanilla seems to increase arrow count if $v4->entity is mob $this->close(); @@ -210,36 +204,36 @@ class Arrow extends Entity{ $this->xTile = $v4->blockX; $this->yTile = $v4->blockY; $this->zTile = $v4->blockZ; - + [$this->inTile, $this->inData] = $this->level->level->getBlock($this->xTile, $this->yTile, $this->zTile); - + $this->speedX = $v4->hitVector->x - $this->x; $this->speedY = $v4->hitVector->y - $this->y; $this->speedZ = $v4->hitVector->z - $this->z; - - $v21 = sqrt($this->speedX * $this->speedX + $this->speedY * $this->speedY + $this->speedZ * $this->speedZ); + + $v21 = sqrt($this->speedX*$this->speedX + $this->speedY*$this->speedY + $this->speedZ*$this->speedZ); if($v21 != 0){ $this->x -= $this->speedX / $v21 * 0.05; $this->y -= $this->speedY / $v21 * 0.05; $this->z -= $this->speedZ / $v21 * 0.05; } - + $this->inGround = true; $this->shake = 7; $this->criticial = false; } } - + $this->x += $this->speedX; $this->y += $this->speedY; $this->z += $this->speedZ; - $v21 = sqrt($this->speedX * $this->speedX + $this->speedZ * $this->speedZ); + $v21 = sqrt($this->speedX*$this->speedX + $this->speedZ*$this->speedZ); $this->yaw = atan2($this->speedX, $this->speedZ) * 180 / M_PI; $this->pitch = atan2($this->speedY, $v21) * 180 / M_PI; - + $this->pitch = $this->lastPitch + ($this->pitch - $this->lastPitch) * 0.2; $this->yaw = $this->lastYaw + ($this->yaw - $this->lastYaw) * 0.2; - + $v24 = $this->inWater ? 0.8 : 0.99; $this->speedX *= $v24; $this->speedY *= $v24; @@ -249,25 +243,29 @@ class Arrow extends Entity{ $v7 = $this->width / 2; $v8 = $this->height; $this->boundingBox->setBounds($this->x - $v7, $this->y - $this->yOffset /*+ $this->ySize*/, $this->z - $v7, $this->x + $v7, $this->y - $this->yOffset + $v8 /*+ $this->ySize*/, $this->z + $v7); - + $this->doBlocksCollision(); } - } - - public function spawn($player){ - if($this->type === OBJECT_ARROW){ + + public function spawn(Player $player){ + if(!($this->type == OBJECT_ARROW)) return false; + if(!$player->hasEntity($this)){ + $player->addEntity($this); $pk = new AddEntityPacket; $pk->eid = $this->eid; $pk->type = $this->type; $pk->x = $this->x; $pk->y = $this->y; $pk->z = $this->z; - $pk->did = 1; + $pk->did = 1; $pk->speedX = $this->speedX; $pk->speedY = $this->speedY; $pk->speedZ = $this->speedZ; - $player->dataPacket($pk); + $player->entityQueueDataPacket($pk); + $this->sendLinkPackets($player); + return true; } + return false; } } diff --git a/src/entity/object/FallingSand.php b/src/entity/object/FallingSand.php index 8bb6c936..10f93c2d 100644 --- a/src/entity/object/FallingSand.php +++ b/src/entity/object/FallingSand.php @@ -3,26 +3,46 @@ class FallingSand extends Entity{ const TYPE = FALLING_SAND; const CLASS_TYPE = ENTITY_FALLING; - + public $fallTime = 0; - + public function __construct($level, $eid, $class, $type = 0, $data = []){ parent::__construct($level, $eid, $class, $type, $data); - $this->setHealth(PHP_INT_MAX, "generic"); + $this->setHealth(PHP_INT_MAX, "generic", allowHarm: false); $this->height = 0.98; $this->width = 0.98; $this->yOffset = $this->height / 2; $this->hasGravity = true; $this->gravity = 0.04; } - + public function isPickable(){ return !$this->dead; } - + public function spawn($player) + { + if(!$player->hasEntity($this)){ + $player->addEntity($this); + $pk = new AddEntityPacket(); + $pk->eid = $this->eid; + $pk->type = $this->type; + $pk->x = $this->x; + $pk->y = $this->y; + $pk->z = $this->z; + $pk->speedX = $this->speedX; + $pk->speedY = $this->speedY; + $pk->speedZ = $this->speedZ; + $pk->did = -$this->data["Tile"]; + $player->entityQueueDataPacket($pk); + $this->sendLinkPackets($player); + return true; + } + return false; + } + public function update($now){ if($this->closed) return; - + if( $this->data["Tile"] == AIR) { $this->close(); return; @@ -45,15 +65,15 @@ class FallingSand extends Entity{ ++$this->fallTime; $this->speedY -= 0.04; $this->move($this->speedX, $this->speedY, $this->speedZ); - + $this->speedX *= 0.98; $this->speedY *= 0.98; $this->speedZ *= 0.98; - + $x = floor($this->x); $y = floor($this->y); $z = floor($this->z); - + if(($blockAt = $this->level->level->getBlockID($x, $y, $z)) != 0){ //TODO vanilla-like checking? if(StaticBlock::getIsTransparent($blockAt) && !StaticBlock::getIsLiquid($blockAt)){ @@ -62,7 +82,6 @@ class FallingSand extends Entity{ return; } } - if($this->onGround){ $this->speedX *= 0.7; $this->speedZ *= 0.7; diff --git a/src/entity/object/ItemEntity.php b/src/entity/object/ItemEntity.php index f290fe07..56b07195 100644 --- a/src/entity/object/ItemEntity.php +++ b/src/entity/object/ItemEntity.php @@ -4,10 +4,10 @@ class ItemEntity extends Entity{ const TYPE = ENTITY_ITEM_TYPE; const CLASS_TYPE = ENTITY_ITEM; public static $searchRadiusX = 0.5, $searchRadiusY = 0.0, $searchRadiusZ = 0.5; - + public $meta, $stack, $itemID; - - public function __construct(Level $level, $eid, $class, $type = 0, $data = []) + + public function __construct(Level $level, $eid, $class, $type = 0, $data = array()) { parent::__construct($level, $eid, $class, $type, $data); $this->setSize(0.25, 0.25); @@ -22,56 +22,56 @@ class ItemEntity extends Entity{ $this->itemID = (int) $data["itemID"]; } $this->hasGravity = true; - $this->setHealth(5, "generic"); + $this->setHealth(5, "generic", allowHarm: false); $this->gravity = 0.04; $this->delayBeforePickup = 40; //in vanilla it is 0 by default $this->stepHeight = 0; } - + public function counterUpdate(){ parent::counterUpdate(); if($this->delayBeforePickup > 0) --$this->delayBeforePickup; } - + public function searchForOtherItemsNearby(){ $ents = $this->level->getEntitiesInAABBOfType($this->boundingBox->expand(self::$searchRadiusX, self::$searchRadiusY, self::$searchRadiusZ), ENTITY_ITEM); - + foreach($ents as $e){ $this->tryCombining($e); } - + } - - public function spawn($player) + + public function spawn(Player $player) { - $pk = new AddItemEntityPacket(); - $pk->eid = $this->eid; - $pk->x = $this->x; - $pk->y = $this->y; - $pk->z = $this->z; - $pk->yaw = $this->yaw; - $pk->pitch = $this->pitch; - $pk->roll = 0; - $pk->item = BlockAPI::getItem($this->itemID, $this->meta, $this->stack); - $pk->metadata = $this->getMetadata(); - $player->dataPacket($pk); - - $pk = new SetEntityMotionPacket(); - $pk->eid = $this->eid; - $pk->speedX = $this->speedX; - $pk->speedY = $this->speedY; - $pk->speedZ = $this->speedZ; - $player->dataPacket($pk); + if(!$player->hasEntity($this)){ + $player->addEntity($this); + $pk = new AddItemEntityPacket(); + $pk->eid = $this->eid; + $pk->x = $this->x; + $pk->y = $this->y; + $pk->z = $this->z; + $pk->speedX = $this->speedX; + $pk->speedY = $this->speedY; + $pk->speedZ = $this->speedZ; + $pk->item = BlockAPI::getItem($this->itemID, $this->meta, $this->stack); + $pk->metadata = $this->getMetadata(); + $player->entityQueueDataPacket($pk); + $this->sendLinkPackets($player); + return true; + } + return false; } - + + public function tryCombining(Entity $another){ - + if($another->eid == $this->eid) return false; - + if(!$another->closed && !$this->closed){ if($another->itemID == $this->itemID && $another->meta == $this->meta){ if(($another->stack + $this->stack) > 64) return false; //TODO dynamic stack size - + $another->stack += $this->stack; $another->age = min($this->age, $another->age); $this->close(); @@ -83,29 +83,30 @@ class ItemEntity extends Entity{ $xFloor = floor($x); $yFloor = floor($y); $zFloor = floor($z); - + $id = $this->level->level->getBlockID($xFloor, $yFloor, $zFloor); - - if(StaticBlock::getIsSolid($id)){ + + if(StaticBlock::getIsSolid($id) && StaticBlock::getIsFullBlock($id)){ $xDiff = $x - $xFloor; - + $id = $this->level->level->getBlockID($xFloor - 1, $yFloor, $zFloor); - $xNeg = StaticBlock::getIsSolid($id); - + $xNeg = StaticBlock::getIsSolid($id) && StaticBlock::getIsFullBlock($id); + $id = $this->level->level->getBlockID($xFloor + 1, $yFloor, $zFloor); - $xPos = StaticBlock::getIsSolid($id); - + $xPos = StaticBlock::getIsSolid($id) && StaticBlock::getIsFullBlock($id); + $id = $this->level->level->getBlockID($xFloor, $yFloor - 1, $zFloor); - $yNeg = StaticBlock::getIsSolid($id); - + $yNeg = StaticBlock::getIsSolid($id) && StaticBlock::getIsFullBlock($id); + $id = $this->level->level->getBlockID($xFloor, $yFloor + 1, $zFloor); - $yPos = StaticBlock::getIsSolid($id); - - $id = $this->level->level->getBlockID($xFloor - 1, $yFloor, $zFloor - 1); - $zNeg = StaticBlock::getIsSolid($id); - - $zPos = $this->level->level->getBlockID($xFloor + 1, $yFloor, $zFloor + 1); - + $yPos = StaticBlock::getIsSolid($id) && StaticBlock::getIsFullBlock($id); + + $id = $this->level->level->getBlockID($xFloor, $yFloor, $zFloor - 1); + $zNeg = StaticBlock::getIsSolid($id) && StaticBlock::getIsFullBlock($id); + + $id = $this->level->level->getBlockID($xFloor, $yFloor, $zFloor + 1); + $zPos = StaticBlock::getIsSolid($id) && StaticBlock::getIsFullBlock($id); + if($xNeg || $xDiff >= 9999.0){ //TODO not needed check? $v15 = 9999.0; $v16 = -1; @@ -113,22 +114,22 @@ class ItemEntity extends Entity{ $v15 = $xDiff; $v16 = 0; } - + if(!$xPos){ $v17 = 1 - $xDiff; - + if($v17 < $v15){ $v15 = $v17; $v16 = 1; } } - + $yDiff = $y - $yFloor; if(!$yNeg && $yDiff < $v15){ $v15 = $yDiff; $v16 = 2; } - + if(!$yPos){ $v19 = 1.0 - $yDiff; if($v19 < $v15){ @@ -136,17 +137,17 @@ class ItemEntity extends Entity{ $v16 = 3; } } - + $zDiff = $z - $zFloor; if(!$zNeg && $zDiff < $v15){ $v15 = $zDiff; $v16 = 4; } - - if(!StaticBlock::getIsSolid($zPos) && ((1.0 - $zDiff) < $v15)){ + + if(!$zPos && ((1.0 - $zDiff) < $v15)){ $v16 = 5; } - + $v21 = lcg_value() * 0.2 + 0.1; switch($v16){ case 0: @@ -165,24 +166,24 @@ class ItemEntity extends Entity{ $this->speedZ = $v21; return 0; } - + return 0; } } - + public function handleWaterMovement(){ - return $this->level->handleMaterialAcceleration($this->boundingBox, 0, $this); + return $this->level->handleMaterialAcceleration($this->boundingBox, Material::$water, $this); } - + public function updateEntityMovement(){ //TODO custom update( method $this->speedY -= 0.04; //$this->noClip = false; $this->checkInTile($this->x, $this->y, $this->z); $this->move($this->speedX, $this->speedY, $this->speedZ); - - $var1 = (int) $this->x != (int) $this->lastX || (int) $this->y != (int) $this->lastY || (int) $this->z != (int) $this->lastZ; - + + $var1 = (int)$this->x != (int)$this->lastX || (int)$this->y != (int)$this->lastY || (int)$this->z != (int)$this->lastZ; + if($var1 || $this->counter % 25 == 0){ $blockIDAt = $this->level->level->getBlockID(floor($this->x), floor($this->y), floor($this->z)); if($blockIDAt == LAVA || $blockIDAt == STILL_LAVA){ @@ -190,30 +191,30 @@ class ItemEntity extends Entity{ $this->speedX = (lcg_value() - lcg_value()) * 0.2; $this->speedZ = (lcg_value() - lcg_value()) * 0.2; } - + //$this->searchForOtherItemsNearby(); //not in vanilla 0.8.1 } - + if($this->closed) return; - + $friction = 0.98; if($this->onGround){ $friction = 0.588; - $v3 = $this->level->level->getBlockID($this->x, floor($this->boundingBox->minY) - 1, $this->z); + $v3 = $this->level->level->getBlockID(floor($this->x), floor($this->boundingBox->minY) - 1, floor($this->z)); if($v3 > 0) $friction = StaticBlock::getSlipperiness($v3); } - + $this->speedX *= $friction; $this->speedY *= 0.98; $this->speedZ *= $friction; - + if($this->onGround) $this->speedY *= -0.5; - + if(abs($this->speedX) < self::MIN_POSSIBLE_SPEED) $this->speedX = 0; if(abs($this->speedZ) < self::MIN_POSSIBLE_SPEED) $this->speedZ = 0; if(abs($this->speedY) < self::MIN_POSSIBLE_SPEED) $this->speedY = 0; - + ++$this->age; - //TODO despawn after age >= 6000 ?; + //TODO despawn after age >= 6000 ?; } } diff --git a/src/entity/object/Minecart.php b/src/entity/object/Minecart.php index 5361e47e..c7711d73 100644 --- a/src/entity/object/Minecart.php +++ b/src/entity/object/Minecart.php @@ -4,7 +4,7 @@ class Minecart extends Vehicle{ const TYPE = OBJECT_MINECART; /** * A minecart rotation matrix - * @var int[][][] + * @var int[][][] */ private static $matrix = [ [ @@ -48,95 +48,99 @@ class Minecart extends Vehicle{ [1, 0, 0] ] ]; - + private $hurtTime = 0; //syncentdata 17 int private $damage = 0; //syncentdata 19 float - + private $minecartX = 0, $minecartY = 0, $minecartZ = 0; private $turnProgress = 0; public $isInReverse = false; - + function __construct(Level $level, $eid, $class, $type = 0, $data = []){ parent::__construct($level, $eid, $class, $type, $data); $this->canBeAttacked = true; $this->x = $this->data["TileX"] ?? $this->x; $this->y = $this->data["TileY"] ?? $this->y; $this->z = $this->data["TileZ"] ?? $this->z; - $this->setHealth(1, "generic"); //orig: 3 + $this->setHealth(1, "generic", allowHarm: false); //orig: 3 $this->setSize(0.98, 0.7); $this->yOffset = $this->height / 2; $this->stepHeight = 0; } - + public function isPickable(){ return !$this->dead; } - + + public function getRideHeight(){ + return ($this->height * 0) - 0.3; + } + public function getDrops(){ return [ [MINECART, 0, 1] ]; } - + public function getPos($x, $y, $z){ $blockX = floor($x); $blockY = floor($y); $blockZ = floor($z); - + if(RailBaseBlock::isRailBlock($this->level, $blockX, $blockY - 1, $blockZ)) --$blockY; - + [$id, $meta] = $this->level->level->getBlock($blockX, $blockY, $blockZ); if(RailBaseBlock::isRailID($id)){ - + if($id == POWERED_RAIL) $meta &= 7; - + $mat = self::$matrix[$meta]; $v13 = 0; $v15 = $blockX + 0.5 + $mat[0][0] * 0.5; $v17 = $blockY + 0.5 + $mat[0][1] * 0.5; $v19 = $blockZ + 0.5 + $mat[0][2] * 0.5; - + $v21 = $blockX + 0.5 + $mat[1][0] * 0.5; $v23 = $blockY + 0.5 + $mat[1][1] * 0.5; $v25 = $blockZ + 0.5 + $mat[1][2] * 0.5; - + $v27 = $v21 - $v15; $v29 = ($v23 - $v17) * 2; $v31 = $v25 - $v19; - + if($v27 == 0){ $x = $blockX + 0.5; $v13 = $z - $blockZ; - }elseif($v31 == 0){ + }else if($v31 == 0){ $z = $blockZ + 0.5; $v13 = $x - $blockX; }else{ $v33 = $x - $v15; $v35 = $z - $v19; - $v13 = ($v33 * $v27 + $v35 * $v31) * 2; + $v13 = ($v33*$v27 + $v35*$v31) * 2; } - + $x = $v15 + $v27 * $v13; $y = $v17 + $v29 * $v13; $z = $v19 + $v31 * $v13; - + if($v29 < 0) ++$y; if($v29 > 0) $y += 0.5; return [$x, $y, $z]; } - + return false; } - + public function moveAlongTrack($x, $y, $z, $maxSpeed, $boost, $id, $meta){ $this->fallDistance = 0; $vec = $this->getPos($this->x, $this->y, $this->z); $this->y = $y; - + if($id == POWERED_RAIL) $meta &= 7; - + if($meta >= 2 && $meta <= 5) $this->y = $y + 1; - + switch($meta){ case 2: $this->speedX -= $boost; @@ -151,109 +155,109 @@ class Minecart extends Vehicle{ $this->speedZ -= $boost; break; } - + $mat = self::$matrix[$meta]; $matXDiff = $mat[1][0] - $mat[0][0]; $matZDiff = $mat[1][2] - $mat[0][2]; - $matDiffTotal = sqrt($matXDiff * $matXDiff + $matZDiff * $matZDiff); - + $matDiffTotal = sqrt($matXDiff*$matXDiff + $matZDiff*$matZDiff); + if(($this->speedZ * $matZDiff + $this->speedX * $matXDiff) < 0){ $matXDiff = -$matXDiff; $matZDiff = -$matZDiff; } - $speedTotal = sqrt($this->speedZ * $this->speedZ + $this->speedX * $this->speedX); + $speedTotal = sqrt($this->speedZ*$this->speedZ + $this->speedX*$this->speedX); if($speedTotal > 2) $speedTotal = 2; $this->speedX = ($speedTotal * $matXDiff) / $matDiffTotal; $this->speedZ = ($speedTotal * $matZDiff) / $matDiffTotal; - - if($this->linkedEntity != 0 && !$this->isRider){ - $rider = $this->level->entityList[$this->linkedEntity] ?? false; + + if($this->rider != 0){ + $rider = $this->level->entityList[$this->rider] ?? false; if($rider instanceof Entity && ($rider->isPlayer() || $rider->class == ENTITY_MOB)){ if($rider->moveForward > 0){ $v32 = sin($this->yaw * M_PI / 180); $v33 = cos($this->yaw * M_PI / 180); - - if($this->speedZ * $this->speedZ + $this->speedX * $this->speedX < 0.01){ - $this->speedX -= $v32 * 0.1; - $this->speedZ += $v33 * 0.1; + + if($this->speedZ*$this->speedZ + $this->speedX*$this->speedX < 0.01){ + $this->speedX -= $v32*0.1; + $this->speedZ += $v33*0.1; } } } } - + $v38 = ($x + 0.5) + ($mat[0][0] * 0.5); $v39 = ($z + 0.5) + ($mat[0][2] * 0.5); $v40 = (($x + 0.5) + ($mat[1][0] * 0.5)) - $v38; $v41 = (($z + 0.5) + ($mat[1][2] * 0.5)) - $v39; - + if($v40 == 0){ $v42 = $this->z - $z; - }elseif($v41 == 0){ + }else if($v41 == 0){ $v42 = $this->x - $x; }else{ $v44 = (($this->z - $v39) * $v41) + (($this->x - $v38) * $v40); $v42 = $v44 + $v44; } - + $this->x = $v38 + ($v40 * $v42); $this->z = $v39 + ($v41 * $v42); - + $this->setPos($this->x, $this->y + $this->yOffset + 0.00001, $this->z); $dx = $this->speedX; $dz = $this->speedZ; - if($this->linkedEntity != 0 && !$this->isRider){ + if($this->rider != 0){ $dx *= 0.75; $dz *= 0.75; } - + if($dx < -$maxSpeed) $dx = -$maxSpeed; - elseif($dx > $maxSpeed) $dx = $maxSpeed; - + else if($dx > $maxSpeed) $dx = $maxSpeed; + if($dz < -$maxSpeed) $dz = -$maxSpeed; - elseif($dz > $maxSpeed) $dz = $maxSpeed; - + else if($dz > $maxSpeed) $dz = $maxSpeed; + $this->move($dx, 0, $dz); - + if($mat[0][1]){ if((floor($this->x) - $x) == $mat[0][0] && (floor($this->z) - $z) == $mat[0][2]){ $this->setPos($this->x, $mat[0][1] + $this->y, $this->z); - }elseif($mat[1][1]){ + }else if($mat[1][1]){ goto mat_1_1; } - }elseif($mat[1][1]){ + }else if($mat[1][1]){ mat_1_1: if((floor($this->x) - $x) == $mat[1][0] && (floor($this->z) - $z) == $mat[1][2]){ $this->setPos($this->x, $mat[1][1] + $this->y, $this->z); } } - + $this->applyNaturalSlowdown(); $vec2 = $this->getPos($this->x, $this->y, $this->z); if($vec2 !== false && $vec !== false){ $yDiff = ($vec[1] - $vec2[1]) * 0.05; - $totalSpeed = sqrt($this->speedZ * $this->speedZ + $this->speedX * $this->speedX); - + $totalSpeed = sqrt($this->speedZ*$this->speedZ + $this->speedX*$this->speedX); + if($totalSpeed > 0){ $this->speedX = ($this->speedX / $totalSpeed) * ($totalSpeed + $yDiff); - $this->speedZ = ($this->speedZ / $totalSpeed) * ($totalSpeed + $yDiff); + $this->speedZ = ($this->speedZ / $totalSpeed) * ($totalSpeed + $yDiff); } $this->setPos($this->x, $vec2[1], $this->z); } - + if(floor($this->x) != $x || floor($this->z) != $z){ //this breaks everything - $totalSpeed = sqrt($this->speedZ * $this->speedZ + $this->speedX * $this->speedX); + $totalSpeed = sqrt($this->speedZ*$this->speedZ + $this->speedX*$this->speedX); $this->speedX = (floor($this->x) - $x) * $totalSpeed; $this->speedZ = (floor($this->z) - $z) * $totalSpeed; } - + if($id == POWERED_RAIL){ - $totalSpeed = sqrt($this->speedZ * $this->speedZ + $this->speedX * $this->speedX); + $totalSpeed = sqrt($this->speedZ*$this->speedZ + $this->speedX*$this->speedX); if($totalSpeed > 0.01){ $this->speedX += (($this->speedX / $totalSpeed) * 0.06); $this->speedZ += (($this->speedZ / $totalSpeed) * 0.06); return; } - + if($meta == 1){ //TODO Level::isSolidBlockingTile if(StaticBlock::getIsSolid($this->level->level->getBlockID($x - 1, $y, $z))){ @@ -265,7 +269,7 @@ class Minecart extends Vehicle{ $v63 = -0.02; } $this->speedX = $v63; - }elseif($meta == 0){ + }else if($meta == 0){ //TODO Level::isSolidBlockingTile if(StaticBlock::getIsSolid($this->level->level->getBlockID($x, $y, $z - 1))){ return; @@ -278,57 +282,58 @@ class Minecart extends Vehicle{ $this->speedZ = $v64; } } - + } - + + public function applyNaturalSlowdown(){ - $mult = $this->linkedEntity != 0 && !$this->isRider ? 0.997 : 0.96; - + $mult = $this->rider != 0 ? 0.997 : 0.96; + $this->speedX *= $mult; $this->speedY = 0; $this->speedZ *= $mult; } - + public function comeOffTrack($topSpeed){ if($this->speedX < -$topSpeed) $this->speedX = -$topSpeed; - elseif($this->speedX > $topSpeed) $this->speedX = $topSpeed; - + else if($this->speedX > $topSpeed) $this->speedX = $topSpeed; + if($this->speedZ < -$topSpeed) $this->speedZ = -$topSpeed; - elseif($this->speedZ > $topSpeed) $this->speedZ = $topSpeed; - + else if($this->speedZ > $topSpeed) $this->speedZ = $topSpeed; + if($this->onGround){ $this->speedX *= 0.5; $this->speedY *= 0.5; $this->speedZ *= 0.5; } - + $this->move($this->speedX, $this->speedY, $this->speedZ); - + if(!$this->onGround){ $this->speedX *= 0.95; $this->speedY *= 0.95; $this->speedZ *= 0.95; } - + } public function applyCollision(Entity $collided){ $diffX = $collided->x - $this->x; $diffZ = $collided->z - $this->z; - $dist = $diffX * $diffX + $diffZ * $diffZ; + $dist = $diffX*$diffX + $diffZ*$diffZ; if($dist >= 0.0001){ $sqrtMax = sqrt($dist); $diffX /= $sqrtMax; $diffZ /= $sqrtMax; - + $col = (($v = 1 / $sqrtMax) > 1 ? 1 : $v); $diffX *= $col; $diffZ *= $col; $diffX *= 0.1; $diffZ *= 0.1; - + $diffX *= 0.5; $diffZ *= 0.5; - + $this->addVelocity(-$diffX, 0, -$diffZ); $collided->addVelocity($diffX / 4, 0, $diffZ / 4); } @@ -340,18 +345,18 @@ class Minecart extends Vehicle{ } $this->updateLast(); //$this->updatePosition(); - + $this->speedY -= 0.04; //TODO port stuff - + $blockX = floor($this->x); $blockY = floor($this->y); $blockZ = floor($this->z); - + if(RailBaseBlock::isRailBlock($this->level, $blockX, $blockY - 1, $blockZ)){ --$blockY; } - + [$id, $meta] = $this->level->level->getBlock($blockX, $blockY, $blockZ); if(RailBaseBlock::isRailID($id)){ $this->moveAlongTrack($blockX, $blockY, $blockZ, 0.4, 0.0078125, $id, $meta); @@ -361,102 +366,100 @@ class Minecart extends Vehicle{ } $this->doBlocksCollision(); - + $this->pitch = 0; $diffX = $this->lastX - $this->x; $diffZ = $this->lastZ - $this->z; - - if($diffX * $diffX + $diffZ * $diffZ > 0.001){ + + if($diffX*$diffX + $diffZ*$diffZ > 0.001){ $this->yaw = atan2($diffZ, $diffX) * 180 / M_PI; - + if($this->isInReverse) $this->yaw += 180; } - + $yw = fmod($this->yaw - $this->lastYaw, 360); if($yw >= 180) $yw -= 360; if($yw < 180) $yw += 360; - + if($yw < -170 || $yw >= 170){ $this->isInReverse = !$this->isInReverse; $this->yaw = $this->yaw + 180; } - + $bb = $this->boundingBox->expand(0.2, 0, 0.2); - $minChunkX = ((int) ($bb->minX - 2)) >> 4; - $minChunkZ = ((int) ($bb->minZ - 2)) >> 4; - $maxChunkX = ((int) ($bb->minX + 2)) >> 4; - $maxChunkZ = ((int) ($bb->minZ + 2)) >> 4; - + $minChunkX = ((int)($bb->minX - 2)) >> 4; + $minChunkZ = ((int)($bb->minZ - 2)) >> 4; + $maxChunkX = ((int)($bb->minX + 2)) >> 4; + $maxChunkZ = ((int)($bb->minZ + 2)) >> 4; + //TODO also index by chunkY? for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){ for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ){ $ind = "$chunkX $chunkZ"; foreach($this->level->entityListPositioned[$ind] ?? [] as $entid){ $e = ($this->level->entityList[$entid] ?? null); - if($e instanceof Entity && $e->eid != $this->eid && $e->eid != $this->linkedEntity){ + if($e instanceof Entity && $e->eid != $this->eid && $e->eid != $this->rider){ if($e->isPushable() && $e->boundingBox->intersectsWith($bb)){ if($e->isPlayer()){ $this->applyCollision($e); }else{ $e->applyCollision($this); } - + } } } } } } - + public function close() { parent::close(); - if($this->linkedEntity != 0){ - $ent = $this->level->entityList[$this->linkedEntity] ?? false; - if($ent instanceof Entity){ - $ent->stopRiding(); - }else{ - ConsoleAPI::warn("$this is being ridden by invalid entity {$this->linkedEntity}"); - } - } } - + public function isPushable(){ return false; //TODO replace with true } - - public function spawn($player){ - $pk = new AddEntityPacket; - $pk->eid = $this->eid; - $pk->type = $this->type; - $pk->x = $this->x; - $pk->y = $this->y; //+ $this->yOffset; - $pk->z = $this->z; - $pk->yaw = $this->yaw; - $pk->pitch = $this->pitch; - $player->dataPacket($pk); - - $pk = new SetEntityMotionPacket; - $pk->eid = $this->eid; - $pk->speedX = $this->speedX; - $pk->speedY = $this->speedY; - $pk->speedZ = $this->speedZ; - $player->dataPacket($pk); + + public function spawn(Player $player){ + if(!$player->hasEntity($this)){ + $player->addEntity($this); + $pk = new AddEntityPacket; + $pk->eid = $this->eid; + $pk->type = $this->type; + $pk->x = $this->x; + $pk->y = $this->y; //+ $this->yOffset; + $pk->z = $this->z; + $pk->yaw = $this->yaw; + $pk->pitch = $this->pitch; + $player->entityQueueDataPacket($pk); + + $pk = new SetEntityMotionPacket; + $pk->eid = $this->eid; + $pk->speedX = $this->speedX; + $pk->speedY = $this->speedY; + $pk->speedZ = $this->speedZ; + $player->entityQueueDataPacket($pk); + $this->sendLinkPackets($player); + return true; + } + return false; } - + public function interactWith(Entity $e, $action){ if($action === InteractPacket::ACTION_HOLD && $e->isPlayer() && $this->canRide($e)){ $e->setRiding($this); return true; } - if($action === InteractPacket::ACTION_ATTACK && $e->eid == $this->linkedEntity){ + if($action === InteractPacket::ACTION_ATTACK && $e->eid == $this->rider){ return false; //TODO more vanilla way? } parent::interactWith($e, $action); } public function canRide($e) { - return $this->linkedEntity == 0 && $e->linkedEntity == 0; + return $this->rider == 0; } } diff --git a/src/entity/object/Painting.php b/src/entity/object/Painting.php index c451075f..86e625ff 100644 --- a/src/entity/object/Painting.php +++ b/src/entity/object/Painting.php @@ -3,23 +3,23 @@ class Painting extends Entity{ const CLASS_TYPE = ENTITY_OBJECT; const TYPE = OBJECT_PAINTING; - + public $motive; public $direction; public $xPos, $yPos, $zPos; - + public $isValid = true; - + public function __construct(Level $level, $eid, $class, $type = 0, $data = []){ parent::__construct($level, $eid, $class, $type, $data); $this->x = $this->data["TileX"] ?? $this->x; $this->y = $this->data["TileY"] ?? $this->y; $this->z = $this->data["TileZ"] ?? $this->z; - - $this->xPos = $this->data["xPos"] ?? (int) $this->x; - $this->zPos = $this->data["zPos"] ?? (int) $this->z; - $this->yPos = $this->data["yPos"] ?? (int) $this->y; - + + $this->xPos = $this->data["xPos"] ?? (int)$this->x; + $this->zPos = $this->data["zPos"] ?? (int)$this->z; + $this->yPos = $this->data["yPos"] ?? (int)$this->y; + $this->health = 1; $this->canBeAttacked = true; $this->width = 1; @@ -30,30 +30,30 @@ class Painting extends Entity{ if($dir === false){ $dir = floor($this->yaw / 90); } - + if($mot === false){ $this->setRandomMotive($dir); - + }else{ $this->motive = $mot; $this->direction = $dir; $this->setDirection($dir); } } - - public $counter = 0; + + public $scounter = 0; public function update($now){ if($this->closed === true){ return false; } - if(++$this->counter >= 100){ - $this->counter = 0; + if(++$this->scounter >= 100){ + $this->scounter = 0; if(!$this->survives() && !$this->dead){ //maybe dont check entity collision? $this->makeDead("nosurvive"); } } - + return true; } @@ -62,34 +62,34 @@ class Painting extends Entity{ foreach(PaintingItem::$motives as $name => $motive){ $this->motive = $name; $this->setDirection($dir); - + if($this->survives()){ $tochoose[] = $name; } } if(count($tochoose) > 0){ - $ind = mt_rand(0, count($tochoose) - 1); + $ind = mt_rand(0, count($tochoose)-1); }else{ $this->isValid = false; return; } - + $this->motive = $tochoose[$ind]; $this->setDirection($dir); } - + public static function offs($n){ if($n == 32 || $n == 64) return 0.5; return 0; } - + const DIRECTION_OPPOSITE = [2, 3, 0, 1]; public function setDirection($dir){ $this->direction = $dir; $this->lastYaw = $this->yaw = $dir * 90; - $size = PaintingItem::$motives[$this->motive] ?? [1, 1]; - $width = $size[0] * 16; - $height = $size[1] * 16; + $size = PaintingItem::$motives[$this->motive] ?? array(1, 1); + $width = $size[0]*16; + $height = $size[1]*16; if($dir == 2 || $dir == 0){ $v10 = 2; $v9 = $width; @@ -98,28 +98,28 @@ class Painting extends Entity{ $v9 = 2; $v10 = $width; } - + $v12 = $v9 * 0.03125; $v13 = $height * 0.03125; $v14 = $v10 * 0.03125; $v15 = $this->xPos + 0.5; $v16 = $this->yPos + 0.5; $v17 = $this->zPos + 0.5; //XXX check - + if($dir == 2){ $v17 = $v17 - 0.5625; $v15 = $v15 - self::offs($width); - }elseif($dir == 1){ + }else if($dir == 1){ $v15 = $v15 - 0.5625; $v17 = $v17 + self::offs($width); - }elseif($dir == 3){ + }else if($dir == 3){ $v15 = $v15 + 0.5625; $v17 = $v17 - self::offs($width); }else{ $v17 = $v17 + 0.5625; $v15 = $v15 + self::offs($width); } - + $v23 = $v16 + self::offs($height); $this->setPos($v15, $v23, $v17); $this->boundingBox->minX = ($v15 - $v12) + 0.03125; @@ -129,35 +129,35 @@ class Painting extends Entity{ $this->boundingBox->maxY = ($v23 + $v13) - 0.03125; $this->boundingBox->maxZ = ($v17 + $v14) - 0.03125; } - + public function getDrops(){ return [ [PAINTING, 0, 1] ]; } - + public function isPickable(){ return true; } - + public function survives(){ $cubes = $this->level->getCubes($this, $this->boundingBox); if(count($cubes) == 0){ - - $size = PaintingItem::$motives[$this->motive] ?? [1, 1]; + + $size = PaintingItem::$motives[$this->motive] ?? array(1, 1); $width = $size[0]; - $width2 = $width * 16 / 32; + $width2 = $width*16/32; $height = $size[1]; - $height2 = $height * 16 / 32; + $height2 = $height*16/32; if($width < 1) $width = 1; if($height < 1) $height = 1; $positionX = $this->xPos; $positionZ = $this->zPos; if($this->direction == 2 || $this->direction == 0) $positionX = floor($this->x - $width2); if($this->direction == 1 || $this->direction == 3) $positionZ = floor($this->z - $width2); - + $minY = floor($this->y - $height2); - + for($off = 0; $off < $width; ++$off){ for($yoff = 0; $yoff < $height; ++$yoff){ $y = $minY + $yoff; @@ -166,13 +166,13 @@ class Painting extends Entity{ }else{ $id = $this->level->level->getBlockId($positionX + $off, $y, $this->zPos); } - + if(!StaticBlock::getIsSolid($id)){ return false; } } } - + $ents = $this->level->getEntitiesInAABBOfType($this->boundingBox, ENTITY_OBJECT); foreach($ents as $e){ if($e->eid == $this->eid) continue; @@ -182,13 +182,13 @@ class Painting extends Entity{ } return true; } - + return false; } - + public function createSaveData(){ $data = parent::createSaveData(); - + $data["Motive"] = $this->motive; $data["Direction"] = $this->direction; $data["xPos"] = $this->xPos; @@ -197,14 +197,20 @@ class Painting extends Entity{ return $data; } - public function spawn($player){ - $pk = new AddPaintingPacket; - $pk->eid = $this->eid; - $pk->x = (int) $this->xPos; - $pk->y = (int) $this->yPos; - $pk->z = (int) $this->zPos; - $pk->direction = $this->direction; - $pk->title = $this->motive; - $player->dataPacket($pk); + public function spawn(Player $player){ + if(!$player->hasEntity($this)){ + $player->addEntity($this); + $pk = new AddPaintingPacket; + $pk->eid = $this->eid; + $pk->x = (int) $this->xPos; + $pk->y = (int) $this->yPos; + $pk->z = (int) $this->zPos; + $pk->direction = $this->direction; + $pk->title = $this->motive; + $player->entityQueueDataPacket($pk); + $this->sendLinkPackets($player); + return true; + } + return false; } } diff --git a/src/entity/object/PrimedTNT.php b/src/entity/object/PrimedTNT.php index b6be4d6c..9714663a 100644 --- a/src/entity/object/PrimedTNT.php +++ b/src/entity/object/PrimedTNT.php @@ -12,13 +12,13 @@ class PrimedTNT extends Entity{ $this->gravity = 0.04; $this->setSize(0.98, 0.98); $this->yOffset = $this->height / 2; - $this->setHealth(10000000, "generic"); + $this->setHealth(10000000, "generic", allowHarm: false); } - + public function isPickable(){ return !$this->dead; } - + public function getMetadata(){ $d = parent::getMetadata(); $d[16]["value"] = (int) $this->data["fuse"]; @@ -26,34 +26,34 @@ class PrimedTNT extends Entity{ } public function createSaveData(){ $data = parent::createSaveData(); - + $data["fuse"] = $this->data["fuse"]; $data["power"] = $this->data["power"]; - + return $data; } - + public function update($now){ if($this->closed) return; $this->lastX = $this->x; $this->lastY = $this->y; $this->lastZ = $this->z; - + $this->speedY -= 0.04; $this->move($this->speedX, $this->speedY, $this->speedZ); - $this->speedX * -0.98; + $this->speedX *- 0.98; $this->speedY *= 0.98; $this->speedZ *= 0.98; - + if($this->onGround){ $this->speedX *= 0.7; $this->speedZ *= 0.7; - + $this->speedY *= -0.5; } - + $tickDiff = ($now - $this->lastUpdate) / 0.05; - + $this->data["fuse"] -= $tickDiff; $this->updateMetadata(); if($this->data["fuse"] <= 0){ @@ -61,21 +61,28 @@ class PrimedTNT extends Entity{ $explosion = new Explosion($this, $this->data["power"]); $explosion->explode(); } - + $this->lastUpdate = $now; } - - public function spawn($player){ - $pk = new AddEntityPacket; - $pk->eid = $this->eid; - $pk->type = $this->type; - $pk->x = $this->x; - $pk->y = $this->y; - $pk->z = $this->z; - $pk->did = 1; - $pk->speedX = $this->speedX; - $pk->speedY = $this->speedY; - $pk->speedZ = $this->speedZ; - $player->dataPacket($pk); + + public function spawn(Player $player){ + if(!$player->hasEntity($this)){ + $player->addEntity($this); + $pk = new AddEntityPacket; + $pk->eid = $this->eid; + $pk->type = $this->type; + $pk->x = $this->x; + $pk->y = $this->y; + $pk->z = $this->z; + $pk->did = 1; + $pk->speedX = $this->speedX; + $pk->speedY = $this->speedY; + $pk->speedZ = $this->speedZ; + $player->entityQueueDataPacket($pk); + $this->sendLinkPackets($player); + return true; + } + return false; + } } \ No newline at end of file diff --git a/src/entity/object/TripodCamera.php b/src/entity/object/TripodCamera.php index f69339d8..3437d45c 100644 --- a/src/entity/object/TripodCamera.php +++ b/src/entity/object/TripodCamera.php @@ -5,7 +5,7 @@ class TripodCamera extends Entity{ function __construct(Level $level, $eid, $class, $type = 0, $data = []){ parent::__construct($level, $eid, $class, $type, $data); - $this->setHealth(PHP_INT_MAX, "generic"); + $this->setHealth(PHP_INT_MAX, "generic", allowHarm: false); } public function isPickable(){ diff --git a/src/material/ArmorMaterial.php b/src/material/ArmorMaterial.php new file mode 100644 index 00000000..0c65a25c --- /dev/null +++ b/src/material/ArmorMaterial.php @@ -0,0 +1,9 @@ + "AirBlock", - STONE => "StoneBlock", - GRASS => "GrassBlock", - DIRT => "DirtBlock", - COBBLESTONE => "CobblestoneBlock", - PLANKS => "PlanksBlock", - SAPLING => "SaplingBlock", - BEDROCK => "BedrockBlock", - WATER => "WaterBlock", - STILL_WATER => "StillWaterBlock", - LAVA => "LavaBlock", - STILL_LAVA => "StillLavaBlock", - SAND => "SandBlock", - GRAVEL => "GravelBlock", - GOLD_ORE => "GoldOreBlock", - IRON_ORE => "IronOreBlock", - COAL_ORE => "CoalOreBlock", - WOOD => "WoodBlock", - LEAVES => "LeavesBlock", - SPONGE => "SpongeBlock", - GLASS => "GlassBlock", - LAPIS_ORE => "LapisOreBlock", - LAPIS_BLOCK => "LapisBlock", - SANDSTONE => "SandstoneBlock", - BED_BLOCK => "BedBlock", - POWERED_RAIL => "PoweredRailBlock", - COBWEB => "CobwebBlock", - TALL_GRASS => "TallGrassBlock", - DEAD_BUSH => "DeadBushBlock", - WOOL => "WoolBlock", - DANDELION => "DandelionBlock", - CYAN_FLOWER => "CyanFlowerBlock", - BROWN_MUSHROOM => "BrownMushroomBlock", - RED_MUSHROOM => "RedMushRoomBlock", - GOLD_BLOCK => "GoldBlock", - IRON_BLOCK => "IronBlock", - DOUBLE_SLAB => "DoubleSlabBlock", - SLAB => "SlabBlock", - BRICKS_BLOCK => "BricksBlock", - TNT => "TNTBlock", - BOOKSHELF => "BookshelfBlock", - MOSS_STONE => "MossStoneBlock", - OBSIDIAN => "ObsidianBlock", - TORCH => "TorchBlock", - FIRE => "FireBlock", + public static $mushroomSpread = true; + + public static $class = array( + AIR => "AirBlock", + STONE => "StoneBlock", + GRASS => "GrassBlock", + DIRT => "DirtBlock", + COBBLESTONE => "CobblestoneBlock", + PLANKS => "PlanksBlock", + SAPLING => "SaplingBlock", + BEDROCK => "BedrockBlock", + WATER => "WaterBlock", + STILL_WATER => "StillWaterBlock", + LAVA => "LavaBlock", + STILL_LAVA => "StillLavaBlock", + SAND => "SandBlock", + GRAVEL => "GravelBlock", + GOLD_ORE => "GoldOreBlock", + IRON_ORE => "IronOreBlock", + COAL_ORE => "CoalOreBlock", + WOOD => "WoodBlock", + LEAVES => "LeavesBlock", + SPONGE => "SpongeBlock", + GLASS => "GlassBlock", + LAPIS_ORE => "LapisOreBlock", + LAPIS_BLOCK => "LapisBlock", + SANDSTONE => "SandstoneBlock", + BED_BLOCK => "BedBlock", + POWERED_RAIL => "PoweredRailBlock", + COBWEB => "CobwebBlock", + TALL_GRASS => "TallGrassBlock", + DEAD_BUSH => "DeadBushBlock", + WOOL => "WoolBlock", + DANDELION => "DandelionBlock", + CYAN_FLOWER => "CyanFlowerBlock", + BROWN_MUSHROOM => "BrownMushroomBlock", + RED_MUSHROOM => "RedMushRoomBlock", + GOLD_BLOCK => "GoldBlock", + IRON_BLOCK => "IronBlock", + DOUBLE_SLAB => "DoubleSlabBlock", + SLAB => "SlabBlock", + BRICKS_BLOCK => "BricksBlock", + TNT => "TNTBlock", + BOOKSHELF => "BookshelfBlock", + MOSS_STONE => "MossStoneBlock", + OBSIDIAN => "ObsidianBlock", + TORCH => "TorchBlock", + FIRE => "FireBlock", - WOOD_STAIRS => "WoodStairsBlock", - CHEST => "ChestBlock", + WOOD_STAIRS => "WoodStairsBlock", + CHEST => "ChestBlock", - DIAMOND_ORE => "DiamondOreBlock", - DIAMOND_BLOCK => "DiamondBlock", - WORKBENCH => "WorkbenchBlock", - WHEAT_BLOCK => "WheatBlock", - FARMLAND => "FarmlandBlock", - FURNACE => "FurnaceBlock", - BURNING_FURNACE => "BurningFurnaceBlock", - SIGN_POST => "SignPostBlock", - WOOD_DOOR_BLOCK => "WoodDoorBlock", - LADDER => "LadderBlock", - RAIL => "RailBlock", - COBBLESTONE_STAIRS => "CobblestoneStairsBlock", - WALL_SIGN => "WallSignBlock", + DIAMOND_ORE => "DiamondOreBlock", + DIAMOND_BLOCK => "DiamondBlock", + WORKBENCH => "WorkbenchBlock", + WHEAT_BLOCK => "WheatBlock", + FARMLAND => "FarmlandBlock", + FURNACE => "FurnaceBlock", + BURNING_FURNACE => "BurningFurnaceBlock", + SIGN_POST => "SignPostBlock", + WOOD_DOOR_BLOCK => "WoodDoorBlock", + LADDER => "LadderBlock", + RAIL => "RailBlock", + COBBLESTONE_STAIRS => "CobblestoneStairsBlock", + WALL_SIGN => "WallSignBlock", - IRON_DOOR_BLOCK => "IronDoorBlock", - REDSTONE_ORE => "RedstoneOreBlock", - GLOWING_REDSTONE_ORE => "GlowingRedstoneOreBlock", + IRON_DOOR_BLOCK => "IronDoorBlock", + REDSTONE_ORE => "RedstoneOreBlock", + GLOWING_REDSTONE_ORE => "GlowingRedstoneOreBlock", - SNOW_LAYER => "SnowLayerBlock", - ICE => "IceBlock", - SNOW_BLOCK => "SnowBlock", - CACTUS => "CactusBlock", - CLAY_BLOCK => "ClayBlock", - SUGARCANE_BLOCK => "SugarcaneBlock", + SNOW_LAYER => "SnowLayerBlock", + ICE => "IceBlock", + SNOW_BLOCK => "SnowBlock", + CACTUS => "CactusBlock", + CLAY_BLOCK => "ClayBlock", + SUGARCANE_BLOCK => "SugarcaneBlock", - FENCE => "FenceBlock", - PUMPKIN => "PumpkinBlock", - NETHERRACK => "NetherrackBlock", - SOUL_SAND => "SoulSandBlock", - GLOWSTONE_BLOCK => "GlowstoneBlock", + FENCE => "FenceBlock", + PUMPKIN => "PumpkinBlock", + NETHERRACK => "NetherrackBlock", + SOUL_SAND => "SoulSandBlock", + GLOWSTONE_BLOCK => "GlowstoneBlock", - LIT_PUMPKIN => "LitPumpkinBlock", - INVISIBLE_BEDROCK => "InvisibleBedrockBlock", + LIT_PUMPKIN => "LitPumpkinBlock", + INVISIBLE_BEDROCK => "InvisibleBedrockBlock", + + CAKE_BLOCK => "CakeBlock", + + TRAPDOOR => "TrapdoorBlock", - CAKE_BLOCK => "CakeBlock", + STONE_BRICKS => "StoneBricksBlock", - TRAPDOOR => "TrapdoorBlock", + IRON_BARS => "IronBarsBlock", + GLASS_PANE => "GlassPaneBlock", + MELON_BLOCK => "MelonBlock", + PUMPKIN_STEM => "PumpkinStemBlock", + MELON_STEM => "MelonStemBlock", - STONE_BRICKS => "StoneBricksBlock", + FENCE_GATE => "FenceGateBlock", + BRICK_STAIRS => "BrickStairsBlock", + STONE_BRICK_STAIRS => "StoneBrickStairsBlock", - IRON_BARS => "IronBarsBlock", - GLASS_PANE => "GlassPaneBlock", - MELON_BLOCK => "MelonBlock", - PUMPKIN_STEM => "PumpkinStemBlock", - MELON_STEM => "MelonStemBlock", + NETHER_BRICKS => "NetherBricksBlock", - FENCE_GATE => "FenceGateBlock", - BRICK_STAIRS => "BrickStairsBlock", - STONE_BRICK_STAIRS => "StoneBrickStairsBlock", + NETHER_BRICKS_STAIRS => "NetherBricksStairsBlock", - NETHER_BRICKS => "NetherBricksBlock", + SANDSTONE_STAIRS => "SandstoneStairsBlock", + + SPRUCE_WOOD_STAIRS => "SpruceWoodStairsBlock", + BIRCH_WOOD_STAIRS => "BirchWoodStairsBlock", + JUNGLE_WOOD_STAIRS => "JungleWoodStairsBlock", + STONE_WALL => "StoneWallBlock", + + CARROT_BLOCK => "CarrotBlock", + POTATO_BLOCK => "PotatoBlock", - NETHER_BRICKS_STAIRS => "NetherBricksStairsBlock", - - SANDSTONE_STAIRS => "SandstoneStairsBlock", - - SPRUCE_WOOD_STAIRS => "SpruceWoodStairsBlock", - BIRCH_WOOD_STAIRS => "BirchWoodStairsBlock", - JUNGLE_WOOD_STAIRS => "JungleWoodStairsBlock", - STONE_WALL => "StoneWallBlock", - - CARROT_BLOCK => "CarrotBlock", - POTATO_BLOCK => "PotatoBlock", - - QUARTZ_BLOCK => "QuartzBlock", - QUARTZ_STAIRS => "QuartzStairsBlock", - DOUBLE_WOOD_SLAB => "DoubleWoodSlabBlock", - WOOD_SLAB => "WoodSlabBlock", - - HAY_BALE => "HayBaleBlock", - CARPET => "CarpetBlock", - - COAL_BLOCK => "CoalBlock", - - BEETROOT_BLOCK => "BeetrootBlock", - STONECUTTER => "StonecutterBlock", - GLOWING_OBSIDIAN => "GlowingObsidianBlock", - NETHER_REACTOR => "NetherReactorBlock", - INFO_UPDATE => "InfoUpdateBlock", - INFO_UPDATE2 => "InfoUpdate2Block", - RESERVED6 => "Reserved6Block", - ]; + QUARTZ_BLOCK => "QuartzBlock", + QUARTZ_STAIRS => "QuartzStairsBlock", + DOUBLE_WOOD_SLAB => "DoubleWoodSlabBlock", + WOOD_SLAB => "WoodSlabBlock", + + HAY_BALE => "HayBaleBlock", + CARPET => "CarpetBlock", + + COAL_BLOCK => "CoalBlock", + + BEETROOT_BLOCK => "BeetrootBlock", + STONECUTTER => "StonecutterBlock", + GLOWING_OBSIDIAN => "GlowingObsidianBlock", + NETHER_REACTOR => "NetherReactorBlock", + INFO_UPDATE => "InfoUpdateBlock", + INFO_UPDATE2 => "InfoUpdate2Block", + RESERVED6 => "Reserved6Block", + ); + + /** + * @var Material + */ + public $material; + public $id; public $meta; public $name; - public $breakTime; public $boundingBox; public $hardness; + public $breakTime = 0; public $isActivable = false; public $breakable = true; public $isFlowable = false; @@ -154,51 +162,55 @@ abstract class Block extends Position{ public $y = 0; public $z = 0; public $slipperiness; + + public $lightEmission = 0; + public $lightBlock = 0; + public static function interact(Level $level, $x, $y, $z, Player $player){} - + public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){} - + public static function getAABB(Level $level, $x, $y, $z){ return StaticBlock::getAABB(static::$blockID, $x, $y, $z); } - + public static function containsX($id, $v){ return !($v == null) && $v->y >= StaticBlock::$minYs[$id] && $v->y <= StaticBlock::$maxYs[$id] && $v->z >= StaticBlock::$minZs[$id] && $v->z <= StaticBlock::$maxZs[$id]; } - + public static function containsY($id, $v){ return !($v == null) && $v->x >= StaticBlock::$minXs[$id] && $v->x <= StaticBlock::$maxXs[$id] && $v->z >= StaticBlock::$minZs[$id] && $v->z <= StaticBlock::$maxZs[$id]; } - + public static function containsZ($id, $v){ return !($v == null) && $v->x >= StaticBlock::$minXs[$id] && $v->x <= StaticBlock::$maxXs[$id] && $v->y >= StaticBlock::$minYs[$id] && $v->y <= StaticBlock::$maxYs[$id]; } - + public static function updateShape(Level $level, $x, $y, $z){ - + } - + public static function clip(Level $level, $x, $y, $z, Vector3 $start, Vector3 $end){ static::updateShape($level, $x, $y, $z); $id = $level->level->getBlockID($x, $y, $z); - + $start = $start->subtract($x, $y, $z); $end = $end->subtract($x, $y, $z); - + $v7 = $start->clipX($end, StaticBlock::$minXs[$id]); $v8 = $start->clipX($end, StaticBlock::$maxXs[$id]); $v9 = $start->clipY($end, StaticBlock::$minYs[$id]); $v10 = $start->clipY($end, StaticBlock::$maxYs[$id]); $v11 = $start->clipZ($end, StaticBlock::$minZs[$id]); $v12 = $start->clipZ($end, StaticBlock::$maxZs[$id]); - + if(!self::containsX($id, $v7)) $v7 = null; if(!self::containsX($id, $v8)) $v8 = null; if(!self::containsY($id, $v9)) $v9 = null; if(!self::containsY($id, $v10)) $v10 = null; if(!self::containsZ($id, $v11)) $v11 = null; if(!self::containsZ($id, $v12)) $v12 = null; - + $v13 = null; if($v7 != null && ($v13 == null || $start->distanceSquared($v7) < $start->distanceSquared($v13))) $v13 = $v7; if($v8 != null && ($v13 == null || $start->distanceSquared($v8) < $start->distanceSquared($v13))) $v13 = $v8; @@ -206,9 +218,9 @@ abstract class Block extends Position{ if($v10 != null && ($v13 == null || $start->distanceSquared($v10) < $start->distanceSquared($v13))) $v13 = $v10; if($v11 != null && ($v13 == null || $start->distanceSquared($v11) < $start->distanceSquared($v13))) $v13 = $v11; if($v12 != null && ($v13 == null || $start->distanceSquared($v12) < $start->distanceSquared($v13))) $v13 = $v12; - + if($v13 == null) return null; - + $v14 = -1; if($v13 == $v7) $v14 = 4; if($v13 == $v8) $v14 = 5; @@ -216,10 +228,10 @@ abstract class Block extends Position{ if($v13 == $v10) $v14 = 1; if($v13 == $v11) $v14 = 2; if($v13 == $v12) $v14 = 3; - + return MovingObjectPosition::fromBlock($x, $y, $z, $v14, $v13->add($x, $y, $z)); } - + public static function onPlace(Level $level, $x, $y, $z){} public static function addVelocityToEntity(Level $level, $x, $y, $z, Entity $entity, Vector3 $velocityVector){} public static function onRandomTick(Level $level, $x, $y, $z){} @@ -229,25 +241,26 @@ abstract class Block extends Position{ return [static::getAABB($level, $x, $y, $z)]; } public static function onEntityCollidedWithBlock(Level $level, $x, $y, $z, Entity $entity){} - + + public function __construct($id, $meta = 0, $name = "Unknown"){ $this->id = (int) $id; - $this->meta = (int) $meta; + $this->meta = ((int) $meta) & 0xf; $this->name = $name; $this->breakTime = 0.20; $this->hardness = 10; $this->slipperiness = 0.6; $this->boundingBox = new AxisAlignedBB($this->x, $this->y, $this->z, $this->x + 1, $this->y + 1, $this->z + 1); } - + final public function getHardness(){ return ($this->hardness); } - + final public function getName(){ return $this->name; } - + final public function getID(){ return $this->id; } @@ -257,7 +270,19 @@ abstract class Block extends Position{ final public function getMetadata(){ return $this->meta & 0x0F; } - + + public function getDestroyProgress(Player $player){ + if($this->breakTime < 0) return 0; + if($this->breakTime == 0) return INF; //instabreak + $id = $this->getID(); + $meta = $this->getMetadata(); + if($player->canDestroy($id, $meta)){ + return $player->getDestroySpeed($id, $meta) / $this->breakTime / 30; + } + + return (1 / $this->breakTime) / 100; + } + final public function position(Position $v){ $this->level = $v->level; $this->x = (int) $v->x; @@ -265,24 +290,26 @@ abstract class Block extends Position{ $this->z = (int) $v->z; $this->boundingBox->setBounds($this->x, $this->y, $this->z, $this->x + 1, $this->y + 1, $this->z + 1); } - + public function getDrops(Item $item, Player $player){ if(!isset(Block::$class[$this->id])){ //Unknown blocks - return []; + return array(); }else{ - return [ - [$this->id, $this->meta, 1], - ]; + return array( + array($this->id, $this->meta, 1), + ); } } - + public function getBreakTime(Item $item, Player $player){ + if($this->hardness < 0) return INF; if(($player->gamemode & 0x01) === 0x01){ return 0.15; } + if($player->canDestroy($this->getID(), $this->getMetadata())) return $this->breakTime; } - + public function getSide($side, $step = 1){ $v = parent::getSide($side, $step); if($this->level instanceof Level){ @@ -290,17 +317,19 @@ abstract class Block extends Position{ } return $v; } - + final public function __toString(){ return "Block ". $this->name ." (".$this->id.":".$this->meta.")"; } - - abstract function isBreakable(Item $item, Player $player); - + + public function isBreakable(Item $item, Player $player){ + return $this->hardness >= 0; + } + abstract function onBreak(Item $item, Player $player); - + abstract function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz); - + abstract function onActivate(Item $item, Player $player); } diff --git a/src/material/Item.php b/src/material/Item.php index 22e1b392..ca202716 100755 --- a/src/material/Item.php +++ b/src/material/Item.php @@ -5,12 +5,12 @@ class Item{ const TOOL_PICKAXE = 1; const TOOL_AXE = 2; const TOOL_SHOVEL = 3; - const TOOL_HOE = 4; - + const TOOL_HOE = 4; + const DEF_DAMAGE = 1; - - public static $class = [ - + + public static $class = array( + //armor LEATHER_CAP => "LeatherCapItem", LEATHER_TUNIC => "LeatherTunicItem", @@ -32,7 +32,7 @@ class Item{ GOLDEN_CHESTPLATE => "GoldenChestplateItem", GOLDEN_LEGGINGS => "GoldenLeggingsItem", GOLDEN_BOOTS => "GoldenBootsItem", - + //food APPLE => "AppleItem", MUSHROOM_STEW => "MushroomStewItem", @@ -51,7 +51,7 @@ class Item{ PUMPKIN_PIE => "PumpkinPieItem", BEETROOT => "BeetrootItem", BEETROOT_SOUP => "BeetrootSoupItem", - + //generic ARROW => "ArrowItem", COAL => "CoalItem", @@ -95,7 +95,7 @@ class Item{ QUARTZ => "QuartzItem", CAMERA => "CameraItem", BEETROOT_SEEDS => "BeetrootSeedsItem", - + //tool IRON_SHOVEL => "IronShovelItem", IRON_PICKAXE => "IronPickaxeItem", @@ -127,27 +127,28 @@ class Item{ COMPASS => "CompassItem", CLOCK => "ClockItem", SHEARS => "ShearsItem", - - ]; + + ); public $block; public $id; public $meta; public $count; /** - * @var int + * @var int * Max stack size of the item. Use Item::getMaxStackSize to get stack size for specific item. */ public $maxStackSize = 64; public $durability = 0; public $name; public $isActivable = false; - + public function __construct($id, $meta = 0, $count = 1, $name = "Unknown"){ $this->id = (int) $id; - $this->meta = (int) $meta; + $this->meta = ((int) $meta) & 0xffff; $this->count = (int) $count; $this->name = $name; - if(!isset($this->block) and $this->id <= 0xff and isset(Block::$class[$this->id])){ + if(!isset($this->block) && $this->id <= 0xff && isset(Block::$class[$this->id])){ + $this->meta &= 0xf; $this->block = BlockAPI::get($this->id, $this->meta); $this->name = $this->block->getName(); } @@ -155,19 +156,27 @@ class Item{ $this->maxStackSize = 1; } } - + + public function canDestroySpecial($id, $meta){ + return false; + } + + public function getDestroySpeed($id, $meta){ + return 1.0; + } + public function isPickaxe(){ return false; } - + public function getName(){ return $this->name; } - + public function isPlaceable(){ return (($this->block instanceof Block) and $this->block->isPlaceable === true); } - + public function getBlock(){ if($this->block instanceof Block){ return $this->block; @@ -175,23 +184,23 @@ class Item{ return BlockAPI::get(AIR); } } - + public function getID(){ return $this->id; } - + public function getMetadata(){ return $this->meta; - } - + } + public function isArmor(){ return false; } - + public function getMaxStackSize(){ return $this->maxStackSize; } - + public function getFuelTime(){ if(!isset(FuelData::$duration[$this->id])){ return false; @@ -201,54 +210,75 @@ class Item{ } return false; } - + public function getSmeltItem(){ if(!isset(SmeltingData::$product[$this->id])){ return false; } - + if(isset(SmeltingData::$product[$this->id][0]) and !is_array(SmeltingData::$product[$this->id][0])){ return BlockAPI::getItem(SmeltingData::$product[$this->id][0], SmeltingData::$product[$this->id][1]); } - + if(!isset(SmeltingData::$product[$this->id][$this->meta])){ return false; } - + return BlockAPI::getItem(SmeltingData::$product[$this->id][$this->meta][0], SmeltingData::$product[$this->id][$this->meta][1]); - + } - - public function useOn($object, $force = false){ - if($force){ - if(($object instanceof Entity) and !$this->isSword()){ - $this->meta += 2; + + /** + * @param int $dmg - damage dealt to item + * @param Player $player - player who used the item + * @param boolean $helditem - modify player's helditem state or not - should be false if using by non-held item(armor damaging for example) + */ + public function hurtAndBreak($dmg, Player $player, $helditem = true){ + if(($player->gamemode & 1) !== 0) return; //dont break items in creative + + if($this->getMaxDurability() !== false){ + $this->meta += $dmg; + + if($helditem){ + $player->setSlot($player->slot, $this, send: false); + if($this->meta > $this->getMaxDurability()){ + $player->consumeSingleItem(); + } }else{ - $this->meta++; + if($this->meta > $this->getMaxDurability()){ + --$this->count; + } } - return true; } + } + + public function hurtEnemy(Entity $target, Player $attacker){ + + } + + public function mineBlock(Block $block, Player $player){ return false; } - + + public function isTool(){ return false; } - + public function getMaxDurability(){ if(!$this->isTool() and $this->id !== BOW){ return false; } - - $levels = [ //TODO rewrite(item usage too) - 2 => 33, //GOLD - 1 => 60, //WOODEN - 3 => 132, //STONE - 4 => 251, //IRON - 5 => 1562, //DIAMOND(called EMERALD in disassembled code) - FLINT_STEEL => 65, //lets assume it is correct - SHEARS => 239, //x2 - BOW => 385 //x3 + + $levels = [ + 2 => 32, //GOLD + 1 => 59, //WOODEN + 3 => 131, //STONE + 4 => 250, //IRON + 5 => 1561, //DIAMOND(called EMERALD in disassembled code) + FLINT_STEEL => 64, + SHEARS => 238, + BOW => 384 ]; if(($type = $this->getLevel()) === false){ @@ -256,14 +286,14 @@ class Item{ } return $levels[$type]; } - + public function getLevel(){ return false; } - + //TODO remove? public function getPickaxeLevel(){ //Returns false or level of the pickaxe - return match ($this->id) { + return match ($this->id) { WOODEN_PICKAXE => 1, GOLDEN_PICKAXE => 2, STONE_PICKAXE => 3, @@ -272,7 +302,7 @@ class Item{ default => false, }; } - + public function isAxe(){ return false; } @@ -280,11 +310,11 @@ class Item{ public function isSword(){ return false; } - + public function isShovel(){ return false; } - + public function isHoe(){ return false; } @@ -292,23 +322,19 @@ class Item{ public function isShears(){ return ($this->id === SHEARS); } - + public function __toString(){ - return "Item ". $this->name ." (".$this->id.":".$this->meta.")"; + return "Item ". $this->name ." (".$this->id.":".$this->meta."x{$this->count})"; } - + public function getDamageAgainstOf($e){ return Item::DEF_DAMAGE; } - - public function getDestroySpeed(Block $block, Player $player){ - return 1; - } - + public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ return false; } - + public static function getFoodHeal($id){ return match($id){ APPLE => 4, @@ -328,9 +354,16 @@ class Item{ POTATO => 1, BAKED_POTATO => 6, BEETROOT => 1, - + default => 0 }; } - + + /** + * @deprecated Item damaging changed. Use hurtAndBreak to damage the item and update it in the client's inventory correctly. + */ + public function useOn($object, $force = false){ + return false; + } + } diff --git a/src/material/Material.php b/src/material/Material.php index 0608a472..5332b046 100644 --- a/src/material/Material.php +++ b/src/material/Material.php @@ -1,10 +1,84 @@ alwaysDestroyable = true; + $this->flammable = false; + $this->translucent = false; + $this->replaceable = false; + + $this->blocksLight = true; + $this->blocksMotion = true; + $this->isLiquid = false; + $this->isSolid = true; + } + + public function isSolidBlocking(){ + if($this->translucent) return false; + return $this->blocksMotion; + } + public function letsWaterThrough(){ + if($this->isLiquid) return false; + return !$this->isSolid; + } + + public static function init(){ + self::$air = new GasMaterial(); + self::$dirt = new Material(); + self::$wood = new Material(); + self::$wood->flammable = true; + self::$stone = new Material(); + self::$stone->alwaysDestroyable = false; + self::$metal = new Material(); + self::$metal->alwaysDestroyable = false; + self::$water = new LiquidMaterial(); + self::$lava = new LiquidMaterial(); + self::$leaves = new Material(); + self::$leaves->flammable = true; + self::$leaves->translucent = true; + self::$plant = new DecorationMaterial(); + self::$replaceable_plant = new DecorationMaterial(); + self::$replaceable_plant->replaceable = true; + self::$replaceable_plant->flammable = true; + self::$sponge = new Material(); + self::$cloth = new Material(); + self::$cloth->flammable = true; + self::$fire = new GasMaterial(); + self::$fire->replaceable = true; + self::$sand = new Material(); + self::$decoration = new DecorationMaterial(); + self::$glass = new Material(); + self::$glass->translucent = true; + self::$explosive = new Material(); + self::$explosive->flammable = true; + self::$explosive->translucent = true; + self::$coral = new Material(); + self::$ice = new Material(); + self::$ice->translucent = true; + self::$topSnow = new DecorationMaterial(); + self::$topSnow->translucent = true; + self::$topSnow->replaceable = true; + self::$topSnow->alwaysDestroyable = false; + self::$snow = new Material(); + self::$snow->alwaysDestroyable = false; + self::$cactus = new Material(); + self::$cactus->translucent = true; + self::$clay = new Material(); + self::$vegetable = new Material(); + self::$portal = new Material(); + self::$cake = new Material(); + self::$web = new Material(); + self::$web->alwaysDestroyable = false; + self::$web->blocksMotion = false; + } +} + diff --git a/src/material/StaticBlock.php b/src/material/StaticBlock.php index 26a56142..30080e17 100644 --- a/src/material/StaticBlock.php +++ b/src/material/StaticBlock.php @@ -6,7 +6,7 @@ class StaticBlock { const DEFAULT_SLIPPERINESS = 0.6; const DEFAULT_HARDNESS = 0; - + private static $NULL_BOUNDS; public static $prealloc = []; public static $isSolid = []; @@ -17,18 +17,22 @@ class StaticBlock public static $hasPhysics = []; public static $isLiquid = []; public static $isFullBlock = []; - + public static $material = []; public static $hardness = []; + public static $destroyTime = []; public static $slipperiness = []; public static $boundingBoxes = []; + public static $lightBlock = []; + public static $lightEmission = []; public static $minXs = [], $minYs = [], $minZs = [], $maxXs = [], $maxYs = [], $maxZs = []; - + public static function init(){ self::$NULL_BOUNDS = new AxisAlignedBB(0, 0, 0, 0, 0, 0); + for($i = 0; $i < 256; ++$i) self::$lightBlock[$i] = self::$lightEmission[$i] = 0; foreach(Block::$class as $nonstaticname){ /**@var Block $b*/ $b = new $nonstaticname(); - + self::$isSolid[$b->getID()] = $b->isSolid; self::$isTransparent[$b->getID()] = $b->isTransparent; self::$isFlowable[$b->getID()] = $b->isFlowable; @@ -40,12 +44,16 @@ class StaticBlock self::$slipperiness[$b->getID()] = $b->slipperiness; self::$boundingBoxes[$b->getID()] = $b->boundingBox; self::$hardness[$b->getID()] = $b->getHardness(); + self::$destroyTime[$b->getID()] = $b->breakTime; + self::$material[$b->getID()] = $b->material; + self::$lightBlock[$b->getID()] = $b->lightBlock; + self::$lightEmission[$b->getID()] = $b->lightEmission; self::$prealloc[$b->getID()] = $b; $b::$blockID = $b->getID(); FireBlock::setFlammabilityAndCatchingChance($b->getID(), 0, 0); self::setBlockBounds($b->getID(), 0, 0, 0, 1, 1, 1); } - + self::setBlockBounds(BED_BLOCK, 0, 0, 0, 1, 0.5625, 1); //Cake: has bounds based on world state //Chest: has bounds based on world state @@ -68,16 +76,16 @@ class StaticBlock self::setBlockBounds(SLAB, 0, 0, 0, 1, 0.5, 1); self::setBlockBounds(RAIL, 0, 0, 0, 1, 0.125, 1); self::setBlockBounds(POWERED_RAIL, 0, 0, 0, 1, 0.125, 1); - + self::setBlockBounds(DANDELION, 0.3, 0.0, 0.3, 0.7, 0.6, 0.7); //extends Bush self::setBlockBounds(ROSE, 0.3, 0.0, 0.3, 0.7, 0.6, 0.7); //extends Bush - + self::setBlockBounds(SUGARCANE_BLOCK, 0.5 - 0.375, 0, 0.5 - 0.375, 0.5 + 0.375, 1, 0.5 + 0.375); self::setBlockBounds(SNOW_LAYER, 0, 0, 0, 1, 0.125, 1); self::setBlockBounds(CARPET, 0, 0, 0, 1, 0, 1); //Stairs: based on different factors //Stone wall: based on state - + //Fire related stuff FireBlock::setFlammabilityAndCatchingChance(PLANKS, 5, 20); FireBlock::setFlammabilityAndCatchingChance(DOUBLE_WOOD_SLAB, 5, 20); @@ -101,29 +109,33 @@ class StaticBlock FireBlock::setFlammabilityAndCatchingChance(HAY_BALE, 60, 20); FireBlock::setFlammabilityAndCatchingChance(SPONGE, 30, 60); } - + + public static function getMaterial($blockID){ + return self::$material[$blockID] ?? Material::$air; + } + public static function setBlockBounds($blockID, $minX, $minY, $minZ, $maxX, $maxY, $maxZ){ self::$maxXs[$blockID] = $maxX; self::$maxYs[$blockID] = $maxY; self::$maxZs[$blockID] = $maxZ; - + self::$minXs[$blockID] = $minX; self::$minYs[$blockID] = $minY; self::$minZs[$blockID] = $minZ; } - + public static function getAABB($id, $x, $y, $z){ return new AxisAlignedBB(self::$minXs[$id] + $x, self::$minYs[$id] + $y, self::$minZs[$id] + $z, self::$maxXs[$id] + $x, self::$maxYs[$id] + $y, self::$maxZs[$id] + $z); //TODO get bb from self::$boundingBoxes ? } - + public static function getBlock($id){ return self::$prealloc[$id] ?? self::$prealloc[0]; //accessing preallocated instances is faster Block::$class[$id] ?? Block::$class[0]; } - + public static function getHardness($id){ - return self::$hardness[$id] ?? StaticBlock::DEFAULT_HARDNESS; + return self::$hardness[$id] ?? StaticBlock::DEFAULT_HARDNESS; } - + //TODO: use static block min/max public static function getBoundingBoxForBlockCoords($id, $x, $y, $z){ /**@var AxisAlignedBB $bb*/ @@ -134,39 +146,40 @@ class StaticBlock $bb = clone $bb; return $bb->setBounds($x + $bb->minX, $y + $bb->minY, $z + $bb->minZ, $x + $bb->maxX, $y + $bb->maxY, $z + $bb->maxZ); } - + + public static function getSlipperiness($id){ return self::$slipperiness[$id] ?? StaticBlock::DEFAULT_SLIPPERINESS; } - + public static function getIsSolid($id){ return self::$isSolid[$id] ?? false; } - + public static function getIsTransparent($id){ return self::$isTransparent[$id] ?? false; } - + public static function getIsFlowable($id){ return self::$isFlowable[$id] ?? false; } - + public static function getIsReplaceable($id){ return self::$isReplaceable[$id] ?? false; } - + public static function getIsPlaceable($id){ return self::$isPlaceable[$id] ?? false; } - + public static function getHasPhysics($id){ - return self::$hasPhysics[$id] ?? false; + return self::$hasPhysics[$id] ?? false; } - + public static function getIsLiquid($id){ return self::$isLiquid[$id] ?? false; } - + public static function getIsFullBlock($id){ return self::$isFullBlock[$id] ?? false; } diff --git a/src/material/block/DoorBlock.php b/src/material/block/DoorBlock.php index fdfdb0c6..a1634cde 100644 --- a/src/material/block/DoorBlock.php +++ b/src/material/block/DoorBlock.php @@ -86,13 +86,14 @@ class DoorBlock extends TransparentBlock{ } break; } - + + return [$aabb->offset($x, $y, $z)]; } - + public static function getCompositeData(Level $level, $x, $y, $z){ $myMeta = $level->level->getBlockDamage($x, $y, $z); - + if(($myMeta & 8) != 0){ $metaLower = $level->level->getBlockDamage($x, $y - 1, $z); $metaUpper = $myMeta; @@ -100,18 +101,22 @@ class DoorBlock extends TransparentBlock{ $metaLower = $myMeta; $metaUpper = $level->level->getBlockDamage($x, $y + 1, $z); } - + return $metaLower & 7 | (($myMeta & 8) != 0 ? 8 : 0) | (($metaUpper & 1 != 0) ? 16 : 0); } + public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ - if($level->level->getBlockID($x, $y - 1, $z) == AIR){ //Replace with common break method + if($level->level->getBlockID($x, $y - 1, $z) == AIR){ + + [$id, $meta] = $level->level->getBlock($x, $y, $z); + $level->fastSetBlockUpdate($x, $y, $z, 0, 0); - $id = $level->level->getBlockID($x, $y, $z); - - if($id == 64) ServerAPI::request()->api->entity->drop(new Position($x + 0.5, $y, $z + 0.5, $level), BlockAPI::getItem(324, 0, 1)); - elseif($id == 71) ServerAPI::request()->api->entity->drop(new Position($x + 0.5, $y, $z + 0.5, $level), BlockAPI::getItem(330, 0, 1)); - + if(($meta & 8) == 0){ + if($id == DOOR_BLOCK) ServerAPI::request()->api->entity->drop(new Position($x+0.5, $y, $z+0.5, $level), BlockAPI::getItem(WOODEN_DOOR, 0, 1)); + elseif($id == IRON_DOOR_BLOCK) ServerAPI::request()->api->entity->drop(new Position($x+0.5, $y, $z+0.5, $level), BlockAPI::getItem(IRON_DOOR, 0, 1)); + } + $top = $level->level->getBlockID($x, $y + 1, $z); if($top == IRON_DOOR_BLOCK || $top == DOOR_BLOCK){ $level->fastSetBlockUpdate($x, $y + 1, $z, 0, 0); @@ -119,7 +124,12 @@ class DoorBlock extends TransparentBlock{ } } + /** + * @param Item $item + * @param Player $player + * @param Block $block + * @param Block $target * @param integer $face * @param integer $fx * @param integer $fy @@ -135,12 +145,12 @@ class DoorBlock extends TransparentBlock{ return false; } $direction = $player->entity->getDirection(); - $face = [ + $face = array( 0 => 3, 1 => 4, 2 => 2, 3 => 5, - ]; + ); $next = $this->getSide($face[(($direction + 2) % 4)]); $next2 = $this->getSide($face[$direction]); $metaUp = 0x08; @@ -148,15 +158,17 @@ class DoorBlock extends TransparentBlock{ $metaUp |= 0x01; } $this->level->setBlock($blockUp, BlockAPI::get($this->id, $metaUp), true, false, true); //Top - + $this->meta = $direction & 0x03; $this->level->setBlock($block, $this, true, false, true); //Bottom - return true; + return true; } return false; } /** + * @param Item $item + * @param Player $player * * @return boolean */ @@ -177,6 +189,8 @@ class DoorBlock extends TransparentBlock{ } /** + * @param Item $item + * @param Player $player * * @return boolean */ @@ -194,7 +208,7 @@ class DoorBlock extends TransparentBlock{ $pk->z = $this->z; $pk->evid = 1003; $pk->data = 0; - ServerAPI::request()->api->player->broadcastPacket($players, $pk); + ServerAPI::request()->api->player->broadcastPacket($players, $pk); //TODO use block queue? return true; } return false; diff --git a/src/material/block/GenericBlock.php b/src/material/block/GenericBlock.php index a2b23d1b..99abc099 100644 --- a/src/material/block/GenericBlock.php +++ b/src/material/block/GenericBlock.php @@ -1,5 +1,6 @@ level->getBlock($x, $y, $z); - $down = $level->level->getBlockID($x, $y - 1, $z); - if($down == AIR || StaticBlock::getIsLiquid($down)){ - $data = [ - "x" => $x + 0.5, - "y" => $y, - "z" => $z + 0.5, - "Tile" => $id, - ]; - $server = ServerAPI::request(); - $e = $server->api->entity->add($level, ENTITY_FALLING, FALLING_SAND, $data); - $server->api->entity->spawnToAll($e); + if(StaticBlock::getHasPhysics($id)){ + $down = $level->level->getBlockID($x, $y - 1, $z); + + if($down == AIR || StaticBlock::getIsLiquid($down)){ + $data = array( + "x" => $x + 0.5, + "y" => $y, + "z" => $z + 0.5, + "Tile" => $id, + ); + $server = ServerAPI::request(); + $e = $server->api->entity->add($level, ENTITY_FALLING, FALLING_SAND, $data); + $server->api->entity->spawnToAll($e); + } } } - + /** + * @param integer $type * * @return boolean */ @@ -75,6 +88,8 @@ class GenericBlock extends Block{ } /** + * @param Item $item + * @param Player $player * * @return boolean */ diff --git a/src/material/block/attachable/LadderBlock.php b/src/material/block/attachable/LadderBlock.php index 571d18d4..31ae7cd5 100644 --- a/src/material/block/attachable/LadderBlock.php +++ b/src/material/block/attachable/LadderBlock.php @@ -23,11 +23,18 @@ class LadderBlock extends TransparentBlock{ return parent::getAABB($level, $x, $y, $z); } + + public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ + return [static::getAABB($level, $x, $y, $z)]; + } + public function __construct($meta = 0){ parent::__construct(LADDER, $meta, "Ladder"); $this->isSolid = false; $this->isFullBlock = false; $this->hardness = 2; + $this->breakTime = 0.4; + $this->material = Material::$decoration; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ if($face === 0 || $face === 1){ diff --git a/src/material/block/attachable/SignPostBlock.php b/src/material/block/attachable/SignPostBlock.php index ea7e15b2..0b3ecd68 100644 --- a/src/material/block/attachable/SignPostBlock.php +++ b/src/material/block/attachable/SignPostBlock.php @@ -16,10 +16,12 @@ class SignPostBlock extends TransparentBlock{ $this->isSolid = false; $this->isFullBlock = false; $this->hardness = 5; + $this->breakTime = 1; + $this->material = Material::$wood; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ - if(($target->isSolid || $target->getID() === SIGN_POST || $target->getID() === WALL_SIGN) && $face !== 0){ + if(($target->isSolid || $target->getID() === SIGN_POST || $target->getID() === WALL_SIGN || $target->getID() === GLASS_PANE || $target->getID() === IRON_BARS || $target->getID() === STONE_WALL) && $face !== 0){ if(!isset(self::$faces[$face])){ $this->meta = floor((($player->entity->yaw + 180) * 16 / 360) + 0.5) & 0x0F; $this->level->setBlock($block, BlockAPI::get(SIGN_POST, $this->meta), true, false, true); diff --git a/src/material/block/attachable/TorchBlock.php b/src/material/block/attachable/TorchBlock.php index 69c0f5be..878afd48 100644 --- a/src/material/block/attachable/TorchBlock.php +++ b/src/material/block/attachable/TorchBlock.php @@ -5,6 +5,9 @@ class TorchBlock extends FlowableBlock implements LightingBlock{ public function __construct($meta = 0){ parent::__construct(TORCH, $meta, "Torch"); $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$decoration; + $this->lightEmission = 14; } public function getMaxLightValue(){ diff --git a/src/material/block/attachable/TrapdoorBlock.php b/src/material/block/attachable/TrapdoorBlock.php index 48d2de84..1aa47ab0 100644 --- a/src/material/block/attachable/TrapdoorBlock.php +++ b/src/material/block/attachable/TrapdoorBlock.php @@ -11,6 +11,8 @@ class TrapdoorBlock extends TransparentBlock{ $this->isFullBlock = true; } $this->hardness = 15; + $this->breakTime = 3; + $this->material = Material::$wood; } public function canAttachTo(Block $target){ diff --git a/src/material/block/attachable/WallSignBlock.php b/src/material/block/attachable/WallSignBlock.php index 1a61c615..d92d67ba 100644 --- a/src/material/block/attachable/WallSignBlock.php +++ b/src/material/block/attachable/WallSignBlock.php @@ -9,8 +9,11 @@ class WallSignBlock extends SignPostBlock{ public function __construct($meta = 0){ TransparentBlock::__construct(WALL_SIGN, $meta, "Wall Sign"); $this->isSolid = false; + $this->breakTime = 1; + $this->hardness = 5; + $this->material = Material::$wood; } - + public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ $attached = match($level->level->getBlockDamage($x, $y, $z)){ 2 => $level->level->getBlockID($x, $y, $z + 1), @@ -19,8 +22,8 @@ class WallSignBlock extends SignPostBlock{ 5 => $level->level->getBlockID($x - 1, $y, $z), default => WALL_SIGN }; - - if(!StaticBlock::getIsSolid($attached) && $attached != SIGN_POST && $attached != WALL_SIGN){ + + if(!StaticBlock::getIsSolid($attached) && $attached != SIGN_POST && $attached != WALL_SIGN && $attached != GLASS_PANE && $attached != IRON_BARS && $attached != STONE_WALL){ $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true, true); (ServerAPI::request())->api->entity->drop(new Position($x + 0.5, $y + 0.5, $z + 0.5, $level), BlockAPI::getItem(SIGN, 0, 1)); } diff --git a/src/material/block/liquid/LavaBlock.php b/src/material/block/liquid/LavaBlock.php index ed80bbf1..f011073d 100644 --- a/src/material/block/liquid/LavaBlock.php +++ b/src/material/block/liquid/LavaBlock.php @@ -6,7 +6,11 @@ class LavaBlock extends LiquidBlockDynamic implements LightingBlock{ public static $blockID = LAVA; public function __construct($meta = 0){ parent::__construct(LAVA, $meta, "Lava"); - $this->hardness = 500; + $this->hardness = 500; //0 in vanilla + $this->breakTime = -1; //in vanilla it is 0, but you cant interact with the block so it is not possible to destroy it + $this->material = Material::$lava; + $this->lightEmission = 15; + $this->lightBlock = 255; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ diff --git a/src/material/block/liquid/LiquidBlockDynamic.php b/src/material/block/liquid/LiquidBlockDynamic.php index 5d35973b..d26acfd1 100644 --- a/src/material/block/liquid/LiquidBlockDynamic.php +++ b/src/material/block/liquid/LiquidBlockDynamic.php @@ -4,55 +4,55 @@ class LiquidBlockDynamic extends LiquidBlock{ public function __construct($id, $meta = 0, $name = "Unknown"){ parent::__construct($id, $meta, $name); } - + public static $blockID = 0; public static $sourcesAround = 0; public static $spread = [0, 0, 0, 0]; - + public static function getHighest(Level $level, $x, $y, $z, $highest){ $depth = static::getDepth($level, $x, $y, $z); if($depth < 0) return $highest; if($depth == 0) ++static::$sourcesAround; if($depth >= 8) $depth = 0; - + return $highest >= 0 && $depth >= $highest ? $highest : $depth; } - + public static function setStatic(Level $level, $x, $y, $z){ $meta = $level->level->getBlockDamage($x, $y, $z); - + $level->fastSetBlockUpdate($x, $y, $z, static::$blockID + 1, $meta); } - + public static function isWaterBlocking(Level $level, $x, $y, $z){ $id = $level->level->getBlockID($x, $y, $z); - + if($id == AIR) return false; - + if($id == DOOR_BLOCK || $id == SIGN_POST || $id == WALL_SIGN || $id == LADDER || $id == SUGARCANE_BLOCK) return true; - + if($id == CARPET || $id == SNOW_LAYER || $id == RAIL || $id == POWERED_RAIL) return false; //TODO Tile::getThickness() > 0 - - //TODO materials - //if(!StaticBlock::getIsFlowable($id)) return true; - return StaticBlock::getIsSolid($id); + + $mat = StaticBlock::getMaterial($id); + if($mat->blocksMotion) return true; + return $mat->isSolid; } - + public static function canSpreadTo(Level $level, $x, $y, $z){ $id = $level->level->getBlockID($x, $y, $z); if($id == LAVA || $id == STILL_LAVA) return false; if((static::$blockID == WATER) && ($id == WATER || $id == STILL_WATER)) return false; - + return static::isWaterBlocking($level, $x, $y, $z) ^ 1; } - + public static function getSpread(Level $level, $x, $y, $z){ for($i = 0; $i < 4; ++$i){ static::$spread[$i] = 1000; $xs = $x; $ys = $y; $zs = $z; - + switch($i){ case 0: --$xs; @@ -67,13 +67,13 @@ class LiquidBlockDynamic extends LiquidBlock{ ++$zs; break; } - + if(static::isWaterBlocking($level, $xs, $ys, $zs)) continue; [$id, $meta] = $level->level->getBlock($xs, $ys, $zs); if(((static::$blockID == WATER && ($id == WATER || $id == STILL_WATER)) || (static::$blockID == LAVA && ($id == LAVA || $id == STILL_LAVA))) && $meta == 0){ continue; } - + if(!static::isWaterBlocking($level, $xs, $ys - 1, $zs)) static::$spread[$i] = 0; else static::$spread[$i] = static::getSlopeDistance($level, $xs, $ys, $zs, 1, $i); } @@ -85,18 +85,18 @@ class LiquidBlockDynamic extends LiquidBlock{ for($i = 0; $i < 4; ++$i) $ba[$i] = ($i1 == static::$spread[$i]); return $ba; } - + public static function getSlopeDistance(Level $level, $x, $y, $z, $l, $i1){ $j1 = 1000; for($k1 = 0; $k1 < 4; ++$k1){ - if($k1 == 0 && $i1 == 1 || $k1 == 1 && $i1 == 0 || $k1 == 2 && $i1 == 3 || $k1 == 3 && $i1 == 2){ + if($k1 == 0 && $i1 == 1 || $k1 == 1 && $i1 == 0 || $k1 == 2 && $i1 == 3 || $k1 == 3 && $i1 == 2){ continue; } - + $xs = $x; $ys = $y; $zs = $z; - + switch($k1){ case 0: --$xs; @@ -111,10 +111,10 @@ class LiquidBlockDynamic extends LiquidBlock{ ++$zs; break; } - + if(static::isWaterBlocking($level, $xs, $ys, $zs)) continue; [$id, $meta] = $level->level->getBlock($xs, $ys, $zs); - + if( ((static::$blockID == WATER && ($id == WATER || $id == STILL_WATER)) || (static::$blockID == LAVA && ($id == LAVA || $id == STILL_LAVA))) && @@ -122,20 +122,20 @@ class LiquidBlockDynamic extends LiquidBlock{ ){ continue; } - + if(!static::isWaterBlocking($level, $xs, $ys - 1, $zs)) return $l; - + if($l >= 4) continue; $k2 = static::getSlopeDistance($level, $xs, $ys, $zs, $l + 1, $k1); if($k2 < $j1) $j1 = $k2; } return $j1; } - + public static function trySpreadTo(Level $level, $x, $y, $z, $meta){ if(static::canSpreadTo($level, $x, $y, $z)){ [$id, $meta2] = $level->level->getBlock($x, $y, $z); - + if($id > 0){ if(($id == LAVA || $id == STILL_LAVA) && (static::$blockID == LAVA || static::$blockID == STILL_LAVA)); //fizz else{ @@ -147,23 +147,23 @@ class LiquidBlockDynamic extends LiquidBlock{ } } } - + $level->fastSetBlockUpdate($x, $y, $z, static::$blockID, $meta, true); } } - + public static function onPlace(Level $level, $x, $y, $z){ static::updateLiquid($level, $x, $y, $z); $id = $level->level->getBlockID($x, $y, $z); if($id == static::$blockID) ServerAPI::request()->api->block->scheduleBlockUpdateXYZ($level, $x, $y, $z, BLOCK_UPDATE_SCHEDULED, static::getTickDelay()); } - + public static function onUpdate(Level $level, $x, $y, $z, $type){ $id = $level->level->getBlockID($x, $y, $z); $depth = static::getDepth($level, $x, $y, $z); $flowAdd = (static::$blockID == LAVA) ? 2 : 1; $flag = true; - + if($depth > 0){ static::$sourcesAround = 0; $highest = static::getHighest($level, $x - 1, $y, $z, -100); @@ -174,19 +174,19 @@ class LiquidBlockDynamic extends LiquidBlock{ if($j1 >= 8 || $highest < 0) $j1 = -1; $l1 = static::getDepth($level, $x, $y + 1, $z); if($l1 >= 0) $j1 = ($l1 >= 8 ? $l1 : $l1 + 8); - + if(static::$sourcesAround >= 2 && static::$blockID == WATER){ $idBot = $level->level->getBlockID($x, $y - 1, $z); if($idBot > 0){ if(StaticBlock::getIsSolid($idBot) || (($idBot == WATER || $idBot == STILL_WATER) && $level->level->getBlockDamage($x, $y, $z) == 0)) $j1 = 0; } } - + //if(static::$blockID == LAVA && $depth < 8 && $j1 < 8 && $j1 > $depth && mt_rand(0, 4) != 0){ TODO fix later // $j1 = $depth; // $flag = false; //} - + if($j1 != $depth){ $depth = $j1; if($depth < 0) $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); @@ -195,16 +195,16 @@ class LiquidBlockDynamic extends LiquidBlock{ ServerAPI::request()->api->block->scheduleBlockUpdateXYZ($level, $x, $y, $z, BLOCK_UPDATE_SCHEDULED, static::getTickDelay()); $level->updateNeighborsAt($x, $y, $z, static::$blockID); //TODO check is needed } - }elseif($flag){ + }else if($flag){ static::setStatic($level, $x, $y, $z); } }else{ static::setStatic($level, $x, $y, $z); } - + if(static::canSpreadTo($level, $x, $y - 1, $z)){ $level->fastSetBlockUpdate($x, $y - 1, $z, static::$blockID, ($depth >= 8 ? $depth : $depth + 8) & 0xf, true); - }elseif($depth >= 0 && ($depth == 0 || static::isWaterBlocking($level, $x, $y - 1, $z))){ + }else if($depth >= 0 && ($depth == 0 || static::isWaterBlocking($level, $x, $y - 1, $z))){ $flags = static::getSpread($level, $x, $y, $z); $k1 = $depth >= 8 ? 1 : ($depth + $flowAdd); if($k1 >= 8) return; diff --git a/src/material/block/liquid/StillLavaBlock.php b/src/material/block/liquid/StillLavaBlock.php index 2ca2daa2..455ce2cc 100644 --- a/src/material/block/liquid/StillLavaBlock.php +++ b/src/material/block/liquid/StillLavaBlock.php @@ -7,6 +7,10 @@ class StillLavaBlock extends LiquidBlockStatic{ public function __construct($meta = 0){ parent::__construct(STILL_LAVA, $meta, "Still Lava"); $this->hardness = 500; + $this->breakTime = -1; //in vanilla it is 100, but you cant interact with the block so it is not possible to destroy it + $this->material = Material::$lava; + $this->lightEmission = 15; + $this->lightBlock = 255; } public static function getTickDelay(){ diff --git a/src/material/block/liquid/StillWaterBlock.php b/src/material/block/liquid/StillWaterBlock.php index 9e79836b..9e9566ec 100644 --- a/src/material/block/liquid/StillWaterBlock.php +++ b/src/material/block/liquid/StillWaterBlock.php @@ -11,6 +11,9 @@ class StillWaterBlock extends LiquidBlockStatic{ public function __construct($meta = 0){ LiquidBlock::__construct(STILL_WATER, $meta, "Still Water"); $this->hardness = 500; + $this->breakTime = -1; //in vanilla it is 100, but you cant interact with the block so it is not possible to destroy it + $this->material = Material::$water; + $this->lightBlock = 3; } public static function getTickDelay(){ diff --git a/src/material/block/liquid/WaterBlock.php b/src/material/block/liquid/WaterBlock.php index 3356ca72..179445b8 100644 --- a/src/material/block/liquid/WaterBlock.php +++ b/src/material/block/liquid/WaterBlock.php @@ -8,6 +8,9 @@ class WaterBlock extends LiquidBlockDynamic{ public function __construct($meta = 0){ parent::__construct(WATER, $meta, "Water"); $this->hardness = 500; + $this->breakTime = -1; //in vanilla it is 100, but you cant interact with the block so it is not possible to destroy it + $this->material = Material::$water; + $this->lightBlock = 3; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ diff --git a/src/material/block/misc/AirBlock.php b/src/material/block/misc/AirBlock.php index defdaf3f..07499700 100644 --- a/src/material/block/misc/AirBlock.php +++ b/src/material/block/misc/AirBlock.php @@ -2,7 +2,7 @@ class AirBlock extends TransparentBlock{ public static $blockID; - + public function __construct(){ parent::__construct(AIR, 0, "Air"); $this->isActivable = false; @@ -15,7 +15,8 @@ class AirBlock extends TransparentBlock{ $this->isSolid = false; $this->isFullBlock = true; $this->hardness = 0; - + $this->material = Material::$air; + } - + } \ No newline at end of file diff --git a/src/material/block/misc/BedBlock.php b/src/material/block/misc/BedBlock.php index db72ca0c..be845c70 100644 --- a/src/material/block/misc/BedBlock.php +++ b/src/material/block/misc/BedBlock.php @@ -14,43 +14,47 @@ class BedBlock extends TransparentBlock{ [0, -1], [1, 0] ]; + const PLAYER_BED_OFFS_X = [0.5, 0.1, 0.5, 0.9]; + const PLAYER_BED_OFFS_Z = [0.9, 0.5, 0.1, 0.5]; public function __construct($type = 0){ parent::__construct(BED_BLOCK, $type, "Bed Block"); $this->isActivable = true; $this->isFullBlock = false; $this->hardness = 1; + $this->breakTime = 0.2; + $this->material = Material::$cloth; } - + public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ return [static::getAABB($level, $x, $y, $z)]; } public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ - + $meta = $level->level->getBlockDamage($x, $y, $z); $dir = $meta & 3; $isHead = ($meta >> 3) & 1; - + $offX = self::HEAD_DIRECTION_OFFSETS[$dir][0]; $offZ = self::HEAD_DIRECTION_OFFSETS[$dir][1]; - + if($isHead){ if($level->level->getBlockID($x - $offX, $y, $z - $offZ) != BED_BLOCK){ $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); } - }elseif($level->level->getBlockID($x + $offX, $y, $z + $offZ) != BED_BLOCK){ + }else if($level->level->getBlockID($x + $offX, $y, $z + $offZ) != BED_BLOCK){ $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); - + ServerAPI::request()->api->entity->dropRawPos( - $level, - $x + (lcg_value() * 0.7) + 0.15, - $y + (lcg_value() * 0.7) + 0.15, - $z + (lcg_value() * 0.7) + 0.15, - BlockAPI::getItem(BED, 0, 1), + $level, + $x + (lcg_value() * 0.7) + 0.15, + $y + (lcg_value() * 0.7) + 0.15, + $z + (lcg_value() * 0.7) + 0.15, + BlockAPI::getItem(BED, 0, 1), lcg_value() * 0.2 - 0.1, 0.2, lcg_value() * 0.2 - 0.1 ); - + } - + } public static function findStandUpPosition(Level $level, $x, $y, $z){ $blockMeta = $level->level->getBlockDamage($x, $y, $z); @@ -60,63 +64,48 @@ class BedBlock extends TransparentBlock{ $minZ = $z - self::HEAD_DIRECTION_OFFSETS[$direction][1] * $v7 - 1; $maxX = $minX + 2; $maxZ = $minZ + 2; - + for($xCheck = $minX; $xCheck <= $maxX; ++$xCheck){ for($zCheck = $minZ; $zCheck <= $maxZ; ++$zCheck){ $idCheck = $level->level->getBlockID($xCheck, $y - 1, $zCheck); if(!StaticBlock::getIsTransparent($idCheck) && $level->level->getBlockID($xCheck, $y, $zCheck) == 0 && $level->level->getBlockID($xCheck, $y + 1, $zCheck) == 0){ - return new Vector3($xCheck, $y, $zCheck); + return new Position($xCheck, $y, $zCheck, $level); } } } } - + return null; } - + public function onActivate(Item $item, Player $player){ if(ServerAPI::request()->api->time->getPhase($player->level) !== "night"){ - $pk = new ChatPacket; - $pk->message = "You can only sleep at night"; - $player->dataPacket($pk); + $player->sendChat("You can only sleep at night"); return true; } - - $blockNorth = $this->getSide(2); //Gets the blocks around them - $blockSouth = $this->getSide(3); - $blockEast = $this->getSide(5); - $blockWest = $this->getSide(4); - if(($this->meta & 0x08) === 0x08){ //This is the Top part of bed + + if(($this->meta & 0x08) === 0x08){ //This is the Top part of bed $b = $this; }else{ //Bottom Part of Bed - if($blockNorth->getID() === $this->id and ($blockNorth->meta & 0x08) === 0x08){ - $b = $blockNorth; - }elseif($blockSouth->getID() === $this->id and ($blockSouth->meta & 0x08) === 0x08){ - $b = $blockSouth; - }elseif($blockEast->getID() === $this->id and ($blockEast->meta & 0x08) === 0x08){ - $b = $blockEast; - }elseif($blockWest->getID() === $this->id and ($blockWest->meta & 0x08) === 0x08){ - $b = $blockWest; - }else{ - $pk = new ChatPacket; - $pk->message = "This bed is incomplete"; - $player->dataPacket($pk); + $dir = ($this->meta & 3); + $o = BedBlock::HEAD_DIRECTION_OFFSETS[$dir]; + $b = $this->level->getBlockWithoutVector($this->x + $o[0], $this->y, $this->z + $o[1]); + if($b->getID() != BED_BLOCK){ + $player->sendChat("This bed is incomplete"); return true; } } if($player->sleepOn($b) === false){ - $pk = new ChatPacket; - $pk->message = "This bed is occupied"; - $player->dataPacket($pk); + $player->sendChat("This bed is occupied"); } return true; } - + public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ $down = $this->getSide(0); if($down->isTransparent === false){ - + $d = $player->entity->getDirection(); $next = $this->getSide(self::$faces[(($d + 3) % 4)]); $downNext = $next->getSide(0); @@ -128,15 +117,15 @@ class BedBlock extends TransparentBlock{ } } return false; - } - + } + public function onBreak(Item $item, Player $player){ $blockNorth = $this->getSide(2); //Gets the blocks around them $blockSouth = $this->getSide(3); $blockEast = $this->getSide(5); $blockWest = $this->getSide(4); - - if(($this->meta & 0x08) === 0x08){ //This is the Top part of bed + + if(($this->meta & 0x08) === 0x08){ //This is the Top part of bed switch($this->meta & 0x7){ case 0: if($blockNorth->id === $this->id) $this->level->setBlock($blockNorth, new AirBlock(), true, false, true); @@ -170,11 +159,11 @@ class BedBlock extends TransparentBlock{ $this->level->setBlock($this, new AirBlock(), true, false, true); return true; } - + public function getDrops(Item $item, Player $player){ - return [ - [BED, 0, 1], - ]; + return array( + array(BED, 0, 1), + ); } - + } \ No newline at end of file diff --git a/src/material/block/misc/FireBlock.php b/src/material/block/misc/FireBlock.php index 778f1f29..3fbf4ab1 100644 --- a/src/material/block/misc/FireBlock.php +++ b/src/material/block/misc/FireBlock.php @@ -11,6 +11,9 @@ class FireBlock extends FlowableBlock implements LightingBlock{ $this->breakable = false; $this->isFullBlock = true; $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$fire; + $this->lightEmission = 15; } public static function getAABB(Level $level, $x, $y, $z){ return null; diff --git a/src/material/block/misc/NetherReactorBlock.php b/src/material/block/misc/NetherReactorBlock.php index 52d79589..7049fb2f 100644 --- a/src/material/block/misc/NetherReactorBlock.php +++ b/src/material/block/misc/NetherReactorBlock.php @@ -6,6 +6,10 @@ class NetherReactorBlock extends SolidBlock{ public function __construct($meta = 0){ parent::__construct(NETHER_REACTOR, $meta, "Nether Reactor"); $this->isActivable = true; + $this->hardness = 15; + $this->breakTime = 3; + $this->material = Material::$metal; + $this->lightBlock = 255; } public function onActivate(Item $item, Player $player){ diff --git a/src/material/block/misc/TNTBlock.php b/src/material/block/misc/TNTBlock.php index 80018057..19d847f8 100644 --- a/src/material/block/misc/TNTBlock.php +++ b/src/material/block/misc/TNTBlock.php @@ -5,21 +5,22 @@ class TNTBlock extends SolidBlock{ public function __construct(){ parent::__construct(TNT, 0, "TNT"); $this->hardness = 0; + $this->breakTime = 0; $this->isActivable = true; + $this->material = Material::$explosive; + $this->lightBlock = 255; } - + public function onActivate(Item $item, Player $player){ if($item->getID() === FLINT_STEEL){ - if(($player->gamemode & 0x01) === 0){ - $item->useOn($this); - } - $data = [ + $item->hurtAndBreak(1, $player); + $data = array( "x" => $this->x + 0.5, "y" => $this->y, "z" => $this->z + 0.5, "power" => 3, "fuse" => 20 * 4, //4 seconds - ]; + ); $this->level->fastSetBlockUpdate($this->x, $this->y, $this->z, 0, 0, true); $e = ServerAPI::request()->api->entity->add($this->level, ENTITY_OBJECT, OBJECT_PRIMEDTNT, $data); ServerAPI::request()->api->entity->spawnToAll($e); diff --git a/src/material/block/nonfull/CakeBlock.php b/src/material/block/nonfull/CakeBlock.php index fc9740e9..97dd01b8 100644 --- a/src/material/block/nonfull/CakeBlock.php +++ b/src/material/block/nonfull/CakeBlock.php @@ -8,6 +8,8 @@ class CakeBlock extends TransparentBlock{ $this->isActivable = true; $this->meta = $meta & 0x07; $this->hardness = 2.5; + $this->breakTime = 0.5; + $this->material = Material::$cake; } public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ diff --git a/src/material/block/nonfull/CarpetBlock.php b/src/material/block/nonfull/CarpetBlock.php index bfe18df4..6128c357 100644 --- a/src/material/block/nonfull/CarpetBlock.php +++ b/src/material/block/nonfull/CarpetBlock.php @@ -4,7 +4,7 @@ class CarpetBlock extends FlowableBlock{ public static $blockID; public function __construct($meta = 0){ parent::__construct(CARPET, $meta, "Carpet"); - $names = [ + $names = array( 0 => "White Carpet", 1 => "Orange Carpet", 2 => "Magenta Carpet", @@ -21,11 +21,13 @@ class CarpetBlock extends FlowableBlock{ 13 => "Green Carpet", 14 => "Red Carpet", 15 => "Black Carpet", - ]; + ); $this->name = $names[$this->meta]; - $this->hardness = 0; - $this->isFullBlock = false; + $this->hardness = 0.5; + $this->breakTime = 0.1; + $this->isFullBlock = false; $this->isSolid = true; + $this->material = Material::$cloth; } public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ return [static::getAABB($level, $x, $y, $z)]; diff --git a/src/material/block/nonfull/ChestBlock.php b/src/material/block/nonfull/ChestBlock.php index b3a3422d..d27a5481 100644 --- a/src/material/block/nonfull/ChestBlock.php +++ b/src/material/block/nonfull/ChestBlock.php @@ -7,6 +7,8 @@ class ChestBlock extends TransparentBlock{ $this->isActivable = true; $this->isFullBlock = false; $this->hardness = 15; + $this->breakTime = 2.5; + $this->material = Material::$wood; } public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ return [new AxisAlignedBB($x + 0.025, $y, $z + 0.025, $x + 0.975, $y + 0.95, $z + 0.975)]; diff --git a/src/material/block/nonfull/CobwebBlock.php b/src/material/block/nonfull/CobwebBlock.php index 558dbd69..60e96fe3 100644 --- a/src/material/block/nonfull/CobwebBlock.php +++ b/src/material/block/nonfull/CobwebBlock.php @@ -6,7 +6,10 @@ class CobwebBlock extends FlowableBlock{ parent::__construct(COBWEB, 0, "Cobweb"); $this->isSolid = true; $this->isFullBlock = false; - $this->hardness = 25; + $this->hardness = 30; + $this->breakTime = 4; + $this->material = Material::$web; + $this->lightBlock = 1; } public static function getAABB(Level $level, $x, $y, $z){ diff --git a/src/material/block/nonfull/FarmlandBlock.php b/src/material/block/nonfull/FarmlandBlock.php index 6f30afea..0f26343c 100644 --- a/src/material/block/nonfull/FarmlandBlock.php +++ b/src/material/block/nonfull/FarmlandBlock.php @@ -5,6 +5,8 @@ class FarmlandBlock extends TransparentBlock{ public function __construct($meta = 0){ parent::__construct(FARMLAND, $meta, "Farmland"); $this->hardness = 3; + $this->breakTime = 0.6; + $this->material = Material::$dirt; } public function getDrops(Item $item, Player $player){ return [ @@ -24,7 +26,7 @@ class FarmlandBlock extends TransparentBlock{ public static function fallOn(Level $level, $x, $y, $z, Entity $entity, $fallDistance){ $rv = lcg_value(); if($rv < ($fallDistance - 0.5)){ - $level->fastSetBlockUpdate($x, $y, $z, DIRT, 0); + $level->fastSetBlockUpdate($x, $y, $z, DIRT, 0, true); } } diff --git a/src/material/block/nonfull/FenceBlock.php b/src/material/block/nonfull/FenceBlock.php index 47b17932..fddb9c80 100644 --- a/src/material/block/nonfull/FenceBlock.php +++ b/src/material/block/nonfull/FenceBlock.php @@ -6,17 +6,26 @@ class FenceBlock extends TransparentBlock{ parent::__construct(FENCE, 0, "Fence"); $this->isFullBlock = false; $this->hardness = 15; + $this->breakTime = 2; + $this->material = Material::$wood; } - + public static function canConnectTo(Level $level, $x, $y, $z){ $id = $level->level->getBlockID($x, $y, $z); - + /*if($id == FENCE || $id == FENCE_GATE) return true; + if($id == 0) return false; + $mat = StaticBlock::getMaterial($id); + if($mat->isSolidBlocking() && tile->isCubeShaped()){ //TODO tile->isCubeShaped + return $mat != Material::$vegetable; + } + return false;*/ + if($id != FENCE && $id != FENCE_GATE){ - return StaticBlock::getIsSolid($id) && $id != PUMPKIN; //TODO check var6 != null && var6.blockMaterial.isOpaque() && var6.renderAsNormalBlock() ? var6.blockMaterial != Material.pumpkin : false; + return StaticBlock::getIsSolid($id) && $id != PUMPKIN; } return true; } - + public static function getAABB(Level $level, $x, $y, $z){ $v9 = self::canConnectTo($level, $x, $y, $z - 1); $v10 = self::canConnectTo($level, $x, $y, $z + 1); @@ -29,7 +38,7 @@ class FenceBlock extends TransparentBlock{ StaticBlock::setBlockBounds(static::$blockID, $minX, 0, $minZ, $maxX, 1.5, $maxZ); return parent::getAABB($level, $x, $y, $z); } - + public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ $v8 = self::canConnectTo($level, $x, $y, $z - 1); $v9 = self::canConnectTo($level, $x, $y, $z + 1); @@ -47,11 +56,11 @@ class FenceBlock extends TransparentBlock{ $v15 = 0.625; if($v10) $v12 = 0; if($v11) $v13 = 1; - + if($v10 || $v11 || !$v8 && !$v9){ $arr[] = new AxisAlignedBB($x + $v12, $y + 0, $z + $v14, $x + $v13, $y + 1.5, $z + $v15); } return $arr; } - + } \ No newline at end of file diff --git a/src/material/block/nonfull/FenceGateBlock.php b/src/material/block/nonfull/FenceGateBlock.php index 0de9a354..b24bb34c 100644 --- a/src/material/block/nonfull/FenceGateBlock.php +++ b/src/material/block/nonfull/FenceGateBlock.php @@ -31,6 +31,8 @@ class FenceGateBlock extends TransparentBlock{ $this->isFullBlock = false; } $this->hardness = 15; + $this->breakTime = 2; + $this->material = Material::$wood; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ $faces = [ @@ -73,7 +75,7 @@ class FenceGateBlock extends TransparentBlock{ $pk->z = $this->z; $pk->evid = 1003; $pk->data = 0; - ServerAPI::request()->api->player->broadcastPacket($players, $pk); + ServerAPI::request()->api->player->broadcastPacket($players, $pk); //TODO use blok queue? return true; } } diff --git a/src/material/block/nonfull/GlassPaneBlock.php b/src/material/block/nonfull/GlassPaneBlock.php index 959cdd22..e89b5489 100644 --- a/src/material/block/nonfull/GlassPaneBlock.php +++ b/src/material/block/nonfull/GlassPaneBlock.php @@ -6,6 +6,9 @@ class GlassPaneBlock extends TransparentBlock{ parent::__construct(GLASS_PANE, 0, "Glass Pane"); $this->isFullBlock = false; $this->isSolid = false; + $this->breakTime = 0.3; + $this->hardness = 0.3*5; + $this->material = Material::$glass; } public static function updateShape(Level $level, $x, $y, $z){ $id = $level->level->getBlockID($x, $y, $z); diff --git a/src/material/block/nonfull/IronBarsBlock.php b/src/material/block/nonfull/IronBarsBlock.php index 3666bc6f..4104ce20 100644 --- a/src/material/block/nonfull/IronBarsBlock.php +++ b/src/material/block/nonfull/IronBarsBlock.php @@ -6,6 +6,9 @@ class IronBarsBlock extends TransparentBlock{ parent::__construct(IRON_BARS, 0, "Iron Bars"); $this->isFullBlock = false; $this->isSolid = false; + $this->breakTime = 5; + $this->hardness = 30; + $this->material = Material::$metal; } public static function updateShape(Level $level, $x, $y, $z){ diff --git a/src/material/block/nonfull/IronDoorBlock.php b/src/material/block/nonfull/IronDoorBlock.php index fd3b24f3..c9196533 100644 --- a/src/material/block/nonfull/IronDoorBlock.php +++ b/src/material/block/nonfull/IronDoorBlock.php @@ -6,6 +6,8 @@ class IronDoorBlock extends DoorBlock{ parent::__construct(IRON_DOOR_BLOCK, $meta, "Iron Door Block"); //$this->isActivable = true; $this->hardness = 25; + $this->breakTime = 5; + $this->material = Material::$metal; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/nonfull/PoweredRailBlock.php b/src/material/block/nonfull/PoweredRailBlock.php index 0de0c7cd..e7bb2b35 100644 --- a/src/material/block/nonfull/PoweredRailBlock.php +++ b/src/material/block/nonfull/PoweredRailBlock.php @@ -1,13 +1,14 @@ hardness = 0.7; - $this->isFullBlock = false; + $this->isFullBlock = false; $this->isSolid = false; + $this->hardness = 3.5; + $this->breakTime = 0.7; + $this->material = Material::$decoration; } - + } \ No newline at end of file diff --git a/src/material/block/nonfull/RailBlock.php b/src/material/block/nonfull/RailBlock.php index b129d8af..b6b18594 100644 --- a/src/material/block/nonfull/RailBlock.php +++ b/src/material/block/nonfull/RailBlock.php @@ -1,20 +1,21 @@ hardness = 0.7; - $this->isFullBlock = false; + $this->hardness = 0.7*5; + $this->breakTime = 0.7; + $this->isFullBlock = false; $this->isSolid = false; + $this->material = Material::$decoration; } - + public function updateState(){ $logic = (new RailLogic($this)); if($logic->countPotentialConnections() == 3){ $logic->place(false, false); } } - + } \ No newline at end of file diff --git a/src/material/block/nonfull/SlabBlock.php b/src/material/block/nonfull/SlabBlock.php index 9a6cec6d..008a45a0 100644 --- a/src/material/block/nonfull/SlabBlock.php +++ b/src/material/block/nonfull/SlabBlock.php @@ -22,6 +22,8 @@ class SlabBlock extends TransparentBlock{ $this->isFullBlock = false; } $this->hardness = 30; + $this->breakTime = 2; + $this->material = Material::$stone; } public static function updateShape(Level $level, $x, $y, $z){ diff --git a/src/material/block/nonfull/SnowLayerBlock.php b/src/material/block/nonfull/SnowLayerBlock.php index 16807094..ccabc6ed 100644 --- a/src/material/block/nonfull/SnowLayerBlock.php +++ b/src/material/block/nonfull/SnowLayerBlock.php @@ -8,6 +8,8 @@ class SnowLayerBlock extends FlowableBlock{ $this->isSolid = false; $this->isFullBlock = false; $this->hardness = 0.5; + $this->breakTime = 0.1; + $this->material = Material::$topSnow; } public static function getAABB(Level $level, $x, $y, $z){ return null; @@ -20,20 +22,26 @@ class SnowLayerBlock extends FlowableBlock{ } return false; } - + public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ if($level->level->getBlockID($x, $y - 1, $z) == AIR){ //Replace with common break method $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); } } + public static function onRandomTick(Level $level, $x, $y, $z){ + if($level->level->getBlockLight($x, $y, $z) > 11){ + $level->fastSetBlockUpdate($x, $y, $z, 0, true); + } + } + public function getDrops(Item $item, Player $player){ if($item->isShovel() !== false){ - return [ - [SNOWBALL, 0, 1], - ]; + return array( + array(SNOWBALL, 0, 1), + ); } - - return []; + + return array(); } } \ No newline at end of file diff --git a/src/material/block/nonfull/StoneWallBlock.php b/src/material/block/nonfull/StoneWallBlock.php index 16f41faa..dfeb5b3f 100644 --- a/src/material/block/nonfull/StoneWallBlock.php +++ b/src/material/block/nonfull/StoneWallBlock.php @@ -7,7 +7,9 @@ class StoneWallBlock extends TransparentBlock{ parent::__construct(STONE_WALL, $meta & 0x01, $meta === 1 ? "Mossy Cobblestone Wall" : "Cobblestone Wall"); $this->isFullBlock = false; $this->isSolid = false; - $this->hardness = 30; + $this->hardness = 50; + $this->breakTime = 10; + $this->material = Material::$stone; } public function getDrops(Item $item, Player $player){ if($item->isPickaxe()){ diff --git a/src/material/block/nonfull/WoodDoorBlock.php b/src/material/block/nonfull/WoodDoorBlock.php index 43c5827f..e19dbc89 100644 --- a/src/material/block/nonfull/WoodDoorBlock.php +++ b/src/material/block/nonfull/WoodDoorBlock.php @@ -6,6 +6,8 @@ class WoodDoorBlock extends DoorBlock{ parent::__construct(WOOD_DOOR_BLOCK, $meta, "Wood Door Block"); $this->isActivable = true; $this->hardness = 15; + $this->breakTime = 3; + $this->material = Material::$wood; } public function getDrops(Item $item, Player $player){ diff --git a/src/material/block/nonfull/WoodSlabBlock.php b/src/material/block/nonfull/WoodSlabBlock.php index e2f6c84e..64ced90a 100644 --- a/src/material/block/nonfull/WoodSlabBlock.php +++ b/src/material/block/nonfull/WoodSlabBlock.php @@ -1,29 +1,30 @@ "Oak", 1 => "Spruce", 2 => "Birch", 3 => "Jungle", - ]; - $this->name = (($this->meta & 0x08) === 0x08 ? "Upper ":"") . $names[$this->meta & 0x07] . " Wooden Slab"; + ); + $this->name = (($this->meta & 0x08) === 0x08 ? "Upper ":"") . $names[$this->meta & 0x07] . " Wooden Slab"; if(($this->meta & 0x08) === 0x08){ $this->isFullBlock = true; }else{ $this->isFullBlock = false; - } - $this->hardness = 15; + } + $this->hardness = 30; + $this->breakTime = 2; + $this->material = Material::$wood; } - + public static function updateShape(Level $level, $x, $y, $z){ - + [$id, $meta] = $level->level->getBlock($x, $y, $z); - + if($meta & 0x08 == 0x08){ StaticBlock::setBlockBounds($id, 0, 0, 0, 1, 1, 1); }else{ @@ -32,11 +33,11 @@ class WoodSlabBlock extends TransparentBlock{ else StaticBlock::setBlockBounds($id, 0, 0.5, 0, 1, 1, 1); } } - + public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ self::updateShape($level, $x, $y, $z); $id = $level->level->getBlockID($x, $y, $z); - + return [ new AxisAlignedBB( $x + StaticBlock::$minXs[$id], $y + StaticBlock::$minYs[$id], $z + StaticBlock::$minZs[$id], @@ -44,7 +45,7 @@ class WoodSlabBlock extends TransparentBlock{ ) ]; } - + public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ $this->meta &= 0x07; if($face === 0){ @@ -91,7 +92,9 @@ class WoodSlabBlock extends TransparentBlock{ if(($player->gamemode & 0x01) === 0x01){ return 0.20; } - return match ($item->isAxe()) { + if(!$item->isAxe()) return 3; + + return match ($item->getLevel()) { 5 => 0.4, 4 => 0.5, 3 => 0.75, @@ -100,10 +103,10 @@ class WoodSlabBlock extends TransparentBlock{ default => 3, }; } - + public function getDrops(Item $item, Player $player){ - return [ - [$this->id, $this->meta & 0x07, 1], - ]; + return array( + array($this->id, $this->meta & 0x07, 1), + ); } } diff --git a/src/material/block/nonfull/stairs/BirchWoodStairsBlock.php b/src/material/block/nonfull/stairs/BirchWoodStairsBlock.php index 5cebc8dd..694b7db5 100644 --- a/src/material/block/nonfull/stairs/BirchWoodStairsBlock.php +++ b/src/material/block/nonfull/stairs/BirchWoodStairsBlock.php @@ -4,6 +4,9 @@ class BirchWoodStairsBlock extends StairBlock{ public static $blockID; public function __construct($meta = 0){ parent::__construct(BIRCH_WOOD_STAIRS, $meta, "Birch Wood Stairs"); + $this->hardness = 15; + $this->breakTime = 2; + $this->material = Material::$wood; } public function getDrops(Item $item, Player $player){ diff --git a/src/material/block/nonfull/stairs/BrickStairsBlock.php b/src/material/block/nonfull/stairs/BrickStairsBlock.php index 52ee5a7f..d6a0743d 100644 --- a/src/material/block/nonfull/stairs/BrickStairsBlock.php +++ b/src/material/block/nonfull/stairs/BrickStairsBlock.php @@ -4,6 +4,9 @@ class BrickStairsBlock extends StairBlock{ public static $blockID; public function __construct($meta = 0){ parent::__construct(BRICK_STAIRS, $meta, "Brick Stairs"); + $this->breakTime = 2; + $this->hardness = 30; + $this->material = Material::$stone; } } \ No newline at end of file diff --git a/src/material/block/nonfull/stairs/CobblestoneStairsBlock.php b/src/material/block/nonfull/stairs/CobblestoneStairsBlock.php index dbe84da3..7e74c7cd 100644 --- a/src/material/block/nonfull/stairs/CobblestoneStairsBlock.php +++ b/src/material/block/nonfull/stairs/CobblestoneStairsBlock.php @@ -4,6 +4,9 @@ class CobblestoneStairsBlock extends StairBlock{ public static $blockID; public function __construct($meta = 0){ parent::__construct(COBBLESTONE_STAIRS, $meta, "Cobblestone Stairs"); + $this->breakTime = 2; + $this->hardness = 30; + $this->material = Material::$stone; } } \ No newline at end of file diff --git a/src/material/block/nonfull/stairs/JungleWoodStairsBlock.php b/src/material/block/nonfull/stairs/JungleWoodStairsBlock.php index c466fda2..07defb89 100644 --- a/src/material/block/nonfull/stairs/JungleWoodStairsBlock.php +++ b/src/material/block/nonfull/stairs/JungleWoodStairsBlock.php @@ -4,6 +4,9 @@ class JungleWoodStairsBlock extends StairBlock{ public static $blockID; public function __construct($meta = 0){ parent::__construct(JUNGLE_WOOD_STAIRS, $meta, "Jungle Wood Stairs"); + $this->hardness = 15; + $this->breakTime = 2; + $this->material = Material::$wood; } public function getDrops(Item $item, Player $player){ diff --git a/src/material/block/nonfull/stairs/NetherBricksStairsBlock.php b/src/material/block/nonfull/stairs/NetherBricksStairsBlock.php index d798d1e5..9a732c4d 100644 --- a/src/material/block/nonfull/stairs/NetherBricksStairsBlock.php +++ b/src/material/block/nonfull/stairs/NetherBricksStairsBlock.php @@ -4,6 +4,9 @@ class NetherBricksStairsBlock extends StairBlock{ public static $blockID; public function __construct($meta = 0){ parent::__construct(NETHER_BRICKS_STAIRS, $meta, "Nether Bricks Stairs"); + $this->hardness = 30; + $this->breakTime = 2; + $this->material = Material::$stone; } } \ No newline at end of file diff --git a/src/material/block/nonfull/stairs/QuartzStairsBlock.php b/src/material/block/nonfull/stairs/QuartzStairsBlock.php index b9f7ac8d..fe7502da 100644 --- a/src/material/block/nonfull/stairs/QuartzStairsBlock.php +++ b/src/material/block/nonfull/stairs/QuartzStairsBlock.php @@ -4,6 +4,9 @@ class QuartzStairsBlock extends StairBlock{ public static $blockID; public function __construct($meta = 0){ parent::__construct(QUARTZ_STAIRS, $meta, "Quartz Stairs"); + $this->breakTime = 0.8; + $this->hardness = 4; + $this->material = Material::$stone; } } \ No newline at end of file diff --git a/src/material/block/nonfull/stairs/SandstoneStairsBlock.php b/src/material/block/nonfull/stairs/SandstoneStairsBlock.php index 89e44b6d..623b2eba 100644 --- a/src/material/block/nonfull/stairs/SandstoneStairsBlock.php +++ b/src/material/block/nonfull/stairs/SandstoneStairsBlock.php @@ -4,6 +4,9 @@ class SandstoneStairsBlock extends StairBlock{ public static $blockID; public function __construct($meta = 0){ parent::__construct(SANDSTONE_STAIRS, $meta, "Sandstone Stairs"); + $this->hardness = 0.8*5; + $this->breakTime = 0.8; + $this->material = Material::$stone; } } \ No newline at end of file diff --git a/src/material/block/nonfull/stairs/SpruceWoodStairsBlock.php b/src/material/block/nonfull/stairs/SpruceWoodStairsBlock.php index 8468e0e2..9e4609de 100644 --- a/src/material/block/nonfull/stairs/SpruceWoodStairsBlock.php +++ b/src/material/block/nonfull/stairs/SpruceWoodStairsBlock.php @@ -4,6 +4,9 @@ class SpruceWoodStairsBlock extends StairBlock{ public static $blockID; public function __construct($meta = 0){ parent::__construct(SPRUCE_WOOD_STAIRS, $meta, "Spruce Wood Stairs"); + $this->hardness = 15; + $this->breakTime = 2; + $this->material = Material::$wood; } public function getDrops(Item $item, Player $player){ diff --git a/src/material/block/nonfull/stairs/StoneBrickStairsBlock.php b/src/material/block/nonfull/stairs/StoneBrickStairsBlock.php index 0a13b42b..deb69fec 100644 --- a/src/material/block/nonfull/stairs/StoneBrickStairsBlock.php +++ b/src/material/block/nonfull/stairs/StoneBrickStairsBlock.php @@ -4,6 +4,9 @@ class StoneBrickStairsBlock extends StairBlock{ public static $blockID; public function __construct($meta = 0){ parent::__construct(STONE_BRICK_STAIRS, $meta, "Stone Brick Stairs"); + $this->hardness = 30; + $this->breakTime = 1.5; + $this->material = Material::$stone; } } \ No newline at end of file diff --git a/src/material/block/nonfull/stairs/WoodStairsBlock.php b/src/material/block/nonfull/stairs/WoodStairsBlock.php index d3cc9e10..a907af50 100644 --- a/src/material/block/nonfull/stairs/WoodStairsBlock.php +++ b/src/material/block/nonfull/stairs/WoodStairsBlock.php @@ -4,13 +4,17 @@ class WoodStairsBlock extends StairBlock{ public static $blockID; public function __construct($meta = 0){ parent::__construct(WOOD_STAIRS, $meta, "Wood Stairs"); + $this->breakTime = 2; + $this->material = Material::$wood; } public function getBreakTime(Item $item, Player $player){ if(($player->gamemode & 0x01) === 0x01){ return 0.20; } - return match ($item->isAxe()) { + if(!$item->isAxe()) return 3; + + return match ($item->getLevel()) { 5 => 0.4, 4 => 0.5, 3 => 0.75, diff --git a/src/material/block/ore/CoalOreBlock.php b/src/material/block/ore/CoalOreBlock.php index 8bc6ce59..08737c5c 100644 --- a/src/material/block/ore/CoalOreBlock.php +++ b/src/material/block/ore/CoalOreBlock.php @@ -5,6 +5,9 @@ class CoalOreBlock extends SolidBlock{ public function __construct(){ parent::__construct(COAL_ORE, 0, "Coal Ore"); $this->hardness = 15; + $this->breakTime = 3.0; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/ore/DiamondOreBlock.php b/src/material/block/ore/DiamondOreBlock.php index 8b4fc682..d7a05106 100644 --- a/src/material/block/ore/DiamondOreBlock.php +++ b/src/material/block/ore/DiamondOreBlock.php @@ -5,6 +5,9 @@ class DiamondOreBlock extends SolidBlock{ public function __construct(){ parent::__construct(DIAMOND_ORE, 0, "Diamond Ore"); $this->hardness = 15; + $this->breakTime = 3; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/ore/GlowingRedstoneOreBlock.php b/src/material/block/ore/GlowingRedstoneOreBlock.php index ed9ad90e..0e1d4871 100644 --- a/src/material/block/ore/GlowingRedstoneOreBlock.php +++ b/src/material/block/ore/GlowingRedstoneOreBlock.php @@ -5,6 +5,10 @@ class GlowingRedstoneOreBlock extends SolidBlock implements LightingBlock{ public function __construct(){ parent::__construct(GLOWING_REDSTONE_ORE, 0, "Glowing Redstone Ore"); $this->hardness = 15; + $this->breakTime = 3; + $this->material = Material::$stone; + $this->lightBlock = 255; + $this->lightEmission = 9; } public static function onRandomTick(Level $level, $x, $y, $z){ diff --git a/src/material/block/ore/GoldOreBlock.php b/src/material/block/ore/GoldOreBlock.php index 2de507f6..ac0b9348 100644 --- a/src/material/block/ore/GoldOreBlock.php +++ b/src/material/block/ore/GoldOreBlock.php @@ -5,6 +5,9 @@ class GoldOreBlock extends SolidBlock{ public function __construct(){ parent::__construct(GOLD_ORE, 0, "Gold Ore"); $this->hardness = 15; + $this->breakTime = 3.0; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/ore/IronOreBlock.php b/src/material/block/ore/IronOreBlock.php index abb023de..bf77c236 100644 --- a/src/material/block/ore/IronOreBlock.php +++ b/src/material/block/ore/IronOreBlock.php @@ -5,6 +5,9 @@ class IronOreBlock extends SolidBlock{ public function __construct(){ parent::__construct(IRON_ORE, 0, "Iron Ore"); $this->hardness = 15; + $this->breakTime = 3.0; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/ore/LapisOreBlock.php b/src/material/block/ore/LapisOreBlock.php index 5130db86..5eb5c99b 100644 --- a/src/material/block/ore/LapisOreBlock.php +++ b/src/material/block/ore/LapisOreBlock.php @@ -5,6 +5,9 @@ class LapisOreBlock extends SolidBlock{ public function __construct(){ parent::__construct(LAPIS_ORE, 0, "Lapis Ore"); $this->hardness = 15; + $this->breakTime = 3.0; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/ore/RedstoneOreBlock.php b/src/material/block/ore/RedstoneOreBlock.php index dfe5c77e..39a52c75 100644 --- a/src/material/block/ore/RedstoneOreBlock.php +++ b/src/material/block/ore/RedstoneOreBlock.php @@ -5,6 +5,9 @@ class RedstoneOreBlock extends SolidBlock{ public function __construct(){ parent::__construct(REDSTONE_ORE, 0, "Redstone Ore"); $this->hardness = 15; + $this->breakTime = 3; + $this->material = Material::$stone; + $this->lightBlock = 255; } public static function interact(Level $level, $x, $y, $z, Player $player){ diff --git a/src/material/block/plant/BaseMushroomBlock.php b/src/material/block/plant/BaseMushroomBlock.php new file mode 100644 index 00000000..02e5df30 --- /dev/null +++ b/src/material/block/plant/BaseMushroomBlock.php @@ -0,0 +1,56 @@ +hardness = 0; + $this->breakTime = 0; + $this->material = Material::$plant; + } + + public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ + if(StaticBlock::getIsTransparent($level->level->getBlockID($x, $y - 1, $z))){ //Replace with common break method + ServerAPI::request()->api->entity->drop(new Position($x+0.5, $y, $z+0.5, $level), BlockAPI::getItem(static::$blockID, 0, 1)); + $level->fastSetBlockUpdate($x, $y, $z, 0, 0); + } + } + + public static function onRandomTick(Level $level, $x, $y, $z){ + if(Block::$mushroomSpread && mt_rand(0, 24) == 0){ + $maxcnt = 5; + for($xx = $x-4; $xx <= $x+4; ++$xx){ + for($zz = $z-4; $zz <= $z+4; ++$zz){ + for($yy = $y-1; $yy <= $y+1; ++$yy){ + if($level->level->getBlockID($xx, $yy, $zz) == static::$blockID){ + if(--$maxcnt <= 0) return; + } + } + } + } + + for($att = 0; $att < 4; ++$att){ + $nx = $x + mt_rand(-1, 1); + $ny = $y + mt_rand(-1, 1); + $nz = $z + mt_rand(-1, 1); + if($ny < 127 && $ny > 0 && $level->level->getBlockID($nx, $ny, $nz) == 0){ + $idb = $level->level->getBlockID($nx, $ny-1, $nz); + if(!StaticBlock::getIsTransparent($idb)){ //TODO better canSurvive check + if($level->getRawBrightness($nx, $ny, $nz) <= 12){ + $level->fastSetBlockUpdate($nx, $ny, $nz, static::$blockID, 0); + return; + } + } + } + } + } + } + + public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ + $down = $this->getSide(0); + if($down->isTransparent === false){ + $this->level->setBlock($block, $this, true, false, true); + return true; + } + return false; + } +} \ No newline at end of file diff --git a/src/material/block/plant/BeetrootBlock.php b/src/material/block/plant/BeetrootBlock.php index 423ed15f..3915dd5c 100644 --- a/src/material/block/plant/BeetrootBlock.php +++ b/src/material/block/plant/BeetrootBlock.php @@ -6,13 +6,14 @@ class BeetrootBlock extends FlowableBlock{ parent::__construct(BEETROOT_BLOCK, $meta, "Beetroot Block"); $this->isActivable = true; $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$plant; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ $down = $this->getSide(0); if($down->getID() === FARMLAND){ $this->level->setBlock($block, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return true; } return false; @@ -32,9 +33,7 @@ class BeetrootBlock extends FlowableBlock{ $this->meta = 7; } $this->level->setBlock($this, $this, true, false, true); - if(($player->gamemode & 0x01) === 0){ - $player->removeItem(DYE,0x0F,1); - } + $player->consumeSingleItem(send:true); return true; } return false; diff --git a/src/material/block/plant/BrownMushroomBlock.php b/src/material/block/plant/BrownMushroomBlock.php index aae803a7..6cf2ebe1 100644 --- a/src/material/block/plant/BrownMushroomBlock.php +++ b/src/material/block/plant/BrownMushroomBlock.php @@ -1,25 +1,9 @@ hardness = 0; - } - - public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ - if(StaticBlock::getIsTransparent($level->level->getBlockID($x, $y - 1, $z))){ //Replace with common break method - ServerAPI::request()->api->entity->drop(new Position($x + 0.5, $y, $z + 0.5, $level), BlockAPI::getItem(BROWN_MUSHROOM)); - $level->fastSetBlockUpdate($x, $y, $z, 0, 0); - } - } - - public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ - $down = $this->getSide(0); - if($down->isTransparent === false){ - $this->level->setBlock($block, $this, true, false, true); - return true; - } - return false; + $this->lightEmission = 1; } } \ No newline at end of file diff --git a/src/material/block/plant/CactusBlock.php b/src/material/block/plant/CactusBlock.php index debb3dc2..e3ebdef0 100644 --- a/src/material/block/plant/CactusBlock.php +++ b/src/material/block/plant/CactusBlock.php @@ -6,6 +6,8 @@ class CactusBlock extends TransparentBlock{ parent::__construct(CACTUS, $meta, "Cactus"); $this->isFullBlock = false; $this->hardness = 2; + $this->breakTime = 0.4; + $this->material = Material::$cactus; } public static function onEntityCollidedWithBlock(Level $level, $x, $y, $z, Entity $entity){ @@ -60,7 +62,6 @@ class CactusBlock extends TransparentBlock{ $block3 = $this->getSide(5); if($block0->isFlowable === true and $block1->isFlowable === true and $block2->isFlowable === true and $block3->isFlowable === true){ $this->level->setBlock($this, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); ServerAPI::request()->api->block->scheduleBlockUpdate(clone $this, 10, BLOCK_UPDATE_NORMAL); return true; } diff --git a/src/material/block/plant/CarrotBlock.php b/src/material/block/plant/CarrotBlock.php index b7fe8619..9482207a 100644 --- a/src/material/block/plant/CarrotBlock.php +++ b/src/material/block/plant/CarrotBlock.php @@ -6,13 +6,14 @@ class CarrotBlock extends FlowableBlock{ parent::__construct(CARROT_BLOCK, $meta, "Carrot Block"); $this->isActivable = true; $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$plant; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ $down = $this->getSide(0); if($down->getID() === FARMLAND){ $this->level->setBlock($block, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return true; } return false; @@ -25,9 +26,7 @@ class CarrotBlock extends FlowableBlock{ $this->meta = 7; } $this->level->setBlock($this, $this, true, false, true); - if(($player->gamemode & 0x01) === 0){ - $player->removeItem(DYE,0x0F,1); - } + $player->consumeSingleItem(send:true); return true; } return false; diff --git a/src/material/block/plant/CyanFlowerBlock.php b/src/material/block/plant/CyanFlowerBlock.php index 60de9639..5d286842 100644 --- a/src/material/block/plant/CyanFlowerBlock.php +++ b/src/material/block/plant/CyanFlowerBlock.php @@ -6,6 +6,8 @@ class CyanFlowerBlock extends FlowableBlock{ parent::__construct(CYAN_FLOWER, 0, "Cyan Flower"); $this->isActivable = true; $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$plant; } public static function getAABB(Level $level, $x, $y, $z){ @@ -31,11 +33,9 @@ class CyanFlowerBlock extends FlowableBlock{ public function onActivate(Item $item, Player $player){ if($item->getID() === DYE and $item->getMetadata() === 0x0F){ - if(($player->gamemode & 0x01) === 0){ - $player->removeItem(DYE,0x0F,1); - } $random = new Random(); self::placeFlowers($this->level, new Vector3($this->x, $this->y, $this->z), $random, $random->nextRange(2, 5), 2); + $player->consumeSingleItem(send:true); return true; } return false; diff --git a/src/material/block/plant/DandelionBlock.php b/src/material/block/plant/DandelionBlock.php index 69f39eef..7388a132 100644 --- a/src/material/block/plant/DandelionBlock.php +++ b/src/material/block/plant/DandelionBlock.php @@ -6,6 +6,8 @@ class DandelionBlock extends FlowableBlock{ parent::__construct(DANDELION, 0, "Dandelion"); $this->isActivable = true; $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$plant; } public static function getAABB(Level $level, $x, $y, $z){ return null; @@ -22,18 +24,16 @@ class DandelionBlock extends FlowableBlock{ public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ $downId = $level->level->getBlockID($x, $y - 1, $z); if(StaticBlock::getIsTransparent($downId) and $downId !== FARMLAND){ //Replace with common break method - ServerAPI::request()->api->entity->drop(new Position($x + 0.5, $y, $z + 0.5, $level), BlockAPI::getItem(CYAN_FLOWER)); + ServerAPI::request()->api->entity->drop(new Position($x+0.5, $y, $z+0.5, $level), BlockAPI::getItem(DANDELION)); $level->fastSetBlockUpdate($x, $y, $z, 0, 0); } } public function onActivate(Item $item, Player $player){ if($item->getID() === DYE and $item->getMetadata() === 0x0F){ - if(($player->gamemode & 0x01) === 0){ - $player->removeItem(DYE,0x0F,1); - } $random = new Random(); self::placeFlowers($this->level, new Vector3($this->x, $this->y, $this->z), $random, $random->nextRange(2, 5), 2); + $player->consumeSingleItem(send:true); return true; } return false; diff --git a/src/material/block/plant/DeadBushBlock.php b/src/material/block/plant/DeadBushBlock.php index b3be7cdc..a74c40bc 100644 --- a/src/material/block/plant/DeadBushBlock.php +++ b/src/material/block/plant/DeadBushBlock.php @@ -6,6 +6,8 @@ class DeadBushBlock extends FlowableBlock{ parent::__construct(DEAD_BUSH, 0, "Dead Bush"); //$this->isReplaceable = true; $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$replaceable_plant; } public static function getAABB(Level $level, $x, $y, $z){ diff --git a/src/material/block/plant/MelonStemBlock.php b/src/material/block/plant/MelonStemBlock.php index 4dee856f..fc4fb4be 100644 --- a/src/material/block/plant/MelonStemBlock.php +++ b/src/material/block/plant/MelonStemBlock.php @@ -6,51 +6,97 @@ class MelonStemBlock extends FlowableBlock{ parent::__construct(MELON_STEM, $meta, "Melon Stem"); $this->isActivable = true; $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$plant; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ $down = $this->getSide(0); if($down->getID() === FARMLAND){ $this->level->setBlock($block, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return true; } return false; } + + public static function getGrowthSpeed(Level $level, $x, $y, $z){ + $zneg = $level->level->getBlockID($x, $y, $z-1); + $zpos = $level->level->getBlockID($x, $y, $z+1); + $xneg = $level->level->getBlockID($x-1, $y, $z); + $xpos = $level->level->getBlockID($x+1, $y, $z); + $znxn = $level->level->getBlockID($x-1, $y, $z-1); + $znxp = $level->level->getBlockID($x+1, $y, $z-1); + $zpxp = $level->level->getBlockID($x+1, $y, $z+1); + $zpxn = $level->level->getBlockID($x-1, $y, $z+1); + $xEqual = $xneg == MELON_STEM || $xpos == MELON_STEM; + $zEqual = $zneg == MELON_STEM || $zpos == MELON_STEM; + $xzEqual = $znxn == MELON_STEM || $znxp == MELON_STEM || $zpxn == MELON_STEM || $zpxp == MELON_STEM; + + $speed = 1; + for($xx = $x-1; $xx >= $x+1; ++$xx){ + for($zz = $z-1; $zz >= $z+1; ++$zz){ + [$id, $meta] = $level->level->getBlock($x, $y, $z); + $v18 = 0; + if($id == FARMLAND) $v18 = $meta > 0 ? 3 : 1; + if($xx != $x || $zz != $z) $v18 *= 0.25; + $speed += $v18; + } + } + if($xzEqual || ($xEqual && $zEqual)) return $speed*0.5; + return $speed; + } + public static function onRandomTick(Level $level, $x, $y, $z){ - if(mt_rand(0, 2) == 1){ - $block = $level->level->getBlock($x, $y, $z); - if($block[1] < 0x07){ - //++$this->meta; - //$this->level->setBlock($this, $this, true, false, true); - $level->fastSetBlockUpdate($x, $y, $z, $block[0], $block[1] + 1); - }else{ - - $position = new AirBlock(); //feke block - $position->x = $x; - $position->y = $y; - $position->z = $z; - $position->level = $level; - for($side = 2; $side <= 5; ++$side){ - $b = $position->getSide($side); - if($b->getID() === MELON_BLOCK){ - return; - } - } - $side = $position->getSide(mt_rand(2,5)); - $d = $side->getSide(0); - if($side->getID() === AIR and ($d->getID() === FARMLAND or $d->getID() === GRASS or $d->getID() === DIRT)){ - $level->setBlock($side, new MelonBlock(), true, false, true); - } + //TODO checkAlive + //if ( Level::getRawBrightness(a2, a3, a4 + 1, a5) > 8 ) TODO - skylight + + $growSpeed = static::getGrowthSpeed($level, $x, $y, $z); + $rand = mt_rand(0, (int)(25/$growSpeed)); + if($rand != 0) return; + + $meta = $level->level->getBlockDamage($x, $y, $z); + if($meta <= 6){ + $level->fastSetBlockUpdateMeta($x, $y, $z, $meta+1); + return; + } + + $xn = $level->level->getBlockID($x-1, $y, $z); + $xp = $level->level->getBlockID($x+1, $y, $z); + $zn = $level->level->getBlockID($x, $y, $z-1); + $zp = $level->level->getBlockID($x, $y, $z+1); + if($xn != MELON_BLOCK && $xp != MELON_BLOCK && $zn != MELON_BLOCK && $zp != MELON_BLOCK){ + $below = $level->level->getBlockID($x-1, $y-1, $z); + if($level->level->getBlockID($x-1, $y, $z) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x-1, $y, $z, MELON_BLOCK, 0); + return; + } + + $below = $level->level->getBlockID($x+1, $y-1, $z); + if($level->level->getBlockID($x+1, $y, $z) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x+1, $y, $z, MELON_BLOCK, 0); + return; + } + + $below = $level->level->getBlockID($x, $y-1, $z-1); + if($level->level->getBlockID($x, $y, $z-1) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x, $y, $z-1, MELON_BLOCK, 0); + return; + } + + $below = $level->level->getBlockID($x, $y-1, $z+1); + if($level->level->getBlockID($x, $y, $z+1) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x, $y, $z+1, MELON_BLOCK, 0); + return; } } } + public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ if($level->level->getBlockID($x, $y - 1, $z) != FARMLAND){ - ServerAPI::request()->api->entity->drop(new Position($x + 0.5, $y, $z + 0.5, $level), BlockAPI::getItem(MELON_SEEDS, 0, mt_rand(0, 2))); + ServerAPI::request()->api->entity->drop(new Position($x+0.5, $y, $z+0.5, $level), BlockAPI::getItem(MELON_SEEDS, 0, mt_rand(0, 2))); $level->fastSetBlockUpdate($x, $y, $z, 0, 0); } } - + public function onActivate(Item $item, Player $player){ if($item->getID() === DYE and $item->getMetadata() === 0x0F){ //Bonemeal $this->meta += mt_rand(0, 3) + 2; @@ -58,24 +104,16 @@ class MelonStemBlock extends FlowableBlock{ $this->meta = 7; } $this->level->setBlock($this, $this, true, false, true); - if(($player->gamemode & 0x01) === 0){ - $player->removeItem(DYE,0x0F,1); - } + $player->consumeSingleItem(send:true); return true; } return false; } - + public function getDrops(Item $item, Player $player){ $drops = []; - if($this->meta >= 0x07){ - $drops[] = [MELON_SEEDS, 0, mt_rand(1, 2)]; - } - elseif($this->meta >= 0x01 and $this->meta <= 0x07){ - $drops[] = [MELON_SEEDS, 0, 1]; - } - else{ - $drops[] = [MELON_SEEDS, 0, 0]; + for($i = 0; $i < 3; ++$i){ + if(mt_rand(0, 15) <= $this->meta) $drops[] = [MELON_SEEDS, 0, 1]; } return $drops; } diff --git a/src/material/block/plant/PotatoBlock.php b/src/material/block/plant/PotatoBlock.php index 62d44ac6..54a5ce24 100644 --- a/src/material/block/plant/PotatoBlock.php +++ b/src/material/block/plant/PotatoBlock.php @@ -6,13 +6,14 @@ class PotatoBlock extends FlowableBlock{ parent::__construct(POTATO_BLOCK, $meta, "Potato Block"); $this->isActivable = true; $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$plant; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ $down = $this->getSide(0); if($down->getID() === FARMLAND){ $this->level->setBlock($block, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return true; } return false; @@ -34,9 +35,7 @@ class PotatoBlock extends FlowableBlock{ $this->meta = 7; } $this->level->setBlock($this, $this, true, false, true); - if(($player->gamemode & 0x01) === 0){ - $player->removeItem(DYE,0x0F,1); - } + $player->consumeSingleItem(send:true); return true; } return false; diff --git a/src/material/block/plant/PumpkinStemBlock.php b/src/material/block/plant/PumpkinStemBlock.php index 00eed1cb..42c966a1 100644 --- a/src/material/block/plant/PumpkinStemBlock.php +++ b/src/material/block/plant/PumpkinStemBlock.php @@ -6,51 +6,96 @@ class PumpkinStemBlock extends FlowableBlock{ parent::__construct(PUMPKIN_STEM, $meta, "Pumpkin Stem"); $this->isActivable = true; $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$plant; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ - $down = $this->getSide(0); - if($down->getID() === FARMLAND){ - $this->level->setBlock($block, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); - return true; - } + $down = $this->getSide(0); + if($down->getID() === FARMLAND){ + $this->level->setBlock($block, $this, true, false, true); + return true; + } return false; } + + public static function getGrowthSpeed(Level $level, $x, $y, $z){ + $zneg = $level->level->getBlockID($x, $y, $z-1); + $zpos = $level->level->getBlockID($x, $y, $z+1); + $xneg = $level->level->getBlockID($x-1, $y, $z); + $xpos = $level->level->getBlockID($x+1, $y, $z); + $znxn = $level->level->getBlockID($x-1, $y, $z-1); + $znxp = $level->level->getBlockID($x+1, $y, $z-1); + $zpxp = $level->level->getBlockID($x+1, $y, $z+1); + $zpxn = $level->level->getBlockID($x-1, $y, $z+1); + $xEqual = $xneg == PUMPKIN_STEM || $xpos == PUMPKIN_STEM; + $zEqual = $zneg == PUMPKIN_STEM || $zpos == PUMPKIN_STEM; + $xzEqual = $znxn == PUMPKIN_STEM || $znxp == PUMPKIN_STEM || $zpxn == PUMPKIN_STEM || $zpxp == PUMPKIN_STEM; + + $speed = 1; + for($xx = $x-1; $xx >= $x+1; ++$xx){ + for($zz = $z-1; $zz >= $z+1; ++$zz){ + [$id, $meta] = $level->level->getBlock($x, $y, $z); + if($id == FARMLAND) $v18 = $meta > 0 ? 3 : 1; + else $v18 = 0; + if($xx != $x || $zz != $z) $v18 *= 0.25; + $speed += $v18; + } + } + if($xzEqual || ($xEqual && $zEqual)) return $speed*0.5; + return $speed; + } + public static function onRandomTick(Level $level, $x, $y, $z){ - if(mt_rand(0, 2) == 1){ - $block = $level->level->getBlock($x, $y, $z); - if($block[1] < 0x07){ - //++$this->meta; - //$this->level->setBlock($this, $this, true, false, true); - $level->fastSetBlockUpdate($x, $y, $z, $block[0], $block[1] + 1); - }else{ - - $position = new AirBlock(); //feke block - $position->x = $x; - $position->y = $y; - $position->z = $z; - $position->level = $level; - for($side = 2; $side <= 5; ++$side){ - $b = $position->getSide($side); - if($b->getID() === PUMPKIN){ - return; - } - } - $side = $position->getSide(mt_rand(2,5)); - $d = $side->getSide(0); - if($side->getID() === AIR and ($d->getID() === FARMLAND or $d->getID() === GRASS or $d->getID() === DIRT)){ - $level->setBlock($side, new PumpkinBlock(), true, false, true); - } + //TODO checkAlive + //if ( Level::getRawBrightness(a2, a3, a4 + 1, a5) > 8 ) TODO - skylight + + $growSpeed = static::getGrowthSpeed($level, $x, $y, $z); + $rand = mt_rand(0, (int)(25/$growSpeed)); + if($rand != 0) return; + + $meta = $level->level->getBlockDamage($x, $y, $z); + if($meta <= 6){ + $level->fastSetBlockUpdateMeta($x, $y, $z, $meta+1); + return; + } + + $xn = $level->level->getBlockID($x-1, $y, $z); + $xp = $level->level->getBlockID($x+1, $y, $z); + $zn = $level->level->getBlockID($x, $y, $z-1); + $zp = $level->level->getBlockID($x, $y, $z+1); + if($xn != PUMPKIN && $xp != PUMPKIN && $zn != PUMPKIN && $zp != PUMPKIN){ + $below = $level->level->getBlockID($x-1, $y-1, $z); + if($level->level->getBlockID($x-1, $y, $z) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x-1, $y, $z, PUMPKIN, 0); + return; + } + + $below = $level->level->getBlockID($x+1, $y-1, $z); + if($level->level->getBlockID($x+1, $y, $z) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x+1, $y, $z, PUMPKIN, 0); + return; + } + + $below = $level->level->getBlockID($x, $y-1, $z-1); + if($level->level->getBlockID($x, $y, $z-1) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x, $y, $z-1, PUMPKIN, 0); + return; + } + + $below = $level->level->getBlockID($x, $y-1, $z+1); + if($level->level->getBlockID($x, $y, $z+1) == 0 && ($below == FARMLAND || $below == DIRT || $below == GRASS)){ + $level->fastSetBlockUpdate($x, $y, $z+1, PUMPKIN, 0); + return; } } } public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ if($level->level->getBlockID($x, $y - 1, $z) != FARMLAND){ - ServerAPI::request()->api->entity->drop(new Position($x + 0.5, $y, $z + 0.5, $level), BlockAPI::getItem(PUMPKIN_SEEDS, 0, mt_rand(0, 2))); + ServerAPI::request()->api->entity->drop(new Position($x+0.5, $y, $z+0.5, $level), BlockAPI::getItem(PUMPKIN_SEEDS, 0, mt_rand(0, 2))); $level->fastSetBlockUpdate($x, $y, $z, 0, 0); } } - + public function onActivate(Item $item, Player $player){ if($item->getID() === DYE and $item->getMetadata() === 0x0F){ //Bonemeal $this->meta += mt_rand(0, 3) + 2; @@ -58,24 +103,16 @@ class PumpkinStemBlock extends FlowableBlock{ $this->meta = 7; } $this->level->setBlock($this, $this, true, false, true); - if(($player->gamemode & 0x01) === 0){ - $player->removeItem(DYE,0x0F,1); - } + $player->consumeSingleItem(send:true); return true; } return false; } - + public function getDrops(Item $item, Player $player){ $drops = []; - if($this->meta >= 0x07){ - $drops[] = [PUMPKIN_SEEDS, 0, mt_rand(1, 2)]; - } - elseif($this->meta >= 0x01 and $this->meta <= 0x07){ - $drops[] = [PUMPKIN_SEEDS, 0, 1]; - } - else{ - $drops[] = [PUMPKIN_SEEDS, 0, 0]; + for($i = 0; $i < 3; ++$i){ + if(mt_rand(0, 15) <= $this->meta) $drops[] = [PUMPKIN_SEEDS, 0, 1]; } return $drops; } diff --git a/src/material/block/plant/RedMushroomBlock.php b/src/material/block/plant/RedMushroomBlock.php index 3ba418b5..d2564bb6 100644 --- a/src/material/block/plant/RedMushroomBlock.php +++ b/src/material/block/plant/RedMushroomBlock.php @@ -1,25 +1,9 @@ hardness = 0; - } - - public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ - if(StaticBlock::getIsTransparent($level->level->getBlockID($x, $y - 1, $z))){ //Replace with common break method - ServerAPI::request()->api->entity->drop(new Position($x + 0.5, $y, $z + 0.5, $level), BlockAPI::getItem(RED_MUSHROOM)); - $level->fastSetBlockUpdate($x, $y, $z, 0, 0); - } - } - - public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ - $down = $this->getSide(0); - if($down->isTransparent === false){ - $this->level->setBlock($block, $this, true, false, true); - return true; - } - return false; } } \ No newline at end of file diff --git a/src/material/block/plant/SaplingBlock.php b/src/material/block/plant/SaplingBlock.php index fd830844..cdce156e 100644 --- a/src/material/block/plant/SaplingBlock.php +++ b/src/material/block/plant/SaplingBlock.php @@ -19,6 +19,8 @@ class SaplingBlock extends FlowableBlock{ ]; $this->name = $names[$this->meta & 0x03]; $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$plant; } public static function getAABB(Level $level, $x, $y, $z){ return null; @@ -27,7 +29,6 @@ class SaplingBlock extends FlowableBlock{ $down = $this->getSide(0); if($down->getID() === GRASS or $down->getID() === DIRT or $down->getID() === FARMLAND){ $this->level->setBlock($block, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return true; } return false; @@ -36,9 +37,7 @@ class SaplingBlock extends FlowableBlock{ public function onActivate(Item $item, Player $player){ if($item->getID() === DYE and $item->getMetadata() === 0x0F){ //Bonemeal TreeObject::growTree($this->level, $this, new Random(), $this->meta & 0x03); - if(($player->gamemode & 0x01) === 0){ - $player->removeItem(DYE,0x0F,1); - } + $player->consumeSingleItem(send:true); return true; } return false; diff --git a/src/material/block/plant/SugarcaneBlock.php b/src/material/block/plant/SugarcaneBlock.php index 660f1393..6e5bcb94 100644 --- a/src/material/block/plant/SugarcaneBlock.php +++ b/src/material/block/plant/SugarcaneBlock.php @@ -6,8 +6,10 @@ class SugarcaneBlock extends FlowableBlock{ parent::__construct(SUGARCANE_BLOCK, $meta, "Sugarcane"); $this->isActivable = true; $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$plant; } - + public function getDrops(Item $item, Player $player){ return [ [SUGARCANE, 0, 1], @@ -28,10 +30,8 @@ class SugarcaneBlock extends FlowableBlock{ $this->meta = 0; $this->level->fastSetBlockUpdateMeta($this->x, $this->y, $this->z, $this->meta, true); } - - if(($player->gamemode & 0x01) === 0){ - $player->removeItem(DYE,0x0F,1); - } + + $player->consumeSingleItem(send:true); return true; } return false; @@ -50,7 +50,7 @@ class SugarcaneBlock extends FlowableBlock{ } } if(StaticBlock::getIsTransparent($down) && $down != SUGARCANE_BLOCK){ //Replace with common break method - ServerAPI::request()->api->entity->drop(new Position($x + 0.5, $y, $z + 0.5, $level), BlockAPI::getItem(SUGARCANE)); + ServerAPI::request()->api->entity->drop(new Position($x+0.5, $y, $z+0.5, $level), BlockAPI::getItem(SUGARCANE)); $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); } } @@ -80,7 +80,7 @@ class SugarcaneBlock extends FlowableBlock{ $x = $this->x; $y = $this->y; $z = $this->z; - + $b0 = $level->level->getBlockID($x, $y - 1, $z - 1); $b1 = $level->level->getBlockID($x, $y - 1, $z + 1); $b2 = $level->level->getBlockID($x - 1, $y - 1, $z); diff --git a/src/material/block/plant/TallGrassBlock.php b/src/material/block/plant/TallGrassBlock.php index 94ec709d..975128ed 100644 --- a/src/material/block/plant/TallGrassBlock.php +++ b/src/material/block/plant/TallGrassBlock.php @@ -12,6 +12,8 @@ class TallGrassBlock extends FlowableBlock{ ]; $this->name = $names[$this->meta & 0x03]; $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$replaceable_plant; } public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ diff --git a/src/material/block/plant/WheatBlock.php b/src/material/block/plant/WheatBlock.php index 36f8d247..6b92570b 100644 --- a/src/material/block/plant/WheatBlock.php +++ b/src/material/block/plant/WheatBlock.php @@ -6,13 +6,14 @@ class WheatBlock extends FlowableBlock{ parent::__construct(WHEAT_BLOCK, $meta, "Wheat Block"); $this->isActivable = true; $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$plant; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ $down = $this->getSide(0); if($down->getID() === FARMLAND){ $this->level->setBlock($block, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return true; } return false; @@ -25,9 +26,7 @@ class WheatBlock extends FlowableBlock{ $this->meta = 7; } $this->level->setBlock($this, $this, true, false, true); - if(($player->gamemode & 0x01) === 0){ - $player->removeItem(DYE,0x0F,1); - } + $player->consumeSingleItem(send:true); return true; } return false; diff --git a/src/material/block/solid/BedrockBlock.php b/src/material/block/solid/BedrockBlock.php index d214a6d8..43350929 100644 --- a/src/material/block/solid/BedrockBlock.php +++ b/src/material/block/solid/BedrockBlock.php @@ -6,6 +6,9 @@ class BedrockBlock extends SolidBlock{ parent::__construct(BEDROCK, 0, "Bedrock"); $this->breakable = false; $this->hardness = 18000000; + $this->breakTime = -1; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function isBreakable(Item $item, Player $player){ diff --git a/src/material/block/solid/BookshelfBlock.php b/src/material/block/solid/BookshelfBlock.php index 4e501fe0..d8ac0e2b 100644 --- a/src/material/block/solid/BookshelfBlock.php +++ b/src/material/block/solid/BookshelfBlock.php @@ -5,6 +5,9 @@ class BookshelfBlock extends SolidBlock{ public function __construct(){ parent::__construct(BOOKSHELF, 0, "Bookshelf"); $this->hardness = 7.5; + $this->breakTime = 1.5; + $this->material = Material::$wood; + $this->lightBlock = 255; } } \ No newline at end of file diff --git a/src/material/block/solid/BricksBlock.php b/src/material/block/solid/BricksBlock.php index 653d398e..ce39f7bc 100644 --- a/src/material/block/solid/BricksBlock.php +++ b/src/material/block/solid/BricksBlock.php @@ -5,6 +5,9 @@ class BricksBlock extends SolidBlock{ public function __construct(){ parent::__construct(BRICKS_BLOCK, 0, "Bricks"); $this->hardness = 30; + $this->breakTime = 2; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/BurningFurnaceBlock.php b/src/material/block/solid/BurningFurnaceBlock.php index 1cfc3039..c77c7ff7 100644 --- a/src/material/block/solid/BurningFurnaceBlock.php +++ b/src/material/block/solid/BurningFurnaceBlock.php @@ -6,6 +6,10 @@ class BurningFurnaceBlock extends SolidBlock implements LightingBlock{ parent::__construct(BURNING_FURNACE, $meta, "Burning Furnace"); $this->isActivable = true; $this->hardness = 17.5; + $this->breakTime = 3.5; + $this->material = Material::$stone; + $this->lightBlock = 255; + $this->lightEmission = 13; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ diff --git a/src/material/block/solid/ClayBlock.php b/src/material/block/solid/ClayBlock.php index 7ce626de..695d583a 100644 --- a/src/material/block/solid/ClayBlock.php +++ b/src/material/block/solid/ClayBlock.php @@ -5,6 +5,9 @@ class ClayBlock extends SolidBlock{ public function __construct(){ parent::__construct(CLAY_BLOCK, 0, "Clay Block"); $this->hardness = 3; + $this->breakTime = 0.6; + $this->material = Material::$clay; + $this->lightBlock = 255; } public function getDrops(Item $item, Player $player){ diff --git a/src/material/block/solid/CoalBlock.php b/src/material/block/solid/CoalBlock.php index 0995aa26..613ea069 100644 --- a/src/material/block/solid/CoalBlock.php +++ b/src/material/block/solid/CoalBlock.php @@ -5,6 +5,9 @@ class CoalBlock extends SolidBlock{ public function __construct(){ parent::__construct(COAL_BLOCK, 0, "Coal Block"); $this->hardness = 30; + $this->breakTime = 5; + $this->material = Material::$metal; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/CobblestoneBlock.php b/src/material/block/solid/CobblestoneBlock.php index 0990c10d..4e47f339 100644 --- a/src/material/block/solid/CobblestoneBlock.php +++ b/src/material/block/solid/CobblestoneBlock.php @@ -5,6 +5,9 @@ class CobblestoneBlock extends SolidBlock{ public function __construct(){ parent::__construct(COBBLESTONE, 0, "Cobblestone"); $this->hardness = 30; + $this->breakTime = 2; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/DiamondBlock.php b/src/material/block/solid/DiamondBlock.php index 7f073778..d5f15a7a 100644 --- a/src/material/block/solid/DiamondBlock.php +++ b/src/material/block/solid/DiamondBlock.php @@ -5,6 +5,9 @@ class DiamondBlock extends SolidBlock{ public function __construct(){ parent::__construct(DIAMOND_BLOCK, 0, "Diamond Block"); $this->hardness = 30; + $this->breakTime = 5; + $this->material = Material::$metal; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/DirtBlock.php b/src/material/block/solid/DirtBlock.php index 64b43604..296e8a6e 100644 --- a/src/material/block/solid/DirtBlock.php +++ b/src/material/block/solid/DirtBlock.php @@ -6,16 +6,15 @@ class DirtBlock extends SolidBlock{ parent::__construct(DIRT, 0, "Dirt"); $this->isActivable = true; $this->hardness = 2.5; + $this->breakTime = 0.5; + $this->material = Material::$dirt; + $this->lightBlock = 255; } public function onActivate(Item $item, Player $player){ if($item->isHoe()){ if($this->getSide(1)->isTransparent === false) return false; - if(($player->gamemode & 0x01) === 0){ - $item->useOn($this); - if($item->getMetadata() >= $item->getMaxDurability()) $player->setSlot($player->slot, new Item(AIR, 0, 0), false); - else $player->setSlot($player->slot, $item, true); - } + $item->hurtAndBreak(1, $player); //TODO move to ItemHoe $this->level->fastSetBlockUpdate($this->x, $this->y, $this->z, FARMLAND, 0, true); return true; } diff --git a/src/material/block/solid/DoubleSlabBlock.php b/src/material/block/solid/DoubleSlabBlock.php index 8211f796..0372066a 100755 --- a/src/material/block/solid/DoubleSlabBlock.php +++ b/src/material/block/solid/DoubleSlabBlock.php @@ -16,6 +16,9 @@ class DoubleSlabBlock extends SolidBlock{ ]; $this->name = "Double " . $names[$this->meta & 0x07] . " Slab"; $this->hardness = 30; + $this->breakTime = 2; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/DoubleWoodSlabBlock.php b/src/material/block/solid/DoubleWoodSlabBlock.php index 61b4648f..3771ffc0 100644 --- a/src/material/block/solid/DoubleWoodSlabBlock.php +++ b/src/material/block/solid/DoubleWoodSlabBlock.php @@ -11,14 +11,19 @@ class DoubleWoodSlabBlock extends SolidBlock{ 3 => "Jungle", ]; $this->name = "Double " . $names[$this->meta & 0x07] . " Wooden Slab"; - $this->hardness = 15; + $this->hardness = 30; + $this->breakTime = 2; + $this->material = Material::$wood; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ if(($player->gamemode & 0x01) === 0x01){ return 0.20; } - return match ($item->isAxe()) { + if(!$item->isAxe()) return 3; + + return match ($item->getLevel()) { 5 => 0.4, 4 => 0.5, 3 => 0.75, diff --git a/src/material/block/solid/FurnaceBlock.php b/src/material/block/solid/FurnaceBlock.php index bbe31df5..083f2613 100644 --- a/src/material/block/solid/FurnaceBlock.php +++ b/src/material/block/solid/FurnaceBlock.php @@ -11,5 +11,8 @@ class FurnaceBlock extends BurningFurnaceBlock{ $this->id = FURNACE; $this->name = "Furnace"; $this->isActivable = true; + $this->material = Material::$stone; + $this->lightBlock = 255; + $this->lightEmission = 0; } } \ No newline at end of file diff --git a/src/material/block/solid/GlassBlock.php b/src/material/block/solid/GlassBlock.php index 6b133b3e..ec105c8d 100644 --- a/src/material/block/solid/GlassBlock.php +++ b/src/material/block/solid/GlassBlock.php @@ -5,6 +5,8 @@ class GlassBlock extends TransparentBlock{ public function __construct(){ parent::__construct(GLASS, 0, "Glass"); $this->hardness = 1.5; + $this->breakTime = 0.3; + $this->material = Material::$glass; } public function getDrops(Item $item, Player $player){ diff --git a/src/material/block/solid/GlowingObsidianBlock.php b/src/material/block/solid/GlowingObsidianBlock.php index 47411822..5f3c642c 100644 --- a/src/material/block/solid/GlowingObsidianBlock.php +++ b/src/material/block/solid/GlowingObsidianBlock.php @@ -4,6 +4,11 @@ class GlowingObsidianBlock extends SolidBlock implements LightingBlock{ public static $blockID; public function __construct($meta = 0){ parent::__construct(GLOWING_OBSIDIAN, $meta, "Glowing Obsidian"); + $this->hardness = 6000; + $this->breakTime = 10; + $this->material = Material::$stone; + $this->lightBlock = 255; + $this->lightEmission = 13; } public function getMaxLightValue(){ diff --git a/src/material/block/solid/GlowstoneBlock.php b/src/material/block/solid/GlowstoneBlock.php index 531ed733..01e6a149 100644 --- a/src/material/block/solid/GlowstoneBlock.php +++ b/src/material/block/solid/GlowstoneBlock.php @@ -5,6 +5,10 @@ class GlowstoneBlock extends TransparentBlock implements LightingBlock{ public function __construct(){ parent::__construct(GLOWSTONE_BLOCK, 0, "Glowstone"); $this->hardness = 1.5; + $this->breakTime = 0.3; + $this->material = Material::$glass; + $this->lightBlock = 255; + $this->lightEmission = 15; } public function getMaxLightValue(){ diff --git a/src/material/block/solid/GoldBlock.php b/src/material/block/solid/GoldBlock.php index 460c2b02..580011e4 100644 --- a/src/material/block/solid/GoldBlock.php +++ b/src/material/block/solid/GoldBlock.php @@ -5,6 +5,9 @@ class GoldBlock extends SolidBlock{ public function __construct(){ parent::__construct(GOLD_BLOCK, 0, "Gold Block"); $this->hardness = 30; + $this->breakTime = 3; + $this->material = Material::$metal; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/GrassBlock.php b/src/material/block/solid/GrassBlock.php index 47ae9f0d..252579c2 100644 --- a/src/material/block/solid/GrassBlock.php +++ b/src/material/block/solid/GrassBlock.php @@ -6,58 +6,55 @@ class GrassBlock extends SolidBlock{ parent::__construct(GRASS, 0, "Grass"); $this->isActivable = true; $this->hardness = 3; + $this->breakTime = 0.6; + $this->material = Material::$dirt; + $this->lightBlock = 255; } public function getDrops(Item $item, Player $player){ - return [ - [DIRT, 0, 1], - ]; + return array( + array(DIRT, 0, 1), + ); } public function onActivate(Item $item, Player $player){ if($item->getID() === DYE and $item->getMetadata() === 0x0F){ - if(($player->gamemode & 0x01) === 0){ - $player->removeItem(DYE,0x0F,1); - } + $player->consumeSingleItem(send:true); TallGrassObject::growGrass($this->level, $this, new Random(), 8, 2); return true; }elseif($item->isHoe()){ if($this->getSide(1)->isTransparent === false) return false; - if(($player->gamemode & 0x01) === 0){ - $item->useOn($this); - if($item->getMetadata() >= $item->getMaxDurability()) $player->setSlot($player->slot, new Item(AIR, 0, 0), false); - else $player->setSlot($player->slot, $item, true); - } + $item->hurtAndBreak(1, $player); //TODO move to ItemHoe $this->level->fastSetBlockUpdate($this->x, $this->y, $this->z, FARMLAND, 0, true); $this->seedsDrop(); return true; } return false; } - + public function seedsDrop(){ $chance = lcg_value() * 100; if($chance <= 1){ - ServerAPI::request()->api->entity->drop(new Position($this->x + 0.5, $this->y + 1, $this->z + 0.5, $this->level), BlockAPI::getItem(BEETROOT_SEEDS,0,1), 10); + ServerAPI::request()->api->entity->drop(new Position($this->x+0.5, $this->y+1, $this->z+0.5, $this->level), BlockAPI::getItem(BEETROOT_SEEDS,0,1), 10); }elseif($chance > 1 and $chance <= 16){ - ServerAPI::request()->api->entity->drop(new Position($this->x + 0.5, $this->y + 1, $this->z + 0.5, $this->level), BlockAPI::getItem(SEEDS,0,1), 10); + ServerAPI::request()->api->entity->drop(new Position($this->x+0.5, $this->y+1, $this->z+0.5, $this->level), BlockAPI::getItem(SEEDS,0,1), 10); } } public static function onRandomTick(Level $level, $x, $y, $z){ if(!StaticBlock::getIsTransparent($level->level->getBlockID($x, $y + 1, $z)) && mt_rand(0, 2) == 1){ $level->fastSetBlockUpdate($x, $y, $z, DIRT, 0); }else{ - for($cnt = 0; $cnt < 4; ++$cnt){ - $x = $x + mt_rand(0, 2) - 1; - $y = $y + mt_rand(0, 4) - 3; - $z = $z + mt_rand(0, 2) - 1; - - $blockUp = $level->level->getBlockID($x, $y + 1, $z); - if(StaticBlock::getIsTransparent($blockUp) && !StaticBlock::getIsLiquid($blockUp) && !($blockUp === 60) && $level->level->getBlockID($x, $y, $z) === DIRT){ - $level->fastSetBlockUpdate($x, $y, $z, GRASS, 0); - } - + //for($cnt = 0; $cnt < 4; ++$cnt){ + $x = $x + mt_rand(0, 2) - 1; + $y = $y + mt_rand(0, 4) - 3; + $z = $z + mt_rand(0, 2) - 1; + + $blockUp = $level->level->getBlockID($x, $y + 1, $z); + if(StaticBlock::getIsTransparent($blockUp) && !StaticBlock::getIsLiquid($blockUp) && !($blockUp == FARMLAND) && $level->level->getBlockID($x, $y, $z) === DIRT){ + $level->fastSetBlockUpdate($x, $y, $z, GRASS, 0); } + + //} } } diff --git a/src/material/block/solid/GravelBlock.php b/src/material/block/solid/GravelBlock.php index 144792f3..48710cf1 100644 --- a/src/material/block/solid/GravelBlock.php +++ b/src/material/block/solid/GravelBlock.php @@ -5,6 +5,9 @@ class GravelBlock extends FallableBlock{ public function __construct(){ parent::__construct(GRAVEL, 0, "Gravel"); $this->hardness = 3; + $this->breakTime = 0.6; + $this->material = Material::$sand; + $this->lightBlock = 255; } public function getDrops(Item $item, Player $player){ diff --git a/src/material/block/solid/HayBaleBlock.php b/src/material/block/solid/HayBaleBlock.php index dd6d52a8..3a19ab12 100644 --- a/src/material/block/solid/HayBaleBlock.php +++ b/src/material/block/solid/HayBaleBlock.php @@ -4,7 +4,10 @@ class HayBaleBlock extends SolidBlock{ public static $blockID; public function __construct($meta = 0){ parent::__construct(HAY_BALE, $meta, "Hay Bale"); - $this->hardness = 10; + $this->hardness = 2.5; + $this->breakTime = 0.5; + $this->material = Material::$dirt; + $this->lightBlock = 255; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ diff --git a/src/material/block/solid/IceBlock.php b/src/material/block/solid/IceBlock.php index 28701ad6..89ebdd7a 100644 --- a/src/material/block/solid/IceBlock.php +++ b/src/material/block/solid/IceBlock.php @@ -5,19 +5,21 @@ class IceBlock extends TransparentBlock{ public function __construct(){ parent::__construct(ICE, 0, "Ice"); $this->hardness = 2.5; + $this->breakTime = 0.5; $this->slipperiness = 0.98; + $this->material = Material::$ice; + $this->lightBlock = 3; } - + public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ return [new AxisAlignedBB($x, $y, $z, $x + 1, $y + 1, $z + 1)]; } - + public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ $ret = $this->level->setBlock($this, $this, true, false, true); - $this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM); return $ret; } - + public function onBreak(Item $item, Player $player){ if(($player->gamemode & 0x01) === 0){ $this->level->setBlock($this, new WaterBlock(), true, false, true); @@ -28,32 +30,12 @@ class IceBlock extends TransparentBlock{ return true; } - private function scanForNearbyLightSources($offsetX, $offsetY, $offsetZ){ - for($x = -$offsetX; $x <= $offsetX; ++$x){ //i hope it is possible to optimize it - for($z = -$offsetZ; $z <= $offsetZ; ++$z){ - for($y = -$offsetY; $y <= $offsetY; ++$y){ - $pX = $this->x + $x; - $pY = $this->y + $y; - $pZ = $this->z + $z; - $block = $this->level->getBlock(new Vector3($pX, $pY, $pZ)); //D= slow what was u thinking of gameherobrine from 2022 - if($block instanceof LightingBlock){ //idk is it possible to make it better - return $block; - } - } - } + public static function onRandomTick(Level $level, $x, $y, $z){ + if($level->level->getBlockLight($x, $y, $z) > 11 - StaticBlock::$lightBlock[ICE]){ + $level->fastSetBlockUpdate($x, $y, $z, STILL_WATER, true); } } - //public static function onUpdate(Level $level, $x, $y, $z, $type){ /*Taken from https://github.com/PocketMine/PocketMine-MP/issues/3249*/ - /*if($type === BLOCK_UPDATE_RANDOM){ - $light = $this->scanForNearbyLightSources(3,3,3); - if(LightUtils::getLightValueFromNearbySource($light,$this) > 12){ - $this->level->setBlock($this, new WaterBlock(), true); - ServerAPI::request()->api->block->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), 10, BLOCK_UPDATE_NORMAL); //additional request for update - } - return BLOCK_UPDATE_RANDOM; - } - return false;*/ //TODO ice melting(after light?) - //} + public function getBreakTime(Item $item, Player $player){ if(($player->gamemode & 0x01) === 0x01){ return 0.20; @@ -69,6 +51,6 @@ class IceBlock extends TransparentBlock{ } public function getDrops(Item $item, Player $player){ - return []; + return array(); } } diff --git a/src/material/block/solid/InfoUpdate2Block.php b/src/material/block/solid/InfoUpdate2Block.php index 1d9a45ea..c2075239 100755 --- a/src/material/block/solid/InfoUpdate2Block.php +++ b/src/material/block/solid/InfoUpdate2Block.php @@ -5,7 +5,10 @@ class InfoUpdate2Block extends SolidBlock{ public function __construct(){ parent::__construct(INFO_UPDATE2, 0, "tile.info_update2.name<"); $this->breakable = true; - $this->hardness = 0; + $this->hardness = 5; + $this->breakTime = 1; + $this->material = Material::$dirt; + $this->lightBlock = 255; } } \ No newline at end of file diff --git a/src/material/block/solid/InfoUpdateBlock.php b/src/material/block/solid/InfoUpdateBlock.php index 81af7276..12c283f7 100755 --- a/src/material/block/solid/InfoUpdateBlock.php +++ b/src/material/block/solid/InfoUpdateBlock.php @@ -5,7 +5,10 @@ class InfoUpdateBlock extends SolidBlock{ public function __construct(){ parent::__construct(INFO_UPDATE, 0, "tile.info_update.name<"); $this->breakable = true; - $this->hardness = 0; + $this->hardness = 5; + $this->breakTime = 1; + $this->material = Material::$dirt; + $this->lightBlock = 255; } } \ No newline at end of file diff --git a/src/material/block/solid/InvisibleBedrockBlock.php b/src/material/block/solid/InvisibleBedrockBlock.php index 2fd0843d..5a0a3f7f 100755 --- a/src/material/block/solid/InvisibleBedrockBlock.php +++ b/src/material/block/solid/InvisibleBedrockBlock.php @@ -5,7 +5,10 @@ class InvisibleBedrockBlock extends SolidBlock{ public function __construct(){ parent::__construct(INVISIBLE_BEDROCK, 0, ".name<"); $this->breakable = false; - $this->hardness = 3600000; + $this->hardness = 18000000; + $this->breakTime = -1; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function isBreakable(Item $item, Player $player){ diff --git a/src/material/block/solid/IronBlock.php b/src/material/block/solid/IronBlock.php index 5db4b364..e5dc40eb 100644 --- a/src/material/block/solid/IronBlock.php +++ b/src/material/block/solid/IronBlock.php @@ -5,6 +5,9 @@ class IronBlock extends SolidBlock{ public function __construct(){ parent::__construct(IRON_BLOCK, 0, "Iron Block"); $this->hardness = 30; + $this->breakTime = 5; + $this->material = Material::$metal; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/LapisBlock.php b/src/material/block/solid/LapisBlock.php index 7d0e790c..19138392 100644 --- a/src/material/block/solid/LapisBlock.php +++ b/src/material/block/solid/LapisBlock.php @@ -5,6 +5,9 @@ class LapisBlock extends SolidBlock{ public function __construct(){ parent::__construct(LAPIS_BLOCK, 0, "Lapis Block"); $this->hardness = 15; + $this->breakTime = 3.0; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/LeavesBlock.php b/src/material/block/solid/LeavesBlock.php index 2862884c..5129752b 100644 --- a/src/material/block/solid/LeavesBlock.php +++ b/src/material/block/solid/LeavesBlock.php @@ -7,87 +7,134 @@ class LeavesBlock extends TransparentBlock{ const BIRCH = 2; public function __construct($meta = 0){ parent::__construct(LEAVES, $meta, "Leaves"); - $names = [ + $names = array( LeavesBlock::OAK => "Oak Leaves", LeavesBlock::SPRUCE => "Spruce Leaves", LeavesBlock::BIRCH => "Birch Leaves", 3 => "", - ]; + ); $this->name = $names[$this->meta & 0x03]; $this->hardness = 1; + $this->breakTime = 0.2; + $this->material = Material::$leaves; + $this->lightBlock = 1; } - + public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ return [new AxisAlignedBB($x, $y, $z, $x + 1, $y + 1, $z + 1)]; } - + 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 + /** + * @deprecated leaf decay was rewritten + */ + public static function findLog(Level $level, $x, $y, $z, array &$visited, $distance){ //port from newest pocketmine $index = self::createIndex($x, $y, $z); if(isset($visited[$index])){ - return false; + return $visited[$index]; } - $visited[$index] = true; + $block = $level->level->getBlockID($x, $y, $z); if($block === WOOD){ //type doesn't matter - return true; + return ($visited[$index] = true); } if($block === LEAVES && $distance <= 4){ - if(self::findLog($level, $x - 1, $y, $z, $visited, $distance + 1)) return true; - if(self::findLog($level, $x + 1, $y, $z, $visited, $distance + 1)) return true; - if(self::findLog($level, $x, $y, $z - 1, $visited, $distance + 1)) return true; - if(self::findLog($level, $x, $y, $z + 1, $visited, $distance + 1)) return true; + if(self::findLog($level, $x - 1, $y, $z, $visited, $distance + 1)) return ($visited[$index] = true); + if(self::findLog($level, $x + 1, $y, $z, $visited, $distance + 1)) return ($visited[$index] = true); + if(self::findLog($level, $x, $y, $z - 1, $visited, $distance + 1)) return ($visited[$index] = true); + if(self::findLog($level, $x, $y, $z + 1, $visited, $distance + 1)) return ($visited[$index] = true); } - return false; + + return ($visited[$index] = false); } + + private static $treeBlocksNearby = null; public static function onRandomTick(Level $level, $x, $y, $z){ $b = $level->level->getBlock($x, $y, $z); $id = $b[0]; $meta = $b[1]; - if(($meta & 0b00001100) === 0x08){ - $meta &= 0x03; - $visited = []; - if(!self::findLog($level, $x, $y, $z, $visited, 0)){ - //$this->level->setBlock($this, new AirBlock(), false, false, true); - $level->fastSetBlockUpdate($x, $y, $z, 0, 0); + //TODO MCPE uses 0x04 for detecting updates + if(($meta & 0b1100) == 0b1000){ + if(self::$treeBlocksNearby == null) self::$treeBlocksNearby = array_fill(0, 32*32*32, 0); + for ($xx = - 4; $xx <= 4; $xx ++) { + for ($yy = - 4; $yy <= 4; $yy ++) { + for ($zz = - 4; $zz <= 4; $zz ++) { + $k3 = $level->level->getBlockID($x + $xx, $y + $yy, $z + $zz); + if ($k3 == TRUNK) { + self::$treeBlocksNearby[($xx + 16) * 1024 + ($yy + 16) * 32 + ($zz + 16)] = 0; + } else if ($k3 == LEAVES) { + self::$treeBlocksNearby[($xx + 16) * 1024 + ($yy + 16) * 32 + ($zz + 16)] = - 2; + } else { + self::$treeBlocksNearby[($xx + 16) * 1024 + ($yy + 16) * 32 + ($zz + 16)] = - 1; + } + } + } + } + + for ($i2 = 1; $i2 <= 4; $i2 ++) { + for ($l2 = - 4; $l2 <= 4; $l2 ++) { + for ($j3 = - 4; $j3 <= 4; $j3 ++) { + for ($l3 = - 4; $l3 <= 4; $l3 ++) { + if (self::$treeBlocksNearby[($l2 + 16) * 1024 + ($j3 + 16) * 32 + ($l3 + 16)] != $i2 - 1) continue; + if (self::$treeBlocksNearby[(($l2 + 16) - 1) * 1024 + ($j3 + 16) * 32 + ($l3 + 16)] == - 2) { + self::$treeBlocksNearby[(($l2 + 16) - 1) * 1024 + ($j3 + 16) * 32 + ($l3 + 16)] = $i2; + } + if (self::$treeBlocksNearby[($l2 + 16 + 1) * 1024 + ($j3 + 16) * 32 + ($l3 + 16)] == - 2) { + self::$treeBlocksNearby[($l2 + 16 + 1) * 1024 + ($j3 + 16) * 32 + ($l3 + 16)] = $i2; + } + if (self::$treeBlocksNearby[($l2 + 16) * 1024 + (($j3 + 16) - 1) * 32 + ($l3 + 16)] == - 2) { + self::$treeBlocksNearby[($l2 + 16) * 1024 + (($j3 + 16) - 1) * 32 + ($l3 + 16)] = $i2; + } + if (self::$treeBlocksNearby[($l2 + 16) * 1024 + ($j3 + 16 + 1) * 32 + ($l3 + 16)] == - 2) { + self::$treeBlocksNearby[($l2 + 16) * 1024 + ($j3 + 16 + 1) * 32 + ($l3 + 16)] = $i2; + } + if (self::$treeBlocksNearby[($l2 + 16) * 1024 + ($j3 + 16) * 32 + (($l3 + 16) - 1)] == - 2) { + self::$treeBlocksNearby[($l2 + 16) * 1024 + ($j3 + 16) * 32 + (($l3 + 16) - 1)] = $i2; + } + if (self::$treeBlocksNearby[($l2 + 16) * 1024 + ($j3 + 16) * 32 + ($l3 + 16 + 1)] == - 2) { + self::$treeBlocksNearby[($l2 + 16) * 1024 + ($j3 + 16) * 32 + ($l3 + 16 + 1)] = $i2; + } + } + } + } + } + $j2 = self::$treeBlocksNearby[(32/2) * (32*32) + (32/2) * 32 + (32/2)]; + if($j2 >= 0) + { + $level->level->setBlockDamage($x, $y, $z, $meta & 0xf7); + } else + { if(mt_rand(1,20) === 1){ //Saplings ServerAPI::request()->api->entity->drop(new Position($x, $y, $z, $level), BlockAPI::getItem(SAPLING, $meta & 0x03, 1)); } if(($meta & 0x03) === LeavesBlock::OAK and mt_rand(1,200) === 1){ //Apples ServerAPI::request()->api->entity->drop(new Position($x, $y, $z, $level), BlockAPI::getItem(APPLE, 0, 1)); } - }else{ - $level->fastSetBlockUpdate($x, $y, $z, $id, $meta); + $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true, false); } } } - public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ - [$id, $meta] = $level->level->getBlock($x, $y, $z); - if(($meta & 0b00001100) === 0){ - $meta |= 0x08; - $level->fastSetBlockUpdate($x, $y, $z, $id, $meta); //TODO maybe use $level->level->setBlock directly, the client doesnt need to know thism info. - } - } - + public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ - $this->meta |= 0x04; + //TODO MCPE uses 0x08 for detecting was it placed by player or not + if($player instanceof Player && $player != PlayerNull::$INSTANCE) $this->meta |= 0x04; $this->level->setBlock($this, $this, true, false, true); } - + public function getDrops(Item $item, Player $player){ - $drops = []; + $drops = array(); if($item->isShears()){ - $drops[] = [LEAVES, $this->meta & 0x03, 1]; + $drops[] = array(LEAVES, $this->meta & 0x03, 1); }else{ if(mt_rand(1,20) === 1){ //Saplings - $drops[] = [SAPLING, $this->meta & 0x03, 1]; + $drops[] = array(SAPLING, $this->meta & 0x03, 1); } if(($this->meta & 0x03) === LeavesBlock::OAK and mt_rand(1,100) === 1){ //Apples - $drops[] = [APPLE, 0, 1]; + $drops[] = array(APPLE, 0, 1); } } return $drops; diff --git a/src/material/block/solid/LitPumpkinBlock.php b/src/material/block/solid/LitPumpkinBlock.php index 2edd0c11..2386cf84 100644 --- a/src/material/block/solid/LitPumpkinBlock.php +++ b/src/material/block/solid/LitPumpkinBlock.php @@ -12,6 +12,10 @@ class LitPumpkinBlock extends SolidBlock implements LightingBlock{ public function __construct($meta = 0){ parent::__construct(LIT_PUMPKIN, $meta, "Jack o'Lantern"); $this->hardness = 5; + $this->breakTime = 1.0; + $this->material = Material::$vegetable; + $this->lightBlock = 255; + $this->lightEmission = 15; } public function getMaxLightValue(){ diff --git a/src/material/block/solid/MelonBlock.php b/src/material/block/solid/MelonBlock.php index 3eaa724e..94ee8a99 100644 --- a/src/material/block/solid/MelonBlock.php +++ b/src/material/block/solid/MelonBlock.php @@ -5,6 +5,9 @@ class MelonBlock extends TransparentBlock{ public function __construct(){ parent::__construct(MELON_BLOCK, 0, "Melon Block"); $this->hardness = 5; + $this->breakTime = 1; + $this->material = Material::$vegetable; + $this->lightBlock = 255; } public function getDrops(Item $item, Player $player){ return [ diff --git a/src/material/block/solid/MossStoneBlock.php b/src/material/block/solid/MossStoneBlock.php index c738c615..fbc2dde8 100644 --- a/src/material/block/solid/MossStoneBlock.php +++ b/src/material/block/solid/MossStoneBlock.php @@ -5,6 +5,9 @@ class MossStoneBlock extends SolidBlock{ public function __construct(){ parent::__construct(MOSS_STONE, 0, "Moss Stone"); $this->hardness = 30; + $this->breakTime = 2; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/NetherBricksBlock.php b/src/material/block/solid/NetherBricksBlock.php index 8211ad7b..2af0ff0e 100644 --- a/src/material/block/solid/NetherBricksBlock.php +++ b/src/material/block/solid/NetherBricksBlock.php @@ -5,6 +5,9 @@ class NetherBricksBlock extends SolidBlock{ public function __construct(){ parent::__construct(NETHER_BRICKS, 0, "Nether Bricks"); $this->hardness = 30; + $this->breakTime = 2; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/NetherrackBlock.php b/src/material/block/solid/NetherrackBlock.php index f93af992..61f0bd85 100644 --- a/src/material/block/solid/NetherrackBlock.php +++ b/src/material/block/solid/NetherrackBlock.php @@ -5,6 +5,9 @@ class NetherrackBlock extends SolidBlock{ public function __construct(){ parent::__construct(NETHERRACK, 0, "Netherrack"); $this->hardness = 2; + $this->breakTime = 0.4; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/ObsidianBlock.php b/src/material/block/solid/ObsidianBlock.php index 71453cc2..6a7b369d 100644 --- a/src/material/block/solid/ObsidianBlock.php +++ b/src/material/block/solid/ObsidianBlock.php @@ -5,8 +5,11 @@ class ObsidianBlock extends SolidBlock{ public function __construct(){ parent::__construct(OBSIDIAN, 0, "Obsidian"); $this->hardness = 6000; + $this->breakTime = 10; + $this->material = Material::$stone; + $this->lightBlock = 255; } - + public function getBreakTime(Item $item, Player $player){ if(($player->gamemode & 0x01) === 0x01){ return 0.20; @@ -17,7 +20,7 @@ class ObsidianBlock extends SolidBlock{ return 250; } } - + public function getDrops(Item $item, Player $player){ if($item->getPickaxeLevel() >= 5){ return [ diff --git a/src/material/block/solid/PlanksBlock.php b/src/material/block/solid/PlanksBlock.php index 2380c10f..b329a384 100644 --- a/src/material/block/solid/PlanksBlock.php +++ b/src/material/block/solid/PlanksBlock.php @@ -12,6 +12,9 @@ class PlanksBlock extends SolidBlock{ ]; $this->name = $names[$this->meta & 0x03]; $this->hardness = 15; + $this->breakTime = 2; + $this->material = Material::$wood; + $this->lightBlock = 255; } } \ No newline at end of file diff --git a/src/material/block/solid/PumpkinBlock.php b/src/material/block/solid/PumpkinBlock.php index cfba83d3..56c66e72 100644 --- a/src/material/block/solid/PumpkinBlock.php +++ b/src/material/block/solid/PumpkinBlock.php @@ -5,18 +5,26 @@ class PumpkinBlock extends SolidBlock{ public function __construct($meta = 0){ parent::__construct(PUMPKIN, $meta, "Pumpkin"); $this->hardness = 5; + $this->breakTime = 1; + $this->material = Material::$vegetable; + $this->lightBlock = 255; } - + public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ - $faces = [ + $faces = array( 0 => 1, 1 => 2, 2 => 3, 3 => 0, - ]; + ); $this->meta = $faces[$player->entity->getDirection()]; $this->level->setBlock($block, $this, true, false, true); return true; } - + + public function getDrops(Item $item, Player $player){ + return [ + [PUMPKIN, 0, 1] + ]; + } } \ No newline at end of file diff --git a/src/material/block/solid/QuartzBlock.php b/src/material/block/solid/QuartzBlock.php index 7eeb9fb1..5e4d1261 100644 --- a/src/material/block/solid/QuartzBlock.php +++ b/src/material/block/solid/QuartzBlock.php @@ -11,6 +11,10 @@ class QuartzBlock extends SolidBlock{ 3 => "Quartz Pillar", ]; $this->name = $names[$this->meta & 0x03]; + $this->breakTime = 0.8; + $this->hardness = 4; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/Reserved6Block.php b/src/material/block/solid/Reserved6Block.php index 65117a4e..fd5601b1 100644 --- a/src/material/block/solid/Reserved6Block.php +++ b/src/material/block/solid/Reserved6Block.php @@ -6,6 +6,9 @@ class Reserved6Block extends SolidBlock{ parent::__construct(RESERVED6, 0, ".name<"); $this->breakable = true; $this->hardness = 0; + $this->breakTime = 0; + $this->material = Material::$dirt; + $this->lightBlock = 255; } } \ No newline at end of file diff --git a/src/material/block/solid/SandBlock.php b/src/material/block/solid/SandBlock.php index 67f92029..36a62d2f 100644 --- a/src/material/block/solid/SandBlock.php +++ b/src/material/block/solid/SandBlock.php @@ -5,6 +5,9 @@ class SandBlock extends FallableBlock{ public function __construct(){ parent::__construct(SAND, 0, "Sand"); $this->hardness = 2.5; + $this->breakTime = 0.5; + $this->material = Material::$sand; + $this->lightBlock = 255; } } \ No newline at end of file diff --git a/src/material/block/solid/SandstoneBlock.php b/src/material/block/solid/SandstoneBlock.php index 790ebe24..9b713bd6 100644 --- a/src/material/block/solid/SandstoneBlock.php +++ b/src/material/block/solid/SandstoneBlock.php @@ -11,6 +11,9 @@ class SandstoneBlock extends SolidBlock{ ]; $this->name = $names[$this->meta & 0x03]; $this->hardness = 4; + $this->breakTime = 0.8; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/SnowBlock.php b/src/material/block/solid/SnowBlock.php index 8fdea37a..054d6389 100644 --- a/src/material/block/solid/SnowBlock.php +++ b/src/material/block/solid/SnowBlock.php @@ -5,6 +5,9 @@ class SnowBlock extends SolidBlock{ public function __construct(){ parent::__construct(SNOW_BLOCK, 0, "Snow Block"); $this->hardness = 1; + $this->breakTime = 0.2; + $this->material = Material::$snow; + $this->lightBlock = 255; } public function getDrops(Item $item, Player $player){ diff --git a/src/material/block/solid/SpongeBlock.php b/src/material/block/solid/SpongeBlock.php index 25a7c060..31237e03 100644 --- a/src/material/block/solid/SpongeBlock.php +++ b/src/material/block/solid/SpongeBlock.php @@ -5,6 +5,9 @@ class SpongeBlock extends SolidBlock{ public function __construct(){ parent::__construct(SPONGE, 0, "Sponge"); $this->hardness = 3; + $this->breakTime = 0.6; + $this->material = Material::$dirt; + $this->lightBlock = 255; } } diff --git a/src/material/block/solid/StoneBlock.php b/src/material/block/solid/StoneBlock.php index 3f56c022..7f3739f0 100644 --- a/src/material/block/solid/StoneBlock.php +++ b/src/material/block/solid/StoneBlock.php @@ -5,6 +5,9 @@ class StoneBlock extends SolidBlock{ public function __construct(){ parent::__construct(STONE, 0, "Stone"); $this->hardness = 30; + $this->breakTime = 1.5; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/StoneBricksBlock.php b/src/material/block/solid/StoneBricksBlock.php index 741ac21f..37558e57 100644 --- a/src/material/block/solid/StoneBricksBlock.php +++ b/src/material/block/solid/StoneBricksBlock.php @@ -12,6 +12,9 @@ class StoneBricksBlock extends SolidBlock{ ]; $this->name = $names[$this->meta & 0x03]; $this->hardness = 30; + $this->breakTime = 1.5; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function getBreakTime(Item $item, Player $player){ diff --git a/src/material/block/solid/StonecutterBlock.php b/src/material/block/solid/StonecutterBlock.php index 2f145ac8..a18b41d9 100644 --- a/src/material/block/solid/StonecutterBlock.php +++ b/src/material/block/solid/StonecutterBlock.php @@ -5,6 +5,10 @@ class StonecutterBlock extends SolidBlock{ public function __construct($meta = 0){ parent::__construct(STONECUTTER, $meta, "Stonecutter"); $this->isActivable = true; + $this->breakTime = 2.5; + $this->hardness = 2.5*5; + $this->material = Material::$stone; + $this->lightBlock = 255; } public function onActivate(Item $item, Player $player){ diff --git a/src/material/block/solid/WoodBlock.php b/src/material/block/solid/WoodBlock.php index 369b7483..7c60603c 100644 --- a/src/material/block/solid/WoodBlock.php +++ b/src/material/block/solid/WoodBlock.php @@ -17,6 +17,9 @@ class WoodBlock extends SolidBlock{ ]; $this->name = $names[$this->meta & 0x03]; $this->hardness = 10; + $this->breakTime = 2.0; + $this->material = Material::$wood; + $this->lightBlock = 255; } public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ @@ -38,12 +41,12 @@ class WoodBlock extends SolidBlock{ for($xOff = -4; $xOff <= 4; ++$xOff){ for($yOff = -4; $yOff <= 4; ++$yOff){ for($zOff = -4; $zOff <= 4; ++$zOff){ - $b = $player->level->level->getBlock($this->x + $xOff, $this->y + $yOff, $this->z + $zOff); + $b = $this->level->level->getBlock($this->x + $xOff, $this->y + $yOff, $this->z + $zOff); $id = $b[0]; $meta = $b[1]; if($id === LEAVES){ - if(($meta & 0x8) === 0){ - $player->level->fastSetBlockUpdate($this->x + $xOff, $this->y + $yOff, $this->z + $zOff, $id, $meta | 8); + if(($meta & 8) == 0){//TODO MCPE uses 0x04 for detecting updates + $b = $this->level->level->setBlockDamage($this->x + $xOff, $this->y + $yOff, $this->z + $zOff, $meta | 8); } } } diff --git a/src/material/block/solid/WoolBlock.php b/src/material/block/solid/WoolBlock.php index c4a370e1..c0e6e7f2 100644 --- a/src/material/block/solid/WoolBlock.php +++ b/src/material/block/solid/WoolBlock.php @@ -2,28 +2,34 @@ class WoolBlock extends SolidBlock{ public static $blockID; + + public static $names = [ + 0 => "White Wool", + 1 => "Orange Wool", + 2 => "Magenta Wool", + 3 => "Light Blue Wool", + 4 => "Yellow Wool", + 5 => "Lime Wool", + 6 => "Pink Wool", + 7 => "Gray Wool", + 8 => "Light Gray Wool", + 9 => "Cyan Wool", + 10 => "Purple Wool", + 11 => "Blue Wool", + 12 => "Brown Wool", + 13 => "Green Wool", + 14 => "Red Wool", + 15 => "Black Wool", + ]; + public function __construct($meta = 0){ parent::__construct(WOOL, $meta, "Wool"); - $names = [ - 0 => "White Wool", - 1 => "Orange Wool", - 2 => "Magenta Wool", - 3 => "Light Blue Wool", - 4 => "Yellow Wool", - 5 => "Lime Wool", - 6 => "Pink Wool", - 7 => "Gray Wool", - 8 => "Light Gray Wool", - 9 => "Cyan Wool", - 10 => "Purple Wool", - 11 => "Blue Wool", - 12 => "Brown Wool", - 13 => "Green Wool", - 14 => "Red Wool", - 15 => "Black Wool", - ]; - $this->name = $names[$this->meta]; + + $this->name = self::$names[$this->meta] ?? "Illegal Wool"; $this->hardness = 4; + $this->breakTime = 0.8; + $this->material = Material::$cloth; + $this->lightBlock = 255; } - + } \ No newline at end of file diff --git a/src/material/block/solid/WorkbenchBlock.php b/src/material/block/solid/WorkbenchBlock.php index 171f5e2a..5ca24f5f 100644 --- a/src/material/block/solid/WorkbenchBlock.php +++ b/src/material/block/solid/WorkbenchBlock.php @@ -5,7 +5,10 @@ class WorkbenchBlock extends SolidBlock{ public function __construct($meta = 0){ parent::__construct(WORKBENCH, $meta, "Crafting Table"); $this->isActivable = true; - $this->hardness = 15; + $this->hardness = 12.5; + $this->breakTime = 2.5; + $this->material = Material::$wood; + $this->lightBlock = 255; } public function onActivate(Item $item, Player $player){ diff --git a/src/material/item/armor/ChainBootsItem.php b/src/material/item/armor/ChainBootsItem.php index afd02dcd..a224571d 100644 --- a/src/material/item/armor/ChainBootsItem.php +++ b/src/material/item/armor/ChainBootsItem.php @@ -7,7 +7,7 @@ class ChainBootsItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::CHAIN; + return ArmorMaterial::CHAIN; } public function getBaseDurability(){ diff --git a/src/material/item/armor/ChainChestplateItem.php b/src/material/item/armor/ChainChestplateItem.php index 19a6d9bd..ab5967cd 100644 --- a/src/material/item/armor/ChainChestplateItem.php +++ b/src/material/item/armor/ChainChestplateItem.php @@ -7,7 +7,7 @@ class ChainChestplateItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::CHAIN; + return ArmorMaterial::CHAIN; } public function getBaseDurability(){ diff --git a/src/material/item/armor/ChainHelmetItem.php b/src/material/item/armor/ChainHelmetItem.php index b78cb920..864eeee9 100644 --- a/src/material/item/armor/ChainHelmetItem.php +++ b/src/material/item/armor/ChainHelmetItem.php @@ -7,7 +7,7 @@ class ChainHelmetItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::CHAIN; + return ArmorMaterial::CHAIN; } public function getBaseDurability(){ diff --git a/src/material/item/armor/ChainLeggingsItem.php b/src/material/item/armor/ChainLeggingsItem.php index de13dc83..a7b1f270 100644 --- a/src/material/item/armor/ChainLeggingsItem.php +++ b/src/material/item/armor/ChainLeggingsItem.php @@ -7,7 +7,7 @@ class ChainLeggingsItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::CHAIN; + return ArmorMaterial::CHAIN; } public function getBaseDurability(){ diff --git a/src/material/item/armor/DiamondBootsItem.php b/src/material/item/armor/DiamondBootsItem.php index 75d8c129..e13df240 100644 --- a/src/material/item/armor/DiamondBootsItem.php +++ b/src/material/item/armor/DiamondBootsItem.php @@ -7,7 +7,7 @@ class DiamondBootsItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::DIAMOND; + return ArmorMaterial::DIAMOND; } public function getBaseDurability(){ diff --git a/src/material/item/armor/DiamondChestplateItem.php b/src/material/item/armor/DiamondChestplateItem.php index 3a6b8a05..e2728b9b 100644 --- a/src/material/item/armor/DiamondChestplateItem.php +++ b/src/material/item/armor/DiamondChestplateItem.php @@ -7,7 +7,7 @@ class DiamondChestplateItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::DIAMOND; + return ArmorMaterial::DIAMOND; } public function getBaseDurability(){ diff --git a/src/material/item/armor/DiamondHelmetItem.php b/src/material/item/armor/DiamondHelmetItem.php index 514986f0..088c4747 100644 --- a/src/material/item/armor/DiamondHelmetItem.php +++ b/src/material/item/armor/DiamondHelmetItem.php @@ -7,7 +7,7 @@ class DiamondHelmetItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::DIAMOND; + return ArmorMaterial::DIAMOND; } public function getBaseDurability(){ diff --git a/src/material/item/armor/DiamondLeggingsItem.php b/src/material/item/armor/DiamondLeggingsItem.php index 55eb9356..7255dce9 100644 --- a/src/material/item/armor/DiamondLeggingsItem.php +++ b/src/material/item/armor/DiamondLeggingsItem.php @@ -7,7 +7,7 @@ class DiamondLeggingsItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::DIAMOND; + return ArmorMaterial::DIAMOND; } public function getBaseDurability(){ diff --git a/src/material/item/armor/GoldenBootsItem.php b/src/material/item/armor/GoldenBootsItem.php index 8f9b7581..d7571114 100644 --- a/src/material/item/armor/GoldenBootsItem.php +++ b/src/material/item/armor/GoldenBootsItem.php @@ -7,7 +7,7 @@ class GoldenBootsItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::GOLD; + return ArmorMaterial::GOLD; } public function getBaseDurability(){ diff --git a/src/material/item/armor/GoldenChestplateItem.php b/src/material/item/armor/GoldenChestplateItem.php index 05b3aed0..116cf9a4 100644 --- a/src/material/item/armor/GoldenChestplateItem.php +++ b/src/material/item/armor/GoldenChestplateItem.php @@ -7,7 +7,7 @@ class GoldenChestplateItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::GOLD; + return ArmorMaterial::GOLD; } public function getBaseDurability(){ diff --git a/src/material/item/armor/GoldenHelmetItem.php b/src/material/item/armor/GoldenHelmetItem.php index 11a94256..9abe5c01 100644 --- a/src/material/item/armor/GoldenHelmetItem.php +++ b/src/material/item/armor/GoldenHelmetItem.php @@ -7,7 +7,7 @@ class GoldenHelmetItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::GOLD; + return ArmorMaterial::GOLD; } public function getBaseDurability(){ diff --git a/src/material/item/armor/GoldenLeggingsItem.php b/src/material/item/armor/GoldenLeggingsItem.php index d2fb35a0..fb5054e8 100644 --- a/src/material/item/armor/GoldenLeggingsItem.php +++ b/src/material/item/armor/GoldenLeggingsItem.php @@ -7,7 +7,7 @@ class GoldenLeggingsItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::GOLD; + return ArmorMaterial::GOLD; } public function getBaseDurability(){ diff --git a/src/material/item/armor/IronBootsItem.php b/src/material/item/armor/IronBootsItem.php index 6ed18894..2d091aba 100644 --- a/src/material/item/armor/IronBootsItem.php +++ b/src/material/item/armor/IronBootsItem.php @@ -7,7 +7,7 @@ class IronBootsItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::IRON; + return ArmorMaterial::IRON; } public function getBaseDurability(){ diff --git a/src/material/item/armor/IronChestplateItem.php b/src/material/item/armor/IronChestplateItem.php index d7229d4b..69d0ae5a 100644 --- a/src/material/item/armor/IronChestplateItem.php +++ b/src/material/item/armor/IronChestplateItem.php @@ -7,7 +7,7 @@ class IronChestplateItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::IRON; + return ArmorMaterial::IRON; } public function getBaseDurability(){ diff --git a/src/material/item/armor/IronHelmetItem.php b/src/material/item/armor/IronHelmetItem.php index 78300ed4..72704f10 100644 --- a/src/material/item/armor/IronHelmetItem.php +++ b/src/material/item/armor/IronHelmetItem.php @@ -7,7 +7,7 @@ class IronHelmetItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::IRON; + return ArmorMaterial::IRON; } public function getBaseDurability(){ diff --git a/src/material/item/armor/IronLeggingsItem.php b/src/material/item/armor/IronLeggingsItem.php index a7734651..593a1553 100644 --- a/src/material/item/armor/IronLeggingsItem.php +++ b/src/material/item/armor/IronLeggingsItem.php @@ -7,7 +7,7 @@ class IronLeggingsItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::IRON; + return ArmorMaterial::IRON; } public function getBaseDurability(){ diff --git a/src/material/item/armor/LeatherBootsItem.php b/src/material/item/armor/LeatherBootsItem.php index 8bbf9ed5..034c2b82 100644 --- a/src/material/item/armor/LeatherBootsItem.php +++ b/src/material/item/armor/LeatherBootsItem.php @@ -7,7 +7,7 @@ class LeatherBootsItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::LEATHER; + return ArmorMaterial::LEATHER; } public function getBaseDurability(){ diff --git a/src/material/item/armor/LeatherCapItem.php b/src/material/item/armor/LeatherCapItem.php index 2950c741..d70140f8 100755 --- a/src/material/item/armor/LeatherCapItem.php +++ b/src/material/item/armor/LeatherCapItem.php @@ -7,7 +7,7 @@ class LeatherCapItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::LEATHER; + return ArmorMaterial::LEATHER; } public function getBaseDurability(){ diff --git a/src/material/item/armor/LeatherPantsItem.php b/src/material/item/armor/LeatherPantsItem.php index a1ad3b88..565f717c 100644 --- a/src/material/item/armor/LeatherPantsItem.php +++ b/src/material/item/armor/LeatherPantsItem.php @@ -7,7 +7,7 @@ class LeatherPantsItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::LEATHER; + return ArmorMaterial::LEATHER; } public function getBaseDurability(){ diff --git a/src/material/item/armor/LeatherTunicItem.php b/src/material/item/armor/LeatherTunicItem.php index 2be71577..cdc0d5a8 100644 --- a/src/material/item/armor/LeatherTunicItem.php +++ b/src/material/item/armor/LeatherTunicItem.php @@ -7,7 +7,7 @@ class LeatherTunicItem extends ArmorItem{ } public function getMaterialDurability(){ - return Material::LEATHER; + return ArmorMaterial::LEATHER; } public function getBaseDurability(){ diff --git a/src/material/item/base/ItemAxe.php b/src/material/item/base/ItemAxe.php index d911950f..fc669ac7 100644 --- a/src/material/item/base/ItemAxe.php +++ b/src/material/item/base/ItemAxe.php @@ -16,5 +16,12 @@ abstract class ItemAxe extends ItemTool default => false, }; } + public function getDestroySpeed($id, $meta){ + $effMult = ItemTool::TIER_EFFICIENCY_MULTIPLIER[$this->getLevel()] ?? ItemTool::TIER_EFFICIENCY_MULTIPLIER[0]; + + $mat = StaticBlock::getMaterial($id); + if($mat == Material::$wood) return $effMult; + return parent::getDestroySpeed($id, $meta); + } } diff --git a/src/material/item/base/ItemHoe.php b/src/material/item/base/ItemHoe.php index 09675cca..0c3cb416 100644 --- a/src/material/item/base/ItemHoe.php +++ b/src/material/item/base/ItemHoe.php @@ -6,15 +6,6 @@ abstract class ItemHoe extends ItemTool return true; } - public function useOn($object, $force = false){ - if(($object instanceof Block) and ($object->getID() === GRASS or $object->getID() === DIRT)){ - $this->meta++; - return true; - }else{ - return parent::useOn($object, $force); - } - } - public function getLevel(){ return match ($this->id) { WOODEN_HOE => 1, diff --git a/src/material/item/base/ItemPickaxe.php b/src/material/item/base/ItemPickaxe.php index 87ed2025..e7cc6fdf 100644 --- a/src/material/item/base/ItemPickaxe.php +++ b/src/material/item/base/ItemPickaxe.php @@ -21,5 +21,24 @@ abstract class ItemPickaxe extends ItemTool default => false, }; } + + public function canDestroySpecial($id, $meta){ + $level = ItemTool::TIER_MINING_LEVEL[$this->getLevel()] ?? 0; + $mat = StaticBlock::getMaterial($id); + if($id == OBSIDIAN || $id == GLOWING_OBSIDIAN) return $level == 3; + if($id == DIAMOND_BLOCK || $id == DIAMOND_ORE || $id == GOLD_BLOCK || $id == GOLD_ORE || $id == REDSTONE_ORE || $id == GLOWING_REDSTONE_ORE) return $level > 1; + if($id == IRON_BLOCK || $id == IRON_ORE || $id == LAPIS_BLOCK || $id == LAPIS_ORE) return $level > 0; + if($mat == Material::$stone) return true; + return $mat == Material::$metal; + + } + + public function getDestroySpeed($id, $meta){ + $effMult = ItemTool::TIER_EFFICIENCY_MULTIPLIER[$this->getLevel()] ?? ItemTool::TIER_EFFICIENCY_MULTIPLIER[0]; + + $mat = StaticBlock::getMaterial($id); + if($mat == Material::$metal || $mat == Material::$stone) return $effMult; + return parent::getDestroySpeed($id, $meta); + } } diff --git a/src/material/item/base/ItemShovel.php b/src/material/item/base/ItemShovel.php index 20b61eba..84bbb9cd 100644 --- a/src/material/item/base/ItemShovel.php +++ b/src/material/item/base/ItemShovel.php @@ -16,5 +16,15 @@ class ItemShovel extends ItemTool default => false, }; } + + public function canDestroySpecial($id, $meta){ + return $id == SNOW_LAYER || $id == SNOW_BLOCK; + } + public function getDestroySpeed($id, $meta){ + $effMult = ItemTool::TIER_EFFICIENCY_MULTIPLIER[$this->getLevel()] ?? ItemTool::TIER_EFFICIENCY_MULTIPLIER[0]; + + if($id == GRASS || $id == DIRT || $id == SAND || $id == GRAVEL || $id == SNOW_LAYER || $id == SNOW || $id == CLAY_BLOCK || $id == FARMLAND) return $effMult; + return parent::getDestroySpeed($id, $meta); + } } diff --git a/src/material/item/base/ItemSword.php b/src/material/item/base/ItemSword.php index 6bd725e0..90679e37 100644 --- a/src/material/item/base/ItemSword.php +++ b/src/material/item/base/ItemSword.php @@ -17,5 +17,22 @@ abstract class ItemSword extends ItemTool default => false, }; } + + public function canDestroySpecial($id, $meta){ + return $id == COBWEB; + } + public function getDestroySpeed($id, $meta){ + if($id == COBWEB) return 15; + return 1.5; //in 0.8.1 it is faster than other items + } + public function hurtEnemy(Entity $target, Player $attacker){ + $this->hurtAndBreak(1, $attacker); + } + + + public function mineBlock(Block $block, Player $player){ + $this->hurtAndBreak(2, $player); + return true; + } } diff --git a/src/material/item/base/ItemTool.php b/src/material/item/base/ItemTool.php index 8875cca6..af4be2ce 100644 --- a/src/material/item/base/ItemTool.php +++ b/src/material/item/base/ItemTool.php @@ -7,20 +7,42 @@ abstract class ItemTool extends Item const STONE_LEVEL = 3; const IRON_LEVEL = 4; const DIAMOND_LEVEL = 5; - + + public const TIER_MINING_LEVEL = [ + 1 => 0, //wooden + 2 => 0, //golden + 3 => 1, //stone + 4 => 2, //iron + 5 => 3, //diamond + ]; + public const TIER_EFFICIENCY_MULTIPLIER = [ + 1 => 2.0, //wooden + 2 => 12.0, //golden + 3 => 4.0, //stone + 4 => 6.0, //iron + 5 => 8.0, //diamond + ]; + public function isTool(){ return true; } - public function useOn($object, $force = false){ - - if($this->isSword() && !($object instanceof Entity)){ - $this->meta += 2; - }elseif(($object instanceof Entity) && !$this->isSword()){ - $this->meta += 2; - }else{ - $this->meta++; + + public function hurtEnemy(Entity $target, Player $attacker){ + if($this->isPickaxe() || $this->isAxe() || $this->isShovel()){ + $this->hurtAndBreak(2, $attacker); + return; } - return true; + + parent::hurtEnemy($target, $attacker); + } + + public function mineBlock(Block $block, Player $player){ + if($this->isPickaxe() || $this->isAxe() || $this->isShovel()){ + $this->hurtAndBreak(1, $player); + return true; + } + + return parent::mineBlock($block, $player); } } diff --git a/src/material/item/generic/BucketItem.php b/src/material/item/generic/BucketItem.php index 18823a31..562400f9 100644 --- a/src/material/item/generic/BucketItem.php +++ b/src/material/item/generic/BucketItem.php @@ -39,7 +39,7 @@ class BucketItem extends Item{ return true; } }elseif($this->meta === WATER){ - if($block->getID() === AIR || $block instanceof LiquidBlock){ + if($block->getID() === AIR || $block->getID() === TORCH || $block instanceof LiquidBlock){ $water = new WaterBlock(); $level->setBlock($block, $water, true, false, true); //$water->place($this, $player, $block, $target, $face, $fx, $fy, $fz); @@ -54,7 +54,7 @@ class BucketItem extends Item{ return true; } }elseif($this->meta === LAVA){ - if($block->getID() === AIR || $block instanceof LiquidBlock){ + if($block->getID() === AIR || $block->getID() === TORCH || $block instanceof LiquidBlock){ $lava = new LavaBlock(); $level->setBlock($block, $lava, true, false, true); //$lava->place(clone $this, $player, $block, $target, $face, $fx, $fy, $fz); diff --git a/src/material/item/generic/DyeItem.php b/src/material/item/generic/DyeItem.php index 380e3f97..a85a3dce 100755 --- a/src/material/item/generic/DyeItem.php +++ b/src/material/item/generic/DyeItem.php @@ -1,26 +1,29 @@ "Ink Sac", + 1 => "Rose Red", + 2 => "Cactus Green", + 3 => "Cocoa Beans", + 4 => "Lapis Lazuli", + 5 => "Purple Dye", + 6 => "Cyan Dye", + 7 => "Light Gray Dye", + 8 => "Gray Dye", + 9 => "Pink Dye", + 10 => "Lime Dye", + 11 => "Dandelion Yellow", + 12 => "Light Blue Dye", + 13 => "Magenta Dye", + 14 => "Orange Dye", + 15 => "Bone Meal", + ); + public function __construct($meta = 0, $count = 1){ - parent::__construct(DYE, $meta, $count, "Dye"); - $names = array( - 0 => "Ink Sac", - 1 => "Rose Red", - 2 => "Cactus Green", - 3 => "Cocoa Beans", - 4 => "Lapis Lazuli", - 5 => "Purple Dye", - 6 => "Cyan Dye", - 7 => "Light Gray Dye", - 8 => "Gray Dye", - 9 => "Pink Dye", - 10 => "Lime Dye", - 11 => "Dandelion Yellow", - 12 => "Light Blue Dye", - 13 => "Magenta Dye", - 14 => "Orange Dye", - 15 => "Bone Meal", - ]; - $this->name = $names[$this->meta]; + parent::__construct(DYE, $meta & 0xf, $count, "Dye"); + + $this->name = self::$names[$this->meta]; } } diff --git a/src/material/item/generic/MinecartItem.php b/src/material/item/generic/MinecartItem.php index d3807928..f550e547 100755 --- a/src/material/item/generic/MinecartItem.php +++ b/src/material/item/generic/MinecartItem.php @@ -18,8 +18,6 @@ class MinecartItem extends Item{ ]; $e = $server->api->entity->add($level, ENTITY_OBJECT, OBJECT_MINECART, $data); $server->api->entity->spawnToAll($e); - if(($player->gamemode & 0x01) === 0x00){ - $player->removeItem($this->getID(), $this->getMetadata(), 1, false); - } + $player->consumeSingleItem(); } } \ No newline at end of file diff --git a/src/material/item/generic/PaintingItem.php b/src/material/item/generic/PaintingItem.php index f8e134be..0fd6c693 100644 --- a/src/material/item/generic/PaintingItem.php +++ b/src/material/item/generic/PaintingItem.php @@ -38,7 +38,7 @@ class PaintingItem extends Item{ private static $right = [4, 5, 3, 2]; public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ - if($target->isTransparent === false and $face > 1 and $block->isSolid === false){ + if($target->isTransparent === false && $face > 1 and $block->isSolid === false){ $server = ServerAPI::request(); if($face < 2 || $face > 5) return; @@ -65,9 +65,8 @@ class PaintingItem extends Item{ $painting->eid = $server->api->entity->getNextEID(); $server->api->entity->addRaw($painting); $server->api->entity->spawnToAll($painting); - if(($player->gamemode & 0x01) === 0x00){ - $player->removeItem($this->getID(), $this->getMetadata(), 1, false); - } + + $player->consumeSingleItem(); return true; } return false; diff --git a/src/material/item/generic/SpawnEggItem.php b/src/material/item/generic/SpawnEggItem.php index 7d755b4f..68de416d 100644 --- a/src/material/item/generic/SpawnEggItem.php +++ b/src/material/item/generic/SpawnEggItem.php @@ -6,20 +6,18 @@ class SpawnEggItem extends Item{ $this->meta = $meta; $this->isActivable = true; } - + public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ $ageable = $this->meta === MOB_CHICKEN || $this->meta === MOB_COW || $this->meta === MOB_SHEEP || $this->meta === MOB_PIG; - $data = [ + $data = array( "x" => $block->x + 0.5, "y" => $block->y, "z" => $block->z + 0.5, "IsBaby" => $ageable ? mt_rand(0, 5) == 0 ? 1 : 0 : 0 - ]; + ); $e = ServerAPI::request()->api->entity->add($block->level, ENTITY_MOB, $this->meta, $data); ServerAPI::request()->api->entity->spawnToAll($e); - if(($player->gamemode & 0x01) === 0){ - --$this->count; - } + $player->consumeSingleItem(); return true; } } \ No newline at end of file diff --git a/src/material/item/tool/FlintSteelItem.php b/src/material/item/tool/FlintSteelItem.php index 9de35dbb..b9a9f825 100644 --- a/src/material/item/tool/FlintSteelItem.php +++ b/src/material/item/tool/FlintSteelItem.php @@ -6,21 +6,13 @@ class FlintSteelItem extends ItemTool{ $this->isActivable = true; $this->maxStackSize = 1; } - + public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ - if(($player->gamemode & 0x01) === 0 and $this->useOn($block) and $this->getMetadata() >= $this->getMaxDurability()){ - $player->setSlot($player->slot, new Item(AIR, 0, 0), false); - } - + $this->hurtAndBreak(1, $player); if($block->getID() === AIR && $target->isSolid){ $level->fastSetBlockUpdate($block->x, $block->y, $block->z, FIRE, 0, true); return true; } return false; } - - public function useOn($object, $force = false){ - ++$this->meta; - return true; - } } \ No newline at end of file diff --git a/src/material/item/tool/ShearsItem.php b/src/material/item/tool/ShearsItem.php index 53ff3a11..1cc66972 100755 --- a/src/material/item/tool/ShearsItem.php +++ b/src/material/item/tool/ShearsItem.php @@ -4,12 +4,21 @@ class ShearsItem extends ItemTool{ public function __construct($meta = 0, $count = 1){ parent::__construct(SHEARS, $meta, $count, "Shears"); } - - public function useOn($object, $force = false){ - if(($object instanceof Sheep) and $this->id === SHEARS){ - $this->meta++; + + public function mineBlock(Block $block, Player $player){ + if($block->getID() === LEAVES || $block->getID() === COBWEB){ + $this->hurtAndBreak(1, $player); return true; } - parent::useOn($object, $force); + return parent::mineBlock($block, $player); + } + + public function canDestroySpecial($id, $meta){ + return $id == COBWEB; + } + public function getDestroySpeed($id, $meta){ + if($id == COBWEB || $id == LEAVES) return 15; + if($id == WOOL) return 5; + return parent::getDestroySpeed($id, $meta); } } \ No newline at end of file diff --git a/src/material/materials/DecorationMaterial.php b/src/material/materials/DecorationMaterial.php new file mode 100644 index 00000000..893a7d03 --- /dev/null +++ b/src/material/materials/DecorationMaterial.php @@ -0,0 +1,18 @@ +flammable = false; + $this->translucent = false; + $this->alwaysDestroyable = false; + $this->replaceable = false; + + $this->blocksMotion = false; + $this->blocksLight = false; + $this->isSolid = false; + } +} + diff --git a/src/material/materials/GasMaterial.php b/src/material/materials/GasMaterial.php new file mode 100644 index 00000000..892fac4a --- /dev/null +++ b/src/material/materials/GasMaterial.php @@ -0,0 +1,14 @@ +blocksLight = false; + $this->blocksMotion = false; + $this->isSolid = false; + $this->replaceable = true; + } +} + diff --git a/src/material/materials/LiquidMaterial.php b/src/material/materials/LiquidMaterial.php new file mode 100644 index 00000000..b5775484 --- /dev/null +++ b/src/material/materials/LiquidMaterial.php @@ -0,0 +1,14 @@ +blocksMotion = false; + $this->isLiquid = true; + $this->isSolid = false; + $this->replaceable = true; + } +} + diff --git a/src/math/AxisAlignedBB.php b/src/math/AxisAlignedBB.php index d778842b..a186fa68 100644 --- a/src/math/AxisAlignedBB.php +++ b/src/math/AxisAlignedBB.php @@ -1,5 +1,4 @@ minX = $minX; $this->minY = $minY; @@ -31,7 +30,7 @@ class AxisAlignedBB{ public function addMinMax($minX, $minY, $minZ, $maxX, $maxY, $maxZ){ return new AxisAlignedBB($this->minX + $minX, $this->minY + $minY, $this->minZ + $minZ, $this->maxX + $maxX, $this->maxY + $maxY, $this->maxZ + $maxZ); } - + public function addCoord($x, $y, $z){ $minX = $this->minX; $minY = $this->minY; @@ -76,7 +75,14 @@ class AxisAlignedBB{ $this->maxX += $x; $this->maxY += $y; $this->maxZ += $z; - + + if($this->minX < 1e-6 && $this->minX > -1e-6)$this->minX = 0; + if($this->minY < 1e-6 && $this->minY > -1e-6)$this->minY = 0; + if($this->minZ < 1e-6 && $this->minZ > -1e-6)$this->minZ = 0; + if($this->maxX < 1e-6 && $this->maxX > -1e-6)$this->maxX = 0; + if($this->maxY < 1e-6 && $this->maxY > -1e-6)$this->maxY = 0; + if($this->maxZ < 1e-6 && $this->maxZ > -1e-6)$this->maxZ = 0; + return $this; } @@ -170,7 +176,11 @@ class AxisAlignedBB{ return $z; } - + + public function intersectsWith_(AxisAlignedBB $bb){ + return $bb->maxX > $this->minX && $bb->minX < $this->maxX && $bb->maxY > $this->minY && $bb->minY < $this->maxY && $bb->maxZ > $this->minZ && $bb->minZ < $this->maxZ; + } + public function intersectsWith(AxisAlignedBB $bb){ return $bb->maxX >= $this->minX && $bb->minX <= $this->maxX && $bb->maxZ >= $this->minZ && $bb->minZ <= $this->maxZ && $bb->maxY >= $this->minY && $bb->minY <= $this->maxY; } @@ -181,7 +191,7 @@ class AxisAlignedBB{ if($y < $this->minY or $y > $this->maxY){ return false; } - + return $z > $this->minZ and $z < $this->maxZ; } public function isXYZInside($x, $y, $z){ @@ -191,7 +201,7 @@ class AxisAlignedBB{ if($y < $this->minY or $y > $this->maxY){ return false; } - + return $z > $this->minZ and $z < $this->maxZ; } public function isVectorInside(Vector3 $vector){ @@ -220,8 +230,10 @@ class AxisAlignedBB{ public function isVectorInXY(Vector3 $vector){ return $vector->x >= $this->minX and $vector->x <= $this->maxX and $vector->y >= $this->minY and $vector->y <= $this->maxY; } - + /** + * @param Vector3 $pos1 + * @param Vector3 $pos2 * @return NULL|MovingObjectPosition */ public function calculateIntercept(Vector3 $pos1, Vector3 $pos2){ @@ -300,9 +312,9 @@ class AxisAlignedBB{ return MovingObjectPosition::fromBlock(0, 0, 0, $f, $vector); } - + public function __toString(){ return "AABB min: {$this->minX}, {$this->minY}, {$this->minZ}, max: {$this->maxX}, {$this->maxY}, {$this->maxZ}"; } - + } \ No newline at end of file diff --git a/src/network/MinecraftInterface.php b/src/network/MinecraftInterface.php index ef43122a..725d99ef 100644 --- a/src/network/MinecraftInterface.php +++ b/src/network/MinecraftInterface.php @@ -41,21 +41,21 @@ class MinecraftInterface{ $pid = ord($buffer[0]); if(RakNetInfo::isValid($pid)){ - $parser = new RakNetParser($buffer, $source); - if($parser->packet !== false){ - $parser->packet->ip = $source; - $parser->packet->port = $port; - if(EventHandler::callEvent(new PacketReceiveEvent($parser->packet)) === BaseEvent::DENY){ + $packet = RakNetParser::parse($buffer); + if($packet !== false){ + $packet->ip = $source; + $packet->port = $port; + if(EventHandler::callEvent(new PacketReceiveEvent($packet)) === BaseEvent::DENY){ return false; } - return $parser->packet; + return $packet; } return false; }elseif($pid === 0xfe and $buffer[1] === "\xfd" and ServerAPI::request()->api->query instanceof QueryHandler){ $packet = new QueryPacket; $packet->ip = $source; $packet->port = $port; - $packet->buffer = &$buffer; + $packet->buffer =& $buffer; if(EventHandler::callEvent(new PacketReceiveEvent($packet)) === BaseEvent::DENY){ return false; } @@ -64,7 +64,7 @@ class MinecraftInterface{ $packet = new Packet(); $packet->ip = $source; $packet->port = $port; - $packet->buffer = &$buffer; + $packet->buffer =& $buffer; EventHandler::callEvent(new PacketReceiveEvent($packet)); return false; } @@ -74,7 +74,7 @@ class MinecraftInterface{ if(EventHandler::callEvent(new PacketSendEvent($packet)) === BaseEvent::DENY){ return 0; }elseif($packet instanceof RakNetPacket){ - $codec = new RakNetCodec($packet); + RakNetCodec::encode($packet); } $write = $this->socket->write($packet->buffer, $packet->ip, $packet->port); $this->bandwidth[1] += $write; diff --git a/src/network/UDPSocket.php b/src/network/UDPSocket.php index 772df211..260a1d4b 100644 --- a/src/network/UDPSocket.php +++ b/src/network/UDPSocket.php @@ -3,7 +3,6 @@ class UDPSocket{ public $connected, $sock, $server, $port; - function __construct($server, $port, $listen = false, $serverip = "0.0.0.0"){ $this->server = $server; $this->port = $port; @@ -42,6 +41,14 @@ class UDPSocket{ if($this->connected === false){ return false; } + if(PocketMinecraftServer::$TICKING_MODE == PocketMinecraftServer::TICK_NETWAIT){ + $read = [$this->sock]; + $next = (ServerAPI::request()->lastTick + 0.05); + $waitTime = $next - microtime(true); + if($waitTime < 0) $waitTime = 0; + $c = socket_select($read, $_, $_, 0, (int)($waitTime*1000000)); + if($c === false || $c <= 0) return false; + } return @socket_recvfrom($this->sock, $buf, 65535, 0, $source, $port); } @@ -52,4 +59,4 @@ class UDPSocket{ return @socket_sendto($this->sock, $data, strlen($data), 0, $dest, $port); } -} \ No newline at end of file +} diff --git a/src/network/protocol/ProtocolInfo.php b/src/network/protocol/ProtocolInfo.php index 79fc5a36..1418d913 100644 --- a/src/network/protocol/ProtocolInfo.php +++ b/src/network/protocol/ProtocolInfo.php @@ -69,7 +69,6 @@ abstract class ProtocolInfo{ const ADVENTURE_SETTINGS_PACKET = 0xb7; const ENTITY_DATA_PACKET = 0xb8; const PLAYER_INPUT_PACKET = 0xb9; - } /*Unused: * 0x96 @@ -489,4 +488,4 @@ abstract class ProtocolInfo3{ } /***REM_START***/ require_once(FILE_PATH . "src/network/raknet/RakNetDataPacket.php"); -/***REM_END***/ \ No newline at end of file +/***REM_END***/ diff --git a/src/network/protocol/packet/AddEntityPacket.php b/src/network/protocol/packet/AddEntityPacket.php index d01d2fd7..d0a3e278 100644 --- a/src/network/protocol/packet/AddEntityPacket.php +++ b/src/network/protocol/packet/AddEntityPacket.php @@ -36,5 +36,14 @@ class AddEntityPacket extends RakNetDataPacket{ $this->putShort((int) ($this->speedZ * 8000)); } } + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/AddItemEntityPacket.php b/src/network/protocol/packet/AddItemEntityPacket.php index 0ba0e2c6..70a9cc3f 100644 --- a/src/network/protocol/packet/AddItemEntityPacket.php +++ b/src/network/protocol/packet/AddItemEntityPacket.php @@ -6,21 +6,21 @@ class AddItemEntityPacket extends RakNetDataPacket{ public $x; public $y; public $z; - public $yaw; - public $pitch; - public $roll; - + public $speedX; + public $speedY; + public $speedZ; + public function pid(){ if($this->PROTOCOL < ProtocolInfo6::CURRENT_PROTOCOL_6){ return ProtocolInfo4::ADD_ITEM_ENTITY_PACKET; } return ProtocolInfo::ADD_ITEM_ENTITY_PACKET; } - + public function decode(){ } - + public function encode(){ $this->reset(); $this->putInt($this->eid); @@ -28,9 +28,16 @@ class AddItemEntityPacket extends RakNetDataPacket{ $this->putFloat($this->x); $this->putFloat($this->y); $this->putFloat($this->z); - $this->putByte($this->yaw); - $this->putByte($this->pitch); - $this->putByte($this->roll); + $this->putByte((int)($this->speedX * 128)); + $this->putByte((int)($this->speedY * 128)); + $this->putByte((int)($this->speedZ * 128)); + } + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; } - } \ No newline at end of file diff --git a/src/network/protocol/packet/AddMobPacket.php b/src/network/protocol/packet/AddMobPacket.php index 4a469196..1cee76f2 100644 --- a/src/network/protocol/packet/AddMobPacket.php +++ b/src/network/protocol/packet/AddMobPacket.php @@ -29,5 +29,13 @@ class AddMobPacket extends RakNetDataPacket{ $this->putByte($this->pitch); $this->put(Utils::writeMetadata($this->metadata)); } - + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/AddPaintingPacket.php b/src/network/protocol/packet/AddPaintingPacket.php index 405f22d4..8017344c 100644 --- a/src/network/protocol/packet/AddPaintingPacket.php +++ b/src/network/protocol/packet/AddPaintingPacket.php @@ -28,5 +28,13 @@ class AddPaintingPacket extends RakNetDataPacket{ $this->putInt($this->direction); $this->putString($this->title); } - + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/AddPlayerPacket.php b/src/network/protocol/packet/AddPlayerPacket.php index 709c1a30..00881dc4 100644 --- a/src/network/protocol/packet/AddPlayerPacket.php +++ b/src/network/protocol/packet/AddPlayerPacket.php @@ -46,5 +46,13 @@ class AddPlayerPacket extends RakNetDataPacket{ $this->putShort($this->itemAuxValue); //Example: bow shooting power $this->put(Utils::writeMetadata($this->metadata)); } - + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/AnimatePacket.php b/src/network/protocol/packet/AnimatePacket.php index 84b980cf..31ee66c3 100644 --- a/src/network/protocol/packet/AnimatePacket.php +++ b/src/network/protocol/packet/AnimatePacket.php @@ -35,4 +35,21 @@ class AnimatePacket extends RakNetDataPacket{ $this->putInt($this->eid); } + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/ContainerSetContentPacket.php b/src/network/protocol/packet/ContainerSetContentPacket.php index 115058e6..27254650 100644 --- a/src/network/protocol/packet/ContainerSetContentPacket.php +++ b/src/network/protocol/packet/ContainerSetContentPacket.php @@ -2,9 +2,9 @@ class ContainerSetContentPacket extends RakNetDataPacket{ public $windowid; - public $slots = []; - public $hotbar = []; - + public $slots = array(); + public $hotbar = array(); + public function pid(){ if($this->PROTOCOL < ProtocolInfo4::CURRENT_PROTOCOL_4){ return ProtocolInfo3::CONTAINER_SET_CONTENT_PACKET; @@ -21,7 +21,7 @@ class ContainerSetContentPacket extends RakNetDataPacket{ } return ProtocolInfo::CONTAINER_SET_CONTENT_PACKET; } - + public function decode(){ $this->windowid = $this->getByte(); $count = $this->getShort(); @@ -31,14 +31,12 @@ class ContainerSetContentPacket extends RakNetDataPacket{ if($this->PROTOCOL <= ProtocolInfo9::CURRENT_PROTOCOL_9){ return; } - if($this->windowid === 0){ - $count = $this->getShort(); - for($s = 0; $s < $count and !$this->feof(); ++$s){ - $this->hotbar[$s] = $this->getInt(); - } - } + $count = $this->getShort(); + for($s = 0; $s < $count and !$this->feof(); ++$s){ + $this->hotbar[$s] = $this->getInt(); + } } - + public function encode(){ $this->reset(); $this->putByte($this->windowid); @@ -54,7 +52,9 @@ class ContainerSetContentPacket extends RakNetDataPacket{ foreach($this->hotbar as $slot){ $this->putInt($slot); } + }else{ + $this->putShort(0); } } -} \ No newline at end of file +} diff --git a/src/network/protocol/packet/DropItemPacket.php b/src/network/protocol/packet/DropItemPacket.php index b3fccc5c..c9fa9fa3 100644 --- a/src/network/protocol/packet/DropItemPacket.php +++ b/src/network/protocol/packet/DropItemPacket.php @@ -2,7 +2,7 @@ class DropItemPacket extends RakNetDataPacket{ public $eid; - public $unknown; + public $randomly; public $item; public function pid(){ @@ -25,7 +25,7 @@ class DropItemPacket extends RakNetDataPacket{ public function decode(){ //if($this->PROTOCOL < ProtocolInfo8::CURRENT_PROTOCOL_8)$this->reset(); $this->eid = $this->getInt(); - $this->unknown = $this->getByte(); + $this->randomly = $this->getByte(); $this->item = $this->getSlot(); } @@ -35,5 +35,13 @@ class DropItemPacket extends RakNetDataPacket{ $this->putByte($this->unknown); $this->putSlot($this->item);*/ } - -} \ No newline at end of file + + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } +} diff --git a/src/network/protocol/packet/EntityEventPacket.php b/src/network/protocol/packet/EntityEventPacket.php index 4ddb4d8c..ca7aa6e0 100644 --- a/src/network/protocol/packet/EntityEventPacket.php +++ b/src/network/protocol/packet/EntityEventPacket.php @@ -6,6 +6,10 @@ class EntityEventPacket extends RakNetDataPacket{ const ENTITY_DAMAGE = 2; const ENTITY_DEAD = 3; + /** + * Works only for player entities + */ + const ENTITY_COMPLETE_USING_ITEM = 9; const ENTITY_ANIM_10 = 10; public function __construct($eid = null, $event = null){ @@ -36,5 +40,22 @@ class EntityEventPacket extends RakNetDataPacket{ $this->putInt($this->eid); $this->putByte($this->event); } - -} \ No newline at end of file + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } +} diff --git a/src/network/protocol/packet/InteractPacket.php b/src/network/protocol/packet/InteractPacket.php index 3f07246e..fe73beb2 100644 --- a/src/network/protocol/packet/InteractPacket.php +++ b/src/network/protocol/packet/InteractPacket.php @@ -35,5 +35,24 @@ class InteractPacket extends RakNetDataPacket{ $this->putInt($this->eid); $this->putInt($this->target); } - + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + $this->target = $p->global2localEID[$this->target] ?? false; + if($this->eid === false || $this->target === false) return false; + } + return true; + } + + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + $this->target = $p->local2GlobalEID[$this->target] ?? false; + if($this->eid === false || $this->target === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/MoveEntityPacket_PosRot.php b/src/network/protocol/packet/MoveEntityPacket_PosRot.php index 5ec9632d..61b5ba35 100644 --- a/src/network/protocol/packet/MoveEntityPacket_PosRot.php +++ b/src/network/protocol/packet/MoveEntityPacket_PosRot.php @@ -35,4 +35,20 @@ class MoveEntityPacket_PosRot extends RakNetDataPacket{ $this->putFloat($this->pitch); } + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/MovePlayerPacket.php b/src/network/protocol/packet/MovePlayerPacket.php index 276ae2e0..d189449a 100644 --- a/src/network/protocol/packet/MovePlayerPacket.php +++ b/src/network/protocol/packet/MovePlayerPacket.php @@ -43,4 +43,20 @@ class MovePlayerPacket extends RakNetDataPacket{ } } + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/PlayerActionPacket.php b/src/network/protocol/packet/PlayerActionPacket.php index 945347cc..7bec317a 100644 --- a/src/network/protocol/packet/PlayerActionPacket.php +++ b/src/network/protocol/packet/PlayerActionPacket.php @@ -38,5 +38,13 @@ class PlayerActionPacket extends RakNetDataPacket{ $this->putInt($this->face); $this->putInt($this->eid);*/ } - + + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/PlayerArmorEquipmentPacket.php b/src/network/protocol/packet/PlayerArmorEquipmentPacket.php index 41424a25..db7eec47 100644 --- a/src/network/protocol/packet/PlayerArmorEquipmentPacket.php +++ b/src/network/protocol/packet/PlayerArmorEquipmentPacket.php @@ -27,5 +27,22 @@ class PlayerArmorEquipmentPacket extends RakNetDataPacket{ $this->putByte($this->slots[2]); $this->putByte($this->slots[3]); } - + + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/PlayerEquipmentPacket.php b/src/network/protocol/packet/PlayerEquipmentPacket.php index c7806eb5..66bfea7d 100644 --- a/src/network/protocol/packet/PlayerEquipmentPacket.php +++ b/src/network/protocol/packet/PlayerEquipmentPacket.php @@ -33,5 +33,22 @@ class PlayerEquipmentPacket extends RakNetDataPacket{ $this->putShort($this->meta); if($this->PROTOCOL === ProtocolInfo::CURRENT_PROTOCOL){$this->putByte($this->slot);} } - + + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/RemoveBlockPacket.php b/src/network/protocol/packet/RemoveBlockPacket.php index 4c01228c..dbd716f4 100644 --- a/src/network/protocol/packet/RemoveBlockPacket.php +++ b/src/network/protocol/packet/RemoveBlockPacket.php @@ -31,4 +31,12 @@ class RemoveBlockPacket extends RakNetDataPacket{ $this->putInt($this->y);*/ } + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/RemoveEntityPacket.php b/src/network/protocol/packet/RemoveEntityPacket.php index c835d9a9..670a4c77 100644 --- a/src/network/protocol/packet/RemoveEntityPacket.php +++ b/src/network/protocol/packet/RemoveEntityPacket.php @@ -18,5 +18,13 @@ class RemoveEntityPacket extends RakNetDataPacket{ $this->reset(); $this->putInt($this->eid); } - + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/RemovePlayerPacket.php b/src/network/protocol/packet/RemovePlayerPacket.php index 553a46b7..1b2201fe 100644 --- a/src/network/protocol/packet/RemovePlayerPacket.php +++ b/src/network/protocol/packet/RemovePlayerPacket.php @@ -18,4 +18,12 @@ class RemovePlayerPacket extends RakNetDataPacket{ $this->putLong($this->clientID); } + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/RespawnPacket.php b/src/network/protocol/packet/RespawnPacket.php index c88a856a..9550425d 100644 --- a/src/network/protocol/packet/RespawnPacket.php +++ b/src/network/protocol/packet/RespawnPacket.php @@ -37,5 +37,12 @@ class RespawnPacket extends RakNetDataPacket{ $this->putFloat($this->y); $this->putFloat($this->z); } - + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/RotateHeadPacket.php b/src/network/protocol/packet/RotateHeadPacket.php index 634e3851..de06551f 100644 --- a/src/network/protocol/packet/RotateHeadPacket.php +++ b/src/network/protocol/packet/RotateHeadPacket.php @@ -29,4 +29,21 @@ class RotateHeadPacket extends RakNetDataPacket{ $this->putByte($this->rawYaw ? $this->yaw : ($this->yaw / 360 / 0.0039062)); //wraps 360 angle to 0xff } + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/SendInventoryPacket.php b/src/network/protocol/packet/SendInventoryPacket.php index e1e2ef0a..ea012548 100644 --- a/src/network/protocol/packet/SendInventoryPacket.php +++ b/src/network/protocol/packet/SendInventoryPacket.php @@ -51,5 +51,23 @@ class SendInventoryPacket extends RakNetDataPacket{ } } } + + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/SetEntityDataPacket.php b/src/network/protocol/packet/SetEntityDataPacket.php index 160d35c4..f9030e9b 100644 --- a/src/network/protocol/packet/SetEntityDataPacket.php +++ b/src/network/protocol/packet/SetEntityDataPacket.php @@ -28,5 +28,13 @@ class SetEntityDataPacket extends RakNetDataPacket{ $this->putInt($this->eid); $this->put(Utils::writeMetadata($this->metadata)); } + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/SetEntityLinkPacket.php b/src/network/protocol/packet/SetEntityLinkPacket.php index c473ef13..c9489bd9 100644 --- a/src/network/protocol/packet/SetEntityLinkPacket.php +++ b/src/network/protocol/packet/SetEntityLinkPacket.php @@ -12,7 +12,9 @@ class SetEntityLinkPacket extends RakNetDataPacket{ public $riding; public $type; public function decode() { - + $this->rider = $this->getInt(); + $this->riding = $this->getInt(); + $this->type = $this->getInt(); } public function encode() { $this->reset(); @@ -28,4 +30,23 @@ class SetEntityLinkPacket extends RakNetDataPacket{ return ProtocolInfo::SET_ENTITY_LINK_PACKET; } + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->rider = $p->local2GlobalEID[$this->rider] ?? false; + $this->riding = $p->local2GlobalEID[$this->riding] ?? false; + if($this->rider === false || $this->riding === false) return false; + } + return true; + } + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->rider = $p->global2localEID[$this->rider] ?? false; + $this->riding = $p->global2localEID[$this->riding] ?? false; + if($this->rider === false || $this->riding === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/SetEntityMotionPacket.php b/src/network/protocol/packet/SetEntityMotionPacket.php index 5bd44bf6..cd71f52d 100644 --- a/src/network/protocol/packet/SetEntityMotionPacket.php +++ b/src/network/protocol/packet/SetEntityMotionPacket.php @@ -30,5 +30,12 @@ class SetEntityMotionPacket extends RakNetDataPacket{ $this->putShort((int) ($this->speedY * 8000)); $this->putShort((int) ($this->speedZ * 8000)); } - + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/StartGamePacket.php b/src/network/protocol/packet/StartGamePacket.php index c81898a8..b1bcaa17 100644 --- a/src/network/protocol/packet/StartGamePacket.php +++ b/src/network/protocol/packet/StartGamePacket.php @@ -27,5 +27,13 @@ class StartGamePacket extends RakNetDataPacket{ $this->putFloat($this->y); $this->putFloat($this->z); } - + + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/TakeItemEntityPacket.php b/src/network/protocol/packet/TakeItemEntityPacket.php index 5c3e9eae..f0e36e03 100644 --- a/src/network/protocol/packet/TakeItemEntityPacket.php +++ b/src/network/protocol/packet/TakeItemEntityPacket.php @@ -21,4 +21,14 @@ class TakeItemEntityPacket extends RakNetDataPacket{ $this->putInt($this->eid); } + //TODO convert + public function eidsToLocal(Player $p){ + if(!$this->localEids){ + $this->localEids = true; + $this->eid = $p->global2localEID[$this->eid] ?? false; + $this->target = $p->global2localEID[$this->target] ?? false; + if($this->eid === false || $this->target === false) return false; + } + return true; + } } \ No newline at end of file diff --git a/src/network/protocol/packet/UseItemPacket.php b/src/network/protocol/packet/UseItemPacket.php index 5f086013..be89ec6b 100644 --- a/src/network/protocol/packet/UseItemPacket.php +++ b/src/network/protocol/packet/UseItemPacket.php @@ -66,5 +66,13 @@ class UseItemPacket extends RakNetDataPacket{ $this->putInt($this->eid); $this->putInt($this->unknownInt1);*/ } + public function eidsToGlobal(Player $p){ + if($this->localEids){ + $this->localEids = false; + $this->eid = $p->local2GlobalEID[$this->eid] ?? false; + if($this->eid === false) return false; + } + return true; + } } diff --git a/src/network/raknet/RakNetCodec.php b/src/network/raknet/RakNetCodec.php index 34393bc6..082cfcf5 100644 --- a/src/network/raknet/RakNetCodec.php +++ b/src/network/raknet/RakNetCodec.php @@ -1,46 +1,45 @@ packet = $packet; - $this->buffer = &$this->packet->buffer; - $this->encode(); + private static function encodeIPAddress(RakNetPacket $packet) { + $packet->buffer .= chr(4); + $packet->buffer .= Utils::writeInt($packet->ip); + $packet->buffer .= Utils::writeShort($packet->port); } - private function encode(){ - if($this->packet->buffer != null && strlen($this->packet->buffer) > 0){ + public static function encode(RakNetPacket $packet){ + if($packet->buffer != null && strlen($packet->buffer) > 0){ return; } - $this->buffer .= chr($this->packet->pid()); + $packet->buffer .= chr($packet->pid()); - switch($this->packet->pid()){ + switch($packet->pid()){ case RakNetInfo::OPEN_CONNECTION_REPLY_1: - $this->buffer .= RakNetInfo::MAGIC; - $this->putLong($this->packet->serverID); - $this->putByte(0); //server security - $this->putShort($this->packet->mtuSize); + $packet->buffer .= RakNetInfo::MAGIC; + $packet->buffer .= Utils::writeLong($packet->serverID); + $packet->buffer .= chr(0); //server security + $packet->buffer .= Utils::writeShort($packet->mtuSize); break; case RakNetInfo::OPEN_CONNECTION_REPLY_2: - $this->buffer .= RakNetInfo::MAGIC; - $this->putLong($this->packet->serverID); - $this->putShort($this->packet->port); - $this->putShort($this->packet->mtuSize); - $this->putByte(0); //Server security + $packet->buffer .= RakNetInfo::MAGIC; + $packet->buffer .= Utils::writeLong($packet->serverID); + static::encodeIPAddress($packet); + $packet->buffer .= Utils::writeShort($packet->mtuSize); + $packet->buffer .= chr(0); //Server security break; case RakNetInfo::INCOMPATIBLE_PROTOCOL_VERSION: - $this->putByte(RakNetInfo::STRUCTURE); - $this->buffer .= RakNetInfo::MAGIC; - $this->putLong($this->packet->serverID); + $packet->buffer .= chr(RakNetInfo::STRUCTURE); + $packet->buffer .= RakNetInfo::MAGIC; + $packet->buffer .= Utils::writeLong($packet->serverID); break; case RakNetInfo::UNCONNECTED_PONG: case RakNetInfo::ADVERTISE_SYSTEM: - $this->putLong($this->packet->pingID); - $this->putLong($this->packet->serverID); - $this->buffer .= RakNetInfo::MAGIC; - $this->putString($this->packet->serverType); + $packet->buffer .= Utils::writeLong($packet->pingID); + $packet->buffer .= Utils::writeLong($packet->serverID); + $packet->buffer .= RakNetInfo::MAGIC; + + $packet->buffer .= Utils::writeShort(strlen($packet->serverType)); + $packet->buffer .= $packet->serverType; break; case RakNetInfo::DATA_PACKET_0: case RakNetInfo::DATA_PACKET_1: @@ -58,9 +57,9 @@ class RakNetCodec{ case RakNetInfo::DATA_PACKET_D: case RakNetInfo::DATA_PACKET_E: case RakNetInfo::DATA_PACKET_F: - $this->putLTriad($this->packet->seqNumber); - foreach($this->packet->data as $pk){ - $this->encodeDataPacket($pk); + $packet->buffer .= Utils::writeLTriad($packet->seqNumber); + foreach($packet->data as $pk){ + static::encodeDataPacket($packet, $pk); } break; case RakNetInfo::NACK: @@ -68,14 +67,14 @@ class RakNetCodec{ $payload = b""; $records = 0; $pointer = 0; - sort($this->packet->packets, SORT_NUMERIC); - $max = count($this->packet->packets); + sort($packet->packets, SORT_NUMERIC); + $max = count($packet->packets); while($pointer < $max){ $type = true; - $curr = $start = $this->packet->packets[$pointer]; + $curr = $start = $packet->packets[$pointer]; for($i = $start + 1; $i < $max; ++$i){ - $n = $this->packet->packets[$i]; + $n = $packet->packets[$i]; if(($n - $curr) === 1){ $curr = $end = $n; $type = false; @@ -95,73 +94,61 @@ class RakNetCodec{ } ++$records; } - $this->putShort($records); - $this->buffer .= $payload; + $packet->buffer .= Utils::writeShort($records); + $packet->buffer .= $payload; break; default: } - } - protected function putLong($v){ - $this->buffer .= Utils::writeLong($v); - } - - protected function putByte($v){ - $this->buffer .= chr($v); - } - - protected function putShort($v){ - $this->buffer .= Utils::writeShort($v); - } - - protected function putString($v){ - $this->putShort(strlen($v)); - $this->put($v); - } - - protected function put($str){ - $this->buffer .= $str; - } - - protected function putLTriad($v){ - $this->buffer .= Utils::writeLTriad($v); - } - - private function encodeDataPacket(RakNetDataPacket $pk){ - $this->putByte(($pk->reliability << 5) | ($pk->hasSplit > 0 ? 0b00010000 : 0)); - $this->putShort(strlen($pk->buffer) << 3); - if($pk->reliability === 2 - or $pk->reliability === 3 - or $pk->reliability === 4 - or $pk->reliability === 6 - or $pk->reliability === 7){ - $this->putLTriad($pk->messageIndex); + public static function encodeDataPacket(RakNetPacket $packet, RakNetDataPacket $pk){ + $packet->buffer .= chr(($pk->reliability << 5) | ($pk->hasSplit > 0 ? 0b00010000 : 0)); + $packet->buffer .= Utils::writeShort(strlen($pk->buffer) << 3); + if($pk->reliability === RakNetInfo::RELIABILITY_RELIABLE + or $pk->reliability === RakNetInfo::RELIABILITY_RELIABLE_ORDERED + or $pk->reliability === RakNetInfo::RELIABILITY_RELIABLE_SEQUENCED + or $pk->reliability === RakNetInfo::RELIABILITY_RELIABLE_WITHACKRECEIPT + or $pk->reliability === RakNetInfo::RELIABILITY_RELIABLE_ORDERED_WITHACKRECEIPT){ + $packet->buffer .= Utils::writeLTriad($pk->messageIndex); + } + if($pk->reliability == RakNetInfo::RELIABILITY_UNRELIABLE_SEQUENCED || $pk->reliability == RakNetInfo::RELIABILITY_RELIABLE_SEQUENCED){ + $packet->buffer .= Utils::writeLTriad($pk->seqIndex); } - if($pk->reliability === 1 - or $pk->reliability === 3 - or $pk->reliability === 4 - or $pk->reliability === 7){ - $this->putLTriad($pk->orderIndex); - $this->putByte($pk->orderChannel); + if($pk->reliability === RakNetInfo::RELIABILITY_UNRELIABLE_SEQUENCED + or $pk->reliability === RakNetInfo::RELIABILITY_RELIABLE_ORDERED + or $pk->reliability === RakNetInfo::RELIABILITY_RELIABLE_SEQUENCED + or $pk->reliability === RakNetInfo::RELIABILITY_RELIABLE_ORDERED_WITHACKRECEIPT){ + $packet->buffer .= Utils::writeLTriad($pk->orderIndex); + $packet->buffer .= chr($pk->orderChannel); } if($pk->hasSplit === true){ - $this->putInt($pk->splitCount); - $this->putShort($pk->splitID); - $this->putInt($pk->splitIndex); + $packet->buffer .= Utils::writeInt($pk->splitCount); + $packet->buffer .= Utils::writeShort($pk->splitID); + $packet->buffer .= Utils::writeInt($pk->splitIndex); } - $this->buffer .= $pk->buffer; + $packet->buffer .= $pk->buffer; } - - protected function putInt($v){ - $this->buffer .= Utils::writeInt($v); - } - - protected function putTriad($v){ - $this->buffer .= Utils::writeTriad($v); + + /** + * @deprecated + */ + public $packet; + /** + * @deprecated + */ + public $buffer; + /** + * @deprecated use RakNetCodec::encode + * @param RakNetPacket $packet + */ + public function __construct(RakNetPacket $packet){ + $this->packet = $packet; + $this->buffer = &$packet->buffer; + static::encode($packet); } + } \ No newline at end of file diff --git a/src/network/raknet/RakNetDataPacket.php b/src/network/raknet/RakNetDataPacket.php index 43a3a5b5..e5ea67ca 100755 --- a/src/network/raknet/RakNetDataPacket.php +++ b/src/network/raknet/RakNetDataPacket.php @@ -3,7 +3,7 @@ abstract class RakNetDataPacket extends stdClass{ public $buffer = b""; - public $reliability = 0; + public $reliability = RakNetInfo::RELIABILITY_UNRELIABLE; public $hasSplit = false; public $messageIndex; public $orderIndex; @@ -11,23 +11,31 @@ abstract class RakNetDataPacket extends stdClass{ public $splitCount; public $splitID; public $splitIndex; + public $seqIndex; + public $PROTOCOL = ProtocolInfo::CURRENT_PROTOCOL; private $offset = 0; - public $PROTOCOL = ProtocolInfo::CURRENT_PROTOCOL; + public abstract function encode(); - abstract public function encode(); + public abstract function decode(); - abstract public function decode(); + public $localEids = false; + public function eidsToLocal(Player $p){ + return true; + } + public function eidsToGlobal(Player $p){ + return true; + } public function getBuffer(){ return $this->buffer; } - + public function getOffset(){ return $this->offset; } - + public function setBuffer($buffer = ""){ $this->buffer = $buffer; $this->offset = 0; @@ -134,12 +142,12 @@ abstract class RakNetDataPacket extends stdClass{ protected function getShort($unsigned = false){ return Utils::readShort($this->get(2), $unsigned); } - + public function getSignedByte(){ $b = ord($this->get(1)); - return $b >= 0x80 ? ($b - 256) : $b; + return $b >= 0x80 ? ($b-256) : $b; } - + protected function getByte(){ return ord($this->get(1)); } @@ -155,7 +163,7 @@ abstract class RakNetDataPacket extends stdClass{ } protected function putByte($v){ - $this->buffer .= chr((int) $v); + $this->buffer .= chr((int)$v); } protected function getString(){ diff --git a/src/network/raknet/RakNetInfo.php b/src/network/raknet/RakNetInfo.php index dabb8b75..9126f8fc 100644 --- a/src/network/raknet/RakNetInfo.php +++ b/src/network/raknet/RakNetInfo.php @@ -37,6 +37,15 @@ abstract class RakNetInfo{ const NACK = 0xa0; const ACK = 0xc0; + const RELIABILITY_UNRELIABLE = 0; + const RELIABILITY_UNRELIABLE_SEQUENCED = 1; + const RELIABILITY_RELIABLE = 2; + const RELIABILITY_RELIABLE_ORDERED = 3; + const RELIABILITY_RELIABLE_SEQUENCED = 4; + const RELIABILITY_UNRELIABLE_WITHACKRECEIPT = 5; + const RELIABILITY_RELIABLE_WITHACKRECEIPT = 6; + const RELIABILITY_RELIABLE_ORDERED_WITHACKRECEIPT = 7; + public static function isValid($pid){ return match ((int) $pid) { RakNetInfo::UNCONNECTED_PING, RakNetInfo::UNCONNECTED_PING_OPEN_CONNECTIONS, RakNetInfo::OPEN_CONNECTION_REQUEST_1, RakNetInfo::OPEN_CONNECTION_REPLY_1, RakNetInfo::OPEN_CONNECTION_REQUEST_2, RakNetInfo::OPEN_CONNECTION_REPLY_2, RakNetInfo::INCOMPATIBLE_PROTOCOL_VERSION, RakNetInfo::UNCONNECTED_PONG, RakNetInfo::ADVERTISE_SYSTEM, RakNetInfo::DATA_PACKET_0, RakNetInfo::DATA_PACKET_1, RakNetInfo::DATA_PACKET_2, RakNetInfo::DATA_PACKET_3, RakNetInfo::DATA_PACKET_4, RakNetInfo::DATA_PACKET_5, RakNetInfo::DATA_PACKET_6, RakNetInfo::DATA_PACKET_7, RakNetInfo::DATA_PACKET_8, RakNetInfo::DATA_PACKET_9, RakNetInfo::DATA_PACKET_A, RakNetInfo::DATA_PACKET_B, RakNetInfo::DATA_PACKET_C, RakNetInfo::DATA_PACKET_D, RakNetInfo::DATA_PACKET_E, RakNetInfo::DATA_PACKET_F, RakNetInfo::NACK, RakNetInfo::ACK => true, diff --git a/src/network/raknet/RakNetPacket.php b/src/network/raknet/RakNetPacket.php index d97f8812..870a2733 100644 --- a/src/network/raknet/RakNetPacket.php +++ b/src/network/raknet/RakNetPacket.php @@ -3,7 +3,9 @@ class RakNetPacket extends Packet{ public $packetID; - + public $seqNumber; + public $sendtime; + public function __construct($packetID){ $this->packetID = (int) $packetID; } diff --git a/src/network/raknet/RakNetParser.php b/src/network/raknet/RakNetParser.php index 90677780..74bc3708 100644 --- a/src/network/raknet/RakNetParser.php +++ b/src/network/raknet/RakNetParser.php @@ -1,44 +1,35 @@ source = &$source; - $this->buffer = &$buffer; - $this->offset = 0; - if(strlen($this->buffer) > 0){ - $this->parse(); - }else{ - $this->packet = false; - } - } - - private function parse(){ - $this->packet = new RakNetPacket(ord($this->get(1))); - $this->packet->buffer = &$this->buffer; - $this->packet->length = strlen($this->buffer); - switch($this->packet->pid()){ + public static function parse(&$buffer){ + $offset = 0; + ++$offset; + $packet = new RakNetPacket(ord(substr($buffer, $offset - 1, 1))); + $packet->buffer = &$buffer; + $packet->length = strlen($buffer); + switch($packet->pid()){ case RakNetInfo::UNCONNECTED_PING: case RakNetInfo::UNCONNECTED_PING_OPEN_CONNECTIONS: - $this->packet->pingID = $this->getLong(); - $this->offset += 16; //Magic + $offset += 8; + $packet->pingID = Utils::readLong(substr($buffer, $offset - 8, 8), false); + $offset += 16; //Magic break; case RakNetInfo::OPEN_CONNECTION_REQUEST_1: - $this->offset += 16; //Magic - $this->packet->structure = $this->getByte(); - $this->packet->mtuSize = strlen($this->get(true)); + $offset += 16; //Magic + ++$offset; + $packet->structure = ord(substr($buffer, $offset - 1, 1)); + $packet->mtuSize = strlen(substr($buffer, $offset)); break; case RakNetInfo::OPEN_CONNECTION_REQUEST_2: - $this->offset += 16; //Magic - $this->packet->security = $this->get(5); - $this->packet->port = $this->getShort(false); - $this->packet->mtuSize = $this->getShort(false); - $this->packet->clientID = $this->getLong(); + $offset += 16; //Magic + $offset += 5; + $packet->security = Utils::readLong(substr($buffer, $offset - 5, 5), false); + $offset += 2; + $packet->port = Utils::readShort(substr($buffer, $offset - 2, 2), false); + $offset += 2; + $packet->mtuSize = Utils::readShort(substr($buffer, $offset - 2, 2), false); + $offset += 8; + $packet->clientID = Utils::readLong(substr($buffer, $offset - 8, 8), false); break; case RakNetInfo::DATA_PACKET_0: case RakNetInfo::DATA_PACKET_1: @@ -56,38 +47,43 @@ class RakNetParser{ case RakNetInfo::DATA_PACKET_D: case RakNetInfo::DATA_PACKET_E: case RakNetInfo::DATA_PACKET_F: - $this->packet->seqNumber = $this->getLTriad(); - $this->packet->data = []; - $this->packet->ip = $this->source; - $PROTOCOL = PlayerAPI::decodeProtocol($this->packet->ip); - - while(!$this->feof() and ($pk = $this->parseDataPacket($PROTOCOL)) instanceof RakNetDataPacket){ - $this->packet->data[] = $pk; + $offset += 3; + $packet->seqNumber = Utils::readTriad(strrev(substr($buffer, $offset - 3, 3))); + $packet->data = []; + + while(isset($buffer[$offset]) and ($pk = static::parseDataPacket($offset, $buffer)) instanceof RakNetDataPacket){ + $packet->data[] = $pk; } break; case RakNetInfo::NACK: case RakNetInfo::ACK: - $count = $this->getShort(); - $this->packet->packets = []; - for($i = 0; $i < $count and !$this->feof(); ++$i){ - if($this->getByte() === 0){ - $start = $this->getLTriad(); - $end = $this->getLTriad(); + $offset += 2; + $count = Utils::readShort(substr($buffer, $offset - 2, 2), false); + $packet->packets = []; + for($i = 0; $i < $count && isset($buffer[$offset]); ++$i){ + ++$offset; + if(ord(substr($buffer, $offset - 1, 1)) === 0){ + $offset += 3; + $start = Utils::readTriad(strrev(substr($buffer, $offset - 3, 3))); + $offset += 3; + $end = Utils::readTriad(strrev(substr($buffer, $offset - 3, 3))); if(($end - $start) > 4096){ $end = $start + 4096; } for($c = $start; $c <= $end; ++$c){ - $this->packet->packets[] = $c; + $packet->packets[] = $c; } }else{ - $this->packet->packets[] = $this->getLTriad(); + $offset += 3; + $packet->packets[] = Utils::readTriad(strrev(substr($buffer, $offset - 3, 3))); } } break; default: - $this->packet = false; + $packet = false; break; } + return $packet; } private function get($len){ @@ -102,57 +98,56 @@ class RakNetParser{ return substr($this->buffer, $this->offset - $len, $len); } - private function getLong($unsigned = false){ - return Utils::readLong($this->get(8), $unsigned); - } - private function getByte(){ return ord($this->get(1)); } private function getShort($unsigned = false){ - return Utils::readShort($this->get(2), $unsigned); + return ; } private function getLTriad(){ return Utils::readTriad(strrev($this->get(3))); } - private function feof(){ - return !isset($this->buffer[$this->offset]); - } - - private function parseDataPacket($protocol = ProtocolInfo::CURRENT_PROTOCOL){ - $packetFlags = $this->getByte(); + private static function parseDataPacket(&$offset, &$buffer){ + ++$offset; + $packetFlags = ord(substr($buffer, $offset - 1, 1)); $reliability = ($packetFlags & 0b11100000) >> 5; $hasSplit = ($packetFlags & 0b00010000) > 0; - $length = (int) ceil($this->getShort() / 8); + $offset += 2; + $length = (int) ceil(Utils::readShort(substr($buffer, $offset - 2, 2), false) / 8); - if($reliability === 2 - or $reliability === 3 - or $reliability === 4 - or $reliability === 6 - or $reliability === 7){ - $messageIndex = $this->getLTriad(); + if($reliability == 2 ||$reliability == 3 || $reliability == 4 || $reliability == 6 || $reliability == 7){ + $offset += 3; + $messageIndex = Utils::readTriad(strrev(substr($buffer, $offset - 3, 3))); }else{ $messageIndex = false; } + if($reliability == 1 || $reliability == 4){ + $offset += 3; + $seqIndex = Utils::readTriad(strrev(substr($buffer, $offset - 3, 3))); + }else{ + $seqIndex = false; + } - if($reliability === 1 - or $reliability === 3 - or $reliability === 4 - or $reliability === 7){ - $orderIndex = $this->getLTriad(); - $orderChannel = $this->getByte(); + if($reliability == 1 ||$reliability == 3 || $reliability == 4 || $reliability == 7){ + $offset += 3; + $orderIndex = Utils::readTriad(strrev(substr($buffer, $offset - 3, 3))); + ++$offset; + $orderChannel = ord(substr($buffer, $offset - 1, 1)); }else{ $orderIndex = false; $orderChannel = false; } if($hasSplit){ - $splitCount = $this->getInt(); - $splitID = $this->getShort(); - $splitIndex = $this->getInt(); + $offset += 4; + $splitCount = Utils::readInt(substr($buffer, $offset - 4, 4), false); + $offset += 2; + $splitID = Utils::readShort(substr($buffer, $offset - 2, 2), false); + $offset += 4; + $splitIndex = Utils::readInt(substr($buffer, $offset - 4, 4), false); }else{ $splitCount = false; $splitID = false; @@ -164,13 +159,73 @@ class RakNetParser{ or ($hasSplit === true and $splitIndex >= $splitCount)){ return false; }else{ - $pid = $this->getByte(); - $buffer = $this->get($length - 1); - if(strlen($buffer) < ($length - 1)){ + ++$offset; + $pid = ord(substr($buffer, $offset - 1, 1)); + $offset += $length-1; + $buf = substr($buffer, $offset - ($length - 1), ($length - 1)); + if(strlen($buf) < ($length - 1)){ return false; } - - $data = PacketPool::getPacket($pid, $protocol); + + $data = match($pid){ + ProtocolInfo::PING_PACKET => new PingPacket(), + ProtocolInfo::PONG_PACKET => new PongPacket(), + ProtocolInfo::CLIENT_CONNECT_PACKET => new ClientConnectPacket(), + ProtocolInfo::SERVER_HANDSHAKE_PACKET => new ServerHandshakePacket(), + ProtocolInfo::DISCONNECT_PACKET => new DisconnectPacket(), + ProtocolInfo::LOGIN_PACKET => new LoginPacket(), + ProtocolInfo::LOGIN_STATUS_PACKET => new LoginStatusPacket(), + ProtocolInfo::READY_PACKET => new ReadyPacket(), + ProtocolInfo::MESSAGE_PACKET => new MessagePacket(), + ProtocolInfo::SET_TIME_PACKET => new SetTimePacket(), + ProtocolInfo::START_GAME_PACKET => new StartGamePacket(), + ProtocolInfo::ADD_MOB_PACKET => new AddMobPacket(), + ProtocolInfo::ADD_PLAYER_PACKET => new AddPlayerPacket(), + ProtocolInfo::REMOVE_PLAYER_PACKET => new RemovePlayerPacket(), + ProtocolInfo::ADD_ENTITY_PACKET => new AddEntityPacket(), + ProtocolInfo::REMOVE_ENTITY_PACKET => new RemoveEntityPacket(), + ProtocolInfo::ADD_ITEM_ENTITY_PACKET => new AddItemEntityPacket(), + ProtocolInfo::TAKE_ITEM_ENTITY_PACKET => new TakeItemEntityPacket(), + ProtocolInfo::MOVE_ENTITY_PACKET => new MoveEntityPacket(), + ProtocolInfo::MOVE_ENTITY_PACKET_POSROT => new MoveEntityPacket_PosRot(), + ProtocolInfo::ROTATE_HEAD_PACKET => new RotateHeadPacket(), + ProtocolInfo::MOVE_PLAYER_PACKET => new MovePlayerPacket(), + ProtocolInfo::REMOVE_BLOCK_PACKET => new RemoveBlockPacket(), + ProtocolInfo::UPDATE_BLOCK_PACKET => new UpdateBlockPacket(), + ProtocolInfo::ADD_PAINTING_PACKET => new AddPaintingPacket(), + ProtocolInfo::EXPLODE_PACKET => new ExplodePacket(), + ProtocolInfo::LEVEL_EVENT_PACKET => new LevelEventPacket(), + ProtocolInfo::TILE_EVENT_PACKET => new TileEventPacket(), + ProtocolInfo::ENTITY_EVENT_PACKET => new EntityEventPacket(), + ProtocolInfo::REQUEST_CHUNK_PACKET => new RequestChunkPacket(), + ProtocolInfo::CHUNK_DATA_PACKET => new ChunkDataPacket(), + ProtocolInfo::PLAYER_EQUIPMENT_PACKET => new PlayerEquipmentPacket(), + ProtocolInfo::PLAYER_ARMOR_EQUIPMENT_PACKET => new PlayerArmorEquipmentPacket(), + ProtocolInfo::INTERACT_PACKET => new InteractPacket(), + ProtocolInfo::USE_ITEM_PACKET => new UseItemPacket(), + ProtocolInfo::PLAYER_ACTION_PACKET => new PlayerActionPacket(), + ProtocolInfo::HURT_ARMOR_PACKET => new HurtArmorPacket(), + ProtocolInfo::SET_ENTITY_DATA_PACKET => new SetEntityDataPacket(), + ProtocolInfo::SET_ENTITY_MOTION_PACKET => new SetEntityMotionPacket(), + ProtocolInfo::SET_HEALTH_PACKET => new SetHealthPacket(), + ProtocolInfo::SET_SPAWN_POSITION_PACKET => new SetSpawnPositionPacket(), + ProtocolInfo::ANIMATE_PACKET => new AnimatePacket(), + ProtocolInfo::RESPAWN_PACKET => new RespawnPacket(), + ProtocolInfo::SEND_INVENTORY_PACKET => new SendInventoryPacket(), + ProtocolInfo::DROP_ITEM_PACKET => new DropItemPacket(), + ProtocolInfo::CONTAINER_OPEN_PACKET => new ContainerOpenPacket(), + ProtocolInfo::CONTAINER_CLOSE_PACKET => new ContainerClosePacket(), + ProtocolInfo::CONTAINER_SET_SLOT_PACKET => new ContainerSetSlotPacket(), + ProtocolInfo::CONTAINER_SET_DATA_PACKET => new ContainerSetDataPacket(), + ProtocolInfo::CONTAINER_SET_CONTENT_PACKET => new ContainerSetContentPacket(), + ProtocolInfo::CHAT_PACKET => new ChatPacket(), + ProtocolInfo::ADVENTURE_SETTINGS_PACKET => new AdventureSettingsPacket(), + ProtocolInfo::ENTITY_DATA_PACKET => new EntityDataPacket(), + ProtocolInfo::SET_ENTITY_LINK_PACKET => new SetEntityLinkPacket(), + ProtocolInfo::PLAYER_INPUT_PACKET => new PlayerInputPacket(), + default => new UnknownPacket($pid) + }; + $data->reliability = $reliability; $data->hasSplit = $hasSplit; $data->messageIndex = $messageIndex; @@ -179,13 +234,25 @@ class RakNetParser{ $data->splitCount = $splitCount; $data->splitID = $splitID; $data->splitIndex = $splitIndex; - $data->setBuffer($buffer); + $data->seqIndex = $seqIndex; + $data->localEids = true; + $data->setBuffer($buf); } return $data; } - - private function getInt($unsigned = false){ - return Utils::readInt($this->get(4), $unsigned); + + /** + * @deprecated + */ + public $packet; + /** + * @deprecated use RakNetParser::parse + */ + public function __construct(&$buffer){ + if(strlen($buffer) > 0){ + $this->packet = static::parse($buffer); + }else{ + $this->packet = false; + } } - -} +} \ No newline at end of file diff --git a/src/pmf/PMFLevel.php b/src/pmf/PMFLevel.php index 0439b5bb..0d03bd15 100644 --- a/src/pmf/PMFLevel.php +++ b/src/pmf/PMFLevel.php @@ -3,14 +3,18 @@ define("PMF_CURRENT_LEVEL_VERSION", 0x00); class PMFLevel extends PMF{ - + const NC_DATA_VERSION = 1; public $isLoaded = true; private $levelData = []; + public $hasLight = ""; public $locationTable = []; private $log = 4; //must be 4 or else rip world private $payloadOffset = 0; public $chunks = []; public $chunkChange = []; + /** + * @var Level + */ public $level; public function __construct($file, $blank = false){ if(is_array($blank)){ @@ -40,7 +44,8 @@ class PMFLevel extends PMF{ if(!is_dir($dirname)){ @mkdir($dirname , 0755); } - + + $this->hasLight = str_repeat("\x00", 16*16); for($index = 0; $index < $cnt; ++$index){ $this->chunks[$index] = false; $this->chunkChange[$index] = false; @@ -82,8 +87,83 @@ class PMFLevel extends PMF{ if($locationTable !== false){ $this->writeLocationTable(); } + + $this->writeNCData(); + } + + public function writeNCData(){ + $dir = dirname($this->file); + try{ + $file = fopen("$dir/ncleveldata.pmf", "wb"); + fwrite($file, chr(self::NC_DATA_VERSION), 1); + fwrite($file, $this->hasLight, 16*16); + }finally{ + fclose($file); + } } + public function readNCData(){ + $this->hasLight = str_repeat("\x00", 16*16); + + $dir = dirname($this->file); + $path = "$dir/ncleveldata.pmf"; + if(!is_file($path)){ + ConsoleAPI::notice("No NC Level data found! Old world?"); + return; + } + try{ + $file = fopen($path, "rb"); + $ncdv = ord(fread($file, 1)); + $v = self::NC_DATA_VERSION; + if($ncdv !== $v){ + ConsoleAPI::notice("NC level data version on server($v) does not match the world($ncdv)! Creating NC level data backup."); + $newpath = "$path.bak.".microtime(true); + $f = copy($path, $newpath); + if($f === false) ConsoleAPI::error("NC level data backup creation failed."); + else ConsoleAPI::notice("NC level data backup created. (path: $newpath)"); + } + $this->hasLight = fread($file, 16*16); + }finally{ + fclose($file); + } + } + + /** + * Checks was skylight generated for chunk + * @param int $X - chunk x + * @param int $Z - chunk z + */ + public function hasSkylight($X, $Z){ + if($X < 0 || $X > 15 || $Z < 0 || $Z > 15) return false; + $index = self::getIndex($X, $Z); + return (ord($this->hasLight[$index]) & 2) > 0; + } + /** + * Checks was blocklight generated for chunk + * @param int $X - chunk x + * @param int $Z - chunk z + */ + public function hasBlocklight($X, $Z){ + if($X < 0 || $X > 15 || $Z < 0 || $Z > 15) return false; + $index = self::getIndex($X, $Z); + return (ord($this->hasLight[$index]) & 1) > 0; + } + + public function markHasBlocklight($X, $Z){ + if($X < 0 || $X > 15 || $Z < 0 || $Z > 15) return false; + $index = self::getIndex($X, $Z); + $o = ord($this->hasLight[$index]); + $this->hasLight[$index] = chr($o | 1); + return true; + } + public function markHasSkylight($X, $Z){ + if($X < 0 || $X > 15 || $Z < 0 || $Z > 15) return false; + $index = self::getIndex($X, $Z); + $o = ord($this->hasLight[$index]); + $this->hasLight[$index] = chr($o | 2); + return true; + } + private function writeLocationTable(){ $cnt = pow($this->levelData["width"], 2); @ftruncate($this->fp, $this->payloadOffset); @@ -94,14 +174,14 @@ class PMFLevel extends PMF{ $this->backupLocTable(); } - + public function backupLocTable(){ $dir = dirname($this->file); if(is_file("$dir/loctable.pmf")){ $val = copy("$dir/loctable.pmf", "$dir/loctable.pmf.old"); if($val === false) ConsoleAPI::warn("Failed to backup loctable data!"); } - + $file = fopen("$dir/loctable.pmf", "wb"); try{ $cnt = pow($this->levelData["width"], 2); @@ -111,7 +191,7 @@ class PMFLevel extends PMF{ }finally{ fclose($file); } - + } public function getXZ($index, &$X = null, &$Z = null){ @@ -160,6 +240,7 @@ class PMFLevel extends PMF{ }else{ $this->payloadOffset = ftell($this->fp); } + $this->readNCData(); return $this->readLocationTable(); } @@ -212,7 +293,7 @@ class PMFLevel extends PMF{ unset($this->chunks[$index], $this->chunkChange[$index]); return true; } - + public function isChunkLoaded($X, $Z){ $index = self::getIndex($X, $Z); if(!isset($this->chunks[$index]) or $this->chunks[$index] === false){ @@ -275,13 +356,12 @@ class PMFLevel extends PMF{ return $this->chunks[$index][$Y]; } + public $checkLight = []; public function loadChunk($X, $Z){ - $index = self::getIndex($X, $Z); if($this->isChunkLoaded($X, $Z)){ return true; - }elseif(!isset($this->locationTable[$index])){ return false; } @@ -298,6 +378,7 @@ class PMFLevel extends PMF{ for($Y = 0; $Y < $this->levelData["height"]; ++$Y){ $t = 1 << $Y; if(($info[0] & $t) === $t){ + //TODO do something with skylight // 4096 + 2048 + 2048, Block Data, Meta, Light if(strlen($this->chunks[$index][$Y] = gzread($chunk, 8192)) < 8192){ console("[NOTICE] Empty corrupt chunk detected [$X,$Z,:$Y], recovering contents", true, true, 2); @@ -307,9 +388,31 @@ class PMFLevel extends PMF{ $this->chunks[$index][$Y] = false; } } + $this->checkLight[$index] = [$X, $Z]; + @gzclose($chunk); return true; } + + public function forceLightUpdatesIfNeeded(){ + if(!PocketMinecraftServer::$ENABLE_LIGHT_UPDATES) { + $this->checkLight = []; + return; + } + foreach($this->checkLight as $index => [$X, $Z]){ + $update = false; + if(!$this->hasBlocklight($X, $Z)){ + ConsoleAPI::notice("Chunk $X $Z (Level: {$this->level->getName()}) has no blocklight! Forcing light update(it might take a while)."); + $this->level->updateLight(0, $X*16, 0, $Z*16, $X*16+15, 127, $Z*16+15); + $update = true; + $this->markHasBlocklight($X, $Z); + } + + if($update) while($this->level->updateLights()); + unset($this->checkLight[$index]); + } + + } protected function fillMiniChunk($X, $Z, $Y){ if($this->isChunkLoaded($X, $Z) === false){ @@ -351,16 +454,16 @@ class PMFLevel extends PMF{ public function fastGetBlockID($chunkX, $chunkY, $chunkZ, $blockX, $blockY, $blockZ, $index){ return ($this->chunks[$index][$chunkY] === false) ? 0 : ord($this->chunks[$index][$chunkY][$blockY + ($blockX << 5) + ($blockZ << 9)]); } - + public function getBlockID($x, $y, $z){ if($y > 127 || $y < 0){ return 0; } - + if($x < 0 || $x > 255 || $z < 0 || $z > 255){ return INVISIBLE_BEDROCK; } - + $X = $x >> 4; $Z = $z >> 4; $Y = $y >> 4; @@ -371,9 +474,9 @@ class PMFLevel extends PMF{ $aX = $x & 0xf; $aZ = $z & 0xf; $aY = $y & 0xf; - + $b = ord($this->chunks[$index][$Y][($aY + ($aX << 5) + ($aZ << 9))]); - + return $b; } @@ -381,12 +484,12 @@ class PMFLevel extends PMF{ if($x < 0 || $x > 255 || $z < 0 || $z > 255 || $y < 0 || $y > 127){ return false; } - + $X = $x >> 4; $Z = $z >> 4; $Y = $y >> 4; $block &= 0xFF; - + $index = self::getIndex($X, $Z); $aX = $x & 0xf; $aZ = $z & 0xf; @@ -397,8 +500,9 @@ class PMFLevel extends PMF{ }else{ $this->chunks[$index][$Y][$bind] = chr($block); if($block > 0) StaticBlock::getBlock($block)::onPlace($this->level, $x, $y, $z); + $this->level->updateLight(0, $x, $y, $z, $x, $y, $z); } - + if(!isset($this->chunkChange[$index][$Y])){ $this->chunkChange[$index][$Y] = 1; }else{ @@ -408,6 +512,55 @@ class PMFLevel extends PMF{ return true; } + public function getBlockLight($x, $y, $z){ + if($x < 0 || $x > 255 || $z < 0 || $z > 255 || $y < 0 || $y > 127 || !PocketMinecraftServer::$ENABLE_LIGHT_UPDATES) return 0; + $X = $x >> 4; + $Z = $z >> 4; + $Y = $y >> 4; + $index = self::getIndex($X, $Z); + if(!isset($this->chunks[$index]) || $this->chunks[$index] === false || ($this->chunks[$index][$Y] === false)) return 0; + $aX = $x & 0xf; + $aZ = $z & 0xf; + $aY = $y & 0xf; + $m = ord($this->chunks[$index][$Y][(int) (($aY >> 1) + 24 + ($aX << 5) + ($aZ << 9))]); + return $y & 1 ? $m >> 4 : $m & 0x0F; + } + + public function setBlockLight($x, $y, $z, $value){ + if($x < 0 || $x > 255 || $z < 0 || $z > 255 || $y < 0 || $y > 127 || !PocketMinecraftServer::$ENABLE_LIGHT_UPDATES) return false; + $X = $x >> 4; + $Z = $z >> 4; + $Y = $y >> 4; + $value &= 0x0F; + + $index = self::getIndex($X, $Z); + if(!isset($this->chunks[$index]) || $this->chunks[$index] === false){ + if($this->loadChunk($X, $Z) === false) return false; + }elseif($this->chunks[$index][$Y] === false){ + $this->fillMiniChunk($X, $Z, $Y); + } + + $aX = $x & 0xf; + $aZ = $z & 0xf; + $aY = $y & 0xf; + $mindex = (int) (($aY >> 1) + 24 + ($aX << 5) + ($aZ << 9)); + $old_m = ord($this->chunks[$index][$Y][$mindex]); + if(($y & 1) === 0) $m = ($old_m & 0xF0) | $value; + else $m = ($value << 4) | ($old_m & 0x0F); + + if($old_m != $m){ + $this->chunks[$index][$Y][$mindex] = chr($m); + if(!isset($this->chunkChange[$index][$Y])){ + $this->chunkChange[$index][$Y] = 1; + }else{ + ++$this->chunkChange[$index][$Y]; + } + $this->chunkChange[$index][-1] = true; + return true; + } + return false; + } + public function getBlockDamage($x, $y, $z){ if($x < 0 || $x > 255 || $z < 0 || $z > 255 || $y < 0 || $y > 127){ return 0; @@ -434,7 +587,7 @@ class PMFLevel extends PMF{ $Z = $z >> 4; $Y = $y >> 4; $damage &= 0x0F; - + $index = self::getIndex($X, $Z); $aX = $x & 0xf; $aZ = $z & 0xf; @@ -467,11 +620,11 @@ class PMFLevel extends PMF{ if($x < 0 || $x > 255 || $z < 0 || $z > 255){ return [INVISIBLE_BEDROCK, 0]; } - + $X = $x >> 4; $Z = $z >> 4; $Y = $y >> 4; - + $index = self::getIndex($X, $Z); if(!isset($this->chunks[$index]) || $this->chunks[$index] === false){ if($this->loadChunk($X, $Z) === false){ @@ -484,12 +637,12 @@ class PMFLevel extends PMF{ $aX = $x & 0xf; $aZ = $z & 0xf; $aY = $y & 0xf; - + $b = ord($this->chunks[$index][$Y][($aY + ($aX << 5) + ($aZ << 9))]); - + $m = ord($this->chunks[$index][$Y][(($aY >> 1) + 16 + ($aX << 5) + ($aZ << 9))]); $m = ($y & 1) ? $m >> 4 : $m & 0xf; - + return [$b, $m]; } @@ -517,7 +670,7 @@ class PMFLevel extends PMF{ $mindex = (int) (($aY >> 1) + 16 + ($aX << 5) + ($aZ << 9)); $old_b = ord($this->chunks[$index][$Y][$bindex]); $old_m = ord($this->chunks[$index][$Y][$mindex]); - + $m = ($y & 1) ? (($meta << 4) | ($old_m & 0x0F)) : (($old_m & 0xF0) | $meta); if($old_b !== $block or $old_m !== $m){ @@ -529,8 +682,9 @@ class PMFLevel extends PMF{ ++$this->chunkChange[$index][$Y]; } $this->chunkChange[$index][-1] = true; - + if($block > 0) StaticBlock::getBlock($block)::onPlace($this->level, $x, $y, $z); + $this->level->updateLight(0, $x, $y, $z, $x, $y, $z); return true; } return false; diff --git a/src/recipes/CraftingRecipes.php b/src/recipes/CraftingRecipes.php index e9ac25f6..e42a2da1 100644 --- a/src/recipes/CraftingRecipes.php +++ b/src/recipes/CraftingRecipes.php @@ -186,7 +186,7 @@ class CraftingRecipes{ "MOSSY_STONE:0x6=>STONE_WALL:1x6", "NETHER_BRICK:?x4=>NETHER_BRICKS:0x1", "NETHER_BRICKS:?x6=>NETHER_BRICKS_STAIRS:0x4", - "QUARTZ_BLOCK:0x2=>QUARTZ_BLOCK:2x2", + "QUARTZ_BLOCK:?x2=>QUARTZ_BLOCK:2x2", "QUARTZ_BLOCK:?x3=>SLAB:6x6", "SANDSTONE:0x6=>SANDSTONE_STAIRS:0x4", "SAND:?x4=>SANDSTONE:0x1", @@ -200,155 +200,162 @@ class CraftingRecipes{ "COBBLESTONE:?x6=>COBBLESTONE_STAIRS:0x4", ]; - /** - * Each element structure: - * * 0 - ingridients
- * * 1 - results
- * * 2 - recipe string
- * @var array[] - */ - private static $recipes = []; - + private static $craftingTableRecipes = []; + private static $inventoryRecipes = []; + private static $stoneCutterRecipes = []; + + private static $craftingTablePossibleResults = []; + private static $inventoryPossibleResults = []; + private static $stoneCutterPossibleResults = []; + + + public static function init(){ - $server = ServerAPI::request(); - $id = 1; + foreach(CraftingRecipes::$small as $recipe){ - $recipe = CraftingRecipes::parseRecipe($recipe); - $recipe[3] = self::TYPE_INVENTORY; //Type - CraftingRecipes::$recipes[$id] = $recipe; - ++$id; + CraftingRecipes::addRecipe($recipe, self::TYPE_INVENTORY); + CraftingRecipes::addRecipe($recipe, self::TYPE_CRAFTIGTABLE); } + foreach(CraftingRecipes::$big as $recipe){ - $recipe = CraftingRecipes::parseRecipe($recipe); - $recipe[3] = self::TYPE_CRAFTIGTABLE; - CraftingRecipes::$recipes[$id] = $recipe; - ++$id; + CraftingRecipes::addRecipe($recipe, self::TYPE_CRAFTIGTABLE); } + foreach(CraftingRecipes::$stone as $recipe){ - $recipe = CraftingRecipes::parseRecipe($recipe); - $recipe[3] = self::TYPE_STONECUTTER; - CraftingRecipes::$recipes[$id] = $recipe; - ++$id; - } - - foreach(CraftingRecipes::$recipes as $id => $recipe){ - $server->query("INSERT INTO recipes (id, type, recipe) VALUES (" . $id . ", " . $recipe[3] . ", '" . $recipe[2] . "');"); + CraftingRecipes::addRecipe($recipe, self::TYPE_STONECUTTER); } } - private static function parseRecipe($recipe){ + public static function fromString($str){ + [$idm, $cnt] = explode("x", $str); + [$id, $meta] = explode(":", $idm); + $id = BlockAPI::blockIDFromString($id); + + return [$id, ($meta == "?") ? "?" : ((int)$meta), (int)$cnt]; + } + + public static function addRecipe($recipe, $type){ [$ingridients, $results] = explode("=>", $recipe); - $recipeItems = []; - foreach(explode(",", $ingridients) 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()])){ - $recipeItems[$it->getID()] = [$it->getID(), $meta === "?" ? false : intval($meta) & 0xFFFF, intval($item[1])]; - }else{ - if($it->getMetadata() !== $recipeItems[$it->getID()][1]){ - $recipeItems[$it->getID()][1] = false; - } - $recipeItems[$it->getID()][2] += $it->count; - } + $results_arr = []; //indexed by id, must be rewritten in case some recipe will craft 2 items with same id but different metadata + foreach(explode(",", $results) as $res){ + [$id, $meta, $cnt] = self::fromString($res); + if($meta === "?") throw new RuntimeException("Unknown metadata in result when trying to add $recipe (type: $type)"); + $results_arr[$id] = "{$id}:{$meta}x{$cnt}"; } - ksort($recipeItems); + ksort($results_arr); + $result_index = implode(",", $results_arr); - $craftItems = []; - foreach(explode(",", $results) as $item){ - $item = explode("x", $item); - $id = explode(":", $item[0]); - $meta = array_pop($id); - $id = $id[0]; - $it = BlockAPI::fromString($id); - if(!isset($craftItems[$it->getID()])){ - $craftItems[$it->getID()] = [$it->getID(), intval($meta) & 0xffff, intval($item[1])]; - }else{ - if($it->getMetadata() !== $craftItems[$it->getID()][1]){ - $craftItems[$it->getID()][1] = false; - } - $craftItems[$it->getID()][2] += $it->count; - } - } - ksort($craftItems); - - $recipeString = ""; - $resultString = ""; - foreach($recipeItems as $item){ - $recipeString .= "{$item[0]}x{$item[2]},"; - } - foreach($craftItems as $item){ - $resultString .= "{$item[0]}x{$item[2]},"; + $ingridients_arr = []; + foreach(explode(",", $ingridients) as $resultstr){ + [$id, $meta, $cnt] = self::fromString($resultstr); + $ingridients_arr[] = [$id, $meta, $cnt]; + } + + switch($type){ + case self::TYPE_CRAFTIGTABLE: + $arr = &self::$craftingTableRecipes; + $arr_c = &self::$craftingTablePossibleResults; + break; + case self::TYPE_INVENTORY: + $arr = &self::$inventoryRecipes; + $arr_c = &self::$inventoryPossibleResults; + break; + case self::TYPE_STONECUTTER: + $arr = &self::$stoneCutterRecipes; + $arr_c = &self::$stoneCutterPossibleResults; + break; + default: + throw new RuntimeException("Unknown type: {$type}"); + } + + if(!isset($arr[$result_index])) $arr[$result_index] = []; + $arr[$result_index][] = $ingridients_arr; + + foreach($results_arr as $resitem){ + if(!isset($arr_c[$resitem])){ + $arr_c[$resitem] = []; + } + foreach($results_arr as $resitem2){ + $arr_c[$resitem][$resitem2] = true; + } } - $recipeString = substr($recipeString, 0, -1) . "=>" . substr($resultString, 0, -1); - - return [$recipeItems, $craftItems, $recipeString]; } + /** + * Checks can craft some item + * + * @param array $craftItems items that will be crafted + * @param array $recipeItems items that will be consumed + * @param int $type craft type (CraftingRecipes::TYPE_INVENTORY, CraftingRecipes::TYPE_CRAFTIGTABLE, CraftingRecipes::TYPE_STONECUTTER) + * @return array|true|false recipe that will be used or bool. If returned false, crafting will be aborted. If returned true crafting wont be aborted + */ public static function canCraft(array $craftItems, array $recipeItems, $type){ - ksort($recipeItems); - ksort($craftItems); - - $recipeString = ""; - $resultString = ""; - foreach($recipeItems as $item){ - $recipeString .= $item[0] . "x" . $item[2] . ","; + $craftIndexArr = []; + foreach($craftItems as $it){ + $craftIndexArr[$it[0]] = "{$it[0]}:{$it[1]}x{$it[2]}"; } - foreach($craftItems as $item){ - $resultString .= "{$item[0]}x{$item[2]},"; - } - - $recipeString = substr($recipeString, 0, -1) . "=>" . substr($resultString, 0, -1); - $server = ServerAPI::request(); - $result = $server->query("SELECT id FROM recipes WHERE type == " . $type . " AND recipe == '" . $recipeString . "';"); - if($result instanceof SQLite3Result){ - $continue = true; - while(($r = $result->fetchArray(SQLITE3_NUM)) !== false){ - $continue = true; - $recipe = CraftingRecipes::$recipes[$r[0]]; - foreach($recipe[0] as $item){ //check ingridients - if(!isset($recipeItems[$item[0]])){ - $continue = false; - break; - } - $oitem = $recipeItems[$item[0]]; - - if(($oitem[1] !== $item[1] and $item[1] !== false) or $oitem[2] !== $item[2]){ - $continue = false; - break; - } - } - if($continue === false){ - $continue = false; - continue; - } - foreach($recipe[1] as $item){ //check results - if(!isset($craftItems[$item[0]])){ - $continue = false; - break; - } - $oitem = $craftItems[$item[0]]; - - if(($oitem[1] !== $item[1] and $item[1] !== false) or $oitem[2] !== $item[2]){ - $continue = false; - break; - } - } - if($continue === false){ - $continue = false; - continue; - } - $continue = $recipe; + ksort($craftIndexArr); + $craftIndex = implode(",", $craftIndexArr); + switch($type){ + case self::TYPE_CRAFTIGTABLE: + $arr = &self::$craftingTableRecipes; + $arr_c = &self::$craftingTablePossibleResults; break; - } - }else{ - return true; + case self::TYPE_INVENTORY: + $arr = &self::$inventoryRecipes; + $arr_c = &self::$inventoryPossibleResults; + break; + case self::TYPE_STONECUTTER: + $arr = &self::$stoneCutterRecipes; + $arr_c = &self::$stoneCutterPossibleResults; + break; + default: + ConsoleAPI::error("Tried crafting recipe with unknown type {$type}!"); + return false; } - return $continue; + + if(!isset($arr[$craftIndex])) { //recipe for those ingridients was not found + $allcombos = $arr_c[current($craftIndexArr)] ?? []; + foreach($craftIndexArr as $res){ + if(!isset($allcombos[$res])){ + ConsoleAPI::info("Recipe with $craftIndex is not found. Crafting aborted. $res"); + return false; //recipe not found and wont be found + } + } + ConsoleAPI::info("Recipe with $craftIndex is not found but it might be found later. Crafting continued."); + return true; //recipe might be found next time + } + + foreach($arr[$craftIndex] as $ingridients){ + foreach($ingridients as $item){ + if($item[1] === "?"){ // any metadata is allowed + $needcnt = $item[2]; + foreach($recipeItems as $idmeta => $it){ + $id = $idmeta >> 16; + if($id != $item[0]) continue; + $needcnt -= $it[2]; + } + if($needcnt != 0) { + goto skip_recipe; + } + }else{ + $exceptedIndex = ($item[0] << 16) | ($item[1] & 0xffff); + if(!isset($recipeItems[$exceptedIndex])) { + goto skip_recipe; //dont check count if no idmeta pair is in ingridients + } + $it = $recipeItems[$exceptedIndex]; + if($it[0] != $item[0] || $it[1] != $item[1] || $it[2] != $item[2]) { + goto skip_recipe; + } + } + } + //recipe is correct + return [$craftItems, $ingridients]; + + skip_recipe: + } + return true; } } diff --git a/src/utils/Config.php b/src/utils/Config.php index a196879a..31ac1964 100644 --- a/src/utils/Config.php +++ b/src/utils/Config.php @@ -35,6 +35,9 @@ class Config{ * @var array */ private $config; + + private $comments; + /** * @var string */ @@ -54,8 +57,8 @@ class Config{ * @param array $default * @param null|boolean $correct */ - public function __construct($file, $type = CONFIG_DETECT, $default = [], &$correct = null){ - $this->load($file, $type, $default); + public function __construct($file, $type = CONFIG_DETECT, $default = [], &$correct = null, $comments = []){ + $this->load($file, $type, $default, comments:$comments); $correct = $this->check(); } @@ -66,13 +69,14 @@ class Config{ * * @return boolean */ - public function load($file, $type = CONFIG_DETECT, $default = []){ + public function load($file, $type = CONFIG_DETECT, $default = [], $comments = []){ $this->correct = true; $this->type = (int) $type; $this->file = $file; if(!is_array($default)){ $default = []; } + $this->comments = $comments; if(!file_exists($file)){ $this->config = $default; $this->save(); @@ -113,9 +117,8 @@ class Config{ if(!is_array($this->config)){ $this->config = $default; } - if($this->fillDefaults($default, $this->config) > 0){ - $this->save(); - } + $this->fillDefaults($default, $this->config); + $this->save(); }else{ return false; } @@ -158,6 +161,16 @@ class Config{ private function writeProperties(){ $content = "#Properties Config file\r\n#" . date("D M j H:i:s T Y") . "\r\n"; foreach($this->config as $k => $v){ + //evil \r\n + if(isset($this->comments[$k])){ + $com = $this->comments[$k]; + $gen = ""; + if(!is_array($com)) $gen .= "#$com\r\n"; + else{ + foreach($com as $lin) $gen .= "#$lin\r\n"; + } + $content .= $gen; + } if(is_bool($v) === true){ $v = $v === true ? "on" : "off"; }elseif(is_array($v)){ @@ -169,7 +182,12 @@ class Config{ } private function parseProperties($content){ - if(preg_match_all('/([a-zA-Z0-9\-_\.]*)=([^\r\n]*)/u', $content, $matches) > 0){ //false or 0 matches + $content2 = ""; + foreach(explode("\n", $content) as $cnt){ //regex is very evil and malicious + if((trim($cnt)[0] ?? "") == "#") continue; + $content2 .= $cnt . "\n"; + } + if(preg_match_all("/([a-zA-Z0-9\-_\.]*)=([^\r\n]*)/u", $content2, $matches) > 0){ //false or 0 matches foreach($matches[1] as $i => $k){ $v = trim($matches[2][$i]); switch(strtolower($v)){ diff --git a/src/utils/Utils.php b/src/utils/Utils.php index c3cb47f3..66c36938 100644 --- a/src/utils/Utils.php +++ b/src/utils/Utils.php @@ -21,25 +21,25 @@ class Utils{ default => $id, }; } - + public static function wrapAngleTo360($angle) { $angle = fmod($angle, 360); return $angle < 0 ? $angle + 360 : $angle; } - + public static function getSeedNumeric($seed){ if($seed === "") return false; - elseif(is_int($seed)) return (int) $seed; + elseif(is_int($seed)) return (int)$seed; else{ $i = 0; for($j = 0; $j < strlen($seed); ++$j){ $i = $i * 31 + ord($seed[$j]); } - return (int) $i; + return (int)$i; } } - + public static function sint32($r){ $r &= 0xFFFFFFFF; if ($r & 0x80000000) @@ -49,11 +49,11 @@ class Utils{ } return $r; } - + public static function wrapAngleTo180($angle) { $angle = fmod($angle, 360); - + if($angle >= 180) $angle -= 360; if($angle < -180) $angle += 360; return $angle; @@ -61,22 +61,26 @@ class Utils{ public static function getSign($v){ return $v <=> 0; } - + public static function clampDegrees($v){ return floor(($v % 360 + 360) % 360); } - + /** * PHP8 has internal function for doing it: {@link str_ends_with} */ public static function endsWith($str, $check) { return str_ends_with($str, $check); } - + public static function hasEmoji($s){ return preg_match(Utils::emojiRegex, $s); } - + + public static function replaceEmoji($s){ + return preg_replace(Utils::emojiRegex, " ", $s); + } + public static function getCallableIdentifier(callable $variable){ if(is_array($variable)){ return sha1(strtolower(get_class($variable[0])) . "::" . strtolower($variable[1])); @@ -84,11 +88,11 @@ class Utils{ return sha1(strtolower($variable)); } } - + public static function in_range($num, $min, $max){ return $num >= $min && $num <= $max; } - + public static function getUniqueID($raw = false, $extra = ""){ $machine = php_uname("a"); $machine .= file_exists("/proc/cpuinfo") ? `cat /proc/cpuinfo | grep "model name"` : ""; @@ -181,7 +185,7 @@ class Utils{ return Utils::$ip; } - + public static function makeHeaders($json){ $arr = json_decode($json); $rarr = []; @@ -190,12 +194,12 @@ class Utils{ } return $rarr; } - + public static function curl_get($page, $timeout = 10, $headers = " "){ if(Utils::$online === false){ return false; } - + if($headers != " "){ $headers = Utils::makeHeaders($headers); }else{ @@ -431,9 +435,9 @@ class Utils{ } return $data; } - + public static function readTriad($str){ - return strlen($str) < 3 ? false : @unpack("N", "\x00$str")[1]; + return strlen($str) < 3 ? 0 : @unpack("N", "\x00$str")[1]; //make sure this returns 0 on failure instead of false or else raknet parser will fall into infinite loop if start is false } public static function writeDataArray($data){ @@ -444,11 +448,11 @@ class Utils{ } return $raw; } - + public static function writeLTriad($value){ return substr(pack("V", $value), 0, -1); } - + public static function writeTriad($value){ return substr(pack("N", $value), 1); } @@ -456,11 +460,11 @@ class Utils{ public static function getRandomBytes($length = 16, $secure = true, $raw = true, $startEntropy = "", &$rounds = 0, &$drop = 0){ return $raw ? random_bytes($length) : bin2hex(random_bytes($length)); //nobody would ever notice other parameters } - + public static function chance($i){//GameHerobrine's code return lcg_value() <= $i / 100; } - + /** * @deprecated use lcg_value instead */ @@ -481,10 +485,10 @@ class Utils{ if($pos2 instanceof Vector3){ $pos2 = $pos2->toArray(); } - + return abs($pos2["x"] - $pos1["x"]) + abs($pos2["y"] - $pos1["y"]) + abs($pos2["z"] - $pos1["z"]); } - + /** * Euclidian distance, but without square roots */ @@ -498,11 +502,13 @@ class Utils{ $pX = ($pos1["x"] - $pos2["x"]); $pY = ($pos1["y"] - $pos2["y"]); $pZ = ($pos1["z"] - $pos2["z"]); - return ($pX * $pX) + ($pY * $pY) + ($pZ * $pZ); + return ($pX*$pX) + ($pY*$pY) + ($pZ*$pZ); } - + /** - * + * + * @param $pos1 + * @param $pos2 * @return number */ public static function distance($pos1, $pos2){ @@ -512,9 +518,9 @@ class Utils{ if($pos2 instanceof Vector3){ $pos2 = $pos2->toArray(); } - return sqrt(($pos1["x"] - $pos2["x"]) * ($pos1["x"] - $pos2["x"]) + ($pos1["y"] - $pos2["y"]) * ($pos1["y"] - $pos2["y"]) + ($pos1["z"] - $pos2["z"]) * ($pos1["z"] - $pos2["z"])); + return sqrt(($pos1["x"] - $pos2["x"])*($pos1["x"] - $pos2["x"]) + ($pos1["y"] - $pos2["y"])*($pos1["y"] - $pos2["y"]) + ($pos1["z"] - $pos2["z"])*($pos1["z"] - $pos2["z"])); } - + public static function angle3D($pos1, $pos2){ if($pos1 instanceof Vector3){ $pos1 = $pos1->toArray(); @@ -570,8 +576,8 @@ class Utils{ } public static function readInt($str){ - if(strlen($str) <= 0) return; - + if(strlen($str) < 4) return 0; + return @unpack("N", $str)[1] << 32 >> 32; //php has no signed long unpack } @@ -583,7 +589,8 @@ class Utils{ } public static function readFloat($str){ - list(, $value) = unpack("G", $str); + if(strlen($str) < 4) return 0; + list(, $value) = @unpack("G", $str); return $value; } @@ -605,6 +612,7 @@ class Utils{ } public static function readLDouble($str){ + if(strlen($str) < 8) return 0; list(, $value) = @unpack("e", $str); return $value; } @@ -614,6 +622,7 @@ class Utils{ } public static function readLLong($str){ + if(strlen($str) < 8) return 0; return unpack("P", $str)[1]; } diff --git a/src/utils/XorShift128Random.php b/src/utils/XorShift128Random.php new file mode 100644 index 00000000..0e69b02a --- /dev/null +++ b/src/utils/XorShift128Random.php @@ -0,0 +1,56 @@ +setSeed($seed === null ? microtime(true) : $seed); + } + + public function nextGaussian(){ + if($this->haveNextNextGaussian){ + $this->haveNextNextGaussian = false; + return $this->nextNextGaussian; + }else{ + do{ + $v1 = 2 * $this->nextFloat() - 1; // between -1.0 and 1.0 + $v2 = 2 * $this->nextFloat() - 1; // between -1.0 and 1.0 + $s = $v1 * $v1 + $v2 * $v2; + }while($s >= 1 || $s == 0); + $multiplier = sqrt(-2 * log($s) / $s); + $this->nextNextGaussian = $v2 * $multiplier; + $this->haveNextNextGaussian = true; + return $v1 * $multiplier; + } + } + + public function setSeed($seed){ + $seed = (int)$seed; + $this->x = 123456789 ^ $seed; + $this->y = 362436069 ^ ($seed << 17) | (($seed >> 15) & 0x7fffffff) & 0xffffffff; + $this->z = 521288629 ^ ($seed << 31) | (($seed >> 1 ) & 0x7fffffff) & 0xffffffff; + $this->w = 88675123 ^ ($seed << 18) | (($seed >> 14) & 0x7fffffff) & 0xffffffff; + } + + public function gen(){ + $t = ($this->x ^ ($this->x << 11)) & 0xffffffff; + $this->x = $this->y; + $this->y = $this->z; + $this->z = $this->w; + $this->w = ($this->w ^ (($this->w >> 19) & 0x7fffffff) ^ ($t ^ (($t >> 8) & 0x7fffffff))) & 0xffffffff; + + return $this->w << 32 >> 32; + } + + public function nextInt($bound = null){ + if($bound == null) return $this->gen(); + return (($this->gen() & 0x7fffffff) % $bound); + } + + public function nextFloat(){ + return (($this->gen() & 0x7fffffff) / 0x7fffffff); + } +} diff --git a/src/world/Explosion.php b/src/world/Explosion.php index b92e614d..abbbd233 100644 --- a/src/world/Explosion.php +++ b/src/world/Explosion.php @@ -1,16 +1,10 @@ DIRT, - STONE => COBBLESTONE, - COAL_ORE => COAL, - DIAMOND_ORE => DIAMOND, - REDSTONE_ORE => REDSTONE, - ]; public static $enableExplosions = true; - public $level; //Rays + /** @var Level */ + public $level; + /** @var Position */ public $source; public $size; public $affectedBlocks = []; @@ -18,7 +12,7 @@ class Explosion{ private $rays = 16; private $air; private $nullPlayer; - + public function __construct(Position $center, $size){ $this->level = $center->level; $this->source = $center; @@ -26,12 +20,12 @@ class Explosion{ $this->air = BlockAPI::getItem(AIR, 0, 1); $this->nullPlayer = new PlayerNull(); } - + public function sub_expl($i, $mRays, $j, $k){ $vx = $i / $mRays * 2 - 1; $vy = $j / $mRays * 2 - 1; $vz = $k / $mRays * 2 - 1; - $vlen = sqrt($vx * $vx + $vy * $vy + $vz * $vz); + $vlen = sqrt($vx*$vx + $vy*$vy + $vz*$vz); if($vlen != 0){ $vx = $vx / $vlen * $this->stepLen; $vy = $vy / $vlen * $this->stepLen; @@ -39,7 +33,7 @@ class Explosion{ }else{ $vx = $vy = $vz = 0; } - + $px = $this->source->x; $py = $this->source->y; $pz = $this->source->z; @@ -64,19 +58,19 @@ class Explosion{ $pz += $vz; } } - + public function explode(){ $radius = 2 * $this->size; $server = ServerAPI::request(); if(!Explosion::$enableExplosions){ /*Disable Explosions*/ - foreach($server->api->entity->getRadius($this->source, $radius + 1) as $entity){ + foreach($server->api->entity->getRadius($this->source, $radius+1) as $entity){ $distance = $this->source->distance($entity); $distByRad = $distance / $this->size; if($distByRad <= 1 && $distance != 0){ $diffX = ($entity->x - $this->source->x) / $distance; $diffY = ($entity->y + $entity->getEyeHeight() - $this->source->y) / $distance; $diffZ = ($entity->z - $this->source->z) / $distance; - + $impact = (1 - $distByRad) * 0.5; //TODO calculate block density around the entity instead of 0.5 $damage = (int) (($impact * $impact + $impact) * 8 * $this->size + 1); if($damage > 0){ @@ -84,25 +78,27 @@ class Explosion{ $entity->speedX = $diffX * $impact; $entity->speedY = $diffY * $impact; $entity->speedZ = $diffZ * $impact; - + if($entity->isPlayer()){ $pk = new SetEntityMotionPacket(); $pk->eid = 0; //XXX change $pk->speedX = $entity->speedX; $pk->speedY = $entity->speedY; $pk->speedZ = $entity->speedZ; - $entity->player->dataPacket($pk); + $entity->player->entityQueueDataPacket($pk); } } } } - $pk = new ExplodePacket; //sound fix + $pk = new ExplodePacket; $pk->x = $this->source->x; $pk->y = $this->source->y; $pk->z = $this->source->z; $pk->radius = $this->size; - $pk->records = []; - $server->api->player->broadcastPacket($this->level->players, $pk); + $pk->records = []; //ExplodePacket doesnt seem to use the records provided by this packet, so no need to send more data + foreach ($this->level->players as $player){ + $player->blockQueueDataPacket(clone $pk); + } return; } if($this->size < 0.1 or $server->api->dhandle("entity.explosion", [ @@ -112,7 +108,7 @@ class Explosion{ ]) === false){ return false; } - + $mRays = $this->rays - 1; $i = 0; for($j = 0; $j <= $mRays; ++$j){ @@ -126,21 +122,21 @@ class Explosion{ $this->sub_expl($i, $mRays, $j, $k); } } - + $j = 0; for($i = 1; $i < $mRays; ++$i){ for($k = 0; $k <= $mRays; ++$k){ $this->sub_expl($i, $mRays, $j, $k); } } - + $j = $mRays; for($i = 1; $i < $mRays; ++$i){ for($k = 0; $k <= $mRays; ++$k){ $this->sub_expl($i, $mRays, $j, $k); } } - + $k = 0; for($i = 1; $i < $mRays; ++$i){ for($j = 1; $j < $mRays; ++$j){ @@ -153,9 +149,7 @@ class Explosion{ $this->sub_expl($i, $mRays, $j, $k); } } - //if($i == 0 or $i == $mRays or $j == 0 or $j == $mRays or $k == 0 or $k == $mRays){ - - $send = []; + foreach($server->api->entity->getRadius($this->source, $radius) as $entity){ $distance = $this->source->distance($entity); $distByRad = $distance / $this->size; @@ -163,34 +157,34 @@ class Explosion{ $diffX = ($entity->x - $this->source->x) / $distance; $diffY = ($entity->y + $entity->getEyeHeight() - $this->source->y) / $distance; $diffZ = ($entity->z - $this->source->z) / $distance; - - $impact = (1 - $distByRad) * 0.5; //TODO calculate block density around the entity instead of 0.5 + + $impact = (1 - $distByRad) * 0.5; //TODO calculate block density around the entity instead of 0.5 $damage = (int) (($impact * $impact + $impact) * 8 * $this->size + 1); if($damage > 0){ $entity->harm($damage, "explosion"); $entity->speedX = $diffX * $impact; $entity->speedY = $diffY * $impact; $entity->speedZ = $diffZ * $impact; - + if($entity->isPlayer()){ $pk = new SetEntityMotionPacket(); $pk->eid = 0; //XXX change $pk->speedX = $entity->speedX; $pk->speedY = $entity->speedY; $pk->speedZ = $entity->speedZ; - $entity->player->dataPacket($pk); + $entity->player->entityQueueDataPacket($pk); } } } } - + foreach($this->affectedBlocks as $xyz => $idm){ $id = $idm >> 8 & 0xff; $meta = $idm & 0x0f; $x = $xyz >> 16; $z = $xyz >> 8 & 0xff; $y = $xyz & 0xff; - //console("$x $y $z $id $meta"); + if($id === TNT){ $data = [ "x" => $x + 0.5, @@ -211,14 +205,22 @@ class Explosion{ } } $this->level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); - $send[] = $xyz; } + $pk = new ExplodePacket; $pk->x = $this->source->x; $pk->y = $this->source->y; $pk->z = $this->source->z; $pk->radius = $this->size; - $pk->records = $send; - $server->api->player->broadcastPacket($this->level->players, $pk); + $pk->records = []; //ExplodePacket doesnt seem to use the records provided by this packet, so no need to send more data + foreach ($this->level->players as $player){ + $player->blockQueueDataPacket(clone $pk); + } } + + + /** + * @deprecated unused + */ + public static $specialDrops = []; } diff --git a/src/world/Level.php b/src/world/Level.php index 200d91a9..779afa59 100644 --- a/src/world/Level.php +++ b/src/world/Level.php @@ -1,32 +1,33 @@ true, FARMLAND => true, @@ -42,10 +43,13 @@ class Level{ WHEAT_BLOCK => true, DIRT => true, GRASS => true, + LEAVES => true, + SNOW_LAYER => true, ICE => true, - LEAVES => true + RED_MUSHROOM => true, + BROWN_MUSHROOM => true ]; - + public function __construct(PMFLevel $level, Config $entities, Config $tiles, Config $blockUpdates, $name){ $this->server = ServerAPI::request(); $this->level = $level; @@ -70,31 +74,48 @@ class Level{ } public function close(){ - $this->__destruct(); + if(isset($this->level)){ + $this->save(true, true, true, true); + $this->server->api->block->removeAllBlockUpdates($this); + foreach($this->server->api->player->getAll($this) as $player){ + $player->teleport($this->server->spawn); + } + foreach($this->entityList as $entity){ + if($entity->class !== ENTITY_PLAYER){ + $entity->close(); + } + } + foreach($this->server->api->tile->getAll($this) as $tile){ + $tile->close(); + } + $this->level->close(); + unset($this->level); + } + unset($this->mobSpawner->level); } - + 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; - + return true; } public function rayTraceBlocks(Vector3 $start, Vector3 $end){ - + $par3 = false; //TODO move to params? $par4 = true; - + $xStart = floor($start->x); $yStart = floor($start->y); $zStart = floor($start->z); $xEnd = floor($end->x); $yEnd = floor($end->y); $zEnd = floor($end->z); - + [$startID, $startMeta] = $this->level->getBlock($xStart, $yStart, $zStart); $block = StaticBlock::getBlock($startID); @@ -104,66 +125,66 @@ class Level{ $v14 = $block::clip($this, $xStart, $yStart, $zStart, $start, $end); if($v14 != null) return $v14; } - + 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? 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($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; - + $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){ $v42 = $xEnd > $xStart ? 4 : 5; - + $start->x = $v15; $start->y += $v29 * $v21; $start->z += $v31 * $v21; }elseif($v23 < $v25){ $v42 = $yEnd > $yStart ? 0 : 1; - + $start->x += $v27 * $v23; $start->y = $v17; $start->z += $v31 * $v23; }else{ $v42 = $zEnd > $zStart ? 2 : 3; - + $start->x += $v27 * $v25; $start->y += $v29 * $v25; $start->z = $v19; } - + $xStart = floor($start->x); if($v42 == 5) --$xStart; - + $yStart = floor($start->y); if($v42 == 1) --$yStart; - + $zStart = floor($start->z); if($v42 == 3) --$zStart; - + [$blockID, $blockMeta] = $this->level->getBlock($xStart, $yStart, $zStart); $block = StaticBlock::getBlock($blockID); @@ -173,10 +194,10 @@ class Level{ if($v38 != null) return $v38; } } - + return null; } - + public function isLavaInBB($aabb){ $minX = floor($aabb->minX); $maxX = floor($aabb->maxX + 1); @@ -184,48 +205,49 @@ class Level{ $maxY = floor($aabb->maxY + 1); $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){ $blockId = $this->level->getBlockID($x, $y, $z); - + if($blockId == LAVA || $blockId == STILL_LAVA) return true; } } } - + return false; } - - public function handleMaterialAcceleration(AxisAlignedBB $aabb, $materialType, Entity $entity){ + + public function handleMaterialAcceleration(AxisAlignedBB $aabb, Material $material, Entity $entity){ $minX = floor($aabb->minX); $maxX = ceil($aabb->maxX); $minY = floor($aabb->minY); $maxY = ceil($aabb->maxY); $minZ = floor($aabb->minZ); $maxZ = ceil($aabb->maxZ); - + //1.5.2 checks that all chunks exist, not needed here i think - + $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){ [$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 + $mat = StaticBlock::getMaterial($block); + if($material == $mat){ $v16 = ($y + 1) - LiquidBlock::getPercentAir($meta); if($maxY >= $v16){ $appliedVelocity = true; StaticBlock::$prealloc[$block]::addVelocityToEntity($this, $x, $y, $z, $entity, $velocityVec); } - + } } } } - + if($velocityVec->length() > 0){ //also checks is player flying $velocityVec = $velocityVec->normalize(); //TODO do not use vec methods $v18 = 0.014; @@ -233,10 +255,12 @@ class Level{ $entity->speedY += $velocityVec->y * $v18; $entity->speedZ += $velocityVec->z * $v18; } - + return $appliedVelocity; } /** + * @param Entity $e + * @param AxisAlignedBB $aABB * @return AxisAlignedBB[] */ public function getCubes(Entity $e, AxisAlignedBB $aABB) { @@ -247,34 +271,29 @@ class Level{ $y1 = floor($aABB->maxY + 1); $z0 = floor($aABB->minZ); $z1 = floor($aABB->maxZ + 1); - + for($x = $x0; $x < $x1; ++$x) { for($z = $z0; $z < $z1; ++$z) { for($y = $y0 - 1; $y < $y1; ++$y) { $bid = $this->level->getBlockID($x, $y, $z); 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; + if($aABB->intersectsWith_($blockBound)) $aABBs[] = $blockBound; } } } } } - + return $aABBs; } - + public function __destruct(){ - if(isset($this->level)){ - $this->save(false, false, false, false); - $this->level->close(); - unset($this->level); - } - unset($this->mobSpawner->level); + $this->close(); } - + public function isDay(){ return $this->getTime() % 19200 < TimeAPI::$phases["sunset"]; } @@ -292,7 +311,7 @@ class Level{ if($entities){ $entities = []; - + foreach($this->entityList as $entity){ if($entity instanceof Entity){ $entities[] = $entity->createSaveData(); @@ -353,7 +372,7 @@ class Level{ 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()){ return false; //not the same world @@ -366,12 +385,12 @@ class Level{ } } 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 + if($this->server->api->time->getPhase($this) === "night"){ //TODO vanilla foreach($this->players as $p){ if(!$p->isSleeping || $p->sleepingTime < 100){ return false; @@ -380,17 +399,17 @@ class Level{ $this->server->api->time->set("day", $this); } foreach($this->players as $p){ - $p->stopSleep(); + if($p->isSleeping) $p->stopSleep(); } } - + 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){ arsort($this->changedCount); $reorder = false; @@ -405,30 +424,31 @@ class Level{ unset($this->changedBlocks[$index]); } $this->changedCount = []; - + if($reorder){ foreach($this->players as $p){ $p->orderChunks(); } } - + 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; - $pk->z = ($b >> 16) & 0xff; - $pk->block = ($b >> 8) & 0xff; - $pk->meta = $b & 0xff; - $this->server->api->player->broadcastPacket($this->players, $pk); + $x = ($b >> 32) & 0xff; + $y = ($b >> 24) & 0xff; + $z = ($b >> 16) & 0xff; + $id =($b >> 8) & 0xff; + $meta = $b & 0xff; + foreach($this->players as $p){ + $p->addBlockUpdateIntoQueue($x, $y, $z, $id, $meta); + } } unset($this->changedBlocks[$i]); } $this->changedBlocks = []; } } - + if($this->nextSave < $now){ $this->save(false, true, true, true); } @@ -473,29 +493,29 @@ class Level{ $this->updateNeighborsAt($x, $y, $z, $id); } } - + 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); $block = $this->level->getBlockID($x + 1, $y, $z); 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); $block = $this->level->getBlockID($x, $y + 1, $z); 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); $block = $this->level->getBlockID($x, $y, $z + 1); 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){ $oldID = $this->level->getBlockID($x, $y, $z); - + $this->level->setBlock($x, $y, $z, $id, $meta); - + if($tiles){ //TODO rewrite $this->server->api->tile->invalidateAll($this, $x, $y, $z); } @@ -504,19 +524,215 @@ class Level{ } $this->addBlockToSendQueue($x, $y, $z, $id, $meta); } - + /** + * Contains light updates. Light update is an integer that contains min/max block coords and light layer + * Format: 0011ffeeddccbbaa + * 00 - unused(8th byte) + * 11 - light layer(currently must be 0(block), future: 15(sky)) + * ff, ee, dd - minX, minY, minZ + * cc, bb, aa - maxX, maxY, maxZ + * @var int[] + */ + public $lightUpdates = []; + public $lightUpdateIndx = -1; + public function handleBlockLightUpdate($minX, $minY, $minZ, $maxX, $maxY, $maxZ){ + if(!PocketMinecraftServer::$ENABLE_LIGHT_UPDATES) return; + for($x = $minX; $x <= $maxX; ++$x){ + for($z = $minZ; $z <= $maxZ; ++$z){ + for($y = $minY; $y <= $maxY; ++$y){ + $brightness = $this->level->getBlockLight($x, $y, $z); + $blockID = $this->level->getBlockID($x, $y, $z); + $lightBlock = StaticBlock::$lightBlock[$blockID]; + if($lightBlock == 0) $lightBlock = 1; + $lightEmission = StaticBlock::$lightEmission[$blockID]; + $newBrightness = 0; + if($lightBlock <= 14 || $lightEmission != 0){ + $xNegBright = $this->level->getBlockLight($x-1, $y, $z); + $xPosBright = $this->level->getBlockLight($x+1, $y, $z); + $yNegBright = $this->level->getBlockLight($x, $y-1, $z); + $yPosBright = $this->level->getBlockLight($x, $y+1, $z); + $zNegBright = $this->level->getBlockLight($x, $y, $z-1); + $zPosBright = $this->level->getBlockLight($x, $y, $z+1); + + $v15 = $xNegBright; + if($xPosBright > $v15) $v15 = $xPosBright; + if($yNegBright > $v15) $v15 = $yNegBright; + if($yPosBright > $v15) $v15 = $yPosBright; + if($zNegBright > $v15) $v15 = $zNegBright; + if($zPosBright > $v15) $v15 = $zPosBright; + + $newBrightness = $v15 - $lightBlock; + if($newBrightness < 0) $newBrightness = 0; + if($lightEmission > $newBrightness) $newBrightness = $lightEmission; + } + + if($brightness != $newBrightness){ + $this->level->setBlockLight($x, $y, $z, $newBrightness); + $v4 = $newBrightness - 1; + if($v4 < 0) $v4 = 0; + $this->updateLightIfOtherThan(0, $x-1, $y, $z, $v4); + $this->updateLightIfOtherThan(0, $x, $y-1, $z, $v4); + $this->updateLightIfOtherThan(0, $x, $y, $z-1, $v4); + if($x+1 >= $maxX) $this->updateLightIfOtherThan(0, $x+1, $y, $z, $v4); + if($y+1 >= $maxY) $this->updateLightIfOtherThan(0, $x, $y+1, $z, $v4); + if($z+1 >= $maxZ) $this->updateLightIfOtherThan(0, $x, $y, $z+1, $v4); + } + } + } + } + } + + /** + * Gets block brightness based on skylight, blocklight and subtracts skyDarken. + * @param int $x + * @param int $y + * @param int $z + */ + public function getRawBrightness(int $x, int $y, int $z){ + //TODO special way to do it for some blocks + + $bl = $this->level->getBlockLight($x, $y, $z); + $l = 0; ///*$this->level->getBrightness(LIGHTLAYER_SKY, $x, $y, $z)*/ (15 - $this->skyDarken); no skylight is implemnted + if($bl > $l) $l = $bl; + if($l < 0) $l = 0; + return $l; + } + + /** + * Schedules light update. Make sure to check that coordinates are in range. + * @param int $layer - light layer(0 - block, 15 - sky(not implemented as of now)). + * @param int $minX - must be in range (0, 255). Must be less than maxX. + * @param int $minY - must be in range (0, 127). Must be less than maxY. + * @param int $minZ - must be in range (0, 255). Must be less than maxZ. + * @param int $maxX - must be in range (0, 255). Must be more than minX. + * @param int $maxY - must be in range (0, 127). Must be more than minY. + * @param int $maxZ - must be in range (0, 255). Must be more than minZ. + */ + public function updateLight($layer, $minX, $minY, $minZ, $maxX, $maxY, $maxZ){ + if(!PocketMinecraftServer::$ENABLE_LIGHT_UPDATES) return; + /*$max = 5; //no idea is it needed for block light + $sz = $this->lightUpdateIndx; + if($sz < $max) $max = $sz; + for($i = 0; $i < $max; ++$i){ + $upd = $this->lightUpdates[$i]; + $llayer = $upd >> 48; + + if($layer == $llayer){ + $maZ = $upd & 0xff; + $maY = ($upd >> 8) & 0xff; + $maX = ($upd >> 16) & 0xff; + $miZ = ($upd >> 24) & 0xff; + $miY = ($upd >> 32) & 0xff; + $miX = ($upd >> 40) & 0xff; + if($miX <= $minX && $miY <= $minY && $miZ <= $minZ && $maX >= $maxX && $maY >= $maxY && $maZ >= $maxZ){ + //console("light happen is scheduled to happen already"); + return; + } + if($miX-1 > $minX || $miY-1 > $minY || $miZ-1 > $minZ || $maX+1 < $maxX || $maY+1 < $maxY || $maZ+1 < $maxZ){ + continue; + } + if($miX < $minX) $minX = $miX; + if($miY < $minY) $minY = $miY; + if($miZ < $minZ) $minZ = $miZ; + if($maX > $maxX) $maxX = $maX; + if($maY > $maxY) $maxY = $maY; + if($maZ > $maxZ) $maxZ = $maZ; + + if((($maxZ-$minZ)*($maX-$minY)*($maxX-$minX) - ($maX-$miX)*($maZ-$miZ)*($maY-$miY)) > 2){ + continue; + } + + $indx = $i; + goto update_light_in_array; + } + }*/ + $indx = ++$this->lightUpdateIndx; + /*if($maxX < $minX){ + $s = $minX; + $minX = $maxX; + $maxX = $s; + } + if($maxY < $minY){ + $s = $minY; + $minY = $maxY; + $maxY = $s; + } + if($maxZ < $minZ){ + $s = $minZ; + $minZ = $maxZ; + $maxZ = $s; + } + + update_light_in_array: + if($minX < 0) $minX = 0; + if($minX > 255) $minX = 255; + if($minY < 0) $minY = 0; + if($minY > 127) $minY = 127; + if($minZ < 0) $minZ = 0; + if($minZ > 255) $minZ = 255; + + if($maxX < 0) $minX = 0; + if($maxX > 255) $minX = 255; + if($maxY < 0) $minY = 0; + if($maxY > 127) $minY = 127; + if($maxZ < 0) $maxZ = 0; + if($maxZ > 255) $maxZ = 255;*/ + + $update = ($layer << 48) | ($minX << 40) | ($minY << 32) | ($minZ << 24) | ($maxX << 16) | ($maxY << 8) | ($maxZ); + $this->lightUpdates[$indx] = $update; + } + + public function updateLightIfOtherThan($layer, $x, $y, $z, $level){ + if($y < 0 || $y > 127 || $x < 0 || $x > 255 || $z < 0 || $z > 255) return; + if($layer == 0){ + $blockID = $this->level->getBlockID($x, $y, $z); + $emission = StaticBlock::$lightEmission[$blockID]; + if($emission > $level) $level = $emission; + + if($this->level->getBlockLight($x, $y, $z) != $level){ + $this->updateLight($layer, $x, $y, $z, $x, $y, $z); + } + } + } + public function updateLights(){ + if($this->lightUpdateIndx < 0) return false; + $limit = 500; + do{ + $upd = $this->lightUpdates[$this->lightUpdateIndx]; + unset($this->lightUpdates[$this->lightUpdateIndx]); + --$this->lightUpdateIndx; + $maxZ = $upd & 0xff; + $maxY = ($upd >> 8) & 0xff; + $maxX = ($upd >> 16) & 0xff; + $minZ = ($upd >> 24) & 0xff; + $minY = ($upd >> 32) & 0xff; + $minX = ($upd >> 40) & 0xff; + $layer = $upd >> 48; + if($layer == 0) $this->handleBlockLightUpdate($minX, $minY, $minZ, $maxX, $maxY, $maxZ); + else console("wha"); + if(!--$limit) return true; + }while($this->lightUpdateIndx >= 0); + if(count($this->lightUpdates) > 0) return true; + $this->lightUpdates = []; //php uses a lot of memory without this thing if it performed a lot of light updates + return false; + } public function onTick(PocketMinecraftServer $server, $currentTime){ + $this->level->forceLightUpdatesIfNeeded(); + 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; + $ch = &$this->level->chunks[$index]; 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); + $cy = $ch[$y >> 4]; + if($cy === false) continue; + $id = ord($cy[($y & 0xf) + ($x << 5) + ($z << 9)]); if(isset(self::$randomUpdateBlocks[$id])){ $cl = StaticBlock::$prealloc[$id]; $cl::onRandomTick($this, ($cX << 4) + $x, $y, $z + ($cZ << 4)); @@ -524,9 +740,10 @@ class Level{ } } } + $this->totalMobsAmount = 0; $post = []; - + foreach($this->entityList as $k => $e){ if(!($e instanceof Entity)){ unset($this->entityList[$k]); @@ -534,42 +751,41 @@ class Level{ //TODO try to remove from $entityListPositioned? continue; } - + $dd = CORRECT_ENTITY_CLASSES[$e->class] ?? false; if($dd === false || ($dd !== true && !isset($dd[$e->type]))){ ConsoleAPI::warn("Entity $k has invalid entity! {$e->class} {$e->type}"); $e->close(); - + unset($this->entityList[$k]); unset($this->server->entities[$k]); - - $curChunkX = (int) $e->x >> 4; - $curChunkZ = (int) $e->z >> 4; + + $curChunkX = (int)$e->x >> 4; + $curChunkZ = (int)$e->z >> 4; $index = "$curChunkX $curChunkZ"; - + if(isset($this->entityListPositioned[$index][$k])){ unset($this->entityListPositioned[$index][$k]); } - + continue; } - $curChunkX = (int) $e->x >> 4; - $curChunkZ = (int) $e->z >> 4; + $curChunkX = (int)$e->x >> 4; + $curChunkZ = (int)$e->z >> 4; if($e->class === ENTITY_MOB && !$e->isPlayer()){ ++$this->totalMobsAmount; } - if($e->isPlayer() || $e->needsUpdate){ - $e->update($currentTime); - if(!$e->isPlayer()) $post[] = $k; - } - + + $e->update($currentTime); + if(!$e->isPlayer()) $post[] = $k; + if($e instanceof Entity){ - $newChunkX = (int) $e->x >> 4; - $newChunkZ = (int) $e->z >> 4; + $newChunkX = (int)$e->x >> 4; + $newChunkZ = (int)$e->z >> 4; if($e->chunkX != $newChunkX || $e->chunkZ != $newChunkZ){ $oldIndex = "{$e->chunkX} {$e->chunkZ}"; unset($this->entityListPositioned[$oldIndex][$e->eid]); - + if($e->level == $this){ $e->chunkX = $newChunkX; $e->chunkZ = $newChunkZ; @@ -585,28 +801,32 @@ class Level{ 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){ $e->handlePrePlayerSearcher(); - + 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); + $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"])){ unset($this->entityListPositioned["$curChunkX $curChunkZ"][$k]); } } - + $this->checkSleep(); - + if($server->ticks % 100 === 0){ $this->mobSpawner->handle(); } - + + foreach($this->players as $player){ + if(!$player->spawned) continue; foreach($post as $eid){ $e = $this->entityList[$eid] ?? false; if(!($e instanceof Entity)){ @@ -615,7 +835,7 @@ class Level{ $player->addEntityMovementUpdateToQueue($e); } $player->sendEntityMovementUpdateQueue(); - + foreach($this->queuedBlockUpdates as $ind => $update){ $x = $update[0]; $y = $update[1]; @@ -627,10 +847,11 @@ class Level{ } $player->sendBlockUpdateQueue(); } - + $this->queuedBlockUpdates = []; + $this->updateLights(); } - + public function isBoundingBoxOnFire(AxisAlignedBB $bb){ $minX = floor($bb->minX); $maxX = floor($bb->maxX + 1); @@ -638,7 +859,7 @@ class Level{ $maxY = floor($bb->maxY + 1); $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){ @@ -647,14 +868,14 @@ class Level{ } } } - + return false; } 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; + $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){ @@ -672,13 +893,14 @@ class Level{ return $ents; } /** + * @param AxisAlignedBB $bb * @return Entity[] */ 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; + $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){ @@ -696,20 +918,20 @@ class Level{ } return $ents; } - + 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){ 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($ret === true){ if(!($pos instanceof Position)){ $pos = new Position($pos->x, $pos->y, $pos->z, $this); } @@ -725,15 +947,15 @@ class Level{ $this->changedBlocks[$i][] = ($block->x & 0xff) << 32 | ($block->y & 0xff) << 24 | ($block->z & 0xff) << 16 | ($block->getID() & 0xff) << 8 | ($block->meta & 0xff); ++$this->changedCount[$i]; } - + if($tiles === true){ $this->server->api->tile->invalidateAll($this, $pos->x, $pos->y, $pos->z); } - + if($update === true){ $this->updateNeighborsAt($pos->x, $pos->y, $pos->z, $oldID); } - + } return $ret; } @@ -851,7 +1073,7 @@ class Level{ } return new Position($this->level->getData("spawnX"), $this->level->getData("spawnY"), $this->level->getData("spawnZ"), $this); } - + /** * @param number $x * @param number $y @@ -859,14 +1081,15 @@ class Level{ * @param boolean $positionfy assign coordinates to block or not * @return GenericBlock | false if failed */ - + public function getBlockWithoutVector($x, $y, $z, $positionfy = true){ - $b = $this->level->getBlock((int) $x, (int) $y, (int) $z); + $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); } - + /** * Recommended to use {@link getBlockWithoutVector()} if you dont have the vector + * @param Vector3 $pos * @return Block|false if failed */ public function getBlock(Vector3 $pos){ @@ -915,11 +1138,11 @@ class Level{ $this->time -= 20 * 13; } } - + public function isTimeStopped(){ return $this->stopTime; } - + public function stopTime(){ $this->stopTime = true; $this->startCheck = 0; diff --git a/src/world/LevelImport.php b/src/world/LevelImport.php index 49f21773..0e41139d 100644 --- a/src/world/LevelImport.php +++ b/src/world/LevelImport.php @@ -66,14 +66,17 @@ class LevelImport{ 6 => "", 7 => "" ]; + $pmf->markHasBlocklight($X, $Z); + 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); + $blocklight = $chunks->getChunkColumn($X, $Z, $x, $z, 3); 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"; + $chunk[$Y] .= substr($blocklight, $Y << 3, 8); } } } @@ -84,7 +87,8 @@ class LevelImport{ } console("[NOTICE] Importing level " . ceil(($Z + 1) / 0.16) . "%"); } - $chunks->map = null; + $pmf->writeNCData(); + $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"); diff --git a/src/world/MobSpawner.php b/src/world/MobSpawner.php index 53bf5850..21091ccd 100644 --- a/src/world/MobSpawner.php +++ b/src/world/MobSpawner.php @@ -8,7 +8,7 @@ class MobSpawner{ public $playerAffectedEIDS = []; public $entityAffectedPlayers = []; public static $MOB_LIMIT = 50; - + public function __construct(Level $level){ $this->server = ServerAPI::request(); $this->level = $level; @@ -17,12 +17,12 @@ class MobSpawner{ public function countEntities(){ return $this->level->totalMobsAmount; } - + 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){ @@ -31,16 +31,16 @@ class MobSpawner{ }else{ $diffX = $living->x - $player->x; $diffZ = $living->z - $player->z; - $dist = $diffX * $diffX + $diffZ * $diffZ; + $dist = $diffX*$diffX + $diffZ*$diffZ; if($dist <= 512){ return false; } - + return $dist > 4096 || mt_rand($dist, 4096) == $dist; //force despawn 64 blocks away or despawn randomly } - + } - + public function handle(){ if($this->countEntities() > self::$MOB_LIMIT || count($this->level->players) <= 0){ return false; //not spawning @@ -48,7 +48,7 @@ class MobSpawner{ $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}."); - + return $this->spawnMobs(); } @@ -65,38 +65,39 @@ class MobSpawner{ }else{ return false; } - + foreach($this->level->players as $player){ if(isset($this->playerAffectedEIDS[$player->entity->eid]) && count($this->playerAffectedEIDS[$player->entity->eid]) > $this->totalMobsPerPlayer){ continue; } - - $x = mt_rand($player->entity->x - 32, $player->entity->x + 32); - $z = mt_rand($player->entity->z - 32, $player->entity->z + 32); - $diffX = $x - $player->entity->x; - $diffZ = $z - $player->entity->z; - $dist = $diffX * $diffX + $diffZ * $diffZ; + + $x = mt_rand(floor($player->entity->x - 32), ceil($player->entity->x + 32)); + $z = mt_rand(floor($player->entity->z - 32), ceil($player->entity->z + 32)); + $diffX = $x-$player->entity->x; + $diffZ = $z-$player->entity->z; + $dist = $diffX*$diffX + $diffZ*$diffZ; if($dist < 768){ continue; } - + $cnt = mt_rand(1, 3); - + 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); + + + $y = $this->getSafeY($xMob, $zMob, $grassOnly, $type >= 32 && $type <= 36 && $type != 35, $type >= 32 && $type <= 36); if(!$y || $y < 0){ continue; } - + $data = $this->genPosData($xMob, $y + 0.5, $zMob); if($baby != 2) $data["IsBaby"] = $baby; - + $e = $this->server->api->entity->add($this->level, 2, $type, $data); - + if($e instanceof Entity){ $this->server->api->entity->spawnToAll($e); ConsoleAPI::debug("$type spawned at $xMob, $y, $zMob"); @@ -106,15 +107,16 @@ class MobSpawner{ }else{ $this->playerAffectedEIDS[$player->entity->eid][$e->eid] = true; } - + $this->entityAffectedPlayers[$e->eid] = $player->entity->eid; - + } } - + + return true; } - + private function genPosData($x, $y, $z){ return [ "x" => $x + 0.5, @@ -122,22 +124,25 @@ class MobSpawner{ "z" => $z + 0.5 ]; } - - protected function getSafeY($x, $z, $grassOnly = false, $highMob = false){ //first safe block //TODO check boundingbox + + protected function getSafeY($x, $z, $grassOnly = false, $highMob = false, $isMonster = false){ //first safe block //TODO check boundingbox $allowed = []; 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); if( - !StaticBlock::getIsSolid($b) && !StaticBlock::getIsLiquid($b) && + !StaticBlock::getIsSolid($b) && !StaticBlock::getIsLiquid($b) && (StaticBlock::getIsSolid($b1) && (!$grassOnly || $b1 === GRASS) && (!$highMob || !StaticBlock::getIsSolid($b2) && !StaticBlock::getIsLiquid($b2))) ){ + if($isMonster && ($rb = $this->level->getRawBrightness($x, $y, $z)) > 8){ //dont spawn if too bright + continue; + } $allowed[] = $y; } } - + return empty($allowed) ? -1 : $allowed[mt_rand(0, count($allowed) - 1)]; } } diff --git a/src/world/PocketChunkParser.php b/src/world/PocketChunkParser.php index 2c85bb4a..1620bf83 100644 --- a/src/world/PocketChunkParser.php +++ b/src/world/PocketChunkParser.php @@ -7,6 +7,13 @@ class PocketChunkParser{ var $map; //21 * $sectorLength private $location, $raw = b"", $file; + public function __destruct(){ + unset($this->location); + unset($this->raw); + unset($this->file); + unset($this->map); + } + public function loadFile($file){ if(file_exists($file . ".gz")){ $this->raw = gzinflate(file_get_contents($file . ".gz")); diff --git a/src/world/Tile.php b/src/world/Tile.php index 2ffefb84..1751bc74 100644 --- a/src/world/Tile.php +++ b/src/world/Tile.php @@ -254,7 +254,7 @@ class Tile extends Position{ $pk->x = $this->x; $pk->y = $this->y; $pk->z = $this->z; - $player->dataPacket($pk); + $player->blockQueueDataPacket($pk); $slots = []; if(is_array($player->windows[$id])){ @@ -266,7 +266,9 @@ class Tile extends Position{ $pk->z = $ob->z; $pk->case1 = 1; $pk->case2 = 2; - $this->server->api->player->broadcastPacket($all, $pk); + foreach($this->level->players as $pl){ + $pl->blockQueueDataPacket(clone $pk); + } for($s = 0; $s < CHEST_SLOTS; ++$s){ $slot = $ob->getSlot($s); if($slot->getID() > AIR and $slot->count > 0){ @@ -283,7 +285,10 @@ class Tile extends Position{ $pk->z = $this->z; $pk->case1 = 1; $pk->case2 = 2; - $this->server->api->player->broadcastPacket($this->server->api->player->getAll($this->level), $pk); + foreach($this->level->players as $pl){ + $pl->blockQueueDataPacket(clone $pk); + } + for($s = 0; $s < CHEST_SLOTS; ++$s){ $slot = $this->getSlot($s); if($slot->getID() > AIR and $slot->count > 0){ @@ -297,7 +302,7 @@ class Tile extends Position{ $pk = new ContainerSetContentPacket; $pk->windowid = $id; $pk->slots = $slots; - $player->dataPacket($pk); + $player->blockQueueDataPacket($pk); return true; }elseif($this->class === TILE_FURNACE){ $player->windowCnt++; @@ -311,7 +316,7 @@ class Tile extends Position{ $pk->x = $this->x; $pk->y = $this->y; $pk->z = $this->z; - $player->dataPacket($pk); + $player->blockQueueDataPacket($pk); $slots = []; for($s = 0; $s < FURNACE_SLOTS; ++$s){ @@ -325,7 +330,7 @@ class Tile extends Position{ $pk = new ContainerSetContentPacket; $pk->windowid = $id; $pk->slots = $slots; - $player->dataPacket($pk); + $player->blockQueueDataPacket($pk); return true; } } @@ -342,10 +347,6 @@ class Tile extends Position{ $nbt = new NBT(); $nbt->write(chr(NBT::TAG_COMPOUND) . "\x00\x00"); - $nbt->write(chr(NBT::TAG_STRING)); - $nbt->writeTAG_String("id"); - $nbt->writeTAG_String($this->class); - $nbt->write(chr(NBT::TAG_INT)); $nbt->writeTAG_String("x"); $nbt->writeTAG_Int((int) $this->x); @@ -375,7 +376,7 @@ class Tile extends Position{ $pk->y = $this->y; $pk->z = $this->z; $pk->namedtag = $nbt->binary; - $player->dataPacket($pk); + $player->blockQueueDataPacket($pk); break; case TILE_SIGN: $nbt = new NBT(); @@ -383,23 +384,19 @@ class Tile extends Position{ $nbt->write(chr(NBT::TAG_STRING)); $nbt->writeTAG_String("Text1"); - $nbt->writeTAG_String($this->data["Text1"]); + $nbt->writeTAG_String(mb_substr($this->data["Text1"], 0, 15)); $nbt->write(chr(NBT::TAG_STRING)); $nbt->writeTAG_String("Text2"); - $nbt->writeTAG_String($this->data["Text2"]); + $nbt->writeTAG_String(mb_substr($this->data["Text2"], 0, 15)); $nbt->write(chr(NBT::TAG_STRING)); $nbt->writeTAG_String("Text3"); - $nbt->writeTAG_String($this->data["Text3"]); + $nbt->writeTAG_String(mb_substr($this->data["Text3"], 0, 15)); $nbt->write(chr(NBT::TAG_STRING)); $nbt->writeTAG_String("Text4"); - $nbt->writeTAG_String($this->data["Text4"]); - - $nbt->write(chr(NBT::TAG_STRING)); - $nbt->writeTAG_String("id"); - $nbt->writeTAG_String($this->class); + $nbt->writeTAG_String(mb_substr($this->data["Text4"], 0, 15)); $nbt->write(chr(NBT::TAG_INT)); $nbt->writeTAG_String("x"); @@ -420,7 +417,7 @@ class Tile extends Position{ $pk->y = $this->y; $pk->z = $this->z; $pk->namedtag = $nbt->binary; - $player->dataPacket($pk); + $player->blockQueueDataPacket($pk); break; } } @@ -429,6 +426,13 @@ class Tile extends Position{ if($this->class !== TILE_SIGN){ return false; } + if(Level::$disableEmojisOnSigns){ + $line1 = Utils::replaceEmoji($line1); + $line2 = Utils::replaceEmoji($line2); + $line3 = Utils::replaceEmoji($line3); + $line4 = Utils::replaceEmoji($line4); + + } $this->data["Text1"] = $line1; $this->data["Text2"] = $line2; $this->data["Text3"] = $line3;