Merge branch 'master'

# Conflicts:
#	src/API/AchievementAPI.php
#	src/API/BanAPI.php
#	src/API/BlockAPI.php
#	src/API/EntityAPI.php
#	src/API/PlayerAPI.php
#	src/Player.php
#	src/PocketMinecraftServer.php
#	src/config.php
#	src/entity/Animal.php
#	src/entity/Breedable.php
#	src/entity/Creature.php
#	src/entity/Entity.php
#	src/entity/animal/Sheep.php
#	src/entity/monster/Creeper.php
#	src/entity/monster/Zombie.php
#	src/entity/object/Arrow.php
#	src/entity/object/FallingSand.php
#	src/entity/object/ItemEntity.php
#	src/entity/object/Minecart.php
#	src/entity/object/Painting.php
#	src/entity/object/PrimedTNT.php
#	src/material/Block.php
#	src/material/Item.php
#	src/material/Material.php
#	src/material/StaticBlock.php
#	src/material/block/DoorBlock.php
#	src/material/block/GenericBlock.php
#	src/material/block/attachable/WallSignBlock.php
#	src/material/block/liquid/LiquidBlockDynamic.php
#	src/material/block/misc/AirBlock.php
#	src/material/block/misc/BedBlock.php
#	src/material/block/misc/TNTBlock.php
#	src/material/block/nonfull/CarpetBlock.php
#	src/material/block/nonfull/FenceBlock.php
#	src/material/block/nonfull/PoweredRailBlock.php
#	src/material/block/nonfull/RailBlock.php
#	src/material/block/nonfull/SnowLayerBlock.php
#	src/material/block/nonfull/WoodSlabBlock.php
#	src/material/block/plant/BrownMushroomBlock.php
#	src/material/block/plant/DandelionBlock.php
#	src/material/block/plant/MelonStemBlock.php
#	src/material/block/plant/PumpkinStemBlock.php
#	src/material/block/plant/RedMushroomBlock.php
#	src/material/block/plant/SugarcaneBlock.php
#	src/material/block/solid/GrassBlock.php
#	src/material/block/solid/IceBlock.php
#	src/material/block/solid/LeavesBlock.php
#	src/material/block/solid/ObsidianBlock.php
#	src/material/block/solid/PumpkinBlock.php
#	src/material/block/solid/WoolBlock.php
#	src/material/item/base/ItemHoe.php
#	src/material/item/base/ItemTool.php
#	src/material/item/generic/DyeItem.php
#	src/material/item/generic/SpawnEggItem.php
#	src/material/item/tool/FlintSteelItem.php
#	src/material/item/tool/ShearsItem.php
#	src/math/AxisAlignedBB.php
#	src/network/MinecraftInterface.php
#	src/network/UDPSocket.php
#	src/network/protocol/packet/AddItemEntityPacket.php
#	src/network/protocol/packet/ContainerSetContentPacket.php
#	src/network/raknet/RakNetDataPacket.php
#	src/network/raknet/RakNetParser.php
#	src/pmf/PMFLevel.php
#	src/utils/Utils.php
#	src/world/Explosion.php
#	src/world/Level.php
#	src/world/MobSpawner.php
This commit is contained in:
yefengeeeeeeeeeee 2026-04-04 14:52:08 +08:00
commit 3fbab46e60
245 changed files with 6118 additions and 3408 deletions

View file

@ -10,22 +10,24 @@ Supported MCPE versions: 0.3.0 ~ 0.8.1 (maybe 0.8.2)
<h2> Why should you use NostalgiaCore to run a Minecraft Pocket Edition 0.8.1 server?</h2>
• 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.
<h3> Download Stable NostalgiaCore</h3>

View file

@ -1,7 +1,7 @@
<?php
class AchievementAPI{
public static $achievements = [
/*"openInventory" => 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", "<player>", [$this, "viewAchievements"]);
$this->server->api->console->alias("getplayerachievements", "ach");

View file

@ -1,11 +1,8 @@
<?php
class BanAPI{
/** @var PocketMinecraftServer */
private $server;
/*
* I would use PHPDoc Template here but PHPStorm does not recognise it. - @sekjun9878
*/
/** @var Config */
private $whitelist;
/** @var Config */
@ -14,10 +11,14 @@ class BanAPI{
private $ops;
/** @var Config */
private $bannedIPs;
/**
* Contains commands that can be used by anyone on the server.
* Keys: lowercased command name. Values don't matter.
* @var array
*/
public $cmdWhitelist = [];
public $cmdWhitelist = [];//Command WhiteList
function __construct(){
public function __construct(){
$this->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){

View file

@ -1,9 +1,9 @@
<?php
class BlockAPI{
public static $creativeHotbarSlots = [];
public static $reverseCreativeLookup = [];
public static $creative = [
//Building
[STONE, 0],
[COBBLESTONE, 0],
@ -201,8 +201,33 @@ class BlockAPI{
private $scheduledUpdates = [];
private $randomUpdates = [];
/**
* @param int $id item id
* @param int $meta item metadata
* @return false|int false if item is not accessible from creative mode, otherwise slot id in BlockAPI::$creative
*/
public static function hasCreativeItem($id, $meta){
$rind = ($id << 24) | ($meta);
return static::$reverseCreativeLookup[$rind] ?? false;
}
function __construct(){
$this->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 <x> <y> <z> <block[:damage]>";
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){
}
}

View file

@ -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", "<player> <private message ...>", [$this, "commandHandler"]);
$this->server->api->console->register("reply", "<private message ...>", [$this, "commandHandler"]);
$this->server->api->console->register("me", "<action ...>", [$this, "commandHandler"]);
$this->server->api->console->register("say", "<message ...>", [$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 <message>\n";
break;
return "Usage: /say <message>";
}
$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 <message>\n";
break;
return "Usage: /me <message>";
}
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 <player> <message>\n";
break;
}
if(!($issuer instanceof Player)){
$sender = ucfirst($issuer);
}else{
$sender = $issuer->username;
}
if(!isset($params[0]) or !isset($params[1])) return "Usage: /$cmd <player> <message>\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;
}
/**

View file

@ -1,7 +1,7 @@
<?php
class ConsoleAPI{
private static $loop; //why no Thread::kill in pthreads3
private $loop; //why no Thread::kill in pthreads3. Making it static causes crashes of other threads on some servers(hi nper)
private $server, $event, $help, $cmds, $alias;
public $last;
function __construct(){
@ -15,7 +15,7 @@ class ConsoleAPI{
public function init(){
$this->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 <mode>\n";
break;
return "Usage: /$cmd <mode>";
}
$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)){

View file

@ -1,6 +1,9 @@
<?php
class EntityAPI{
/**
* @var Entity[]
*/
public $entities;
private $server;
private $eCnt = 1;
@ -8,25 +11,26 @@ class EntityAPI{
function __construct(){
$this->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", "<mob>", [$this, "commandHandler"]);
$this->server->api->console->register("spawnmob", "<mob>", [$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 <mob> [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 <mob>
$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 <mob> [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 <mob> [baby]
@ -93,7 +128,7 @@ class EntityAPI{
if(!isset($args[0])){
return "/despawn <all|mobs|objects|items|fallings|minecarts>";
}
$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){
}
}

View file

@ -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;

View file

@ -19,7 +19,7 @@ class PlayerAPI{
$this->registerCmd("ping");
$this->registerCmd("loc");
$this->registerCmd("hotbar", "<slotcount>");
$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 <username>.";
}
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>";
$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 <username>.";
}
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);
}

View file

@ -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;

View file

@ -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 <ID>x<CNT>",
" <ID> - block id to fill the layer",
" <CNT> - layer height",
"Multiple layers are separated by ,",
"STARTY - start y level. Must be more than 0",
"PARAMS - additional patamaters",
" spawn(radius=<N> block=<ID>) - sets spawn parameters",
" radius=<N> - sets spawn radius to <N>",
" block=<ID> - sets block to fill spawn area with",
" decoration(treecount=<N> grasscount=<M>) - 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);

File diff suppressed because it is too large Load diff

View file

@ -1,18 +1,28 @@
<?php
class PocketMinecraftServer{
const TICK_LEGACY = 0;
const TICK_F20TPS = 1;
const TICK_NETWAIT = 2;
public $tCnt, $ticks;
public $extraprops, $serverID, $interface, $database, $version, $invisible, $tickMeasure, $preparedSQL, $seed, $gamemode, $name, $maxClients, $clients, $eidCnt, $custom, $description, $motd, $port, $saveEnabled;
public $extraprops, $serverID, $interface, $database, $version, $invisible, $tickMeasure, $preparedSQL, $seed, $gamemode, $name, $maxClients, $eidCnt, $custom, $description, $motd, $port, $saveEnabled;
/**
* @var ServerAPI
*/
public $api;
private $serverip, $evCnt, $handCnt, $events, $eventsID, $handlers, $serverType, $lastTick, $memoryStats, $async = [], $asyncID = 0;
public $doTick, $levelData, $tiles, $entities, $schedule, $scheduleCnt, $whitelist, $spawn, $difficulty, $stop, $asyncThread;
public static $FORCE_20_TPS = false, $KEEP_CHUNKS_LOADED = true, $PACKET_READING_LIMIT = 100;
/**
* @var Player[]
*/
public $clients;
public $serverip, $evCnt, $handCnt, $events, $eventsID, $handlers, $serverType, $lastTick, $memoryStats, $async = [], $asyncID = 0;
public static $TICKING_MODE = PocketMinecraftServer::TICK_LEGACY;
public $doTick, $levelData, $tiles, $entities, $schedule, $scheduleCnt, $whitelist, $spawn, $difficulty, $stop, $asyncThread;
public static $KEEP_CHUNKS_LOADED = true, $PACKET_READING_LIMIT = 100;
public static $BLOCK_BREAKING_PROGRESS = 0.8;
public static $ENABLE_LIGHT_UPDATES = true;
function __construct($name, $gamemode = SURVIVAL, $seed = false, $port = 19132, $serverip = "0.0.0.0"){
$this->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;
}

View file

@ -1,117 +1,10 @@
<?php
//do not use any modern php features in this file
$errors = 0;
set_time_limit(0);
function parseOffset(string $offset) : string|false{
//Make signed offsets unsigned for date_parse
if(str_starts_with($offset, '-')){
$negative_offset = true;
$offset = str_replace('-', '', $offset);
}else{
if(str_starts_with($offset, '+')){
$negative_offset = false;
$offset = str_replace('+', '', $offset);
}else{
return false;
}
}
$parsed = date_parse($offset);
$offset = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
//After date_parse is done, put the sign back
if($negative_offset){
$offset = -abs($offset);
}
//And then, look the offset up.
//timezone_name_from_abbr is not used because it returns false on some(most) offsets because it's mapping function is weird.
//That's been a bug in PHP since 2008!
foreach(timezone_abbreviations_list() as $zones){
foreach($zones as $timezone){
if($timezone['timezone_id'] !== null && $timezone['offset'] == $offset){
return $timezone['timezone_id'];
}
}
}
return false;
if(version_compare("8.0.0", PHP_VERSION) > 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

116
src/config_post.php Normal file
View file

@ -0,0 +1,116 @@
<?php
set_time_limit(0);
function parseOffset(string $offset) : string|false{
//Make signed offsets unsigned for date_parse
if(str_starts_with($offset, '-')){
$negative_offset = true;
$offset = str_replace('-', '', $offset);
}else{
if(str_starts_with($offset, '+')){
$negative_offset = false;
$offset = str_replace('+', '', $offset);
}else{
return false;
}
}
$parsed = date_parse($offset);
$offset = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
//After date_parse is done, put the sign back
if($negative_offset){
$offset = -abs($offset);
}
//And then, look the offset up.
//timezone_name_from_abbr is not used because it returns false on some(most) offsets because it\'s mapping function is weird.
//That\'s been a bug in PHP since 2008!
foreach(timezone_abbreviations_list() as $zones){
foreach($zones as $timezone){
if($timezone["timezone_id"] !== null && $timezone["offset"] == $offset){
return $timezone["timezone_id"];
}
}
}
return false;
}
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.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));
}

View file

@ -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);

View file

@ -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;

View file

@ -1,15 +1,17 @@
<?php
abstract class Animal extends Creature implements Ageable, Breedable{
public $parent;
public $inLove; //do NOT add it into metadata, it doesnt send it to player
public $age;
public $loveTimeout;
public $closestPlayerThatCanFeedEID = false;
public $closestPlayerThatCanFeedDist = INF;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->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 [];

View file

@ -2,8 +2,8 @@
interface Breedable{
public function isFood($id); //original name
public function spawnChild();
public function spawnChild($mate);
public function isInLove();
}

View file

@ -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;
}
}

File diff suppressed because it is too large Load diff

View file

@ -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;
}
}

View file

@ -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);

View file

@ -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)

View file

@ -2,6 +2,7 @@
class TaskFollowParent extends TaskBase
{
public $speedMultiplier;
public function __construct($speed){
$this->speedMultiplier = $speed;
}

View file

@ -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);

View file

@ -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;

View file

@ -2,6 +2,8 @@
class TaskTempt extends TaskBase
{
public $speedMultiplier;
public $targetDistance;
public function __construct($speed){
$this->speedMultiplier = $speed;
$this->targetDistance = 10 * 10;

View file

@ -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);

View file

@ -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;
}

View file

@ -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

View file

@ -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){

View file

@ -1,5 +1,4 @@
<?php
class Creeper extends Monster{
const TYPE = MOB_CREEPER;
const EXPL_TIME = 30;
@ -8,54 +7,50 @@ class Creeper extends Monster{
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->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)]

View file

@ -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;

View file

@ -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);

View file

@ -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));

View file

@ -1,39 +1,38 @@
<?php
class Zombie extends Monster{
const TYPE = MOB_ZOMBIE;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
function __construct(Level $level, $eid, $class, $type = 0, $data = array()){
$this->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],

View file

@ -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;
}
}

View file

@ -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;

View file

@ -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 ?;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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(){

View file

@ -0,0 +1,9 @@
<?php
/*value - durability*/
class ArmorMaterial{
const LEATHER = 5; //when enums
const CHAIN = 15;
const GOLD = 7;
const IRON = 15;
const DIAMOND = 33;
}

View file

@ -1,144 +1,152 @@
<?php
abstract class Block extends Position{
public static $class = [
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",
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);
}

View file

@ -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;
}
}

View file

@ -1,10 +1,84 @@
<?php
/*value - durability*/
class Material{
const LEATHER = 5; //when enums
const CHAIN = 15;
const GOLD = 7;
const IRON = 15;
const DIAMOND = 33;
}
class Material
{
public static $air, $dirt, $wood, $stone, $metal, $water, $lava, $leaves;
public static $plant, $replaceable_plant, $sponge, $cloth, $fire, $sand;
public static $decoration, $glass, $explosive, $coral, $ice, $topSnow;
public static $snow, $cactus, $clay, $vegetable, $portal, $cake, $web;
public $alwaysDestroyable, $flammable, $translucent, $replaceable;
public $blocksLight, $blocksMotion, $isLiquid, $isSolid;
public function __construct(){
$this->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;
}
}

View file

@ -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;
}

View file

@ -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;

View file

@ -1,5 +1,6 @@
<?php
class GenericBlock extends Block{
/**
* @param int $id
@ -11,6 +12,10 @@ class GenericBlock extends Block{
}
/**
* @param Item $item
* @param Player $player
* @param Block $block
* @param Block $target
* @param integer $face
* @param integer $fx
* @param integer $fy
@ -23,6 +28,8 @@ class GenericBlock extends Block{
}
/**
* @param Item $item
* @param Player $player
*
* @return boolean
*/
@ -31,6 +38,8 @@ class GenericBlock extends Block{
}
/**
* @param Item $item
* @param Player $player
*
* @return mixed
*/
@ -46,24 +55,28 @@ class GenericBlock extends Block{
parent::onPlace($level, $x, $y, $z);
}
}
public static function onUpdate(Level $level, $x, $y, $z, $type){
[$id, $meta] = $level->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
*/

View file

@ -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){

View file

@ -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);

View file

@ -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(){

View file

@ -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){

View file

@ -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));
}

View file

@ -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){

View file

@ -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;

View file

@ -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(){

View file

@ -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(){

View file

@ -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){

View file

@ -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;
}
}

View file

@ -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),
);
}
}

View file

@ -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;

View file

@ -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){

View file

@ -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);

View file

@ -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){

View file

@ -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)];

View file

@ -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)];

View file

@ -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){

View file

@ -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);
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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);

View file

@ -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){

View file

@ -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){

View file

@ -1,13 +1,14 @@
<?php
require_once("RailBaseBlock.php");
class PoweredRailBlock extends RailBaseBlock{
public static $blockID;
public function __construct($meta = 0){
parent::__construct(POWERED_RAIL, 0, "PoweredRailBlock");
$this->hardness = 0.7;
$this->isFullBlock = false;
$this->isFullBlock = false;
$this->isSolid = false;
$this->hardness = 3.5;
$this->breakTime = 0.7;
$this->material = Material::$decoration;
}
}

View file

@ -1,20 +1,21 @@
<?php
require_once("RailBaseBlock.php");
class RailBlock extends RailBaseBlock{
public static $blockID;
public function __construct($meta = 0){
parent::__construct(RAIL, $meta, "Rail");
$this->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);
}
}
}

View file

@ -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){

View file

@ -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();
}
}

View file

@ -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()){

View file

@ -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){

View file

@ -1,29 +1,30 @@
<?php
//TODO make it extend SlabBlock
class WoodSlabBlock extends TransparentBlock{
public static $blockID;
public function __construct($meta = 0){
parent::__construct(WOOD_SLAB, $meta, "Wooden Slab");
$names = [
$names = array(
0 => "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),
);
}
}

View file

@ -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){

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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){

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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){

View file

@ -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;
}
}

View file

@ -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,

View file

@ -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){

View file

@ -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){

View file

@ -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){

View file

@ -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){

View file

@ -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){

View file

@ -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){

View file

@ -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){

Some files were not shown because too many files have changed in this diff Show more