code style fix

This commit is contained in:
Sunch 2025-04-27 20:36:24 +08:00
parent fc5c5625cb
commit 5e8e9330e2
361 changed files with 4766 additions and 4650 deletions

View file

@ -1,7 +1,7 @@
<?php <?php
class AchievementAPI{ class AchievementAPI{
public static $achievements = [ public static $achievements = [
/*"openInventory" => array( /*"openInventory" => array(
"name" => "Taking Inventory", "name" => "Taking Inventory",
@ -79,20 +79,19 @@ class AchievementAPI{
"buildSword", "buildSword",
], ],
], ],
]; ];
private $server; private $server;
function __construct(){ function __construct(){
$this->server = ServerAPI::request(); $this->server = ServerAPI::request();
} }
/** /**
* Add an achievement * Add an achievement
* @param string $achievementId * @param string $achievementId
* @param string $achievementName * @param string $achievementName
* @param array $requires
* @return boolean * @return boolean
*/ */
public static function addAchievement($achievementId, $achievementName, array $requires = []){ public static function addAchievement($achievementId, $achievementName, array $requires = []){
@ -105,7 +104,7 @@ class AchievementAPI{
} }
return false; return false;
} }
public static function grantAchievement(Player $player, $achievementId){ public static function grantAchievement(Player $player, $achievementId){
if(isset(self::$achievements[$achievementId]) and !self::hasAchievement($player, $achievementId)){ if(isset(self::$achievements[$achievementId]) and !self::hasAchievement($player, $achievementId)){
foreach(self::$achievements[$achievementId]["requires"] as $requerimentId){ foreach(self::$achievements[$achievementId]["requires"] as $requerimentId){
@ -123,19 +122,19 @@ class AchievementAPI{
} }
return false; return false;
} }
public static function hasAchievement(Player $player, $achievementId){ public static function hasAchievement(Player $player, $achievementId){
if(!isset(self::$achievements[$achievementId]) or !isset($player->achievements)){ if(!isset(self::$achievements[$achievementId]) or !isset($player->achievements)){
$player->achievements = []; $player->achievements = [];
return false; return false;
} }
if(!isset($player->achievements[$achievementId]) or !$player->achievements[$achievementId]){ if(!isset($player->achievements[$achievementId]) or !$player->achievements[$achievementId]){
return false; return false;
} }
return true; return true;
} }
public static function broadcastAchievement(Player $player, $achievementId){ public static function broadcastAchievement(Player $player, $achievementId){
if(isset(self::$achievements[$achievementId])){ if(isset(self::$achievements[$achievementId])){
$result = ServerAPI::request()->api->dhandle("achievement.broadcast", ["player" => $player, "achievementId" => $achievementId]); $result = ServerAPI::request()->api->dhandle("achievement.broadcast", ["player" => $player, "achievementId" => $achievementId]);
@ -150,13 +149,13 @@ class AchievementAPI{
} }
return false; return false;
} }
public static function removeAchievement(Player $player, $achievementId){ public static function removeAchievement(Player $player, $achievementId){
if(self::hasAchievement($player, $achievementId)){ if(self::hasAchievement($player, $achievementId)){
$player->achievements[$achievementId] = false; $player->achievements[$achievementId] = false;
} }
} }
public function viewAchievements($cmd, $params, $issuer, $alias) public function viewAchievements($cmd, $params, $issuer, $alias)
{ {
if(!isset($params[0])){ if(!isset($params[0])){
@ -171,30 +170,30 @@ class AchievementAPI{
}else{ }else{
return false; return false;
} }
if(!$data){ if(!$data){
return "Player is not found."; return "Player is not found.";
} }
if($data instanceof Config){ if($data instanceof Config){
$achs = $data->get("achievements"); $achs = $data->get("achievements");
}else{ }else{
$achs = $data; $achs = $data;
} }
if(count($achs) <= 0){ if(count($achs) <= 0){
return "Player {$params[0]} unlocked 0 achievements"; return "Player {$params[0]} unlocked 0 achievements";
} }
$output = "Unlocked Achievements(".count($achs)."/".count(self::$achievements)."): "; $output = "Unlocked Achievements(" . count($achs) . "/" . count(self::$achievements) . "): ";
foreach($achs as $achievement => $unlocked){ foreach($achs as $achievement => $unlocked){
if($unlocked && isset(self::$achievements[$achievement])){ if($unlocked && isset(self::$achievements[$achievement])){
$info = self::$achievements[$achievement]; $info = self::$achievements[$achievement];
$output .= "{$info["name"]}, "; $output .= "{$info["name"]}, ";
} }
} }
return substr($output, 0, - 2); return substr($output, 0, -2);
} }
public function init(){ public function init(){
$this->server->api->console->register("ach", "<player>", [$this, "viewAchievements"]); $this->server->api->console->register("ach", "<player>", [$this, "viewAchievements"]);
$this->server->api->console->alias("getplayerachievements", "ach"); $this->server->api->console->alias("getplayerachievements", "ach");

View file

@ -14,7 +14,7 @@ class BanAPI{
private $ops; private $ops;
/** @var Config */ /** @var Config */
private $bannedIPs; private $bannedIPs;
public $cmdWhitelist = [];//Command WhiteList public $cmdWhitelist = [];//Command WhiteList
function __construct(){ function __construct(){

View file

@ -235,7 +235,7 @@ class BlockAPI{
break; break;
} }
$itemheld = $issuer->getSlot($issuer->slot); $itemheld = $issuer->getSlot($issuer->slot);
$output = self::getItem($itemheld->getID(), $itemheld->getMetadata()).""; $output = self::getItem($itemheld->getID(), $itemheld->getMetadata()) . "";
break; break;
case "setblock": case "setblock":
if(!($issuer instanceof Player)){ if(!($issuer instanceof Player)){
@ -259,7 +259,7 @@ class BlockAPI{
$output .= "Usage: /setblock <x> <y> <z> <block[:damage]>"; $output .= "Usage: /setblock <x> <y> <z> <block[:damage]>";
break; break;
} }
$level = $issuer->entity->level; $level = $issuer->entity->level;
$block = self::fromString($args[3])->getBlock(); $block = self::fromString($args[3])->getBlock();
} }
@ -289,13 +289,13 @@ class BlockAPI{
break; break;
}else{ }else{
$level->setBlock($pos, $block, true, false, true); $level->setBlock($pos, $block, true, false, true);
$output .= "Placed $block in ".implode(", ", $coords).", w:".$level->getName(); $output .= "Placed $block in " . implode(", ", $coords) . ", w:" . $level->getName();
} }
break; break;
case "give": case "give":
$player = $this->server->api->player->get($args[0] ?? ""); $player = $this->server->api->player->get($args[0] ?? "");
if($player instanceof Player){ if($player instanceof Player){
$item = self::fromString($args[1] ?? ""); $item = self::fromString($args[1] ?? "");
if(($player->gamemode & 0x01) === 0x01){ if(($player->gamemode & 0x01) === 0x01){
return "Player is in creative mode."; return "Player is in creative mode.";
@ -303,18 +303,18 @@ class BlockAPI{
if($item->getID() === 0){ if($item->getID() === 0){
return "You cannot give an air block to a player."; return "You cannot give an air block to a player.";
} }
if(!isset($args[2])){ if(!isset($args[2])){
$item->count = $item->getMaxStackSize(); $item->count = $item->getMaxStackSize();
}else{ }else{
$item->count = (int) $args[2]; $item->count = (int) $args[2];
} }
$player->addItem($item->getID(), $item->getMetadata(), $item->count); $player->addItem($item->getID(), $item->getMetadata(), $item->count);
$output .= "Giving ".$item->count." of ".$item->getName()." (".$item->getID().":".$item->getMetadata().") to ".$player->username; $output .= "Giving " . $item->count . " of " . $item->getName() . " (" . $item->getID() . ":" . $item->getMetadata() . ") to " . $player->username;
break; break;
}else{ }else{
$item = self::fromString($args[0] ?? ""); $item = self::fromString($args[0] ?? "");
if(!($issuer instanceof Player)){ if(!($issuer instanceof Player)){
return "You cant give an item to a non-player."; return "You cant give an item to a non-player.";
} }
@ -334,7 +334,7 @@ class BlockAPI{
} }
$issuer->addItem($item->getID(), $item->getMetadata(), $item->count); $issuer->addItem($item->getID(), $item->getMetadata(), $item->count);
$output .= "Giving ".$item->count." of ".$item->getName()." (".$item->getID().":".$item->getMetadata().") to ".$issuer->username; $output .= "Giving " . $item->count . " of " . $item->getName() . " (" . $item->getID() . ":" . $item->getMetadata() . ") to " . $issuer->username;
break; break;
} }
} }
@ -412,7 +412,6 @@ class BlockAPI{
return $this->cancelAction($target, $player, false); return $this->cancelAction($target, $player, false);
} }
if(is_array($drops) && ($player->gamemode & 0x01) === 0x00 and count($drops) > 0){ if(is_array($drops) && ($player->gamemode & 0x01) === 0x00 and count($drops) > 0){
foreach($drops as $drop){ 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])); $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]));
@ -456,7 +455,7 @@ class BlockAPI{
return $this->cancelAction($block, $player); return $this->cancelAction($block, $player);
} }
} }
StaticBlock::getBlock($target->getID())::interact($target->level, $target->x, $target->y, $target->z, $player); StaticBlock::getBlock($target->getID())::interact($target->level, $target->x, $target->y, $target->z, $player);
if($target->isActivable === true){ if($target->isActivable === true){
@ -501,14 +500,14 @@ class BlockAPI{
$hand->position($block); $hand->position($block);
//$face = -1; //$face = -1;
} }
if($hand->isSolid === true && ($hand->getID() != BED_BLOCK && $hand->getID() != CARPET)){ if($hand->isSolid === true && ($hand->getID() != BED_BLOCK && $hand->getID() != CARPET)){
$aabb = $hand->getAABB($block->level, $block->x, $block->y, $block->z); $aabb = $hand->getAABB($block->level, $block->x, $block->y, $block->z);
$playerbb = $player->entity->boundingBox; $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)){ 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 return $this->cancelAction($block, $player, false); //Entity in block
} }
} }
if($this->server->api->dhandle("player.block.place", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) === false){ if($this->server->api->dhandle("player.block.place", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) === false){
@ -537,14 +536,12 @@ class BlockAPI{
return false; return false;
} }
$level = $block::onUpdate($pos->level, $pos->x, $pos->y, $pos->z, $type); $level = $block::onUpdate($pos->level, $pos->x, $pos->y, $pos->z, $type);
return $level; return $level;
} }
public function blockUpdateAround(Position $pos, $type = BLOCK_UPDATE_NORMAL, $delay = false){ public function blockUpdateAround(Position $pos, $type = BLOCK_UPDATE_NORMAL, $delay = false){
if($type == BLOCK_UPDATE_NORMAL){ if($type == BLOCK_UPDATE_NORMAL){
try{ try{
throw new Exception("Deprecated: tried updating $pos using BLOCK_UPDATE_NORMAL."); throw new Exception("Deprecated: tried updating $pos using BLOCK_UPDATE_NORMAL.");
@ -554,7 +551,7 @@ class BlockAPI{
} }
return; return;
} }
if($delay !== false){ if($delay !== false){
$this->scheduleBlockUpdate($pos->getSide(0), $delay, $type); $this->scheduleBlockUpdate($pos->getSide(0), $delay, $type);
$this->scheduleBlockUpdate($pos->getSide(1), $delay, $type); $this->scheduleBlockUpdate($pos->getSide(1), $delay, $type);
@ -576,7 +573,7 @@ class BlockAPI{
if($delay < 0){ if($delay < 0){
return false; return false;
} }
$index = $x . "." . $y . "." . $z . "." . $level->getName() . "." . $type; $index = $x . "." . $y . "." . $z . "." . $level->getName() . "." . $type;
$delay = microtime(true) + $delay * 0.05; $delay = microtime(true) + $delay * 0.05;
if(!isset($this->scheduledUpdates[$index])){ if(!isset($this->scheduledUpdates[$index])){
@ -586,7 +583,7 @@ class BlockAPI{
} }
return false; return false;
} }
public function scheduleBlockUpdate(Position $pos, $delay, $type = BLOCK_UPDATE_SCHEDULED){ public function scheduleBlockUpdate(Position $pos, $delay, $type = BLOCK_UPDATE_SCHEDULED){
$type = (int) $type; $type = (int) $type;
if($delay < 0){ if($delay < 0){

View file

@ -103,8 +103,6 @@ class ChatAPI{
/** /**
* @param mixed $owner Can be either Player object or string username. Boolean false for broadcast. * @param mixed $owner Can be either Player object or string username. Boolean false for broadcast.
* @param string $text * @param string $text
* @param $whitelist
* @param $blacklist
*/ */
public function send($owner, $text, $whitelist = false, $blacklist = false){ public function send($owner, $text, $whitelist = false, $blacklist = false){
$message = [ $message = [

View file

@ -24,12 +24,12 @@ class ConsoleAPI{
$this->register("defaultgamemode", "<mode>", [$this, "defaultCommands"]); $this->register("defaultgamemode", "<mode>", [$this, "defaultCommands"]);
$this->server->api->console->alias("tps", "status"); $this->server->api->console->alias("tps", "status");
$this->cmdWhitelist("help"); $this->cmdWhitelist("help");
$this->cmdWhitelist("status"); $this->cmdWhitelist("status");
$this->cmdWhitelist("?"); $this->cmdWhitelist("?");
} }
/** /**
* Whitelists a CMD so everyone can issue it - Even non OPs. * Whitelists a CMD so everyone can issue it - Even non OPs.
* @param string $cmd Command to Whitelist * @param string $cmd Command to Whitelist
@ -37,7 +37,7 @@ class ConsoleAPI{
public function cmdWhitelist($cmd){ public function cmdWhitelist($cmd){
$this->server->api->ban->cmdWhitelist[strtolower(trim($cmd))] = true; $this->server->api->ban->cmdWhitelist[strtolower(trim($cmd))] = true;
} }
public function register($cmd, $help, $callback){ public function register($cmd, $help, $callback){
if(!is_callable($callback)){ if(!is_callable($callback)){
return false; return false;
@ -272,19 +272,19 @@ class ConsoleAPI{
} }
public static function debug($msg){ public static function debug($msg){
console("[DEBUG] ".$msg, true, true, 2); console("[DEBUG] " . $msg, true, true, 2);
} }
public static function info($msg){ public static function info($msg){
console("[INFO] ".$msg); console("[INFO] " . $msg);
} }
public static function notice($msg){ public static function notice($msg){
console("[NOTICE] ".$msg); console("[NOTICE] " . $msg);
} }
public static function warn($msg){ public static function warn($msg){
console("[WARNING] ".$msg); console("[WARNING] " . $msg);
} }
public static function error($msg){ public static function error($msg){
console("[ERROR] ".$msg); console("[ERROR] " . $msg);
} }
} }

View file

@ -8,26 +8,25 @@ class EntityAPI{
function __construct(){ function __construct(){
$this->entities = []; $this->entities = [];
$this->server = ServerAPI::request(); $this->server = ServerAPI::request();
$this->serverSpawnAnimals = $this->server->api->getProperty("spawn-animals"); $this->serverSpawnAnimals = $this->server->api->getProperty("spawn-animals");
$this->serverSpawnMobs = $this->server->api->getProperty("spawn-mobs"); $this->serverSpawnMobs = $this->server->api->getProperty("spawn-mobs");
} }
public function init(){ public function init(){
$this->server->api->console->register("summon", "<mob>", [$this, "commandHandler"]); $this->server->api->console->register("summon", "<mob>", [$this, "commandHandler"]);
$this->server->api->console->register("spawnmob", "<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("despawn", "", [$this, "CommandHandler"]);
$this->server->api->console->register("entcnt", "", [$this, "CommandHandler"]); $this->server->api->console->register("entcnt", "", [$this, "CommandHandler"]);
} }
public function commandHandler($cmd, $args, $issuer, $alias){ public function commandHandler($cmd, $args, $issuer, $alias){
$mob = [ $mob = [
"chicken" => 10, "chicken" => 10,
"cow" => 11, "cow" => 11,
"pig" => 12, "pig" => 12,
"sheep" => 13, "sheep" => 13,
"zombie" => 32, "zombie" => 32,
"creeper" => 33, "creeper" => 33,
"skeleton" => 34, "skeleton" => 34,
@ -37,7 +36,7 @@ class EntityAPI{
$output = ""; $output = "";
switch($cmd){ switch($cmd){
case "entcnt": case "entcnt":
return "Total amount of entities: ". count($this->entities); return "Total amount of entities: " . count($this->entities);
case "summon": case "summon":
case "spawnmob": case "spawnmob":
if(!($issuer instanceof Player)){ if(!($issuer instanceof Player)){
@ -46,24 +45,24 @@ class EntityAPI{
if((count($args) < 1) or (count($args) > 3)){ if((count($args) < 1) or (count($args) > 3)){
return "Usage: /$cmd <mob> [amount] [baby]"; return "Usage: /$cmd <mob> [amount] [baby]";
} }
if(is_int($args[0])) $type = $args[0]; if(is_int($args[0])) $type = $args[0];
else $type = $mob[strtolower($args[0])] ?? 0; else $type = $mob[strtolower($args[0])] ?? 0;
if($type < 10 || $type > 36){ if($type < 10 || $type > 36){
return "Unknown mob."; return "Unknown mob.";
} }
$mobName = ucfirst(array_flip($mob)[$type]); $mobName = 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)){ 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!"; return "$mobName cannot be a baby!";
} }
$x = round($issuer->entity->x, 2, PHP_ROUND_HALF_UP); $x = round($issuer->entity->x, 2, PHP_ROUND_HALF_UP);
$y = round($issuer->entity->y, 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); $z = round($issuer->entity->z, 2, PHP_ROUND_HALF_UP);
$level = $issuer->entity->level; $level = $issuer->entity->level;
$pos = new Position($x, $y, $z, $level); $pos = new Position($x, $y, $z, $level);
if(count($args) === 1){//summon <mob> if(count($args) === 1){//summon <mob>
$this->summon($pos, ENTITY_MOB, $type); $this->summon($pos, ENTITY_MOB, $type);
return "$mobName spawned in $x, $y, $z."; return "$mobName spawned in $x, $y, $z.";
@ -77,12 +76,12 @@ class EntityAPI{
if(isset($args[2]) and strtolower($args[2]) === 'baby'){//summon <mob> [amount] [baby] if(isset($args[2]) and strtolower($args[2]) === 'baby'){//summon <mob> [amount] [baby]
$isBaby = true; $isBaby = true;
} }
for($cnt = $amount; $cnt > 0; --$cnt){ for($cnt = $amount; $cnt > 0; --$cnt){
$this->summon($pos, ENTITY_MOB, $type, ["IsBaby" => $isBaby]); $this->summon($pos, ENTITY_MOB, $type, ["IsBaby" => $isBaby]);
} }
return "$amount ".($isBaby ? "Baby " : "")."$mobName(s) spawned in $x, $y, $z."; return "$amount " . ($isBaby ? "Baby " : "") . "$mobName(s) spawned in $x, $y, $z.";
} }
elseif(strtolower($args[1]) == "baby"){//summon <mob> [baby] elseif(strtolower($args[1]) == "baby"){//summon <mob> [baby]
$this->summon($pos, ENTITY_MOB, $type, ["IsBaby" => 1]); $this->summon($pos, ENTITY_MOB, $type, ["IsBaby" => 1]);
@ -94,7 +93,7 @@ class EntityAPI{
if(!isset($args[0])){ if(!isset($args[0])){
return "/despawn <all|mobs|objects|items|fallings|minecarts>"; return "/despawn <all|mobs|objects|items|fallings|minecarts>";
} }
$despawnclass = 0; $despawnclass = 0;
$despawntype = 0; $despawntype = 0;
switch($args[0]){ switch($args[0]){
@ -138,12 +137,12 @@ class EntityAPI{
} }
} }
} }
return "$cnt entities have been despawned!"; return "$cnt entities have been despawned!";
} }
return $output; return $output;
} }
public function summon(Position $pos, $class, $type, array $data = []){ public function summon(Position $pos, $class, $type, array $data = []){
$entity = $this->add($pos->level, $class, $type, [ $entity = $this->add($pos->level, $class, $type, [
"x" => $pos->x, "x" => $pos->x,
@ -152,16 +151,16 @@ class EntityAPI{
] + $data); ] + $data);
$this->spawnToAll($entity); $this->spawnToAll($entity);
} }
public function getNextEID(){ public function getNextEID(){
return $this->eCnt++; return $this->eCnt++;
} }
public function addRaw(Entity $e){ public function addRaw(Entity $e){
$eid = $e->eid; $eid = $e->eid;
$this->entities[$eid] = $e; $this->entities[$eid] = $e;
$cX = (int)$this->entities[$eid]->x >> 4; $cX = (int) $this->entities[$eid]->x >> 4;
$cZ = (int)$this->entities[$eid]->z >> 4; $cZ = (int) $this->entities[$eid]->z >> 4;
$e->level->entityListPositioned["$cX $cZ"][$eid] = $eid; $e->level->entityListPositioned["$cX $cZ"][$eid] = $eid;
$e->level->entityList[$eid] = &$this->entities[$eid]; $e->level->entityList[$eid] = &$this->entities[$eid];
$this->server->handle("entity.add", $this->entities[$eid]); $this->server->handle("entity.add", $this->entities[$eid]);
@ -178,7 +177,7 @@ class EntityAPI{
} }
return $this->addRaw($e); return $this->addRaw($e);
} }
public function spawnToAll(Entity $e){ public function spawnToAll(Entity $e){
foreach($this->server->api->player->getAll($e->level) as $player){ 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->eid !== false and $player->eid !== $e->eid and $e->class !== ENTITY_PLAYER and $e instanceof Entity){
@ -186,18 +185,18 @@ class EntityAPI{
} }
} }
} }
public function get($eid){ public function get($eid){
return $this->entities[$eid] ?? false; return $this->entities[$eid] ?? false;
} }
public function remove($eid){ public function remove($eid){
if(isset($this->entities[$eid])){ if(isset($this->entities[$eid])){
$level = $this->entities[$eid]->level; $level = $this->entities[$eid]->level;
$this->entities[$eid]->closed = true; $this->entities[$eid]->closed = true;
if($level instanceof Level){ if($level instanceof Level){
$cX = (int)$this->entities[$eid]->x >> 4; $cX = (int) $this->entities[$eid]->x >> 4;
$cZ = (int)$this->entities[$eid]->z >> 4; $cZ = (int) $this->entities[$eid]->z >> 4;
$index = "$cX $cZ"; $index = "$cX $cZ";
unset($level->entityListPositioned[$index][$eid]); unset($level->entityListPositioned[$index][$eid]);
if(isset($level->mobSpawner->entityAffectedPlayers[$eid])){ if(isset($level->mobSpawner->entityAffectedPlayers[$eid])){
@ -221,12 +220,12 @@ class EntityAPI{
unset($this->entities[$eid]); unset($this->entities[$eid]);
} }
} }
public function getRadius(Position $center, $radius = 15, $class = false){ public function getRadius(Position $center, $radius = 15, $class = false){
$minChunkX = ((int)($center->x - $radius)) >> 4; $minChunkX = ((int) ($center->x - $radius)) >> 4;
$minChunkZ = ((int)($center->z - $radius)) >> 4; $minChunkZ = ((int) ($center->z - $radius)) >> 4;
$maxChunkX = ((int)($center->x + $radius)) >> 4; $maxChunkX = ((int) ($center->x + $radius)) >> 4;
$maxChunkZ = ((int)($center->z + $radius)) >> 4; $maxChunkZ = ((int) ($center->z + $radius)) >> 4;
$ents = []; $ents = [];
//TODO also index by chunkY? //TODO also index by chunkY?
for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){ for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){
@ -244,11 +243,11 @@ class EntityAPI{
} }
return $ents; return $ents;
} }
public function heal($eid, $heal, $cause){ public function heal($eid, $heal, $cause){
$this->harm($eid, -$heal, $cause); $this->harm($eid, -$heal, $cause);
} }
public function harm($eid, $attack, $cause, $force = false){ public function harm($eid, $attack, $cause, $force = false){
$e = $this->get($eid); $e = $this->get($eid);
if($e === false or $e->dead === true){ if($e === false or $e->dead === true){
@ -256,7 +255,7 @@ class EntityAPI{
} }
$e->setHealth($e->getHealth() - $attack, $cause, $force); $e->setHealth($e->getHealth() - $attack, $cause, $force);
} }
public function dropRawPos(Level $level, $x, $y, $z, $item, $speedX, $speedY, $speedZ){ public function dropRawPos(Level $level, $x, $y, $z, $item, $speedX, $speedY, $speedZ){
if($item->getID() === AIR or $item->count <= 0){ if($item->getID() === AIR or $item->count <= 0){
return; return;
@ -272,7 +271,7 @@ class EntityAPI{
"item" => $item, "item" => $item,
"itemID" => $item->getID() "itemID" => $item->getID()
]; ];
if($this->server->api->handle("item.drop", $data) !== false){ if($this->server->api->handle("item.drop", $data) !== false){
for($count = $item->count; $count > 0;){ for($count = $item->count; $count > 0;){
$item->count = min($item->getMaxStackSize(), $count); $item->count = min($item->getMaxStackSize(), $count);
@ -283,7 +282,7 @@ class EntityAPI{
} }
} }
} }
public function drop(Position $pos, Item $item, $pickupDelay = 10){ public function drop(Position $pos, Item $item, $pickupDelay = 10){
if($item->getID() === AIR or $item->count <= 0){ if($item->getID() === AIR or $item->count <= 0){
return; return;
@ -310,7 +309,7 @@ class EntityAPI{
} }
} }
} }
public function spawnAll(Player $player){ public function spawnAll(Player $player){
foreach($player->level->entityList as $e){ foreach($player->level->entityList as $e){
if($e->class !== ENTITY_PLAYER){ if($e->class !== ENTITY_PLAYER){
@ -318,18 +317,18 @@ class EntityAPI{
} }
} }
} }
public function getAll($level = null){ public function getAll($level = null){
if($level instanceof Level){ if($level instanceof Level){
return $level->entityList; return $level->entityList;
} }
return $this->entities; return $this->entities;
} }
/** /**
* @deprecated this function doesnt do anything * @deprecated this function doesnt do anything
*/ */
public function updateRadius(Position $center, $radius = 15, $class = false){ public function updateRadius(Position $center, $radius = 15, $class = false){
} }
} }

View file

@ -40,7 +40,7 @@ class LevelAPI{
console("[ERROR] Could not load level \"" . $name . "\""); console("[ERROR] Could not load level \"" . $name . "\"");
return false; return false;
} }
if(PocketMinecraftServer::$KEEP_CHUNKS_LOADED){ if(PocketMinecraftServer::$KEEP_CHUNKS_LOADED){
for($X = 0; $X < 16; ++$X){ for($X = 0; $X < 16; ++$X){
for($Z = 0; $Z < 16; ++$Z){ for($Z = 0; $Z < 16; ++$Z){
@ -48,8 +48,7 @@ class LevelAPI{
} }
} }
} }
$entities = new Config($path . "entities.yml", CONFIG_YAML); $entities = new Config($path . "entities.yml", CONFIG_YAML);
if(file_exists($path . "tileEntities.yml")){ if(file_exists($path . "tileEntities.yml")){
@rename($path . "tileEntities.yml", $path . "tiles.yml"); @rename($path . "tileEntities.yml", $path . "tiles.yml");
@ -61,13 +60,13 @@ class LevelAPI{
if(!isset($entity["id"])){ if(!isset($entity["id"])){
break; break;
} }
$entity["x"] = $entity["Pos"][0]; $entity["x"] = $entity["Pos"][0];
$entity["y"] = $entity["Pos"][1]; $entity["y"] = $entity["Pos"][1];
$entity["z"] = $entity["Pos"][2]; $entity["z"] = $entity["Pos"][2];
$entity["yaw"] = $entity["Rotation"][0]; $entity["yaw"] = $entity["Rotation"][0];
$entity["pitch"] = $entity["Rotation"][1]; $entity["pitch"] = $entity["Rotation"][1];
if($entity["id"] === 64){ //Item Drop if($entity["id"] === 64){ //Item Drop
$e = $this->server->api->entity->add($this->levels[$name], ENTITY_ITEM, ENTITY_ITEM_TYPE, [ $e = $this->server->api->entity->add($this->levels[$name], ENTITY_ITEM, ENTITY_ITEM_TYPE, [
"meta" => $entity["Item"]["Damage"], "meta" => $entity["Item"]["Damage"],
@ -105,7 +104,7 @@ class LevelAPI{
foreach($blockUpdates->getAll() as $bupdate){ foreach($blockUpdates->getAll() as $bupdate){
if($bupdate["type"] !== BLOCK_UPDATE_RANDOM) $this->server->api->block->scheduleBlockUpdate(new Position((int) $bupdate["x"], (int) $bupdate["y"], (int) $bupdate["z"], $this->levels[$name]), (float) $bupdate["delay"], (int) $bupdate["type"]); if($bupdate["type"] !== BLOCK_UPDATE_RANDOM) $this->server->api->block->scheduleBlockUpdate(new Position((int) $bupdate["x"], (int) $bupdate["y"], (int) $bupdate["z"], $this->levels[$name]), (float) $bupdate["delay"], (int) $bupdate["type"]);
} }
return true; return true;
} }
/** /**

View file

@ -19,7 +19,7 @@ class PlayerAPI{
$this->registerCmd("ping"); $this->registerCmd("ping");
$this->registerCmd("loc"); $this->registerCmd("loc");
$this->registerCmd("hotbar", "<slotcount>"); $this->registerCmd("hotbar", "<slotcount>");
$this->server->api->console->alias("lag", "ping"); $this->server->api->console->alias("lag", "ping");
$this->server->api->console->alias("gm", "gamemode"); $this->server->api->console->alias("gm", "gamemode");
$this->server->api->console->alias("who", "list"); $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){ 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}"; $message = " was shot by {$this->server->api->entity->entities[$e->shooterEID]->name}";
}else{ }else{
$message = " was shot"; $message = " was shot";
} }
}else{ }else{
$message = " was killed by {$e->name}"; $message = " was killed by {$e->name}";
} }
@ -104,12 +104,12 @@ class PlayerAPI{
case "hotbar": case "hotbar":
if(!($issuer instanceof Player)) return "Please run this command in-game."; if(!($issuer instanceof Player)) return "Please run this command in-game.";
if(count($args) < 1) return "Slots in hotbar on server: {$issuer->slotCount}"; if(count($args) < 1) return "Slots in hotbar on server: {$issuer->slotCount}";
$scrw = $args[0]; $scrw = $args[0];
if(is_numeric($scrw)){ if(is_numeric($scrw)){
$sc = (int)$scrw; $sc = (int) $scrw;
if($sc < 5 || $sc > 9) return "Slot count must be between 5 and 9."; if($sc < 5 || $sc > 9) return "Slot count must be between 5 and 9.";
$issuer->setSlotCount($sc); $issuer->setSlotCount($sc);
$issuer->sendInventory(); $issuer->sendInventory();
return "Changed slot count to $sc"; return "Changed slot count to $sc";
@ -235,10 +235,10 @@ class PlayerAPI{
$level = $issuer->entity->level->getName(); $level = $issuer->entity->level->getName();
$compass = [0 => "X+", 1 => "Z+", 2 => "X-", 3 => "Z-", null => "null"]; $compass = [0 => "X+", 1 => "Z+", 2 => "X-", 3 => "Z-", null => "null"];
$direction = $compass[$issuer->entity->getDirection()]; $direction = $compass[$issuer->entity->getDirection()];
$xChunk = $x >> 4; $xChunk = $x >> 4;
$zChunk = $z >> 4; $zChunk = $z >> 4;
return "Your coordinates: X: $x ($xChunk), Y: $y, Z: $z ($zChunk), world: $level.\nDirection: $direction"; return "Your coordinates: X: $x ($xChunk), Y: $y, Z: $z ($zChunk), world: $level.\nDirection: $direction";
} }
return $output; return $output;
@ -462,7 +462,7 @@ class PlayerAPI{
unset($player->entity->player); unset($player->entity->player);
//unset($player->entity); //unset($player->entity);
} }
$player = null; $player = null;
unset($player); unset($player);
} }

View file

@ -139,8 +139,8 @@ class PluginAPI extends stdClass{
if($ext2 === "phar"){ if($ext2 === "phar"){
++$pharCnt; ++$pharCnt;
$pluginInfo = []; //TODO: A PluginInfo class? $pluginInfo = []; //TODO: A PluginInfo class?
$filePath = $this->pluginsPath().$file; $filePath = $this->pluginsPath() . $file;
$p = new Phar($this->pluginsPath().$file, 0); $p = new Phar($this->pluginsPath() . $file, 0);
foreach (new RecursiveIteratorIterator($p) as $file) { foreach (new RecursiveIteratorIterator($p) as $file) {
$name = $file->getFileName(); $name = $file->getFileName();
$content = file_get_contents($file->getPathName()); $content = file_get_contents($file->getPathName());
@ -149,23 +149,23 @@ class PluginAPI extends stdClass{
break; break;
} }
} }
console("[INFO] Loading PHAR plugin \"".FORMAT_GREEN.$pluginInfo["name"].FORMAT_RESET."\" ".FORMAT_AQUA.$pluginInfo["version"].FORMAT_RESET." by ".FORMAT_AQUA.$pluginInfo["author"].FORMAT_RESET); console("[INFO] Loading PHAR plugin \"" . FORMAT_GREEN . $pluginInfo["name"] . FORMAT_RESET . "\" " . FORMAT_AQUA . $pluginInfo["version"] . FORMAT_RESET . " by " . FORMAT_AQUA . $pluginInfo["author"] . FORMAT_RESET);
$aver = CURRENT_API_VERSION; $aver = CURRENT_API_VERSION;
if(!in_array((string) CURRENT_API_VERSION, $pluginInfo["api"])){ if(!in_array((string) CURRENT_API_VERSION, $pluginInfo["api"])){
if(is_array($pluginInfo)) $s = implode(",",$pluginInfo["api"]); if(is_array($pluginInfo)) $s = implode(",",$pluginInfo["api"]);
else $s = $pluginInfo["api"]; else $s = $pluginInfo["api"];
console("[WARNING] API is not the same as Core, might cause bugs({$s} != {$aver})"); console("[WARNING] API is not the same as Core, might cause bugs({$s} != {$aver})");
} }
$phr = "phar://$filePath/"; $phr = "phar://$filePath/";
include($phr."/src/".$pluginInfo["classLoader"]); include($phr . "/src/" . $pluginInfo["classLoader"]);
$class = $pluginInfo["CLClass"]; $class = $pluginInfo["CLClass"];
$loader = new $class(); $loader = new $class();
$loader->loadAll($phr); $loader->loadAll($phr);
$pluginName = PharUtils::getNameSpaceClass($pluginInfo["mainFile"]); $pluginName = PharUtils::getNameSpaceClass($pluginInfo["mainFile"]);
include($phr."/src/".$pluginInfo["mainFile"]); include($phr . "/src/" . $pluginInfo["mainFile"]);
$plugin = new $pluginName($this->server->api, false); $plugin = new $pluginName($this->server->api, false);
if(!($plugin instanceof Plugin)){ if(!($plugin instanceof Plugin)){
console("[ERROR] Plugin \"" . $pluginInfo["name"] . "\" doesn't use the Plugin Interface"); console("[ERROR] Plugin \"" . $pluginInfo["name"] . "\" doesn't use the Plugin Interface");
@ -268,7 +268,7 @@ class PluginAPI extends stdClass{
$names[] = $p[1]["name"]; $names[] = $p[1]["name"];
$versions[] = $p[1]["version"]; $versions[] = $p[1]["version"];
} }
foreach($this->plugins as $p){ foreach($this->plugins as $p){
if($p[0] instanceof OtherPluginRequirement){ if($p[0] instanceof OtherPluginRequirement){
foreach($p[0]->getRequiredPlugins() as $required){ foreach($p[0]->getRequiredPlugins() as $required){
@ -312,4 +312,3 @@ class RequiredPluginEntry{ //Use this as object of requirements array
} }
} }

View file

@ -4,7 +4,7 @@ class ServerAPI{
private static $serverRequest = false; private static $serverRequest = false;
public $restart = false; public $restart = false;
/** /**
* @var QueryAPI * @var QueryAPI
*/ */
@ -59,7 +59,7 @@ class ServerAPI{
* @var QueryHandler * @var QueryHandler
*/ */
public $query; public $query;
private $asyncCalls = []; private $asyncCalls = [];
private $server; private $server;
private $config; private $config;

View file

@ -17,7 +17,7 @@ class TileAPI{
} }
return false; return false;
} }
public function invalidateAll(Level $level, $x, $y, $z){ public function invalidateAll(Level $level, $x, $y, $z){
$x = (int) $x; $x = (int) $x;
$y = (int) $y; $y = (int) $y;
@ -31,14 +31,14 @@ class TileAPI{
++$invcnt; ++$invcnt;
$tl->close(); $tl->close();
} }
if($invcnt > 1){ if($invcnt > 1){
ConsoleAPI::warn("{$level->getName()}: ($x $y $z) has more than 1 tile entity! Invalidated ID {$t["ID"]} (Total invaliated: $invcnt)"); ConsoleAPI::warn("{$level->getName()}: ($x $y $z) has more than 1 tile entity! Invalidated ID {$t["ID"]} (Total invaliated: $invcnt)");
} }
} }
} }
} }
public function get(Position $pos){ public function get(Position $pos){
$tile = $this->server->query("SELECT * FROM tiles WHERE level = '" . $pos->level->getName() . "' AND x = {$pos->x} AND y = {$pos->y} AND z = {$pos->z};", true); $tile = $this->server->query("SELECT * FROM tiles WHERE level = '" . $pos->level->getName() . "' AND x = {$pos->x} AND y = {$pos->y} AND z = {$pos->z};", true);
if($tile !== false and $tile !== true and ($tile = $this->getByID($tile["ID"])) !== false){ if($tile !== false and $tile !== true and ($tile = $this->getByID($tile["ID"])) !== false){

View file

@ -175,5 +175,4 @@ class TimeAPI{
return $this->set("sunset"); return $this->set("sunset");
} }
} }

View file

@ -1,6 +1,5 @@
<?php <?php
class Deprecation{ class Deprecation{
public static $events = [ public static $events = [

File diff suppressed because it is too large Load diff

View file

@ -1,18 +1,69 @@
<?php <?php
class PocketMinecraftServer{ class PocketMinecraftServer {
public $tCnt, $ticks; public $tCnt;
public $extraprops, $serverID, $interface, $database, $version, $invisible, $tickMeasure, $preparedSQL, $seed, $gamemode, $name, $maxClients, $clients, $eidCnt, $custom, $description, $motd, $port, $saveEnabled; public $ticks;
public $extraprops;
public $serverID;
public $interface;
public $database;
public $version;
public $invisible;
public $tickMeasure;
public $preparedSQL;
public $seed;
public $gamemode;
public $name;
public $maxClients;
public $clients;
public $eidCnt;
public $custom;
public $description;
public $motd;
public $port;
public $saveEnabled;
/** /**
* @var ServerAPI * @var ServerAPI
*/ */
public $api; public $api;
private $serverip, $evCnt, $handCnt, $events, $eventsID, $handlers, $serverType, $lastTick, $memoryStats, $async = [], $asyncID = 0; private $serverip;
private $evCnt;
public $doTick, $levelData, $tiles, $entities, $schedule, $scheduleCnt, $whitelist, $spawn, $difficulty, $stop, $asyncThread; private $handCnt;
public static $FORCE_20_TPS = false, $KEEP_CHUNKS_LOADED = true, $PACKET_READING_LIMIT = 100; private $events;
function __construct($name, $gamemode = SURVIVAL, $seed = false, $port = 19132, $serverip = "0.0.0.0"){ private $eventsID;
private $handlers;
private $serverType;
private $lastTick;
private $memoryStats;
private $async = [];
private $asyncID = 0;
public $doTick;
public $levelData;
public $tiles;
public $entities;
public $schedule;
public $scheduleCnt;
public $whitelist;
public $spawn;
public $difficulty;
public $stop;
public $asyncThread;
public static $FORCE_20_TPS = false;
public static $KEEP_CHUNKS_LOADED = true;
public static $PACKET_READING_LIMIT = 100;
public function __construct($name, $gamemode = SURVIVAL, $seed = false, $port = 19132, $serverip = "0.0.0.0") {
$this->port = (int) $port; $this->port = (int) $port;
$this->doTick = true; $this->doTick = true;
$this->gamemode = (int) $gamemode; $this->gamemode = (int) $gamemode;
@ -23,11 +74,10 @@ class PocketMinecraftServer{
$this->serverip = $serverip; $this->serverip = $serverip;
$this->load(); $this->load();
} }
public static $SAVE_PLAYER_DATA = true; public static $SAVE_PLAYER_DATA = true;
private function load() {
private function load(){
global $dolog; global $dolog;
/*if(defined("DEBUG") and DEBUG >= 0){ /*if(defined("DEBUG") and DEBUG >= 0){
@cli_set_process_title("NostalgiaCore ".MAJOR_VERSION); @cli_set_process_title("NostalgiaCore ".MAJOR_VERSION);
@ -70,7 +120,7 @@ class PocketMinecraftServer{
$this->interface = new MinecraftInterface("255.255.255.255", $this->port, $this->serverip); $this->interface = new MinecraftInterface("255.255.255.255", $this->port, $this->serverip);
$this->stop = false; $this->stop = false;
$this->ticks = 0; $this->ticks = 0;
if(!defined("NO_THREADS")){ if(!defined("NO_THREADS")) {
$this->asyncThread = new AsyncMultipleQueue(); $this->asyncThread = new AsyncMultipleQueue();
} }
console("[INFO] Loading extra.properties..."); console("[INFO] Loading extra.properties...");
@ -85,10 +135,10 @@ class PocketMinecraftServer{
"discord-ru-smiles" => false, "discord-ru-smiles" => false,
"discord-webhook-url" => "none", "discord-webhook-url" => "none",
"discord-bot-name" => "NostalgiaCore Logger", "discord-bot-name" => "NostalgiaCore Logger",
"despawn-mobs" => true, "despawn-mobs" => true,
"mob-despawn-ticks" => 18000, "mob-despawn-ticks" => 18000,
"16x16x16_chunk_sending" => false, "16x16x16_chunk_sending" => false,
"experimental-mob-ai" => false, "experimental-mob-ai" => false,
"force-20-tps" => false, "force-20-tps" => false,
"enable-mob-pushing" => Living::$entityPushing, "enable-mob-pushing" => Living::$entityPushing,
"keep-chunks-loaded" => self::$KEEP_CHUNKS_LOADED, "keep-chunks-loaded" => self::$KEEP_CHUNKS_LOADED,
@ -107,24 +157,24 @@ class PocketMinecraftServer{
MobController::$ADVANCED = $this->extraprops->get("experimental-mob-ai"); MobController::$ADVANCED = $this->extraprops->get("experimental-mob-ai");
Explosion::$enableExplosions = $this->extraprops->get("enable-explosions"); Explosion::$enableExplosions = $this->extraprops->get("enable-explosions");
NetherReactorBlock::$enableReactor = $this->extraprops->get("enable-nether-reactor"); NetherReactorBlock::$enableReactor = $this->extraprops->get("enable-nether-reactor");
if(self::$FORCE_20_TPS){ if(self::$FORCE_20_TPS) {
ConsoleAPI::warn("Forcing 20 tps. This may result in higher CPU usage!"); ConsoleAPI::warn("Forcing 20 tps. This may result in higher CPU usage!");
} }
if($this->extraprops->get("discord-msg")){ if($this->extraprops->get("discord-msg")) {
if($this->extraprops->get("discord-webhook-url") !== "none"){ if($this->extraprops->get("discord-webhook-url") !== "none") {
console("[INFO] Discord Logger is enabled."); console("[INFO] Discord Logger is enabled.");
}else{ } else {
console("[WARNING] Discord Logger is enabled in extra.properties,"); console("[WARNING] Discord Logger is enabled in extra.properties,");
console("[WARNING] but you didn't put the webhook url, so it won't work."); console("[WARNING] but you didn't put the webhook url, so it won't work.");
} }
}elseif($this->extraprops->get("version") == null){ } elseif($this->extraprops->get("version") == null) {
console("[WARNING] Your extra.properties file is corrupted!"); console("[WARNING] Your extra.properties file is corrupted!");
console("[WARNING] To fix it - just remove it! Server will generate it again automatically."); console("[WARNING] To fix it - just remove it! Server will generate it again automatically.");
} }
$dolog = $this->extraprops->get("save-console-data"); $dolog = $this->extraprops->get("save-console-data");
} }
public function onShutdown(){ public function onShutdown() {
console("[INFO] Saving..."); console("[INFO] Saving...");
$save = $this->saveEnabled; $save = $this->saveEnabled;
$this->saveEnabled = true; $this->saveEnabled = true;
@ -132,7 +182,7 @@ class PocketMinecraftServer{
$this->saveEnabled = $save; $this->saveEnabled = $save;
} }
public function startDatabase(){ public function startDatabase() {
$this->preparedSQL = new stdClass(); $this->preparedSQL = new stdClass();
$this->preparedSQL->entity = new stdClass(); $this->preparedSQL->entity = new stdClass();
$this->database = new SQLite3(":memory:"); $this->database = new SQLite3(":memory:");
@ -154,16 +204,16 @@ class PocketMinecraftServer{
$this->preparedSQL->entity->setLevel = $this->database->prepare("UPDATE entities SET level = :level WHERE EID = :eid ;"); $this->preparedSQL->entity->setLevel = $this->database->prepare("UPDATE entities SET level = :level WHERE EID = :eid ;");
} }
public function query($sql, $fetch = false){ public function query($sql, $fetch = false) {
$result = $this->database->query($sql) or console("[ERROR] [SQL Error] " . $this->database->lastErrorMsg() . ". Query: " . $sql, true, true, 0); $result = $this->database->query($sql) or console("[ERROR] [SQL Error] " . $this->database->lastErrorMsg() . ". Query: " . $sql, true, true, 0);
if($fetch === true and ($result instanceof SQLite3Result)){ if($fetch === true and ($result instanceof SQLite3Result)) {
$result = $result->fetchArray(SQLITE3_ASSOC); $result = $result->fetchArray(SQLITE3_ASSOC);
} }
return $result; return $result;
} }
public function setType($type = "normal"){ public function setType($type = "normal") {
switch(trim(strtolower($type))){ switch(trim(strtolower($type))) {
case "normal": case "normal":
case "demo": case "demo":
$this->serverType = "MCCPP;Demo;"; $this->serverType = "MCCPP;Demo;";
@ -174,9 +224,9 @@ class PocketMinecraftServer{
} }
} }
public function titleTick(){ public function titleTick() {
$time = microtime(true); $time = microtime(true);
if(defined("DEBUG") and DEBUG >= 0){ if(defined("DEBUG") and DEBUG >= 0) {
//echo "\x1b]0;NostalgiaCore " . MAJOR_VERSION . " | Online " . count($this->clients) . "/" . $this->maxClients . " | RAM " . round((memory_get_usage() / 1024) / 1024, 2) . "MB | U " . round(($this->interface->bandwidth[1] / max(1, $time - $this->interface->bandwidth[2])) / 1024, 2) . " D " . round(($this->interface->bandwidth[0] / max(1, $time - $this->interface->bandwidth[2])) / 1024, 2) . " kB/s | TPS " . $this->getTPS() . "\x07"; //echo "\x1b]0;NostalgiaCore " . MAJOR_VERSION . " | Online " . count($this->clients) . "/" . $this->maxClients . " | RAM " . round((memory_get_usage() / 1024) / 1024, 2) . "MB | U " . round(($this->interface->bandwidth[1] / max(1, $time - $this->interface->bandwidth[2])) / 1024, 2) . " D " . round(($this->interface->bandwidth[0] / max(1, $time - $this->interface->bandwidth[2])) / 1024, 2) . " kB/s | TPS " . $this->getTPS() . "\x07";
} }
@ -186,18 +236,18 @@ class PocketMinecraftServer{
/** /**
* @return float * @return float
*/ */
public function getTPS(){ public function getTPS() {
$v = array_values($this->tickMeasure); $v = array_values($this->tickMeasure);
$divval = ($v[39] - $v[0]); $divval = ($v[39] - $v[0]);
if($divval === 0){ if($divval === 0) {
return 0; return 0;
} }
$tps = 40 / $divval; $tps = 40 / $divval;
return round($tps, 4); return round($tps, 4);
} }
public function checkTicks(){ public function checkTicks() {
if($this->getTPS() < 12){ if($this->getTPS() < 12) {
console("[WARNING] Can't keep up! Is the server overloaded?"); console("[WARNING] Can't keep up! Is the server overloaded?");
} }
} }
@ -205,14 +255,14 @@ class PocketMinecraftServer{
/** /**
* @param string $reason * @param string $reason
*/ */
public function close($reason = "server stop"){ public function close($reason = "server stop") {
$this->onShutdown(); $this->onShutdown();
if($this->stop !== true){ if($this->stop !== true) {
if(is_int($reason)){ if(is_int($reason)) {
$reason = "signal stop"; $reason = "signal stop";
} }
if(($this->api instanceof ServerAPI) === true){ if(($this->api instanceof ServerAPI) === true) {
if(($this->api->chat instanceof ChatAPI) === true){ if(($this->api->chat instanceof ChatAPI) === true) {
$this->api->chat->send(false, "Stopping server..."); $this->api->chat->send(false, "Stopping server...");
self::$_tmp = new StopMessageThread($this, "[INFO] Stopping server..."); //broadcast didnt want to send message to discord for some reason self::$_tmp = new StopMessageThread($this, "[INFO] Stopping server..."); //broadcast didnt want to send message to discord for some reason
} }
@ -220,8 +270,8 @@ class PocketMinecraftServer{
$this->stop = true; $this->stop = true;
$this->trigger("server.close", $reason); $this->trigger("server.close", $reason);
$this->interface->close(); $this->interface->close();
if(!defined("NO_THREADS")){ if(!defined("NO_THREADS")) {
$this->asyncThread->synchronized(function ($t){ $this->asyncThread->synchronized(function ($t) {
$t->stop = true; $t->stop = true;
$t->notify(); $t->notify();
}, $this->asyncThread); }, $this->asyncThread);
@ -229,9 +279,9 @@ class PocketMinecraftServer{
} }
release_lock(); release_lock();
} }
public function send2Discord($msg){ public function send2Discord($msg) {
if($this->extraprops->get("discord-msg") and $this->extraprops->get("discord-webhook-url") !== "none"){ if($this->extraprops->get("discord-msg") and $this->extraprops->get("discord-webhook-url") !== "none") {
$url = $this->extraprops->get("discord-webhook-url"); $url = $this->extraprops->get("discord-webhook-url");
$name = $this->extraprops->get("discord-bot-name"); $name = $this->extraprops->get("discord-bot-name");
$this->asyncOperation(ASYNC_CURL_POST, [ $this->asyncOperation(ASYNC_CURL_POST, [
@ -243,16 +293,16 @@ class PocketMinecraftServer{
], null); ], null);
} }
} }
public function asyncOperation($type, array $data, callable $callable = null){ public function asyncOperation($type, array $data, callable $callable = null) {
if(defined("NO_THREADS")){ if(defined("NO_THREADS")) {
return false; return false;
} }
$d = ""; $d = "";
$type = (int) $type; $type = (int) $type;
switch($type){ switch($type) {
case ASYNC_CURL_GET: case ASYNC_CURL_GET:
if(isset($data["headers"])){ if(isset($data["headers"])) {
$jsstr = json_encode($data["headers"]); $jsstr = json_encode($data["headers"]);
} }
$d .= Utils::writeShort(strlen($data["url"])) . $data["url"] . (isset($data["timeout"]) ? Utils::writeShort($data["timeout"]) : Utils::writeShort(10)) . (isset($data["headers"]) ? Utils::writeShort(strlen($jsstr)) . $jsstr : Utils::writeShort(1) . " "); $d .= Utils::writeShort(strlen($data["url"])) . $data["url"] . (isset($data["timeout"]) ? Utils::writeShort($data["timeout"]) : Utils::writeShort(10)) . (isset($data["headers"]) ? Utils::writeShort(strlen($jsstr)) . $jsstr : Utils::writeShort(1) . " ");
@ -260,7 +310,7 @@ class PocketMinecraftServer{
case ASYNC_CURL_POST: case ASYNC_CURL_POST:
$d .= Utils::writeShort(strlen($data["url"])) . $data["url"] . (isset($data["timeout"]) ? Utils::writeShort($data["timeout"]) : Utils::writeShort(10)); $d .= Utils::writeShort(strlen($data["url"])) . $data["url"] . (isset($data["timeout"]) ? Utils::writeShort($data["timeout"]) : Utils::writeShort(10));
$d .= Utils::writeShort(count($data["data"])); $d .= Utils::writeShort(count($data["data"]));
foreach($data["data"] as $key => $value){ foreach($data["data"] as $key => $value) {
$d .= Utils::writeShort(strlen($key)) . $key . Utils::writeInt(strlen($value)) . $value; $d .= Utils::writeShort(strlen($key)) . $key . Utils::writeInt(strlen($value)) . $value;
} }
break; break;
@ -273,55 +323,55 @@ class PocketMinecraftServer{
return $ID; return $ID;
} }
public function trigger($event, $data = ""){ public function trigger($event, $data = "") {
if(isset($this->events[$event])){ if(isset($this->events[$event])) {
foreach($this->events[$event] as $evid => $ev){ foreach($this->events[$event] as $evid => $ev) {
if(!is_callable($ev)){ if(!is_callable($ev)) {
$this->deleteEvent($evid); $this->deleteEvent($evid);
continue; continue;
} }
if(is_array($ev)){ if(is_array($ev)) {
$method = $ev[1]; $method = $ev[1];
$ev[0]->$method($data, $event); $ev[0]->$method($data, $event);
}else{ } else {
$ev($data, $event); $ev($data, $event);
} }
} }
}elseif(isset(Deprecation::$events[$event])){ } elseif(isset(Deprecation::$events[$event])) {
$sub = ""; $sub = "";
if(Deprecation::$events[$event] !== false){ if(Deprecation::$events[$event] !== false) {
$sub = " Substitute \"" . Deprecation::$events[$event] . "\" found."; $sub = " Substitute \"" . Deprecation::$events[$event] . "\" found.";
} }
console("[ERROR] Event \"$event\" has been deprecated.$sub [Trigger]"); console("[ERROR] Event \"$event\" has been deprecated.$sub [Trigger]");
} }
} }
public function deleteEvent($id){ public function deleteEvent($id) {
$id = (int) $id; $id = (int) $id;
if(isset($this->eventsID[$id])){ if(isset($this->eventsID[$id])) {
$ev = $this->eventsID[$id]; $ev = $this->eventsID[$id];
$this->eventsID[$id] = null; $this->eventsID[$id] = null;
unset($this->eventsID[$id]); unset($this->eventsID[$id]);
$this->events[$ev][$id] = null; $this->events[$ev][$id] = null;
unset($this->events[$ev][$id]); unset($this->events[$ev][$id]);
if(count($this->events[$ev]) === 0){ if(count($this->events[$ev]) === 0) {
unset($this->events[$ev]); unset($this->events[$ev]);
} }
} }
} }
public function asyncOperationChecker(){ public function asyncOperationChecker() {
if(defined("NO_THREADS")){ if(defined("NO_THREADS")) {
return false; return false;
} }
if(isset($this->asyncThread->output[5])){ if(isset($this->asyncThread->output[5])) {
$offset = 0; $offset = 0;
$ID = Utils::readInt(substr($this->asyncThread->output, $offset, 4)); $ID = Utils::readInt(substr($this->asyncThread->output, $offset, 4));
$offset += 4; $offset += 4;
$type = Utils::readShort(substr($this->asyncThread->output, $offset, 2)); $type = Utils::readShort(substr($this->asyncThread->output, $offset, 2));
$offset += 2; $offset += 2;
$data = []; $data = [];
switch($type){ switch($type) {
case ASYNC_CURL_GET: case ASYNC_CURL_GET:
case ASYNC_CURL_POST: case ASYNC_CURL_POST:
$len = Utils::readInt(substr($this->asyncThread->output, $offset, 4)); $len = Utils::readInt(substr($this->asyncThread->output, $offset, 4));
@ -333,11 +383,11 @@ class PocketMinecraftServer{
} }
$this->asyncThread->output = substr($this->asyncThread->output, $offset); $this->asyncThread->output = substr($this->asyncThread->output, $offset);
if(isset($this->async[$ID]) and $this->async[$ID] !== null and is_callable($this->async[$ID])){ if(isset($this->async[$ID]) and $this->async[$ID] !== null and is_callable($this->async[$ID])) {
if(is_array($this->async[$ID])){ if(is_array($this->async[$ID])) {
$method = $this->async[$ID][1]; $method = $this->async[$ID][1];
$result = $this->async[$ID][0]->$method($data, $type, $ID); $result = $this->async[$ID][0]->$method($data, $type, $ID);
}else{ } else {
$result = $this->async[$ID]($data, $type, $ID); $result = $this->async[$ID]($data, $type, $ID);
} }
} }
@ -347,17 +397,16 @@ class PocketMinecraftServer{
/** /**
* @param string $event * @param string $event
* @param callable $callable
* @param integer $priority * @param integer $priority
* *
* @return boolean * @return boolean
*/ */
public function addHandler($event, callable $callable, $priority = 5){ public function addHandler($event, callable $callable, $priority = 5) {
if(!is_callable($callable)){ if(!is_callable($callable)) {
return false; return false;
}elseif(isset(Deprecation::$events[$event])){ } elseif(isset(Deprecation::$events[$event])) {
$sub = ""; $sub = "";
if(Deprecation::$events[$event] !== false){ if(Deprecation::$events[$event] !== false) {
$sub = " Substitute \"" . Deprecation::$events[$event] . "\" found."; $sub = " Substitute \"" . Deprecation::$events[$event] . "\" found.";
} }
console("[ERROR] Event \"$event\" has been deprecated.$sub [Adding handle to " . (is_array($callable) ? get_class($callable[0]) . "::" . $callable[1] : $callable) . "]"); console("[ERROR] Event \"$event\" has been deprecated.$sub [Adding handle to " . (is_array($callable) ? get_class($callable[0]) . "::" . $callable[1] : $callable) . "]");
@ -370,77 +419,77 @@ class PocketMinecraftServer{
return $hnid; return $hnid;
} }
public function dhandle($e, $d){ public function dhandle($e, $d) {
return $this->handle($e, $d); return $this->handle($e, $d);
} }
public function handle($event, &$data){ public function handle($event, &$data) {
$this->preparedSQL->selectHandlers->reset(); $this->preparedSQL->selectHandlers->reset();
$this->preparedSQL->selectHandlers->clear(); $this->preparedSQL->selectHandlers->clear();
$this->preparedSQL->selectHandlers->bindValue(":name", $event, SQLITE3_TEXT); $this->preparedSQL->selectHandlers->bindValue(":name", $event, SQLITE3_TEXT);
$handlers = $this->preparedSQL->selectHandlers->execute(); $handlers = $this->preparedSQL->selectHandlers->execute();
$result = null; $result = null;
if($handlers instanceof SQLite3Result){ if($handlers instanceof SQLite3Result) {
$call = []; $call = [];
while(($hn = $handlers->fetchArray(SQLITE3_ASSOC)) !== false){ while(($hn = $handlers->fetchArray(SQLITE3_ASSOC)) !== false) {
$call[(int) $hn["ID"]] = true; $call[(int) $hn["ID"]] = true;
} }
$handlers->finalize(); $handlers->finalize();
foreach($call as $hnid => $boolean){ foreach($call as $hnid => $boolean) {
if($result !== false and $result !== true){ if($result !== false and $result !== true) {
$called[$hnid] = true; $called[$hnid] = true;
$handler = $this->handlers[$hnid]; $handler = $this->handlers[$hnid];
if(is_array($handler)){ if(is_array($handler)) {
$method = $handler[1]; $method = $handler[1];
$result = $handler[0]->$method($data, $event); $result = $handler[0]->$method($data, $event);
}else{ } else {
$result = $handler($data, $event); $result = $handler($data, $event);
} }
}else{ } else {
break; break;
} }
} }
}elseif(isset(Deprecation::$events[$event])){ } elseif(isset(Deprecation::$events[$event])) {
$sub = ""; $sub = "";
if(Deprecation::$events[$event] !== false){ if(Deprecation::$events[$event] !== false) {
$sub = " Substitute \"" . Deprecation::$events[$event] . "\" found."; $sub = " Substitute \"" . Deprecation::$events[$event] . "\" found.";
} }
console("[ERROR] Event \"$event\" has been deprecated.$sub [Handler]"); console("[ERROR] Event \"$event\" has been deprecated.$sub [Handler]");
} }
if($result !== false){ if($result !== false) {
$this->trigger($event, $data); $this->trigger($event, $data);
} }
return $result; return $result;
} }
public function eventHandler($data, $event){ public function eventHandler($data, $event) {
switch($event){ switch($event) {
} }
} }
public function init(){ public function init() {
register_tick_function([$this, "tick"]); register_tick_function([$this, "tick"]);
declare(ticks=5000); //Minimum TPS for main thread locks declare(ticks=5000); //Minimum TPS for main thread locks
$this->loadEvents(); $this->loadEvents();
register_shutdown_function([$this, "dumpError"]); register_shutdown_function([$this, "dumpError"]);
register_shutdown_function([$this, "close"]); register_shutdown_function([$this, "close"]);
if(function_exists("pcntl_signal")){ if(function_exists("pcntl_signal")) {
pcntl_signal(SIGTERM, [$this, "close"]); pcntl_signal(SIGTERM, [$this, "close"]);
pcntl_signal(SIGINT, [$this, "close"]); pcntl_signal(SIGINT, [$this, "close"]);
pcntl_signal(SIGHUP, [$this, "close"]); pcntl_signal(SIGHUP, [$this, "close"]);
} }
console("[INFO] Default game type: " . strtoupper($this->getGamemode())); console("[INFO] Default game type: " . strtoupper($this->getGamemode()));
$this->trigger("server.start", microtime(true)); $this->trigger("server.start", microtime(true));
console('[INFO] Done (' . round(microtime(true) - START_TIME, 3) . 's)! For help, type "help" or "?"'); console('[INFO] Done (' . round(microtime(true) - START_TIME, 3) . 's)! For help, type "help" or "?"');
$this->process(); $this->process();
} }
public function loadEvents(){ public function loadEvents() {
if(ENABLE_ANSI === true){ if(ENABLE_ANSI === true) {
$this->schedule(30, [$this, "titleTick"], [], true); $this->schedule(30, [$this, "titleTick"], [], true);
} }
$this->schedule(20 * 15, [$this, "checkTicks"], [], true); $this->schedule(20 * 15, [$this, "checkTicks"], [], true);
@ -448,11 +497,11 @@ class PocketMinecraftServer{
$this->schedule(20, [$this, "asyncOperationChecker"], [], true); $this->schedule(20, [$this, "asyncOperationChecker"], [], true);
} }
public function schedule($ticks, callable $callback, $data = [], $repeat = false, $eventName = "server.schedule"){ public function schedule($ticks, callable $callback, $data = [], $repeat = false, $eventName = "server.schedule") {
if(!is_callable($callback)){ if(!is_callable($callback)) {
return false; return false;
} }
$chcnt = $this->scheduleCnt++; $chcnt = $this->scheduleCnt++;
$this->schedule[$chcnt] = [$callback, $data, $eventName]; $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) . ");"); $this->query("INSERT INTO actions (ID, interval, last, repeat) VALUES(" . $chcnt . ", " . ($ticks / 20) . ", " . microtime(true) . ", " . (((bool) $repeat) === true ? 1 : 0) . ");");
@ -462,8 +511,8 @@ class PocketMinecraftServer{
/** /**
* @return string * @return string
*/ */
public function getGamemode(){ public function getGamemode() {
switch($this->gamemode){ switch($this->gamemode) {
case SURVIVAL: case SURVIVAL:
return "survival"; return "survival";
case CREATIVE: case CREATIVE:
@ -475,71 +524,69 @@ class PocketMinecraftServer{
} }
} }
public function process() public function process() {
{
$lastLoop = 0; $lastLoop = 0;
if(self::$FORCE_20_TPS){ if(self::$FORCE_20_TPS) {
while($this->stop === false){ while($this->stop === false) {
$packetcnt = 0; $packetcnt = 0;
while($packet = $this->interface->readPacket()){ while($packet = $this->interface->readPacket()) {
if($packet instanceof Packet) { if($packet instanceof Packet) {
$this->packetHandler($packet); $this->packetHandler($packet);
if(++$packetcnt > self::$PACKET_READING_LIMIT){ if(++$packetcnt > self::$PACKET_READING_LIMIT) {
ConsoleAPI::warn("Reading more than ".self::$PACKET_READING_LIMIT." packets per tick! Forcing ticking!"); ConsoleAPI::warn("Reading more than " . self::$PACKET_READING_LIMIT . " packets per tick! Forcing ticking!");
break; break;
} }
} }
} }
$this->tick(); $this->tick();
} }
}else{ } else {
while($this->stop === false){ while($this->stop === false) {
$packetcnt = 0; $packetcnt = 0;
startReadingAgain: startReadingAgain:
$packet = $this->interface->readPacket(); $packet = $this->interface->readPacket();
if($packet instanceof Packet){ if($packet instanceof Packet) {
$this->packetHandler($packet); $this->packetHandler($packet);
$lastLoop = 0; $lastLoop = 0;
if(++$packetcnt > self::$PACKET_READING_LIMIT){ if(++$packetcnt > self::$PACKET_READING_LIMIT) {
ConsoleAPI::warn("Reading more than ".self::$PACKET_READING_LIMIT." packets per tick! Forcing ticking!"); ConsoleAPI::warn("Reading more than " . self::$PACKET_READING_LIMIT . " packets per tick! Forcing ticking!");
}else{ } else {
goto startReadingAgain; goto startReadingAgain;
} }
} elseif($this->tick() > 0){ } elseif($this->tick() > 0) {
$lastLoop = 0; $lastLoop = 0;
} else{ } else {
++$lastLoop; ++$lastLoop;
if($lastLoop < 16){ if($lastLoop < 16) {
usleep(1); usleep(1);
} elseif($lastLoop < 128){ } elseif($lastLoop < 128) {
usleep(100); usleep(100);
} elseif($lastLoop < 256){ } elseif($lastLoop < 256) {
usleep(512); usleep(512);
} else{ } else {
usleep(10000); usleep(10000);
} }
} }
$this->tick(); $this->tick();
} }
} }
} }
public function packetHandler(Packet $packet){ public function packetHandler(Packet $packet) {
$data =& $packet; $data = &$packet;
$CID = PocketMinecraftServer::clientID($packet->ip, $packet->port); $CID = PocketMinecraftServer::clientID($packet->ip, $packet->port);
if(isset($this->clients[$CID])){ if(isset($this->clients[$CID])) {
$this->clients[$CID]->handlePacket($packet); $this->clients[$CID]->handlePacket($packet);
}else{ } else {
if($this->handle("server.noauthpacket." . $packet->pid(), $packet) === false){ if($this->handle("server.noauthpacket." . $packet->pid(), $packet) === false) {
return; return;
} }
switch($packet->pid()){ switch($packet->pid()) {
case RakNetInfo::UNCONNECTED_PING: case RakNetInfo::UNCONNECTED_PING:
case RakNetInfo::UNCONNECTED_PING_OPEN_CONNECTIONS: case RakNetInfo::UNCONNECTED_PING_OPEN_CONNECTIONS:
if($this->invisible === true){ if($this->invisible === true) {
$pk = new RakNetPacket(RakNetInfo::UNCONNECTED_PONG); $pk = new RakNetPacket(RakNetInfo::UNCONNECTED_PONG);
$pk->pingID = $packet->pingID; $pk->pingID = $packet->pingID;
$pk->serverID = $this->serverID; $pk->serverID = $this->serverID;
@ -549,11 +596,11 @@ class PocketMinecraftServer{
$this->send($pk); $this->send($pk);
break; break;
} }
if(!isset($this->custom["times_" . $CID])){ if(!isset($this->custom["times_" . $CID])) {
$this->custom["times_" . $CID] = 0; $this->custom["times_" . $CID] = 0;
} }
$ln = 15; $ln = 15;
if($this->description == "" or !str_ends_with($this->description, " ")){ if($this->description == "" or !str_ends_with($this->description, " ")) {
$this->description .= " "; $this->description .= " ";
} }
$txt = substr($this->description, $this->custom["times_" . $CID], $ln); $txt = substr($this->description, $this->custom["times_" . $CID], $ln);
@ -568,14 +615,14 @@ class PocketMinecraftServer{
$this->custom["times_" . $CID] = ($this->custom["times_" . $CID] + 1) % strlen($this->description); $this->custom["times_" . $CID] = ($this->custom["times_" . $CID] + 1) % strlen($this->description);
break; break;
case RakNetInfo::OPEN_CONNECTION_REQUEST_1: case RakNetInfo::OPEN_CONNECTION_REQUEST_1:
if($packet->structure !== RakNetInfo::STRUCTURE){ if($packet->structure !== RakNetInfo::STRUCTURE) {
console("[DEBUG] Incorrect structure #" . $packet->structure . " from " . $packet->ip . ":" . $packet->port, true, true, 2); console("[DEBUG] Incorrect structure #" . $packet->structure . " from " . $packet->ip . ":" . $packet->port, true, true, 2);
$pk = new RakNetPacket(RakNetInfo::INCOMPATIBLE_PROTOCOL_VERSION); $pk = new RakNetPacket(RakNetInfo::INCOMPATIBLE_PROTOCOL_VERSION);
$pk->serverID = $this->serverID; $pk->serverID = $this->serverID;
$pk->ip = $packet->ip; $pk->ip = $packet->ip;
$pk->port = $packet->port; $pk->port = $packet->port;
$this->send($pk); $this->send($pk);
}else{ } else {
$pk = new RakNetPacket(RakNetInfo::OPEN_CONNECTION_REPLY_1); $pk = new RakNetPacket(RakNetInfo::OPEN_CONNECTION_REPLY_1);
$pk->serverID = $this->serverID; $pk->serverID = $this->serverID;
$pk->mtuSize = strlen($packet->buffer); $pk->mtuSize = strlen($packet->buffer);
@ -585,7 +632,7 @@ class PocketMinecraftServer{
} }
break; break;
case RakNetInfo::OPEN_CONNECTION_REQUEST_2: case RakNetInfo::OPEN_CONNECTION_REQUEST_2:
if($this->invisible === true){ if($this->invisible === true) {
break; break;
} }
@ -601,30 +648,30 @@ class PocketMinecraftServer{
} }
} }
public static function clientID($ip, $port){ public static function clientID($ip, $port) {
return crc32($ip . $port) ^ crc32($port . $ip . BOOTUP_RANDOM); return crc32($ip . $port) ^ crc32($port . $ip . BOOTUP_RANDOM);
//return $ip . ":" . $port; //return $ip . ":" . $port;
} }
public function send(Packet $packet){ public function send(Packet $packet) {
return $this->interface->writePacket($packet); return $this->interface->writePacket($packet);
} }
public function tick(){ public function tick() {
$time = microtime(true); $time = microtime(true);
if($this->lastTick <= ($time - 0.05)){ if($this->lastTick <= ($time - 0.05)) {
$this->tickMeasure[] = $this->lastTick = $time; $this->tickMeasure[] = $this->lastTick = $time;
unset($this->tickMeasure[key($this->tickMeasure)]); unset($this->tickMeasure[key($this->tickMeasure)]);
++$this->ticks; ++$this->ticks;
foreach($this->clients as $client){ foreach($this->clients as $client) {
$client->handlePacketQueues(); $client->handlePacketQueues();
if($this->ticks % 40 == 0){ //2s if($this->ticks % 40 == 0) { //2s
$client->sendPing(); $client->sendPing();
} }
} }
foreach($this->api->level->levels as $l){ foreach($this->api->level->levels as $l) {
$l->onTick($this, $time); $l->onTick($this, $time);
} }
$r = $this->tickerFunction($time); $r = $this->tickerFunction($time);
@ -633,34 +680,34 @@ class PocketMinecraftServer{
return 0; return 0;
} }
public function tickerFunction($time){ public function tickerFunction($time) {
//actions that repeat every x time will go here //actions that repeat every x time will go here
$this->preparedSQL->selectActions->reset(); $this->preparedSQL->selectActions->reset();
$this->preparedSQL->selectActions->bindValue(":time", $time, SQLITE3_FLOAT); $this->preparedSQL->selectActions->bindValue(":time", $time, SQLITE3_FLOAT);
$actions = $this->preparedSQL->selectActions->execute(); $actions = $this->preparedSQL->selectActions->execute();
$actionCount = 0; $actionCount = 0;
if($actions instanceof SQLite3Result){ if($actions instanceof SQLite3Result) {
while(($action = $actions->fetchArray(SQLITE3_ASSOC)) !== false){ while(($action = $actions->fetchArray(SQLITE3_ASSOC)) !== false) {
$cid = $action["ID"]; $cid = $action["ID"];
$this->preparedSQL->updateAction->reset(); $this->preparedSQL->updateAction->reset();
$this->preparedSQL->updateAction->bindValue(":time", $time, SQLITE3_FLOAT); $this->preparedSQL->updateAction->bindValue(":time", $time, SQLITE3_FLOAT);
$this->preparedSQL->updateAction->bindValue(":id", $cid, SQLITE3_INTEGER); $this->preparedSQL->updateAction->bindValue(":id", $cid, SQLITE3_INTEGER);
$this->preparedSQL->updateAction->execute(); $this->preparedSQL->updateAction->execute();
if(isset($this->schedule[$cid]) && is_array($this->schedule[$cid]) && isset($this->schedule[$cid][0]) && is_callable($this->schedule[$cid][0])){ if(isset($this->schedule[$cid]) && is_array($this->schedule[$cid]) && isset($this->schedule[$cid][0]) && is_callable($this->schedule[$cid][0])) {
++$actionCount; ++$actionCount;
try{ try {
$return = @call_user_func($this->schedule[$cid][0] ?? function(){}, $this->schedule[$cid][1], $this->schedule[$cid][2]); //somehow args can be null $return = @call_user_func($this->schedule[$cid][0] ?? function () {}, $this->schedule[$cid][1], $this->schedule[$cid][2]); //somehow args can be null
}catch(TypeError $e){ } catch(TypeError $e) {
$m = $e->getMessage()."\nStack trace:\n".$e->getTraceAsString(); $m = $e->getMessage() . "\nStack trace:\n" . $e->getTraceAsString();
ConsoleAPI::error($m); ConsoleAPI::error($m);
$return = false; $return = false;
} }
}else{ } else {
$return = false; $return = false;
} }
if($action["repeat"] == 0 or $return === false){ if($action["repeat"] == 0 or $return === false) {
$this->query("DELETE FROM actions WHERE ID = " . $action["ID"] . ";"); $this->query("DELETE FROM actions WHERE ID = " . $action["ID"] . ";");
$this->schedule[$cid] = null; $this->schedule[$cid] = null;
unset($this->schedule[$cid]); unset($this->schedule[$cid]);
@ -671,8 +718,8 @@ class PocketMinecraftServer{
return $actionCount; return $actionCount;
} }
public function dumpError(){ public function dumpError() {
if($this->stop === true){ if($this->stop === true) {
return; return;
} }
ini_set("memory_limit", "-1"); //Fix error dump not dumped on memory problems ini_set("memory_limit", "-1"); //Fix error dump not dumped on memory problems
@ -698,18 +745,18 @@ class PocketMinecraftServer{
]; ];
$er["type"] = $errorConversion[$er["type"]] ?? $er["type"]; $er["type"] = $errorConversion[$er["type"]] ?? $er["type"];
$dump .= "Error: " . var_export($er, true) . "\r\n\r\n"; $dump .= "Error: " . var_export($er, true) . "\r\n\r\n";
if(stripos($er["file"], "plugin") !== false){ if(stripos($er["file"], "plugin") !== false) {
$dump .= "THIS ERROR WAS CAUSED BY A PLUGIN. REPORT IT TO THE PLUGIN DEVELOPER.\r\n"; $dump .= "THIS ERROR WAS CAUSED BY A PLUGIN. REPORT IT TO THE PLUGIN DEVELOPER.\r\n";
} }
$dump .= "Code: \r\n"; $dump .= "Code: \r\n";
$file = @file($er["file"], FILE_IGNORE_NEW_LINES); $file = @file($er["file"], FILE_IGNORE_NEW_LINES);
for($l = max(0, $er["line"] - 10); $l < $er["line"] + 10; ++$l){ for($l = max(0, $er["line"] - 10); $l < $er["line"] + 10; ++$l) {
$dump .= "[" . ($l + 1) . "] " . @$file[$l] . "\r\n"; $dump .= "[" . ($l + 1) . "] " . @$file[$l] . "\r\n";
} }
$dump .= "\r\n\r\n"; $dump .= "\r\n\r\n";
$dump .= "Backtrace: \r\n"; $dump .= "Backtrace: \r\n";
foreach(getTrace() as $line){ foreach(getTrace() as $line) {
$dump .= "$line\r\n"; $dump .= "$line\r\n";
} }
$dump .= "\r\n\r\n"; $dump .= "\r\n\r\n";
@ -724,21 +771,21 @@ class PocketMinecraftServer{
global $arguments; global $arguments;
$dump .= "Parameters: " . var_export($arguments, true) . "\r\n\r\n\r\n"; $dump .= "Parameters: " . var_export($arguments, true) . "\r\n\r\n\r\n";
$p = $this->api->getProperties(); $p = $this->api->getProperties();
if($p["rcon.password"] != ""){ if($p["rcon.password"] != "") {
$p["rcon.password"] = "******"; $p["rcon.password"] = "******";
} }
$dump .= "server.properties: " . var_export($p, true) . "\r\n\r\n\r\n"; $dump .= "server.properties: " . var_export($p, true) . "\r\n\r\n\r\n";
if($this->api->plugin instanceof PluginAPI){ if($this->api->plugin instanceof PluginAPI) {
$plist = $this->api->plugin->getList(); $plist = $this->api->plugin->getList();
$dump .= "Loaded plugins:\r\n"; $dump .= "Loaded plugins:\r\n";
foreach($plist as $p){ foreach($plist as $p) {
$dump .= $p["name"] . " " . $p["version"] . " by " . $p["author"] . "\r\n"; $dump .= $p["name"] . " " . $p["version"] . " by " . $p["author"] . "\r\n";
} }
$dump .= "\r\n\r\n"; $dump .= "\r\n\r\n";
} }
$extensions = []; $extensions = [];
foreach(get_loaded_extensions() as $ext){ foreach(get_loaded_extensions() as $ext) {
$extensions[$ext] = phpversion($ext); $extensions[$ext] = phpversion($ext);
} }
@ -759,7 +806,7 @@ class PocketMinecraftServer{
console("[SEVERE] Please submit the \"{$name}.log\" file to the Bug Reporting page. Give as much info as you can.", true, true, 0); console("[SEVERE] Please submit the \"{$name}.log\" file to the Bug Reporting page. Give as much info as you can.", true, true, 0);
} }
public function debugInfo($console = false){ public function debugInfo($console = false) {
$info = []; $info = [];
$info["tps"] = $this->getTPS(); $info["tps"] = $this->getTPS();
$info["memory_usage"] = round((memory_get_usage() / 1024) / 1024, 2) . "MB"; $info["memory_usage"] = round((memory_get_usage() / 1024) / 1024, 2) . "MB";
@ -773,33 +820,33 @@ class PocketMinecraftServer{
$info["actions"] = $info["actions"]["count"]; $info["actions"] = $info["actions"]["count"];
$info["garbage"] = gc_collect_cycles(); $info["garbage"] = gc_collect_cycles();
$this->handle("server.debug", $info); $this->handle("server.debug", $info);
if($console === true){ if($console === true) {
console("[INFO] TPS: " . $info["tps"] . ", Memory usage: " . $info["memory_usage"] . " (Peak " . $info["memory_peak_usage"] . "), Entities: " . $info["entities"] . ", Events: " . $info["events"] . ", Handlers: " . $info["handlers"] . ", Actions: " . $info["actions"] . ", Garbage: " . $info["garbage"], true, true); 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; return $info;
} }
public function checkMemory(){ public function checkMemory() {
$info = $this->debugInfo(); $info = $this->debugInfo();
$data = $info["memory_usage"] . "," . $info["players"] . "," . $info["entities"]; $data = $info["memory_usage"] . "," . $info["players"] . "," . $info["entities"];
$i = count($this->memoryStats) - 1; $i = count($this->memoryStats) - 1;
if($i < 0 or $this->memoryStats[$i] !== $data){ if($i < 0 or $this->memoryStats[$i] !== $data) {
$this->memoryStats[] = $data; $this->memoryStats[] = $data;
} }
} }
public function event($event, callable $func){ public function event($event, callable $func) {
if(!is_callable($func)){ if(!is_callable($func)) {
return false; return false;
}elseif(isset(Deprecation::$events[$event])){ } elseif(isset(Deprecation::$events[$event])) {
$sub = ""; $sub = "";
if(Deprecation::$events[$event] !== false){ if(Deprecation::$events[$event] !== false) {
$sub = " Substitute \"" . Deprecation::$events[$event] . "\" found."; $sub = " Substitute \"" . Deprecation::$events[$event] . "\" found.";
} }
console("[ERROR] Event \"$event\" has been deprecated.$sub [Attach to " . (is_array($func) ? get_class($func[0]) . "::" . $func[1] : $func) . "]"); console("[ERROR] Event \"$event\" has been deprecated.$sub [Attach to " . (is_array($func) ? get_class($func[0]) . "::" . $func[1] : $func) . "]");
} }
$evid = $this->evCnt++; $evid = $this->evCnt++;
if(!isset($this->events[$event])){ if(!isset($this->events[$event])) {
$this->events[$event] = []; $this->events[$event] = [];
} }
$this->events[$event][$evid] = $func; $this->events[$event][$evid] = $func;

View file

@ -1,14 +1,15 @@
<?php <?php
class TileNavigator class TileNavigator
{ {
const OFFSETS = [ const OFFSETS = [
[0, 0, 1], [0, 0, 1],
[0, 0, -1], [0, 0, -1],
[1, 0, 0], [1, 0, 0],
[-1, 0, 0], [-1, 0, 0],
]; ];
public static $pathfinderAccessed = 0; public static $pathfinderAccessed = 0;
public $entity; public $entity;
public $avoidFallDamage = true; public $avoidFallDamage = true;
@ -17,13 +18,13 @@ class TileNavigator
$this->entity = $entity; $this->entity = $entity;
$this->tall = $entity->height > 1; $this->tall = $entity->height > 1;
} }
public function reconstructPath($path, $current){ public function reconstructPath($path, $current){
console("path built"); console("path built");
$totalPath = [$current]; $totalPath = [$current];
while (isset($path[(string)$current])) while (isset($path[(string) $current]))
{ {
$current = $path[(string)$current]; $current = $path[(string) $current];
$totalPath[] = $current; $totalPath[] = $current;
} }
//foreach(array_unique($path) as $k => $p) console($k.":".$p); //foreach(array_unique($path) as $k => $p) console($k.":".$p);
@ -33,17 +34,17 @@ class TileNavigator
} }
public function isLocBlocked(PMFLevel $level, $loc){ public function isLocBlocked(PMFLevel $level, $loc){
$chunkX = $loc >> 20 & 0xf; $chunkX = $loc >> 20 & 0xf;
$chunkZ = $loc >> 12 & 0xf; $chunkZ = $loc >> 12 & 0xf;
$chunkY = $loc >> 4 & 0xf; $chunkY = $loc >> 4 & 0xf;
$index = $chunkZ << 4 | $chunkX; $index = $chunkZ << 4 | $chunkX;
$blockX = $loc >> 16 & 0xf; $blockX = $loc >> 16 & 0xf;
$blockZ = $loc >> 8 & 0xf; $blockZ = $loc >> 8 & 0xf;
$blockY = $loc & 0xf; $blockY = $loc & 0xf;
$id = $level->fastGetBlockID($chunkX, $chunkY, $chunkZ, $blockX, $blockY, $blockZ, $index); $id = $level->fastGetBlockID($chunkX, $chunkY, $chunkZ, $blockX, $blockY, $blockZ, $index);
$b = StaticBlock::getIsSolid($id); $b = StaticBlock::getIsSolid($id);
if($this->tall){ if($this->tall){
@ -53,33 +54,32 @@ class TileNavigator
$id = $level->fastGetBlockID($chunkX, $chunkY, $chunkZ, $blockX, $blockY, $blockZ, $index); $id = $level->fastGetBlockID($chunkX, $chunkY, $chunkZ, $blockX, $blockY, $blockZ, $index);
return $b || StaticBlock::getIsSolid($id); return $b || StaticBlock::getIsSolid($id);
} }
return $b; return $b;
} }
public function navigate(Level $level, $fromX, $fromY, $fromZ, $toX, $toY, $toZ, $maxDist) public function navigate(Level $level, $fromX, $fromY, $fromZ, $toX, $toY, $toZ, $maxDist)
{ {
$from = $fromX << 16 | $fromZ << 8 | $fromY; $from = $fromX << 16 | $fromZ << 8 | $fromY;
$to = $toX << 16 | $toZ << 8 | $toY; $to = $toX << 16 | $toZ << 8 | $toY;
$pmfLevel = $level->level; $pmfLevel = $level->level;
$open = new SplPriorityQueue(); $open = new SplPriorityQueue();
//$open->insert(, 0); //$open->insert(, 0);
$open->insert($from, 0); $open->insert($from, 0);
$path = []; $path = [];
$gScore = []; $gScore = [];
$gScore[(string) $from] = 0; $gScore[(string) $from] = 0;
$has = [(string)$from, true]; $has = [(string) $from, true];
if($this->isLocBlocked($pmfLevel, $to)){ if($this->isLocBlocked($pmfLevel, $to)){
return null; return null;
} }
$visited = []; $visited = [];
$maxDist*=$maxDist; //no square root $maxDist *= $maxDist; //no square root
$closestToTarget = null; $closestToTarget = null;
$closestToTargetDist = INF; $closestToTargetDist = INF;
while(!$open->isEmpty()) while(!$open->isEmpty())
{ {
$current = $open->top(); $current = $open->top();
@ -90,7 +90,7 @@ class TileNavigator
if ($current == $to){ if ($current == $to){
return $this->reconstructPath($path, $current); return $this->reconstructPath($path, $current);
} }
$points = []; $points = [];
foreach(self::OFFSETS as $offset){ foreach(self::OFFSETS as $offset){
$newX = $offset[0] + $currentX; $newX = $offset[0] + $currentX;
@ -98,7 +98,7 @@ class TileNavigator
$newZ = $offset[2] + $currentZ; $newZ = $offset[2] + $currentZ;
if($newX < 0 || $newX > 255 || $newY < 0 || $newY > 255 || $newZ < 0 || $newZ > 255) continue; if($newX < 0 || $newX > 255 || $newY < 0 || $newY > 255 || $newZ < 0 || $newZ > 255) continue;
$new = $newX << 16 | $newZ << 8 | $newY; $new = $newX << 16 | $newZ << 8 | $newY;
if(!$this->isLocBlocked($pmfLevel, $new)){ if(!$this->isLocBlocked($pmfLevel, $new)){
if($newY > 0 && !$this->isLocBlocked($pmfLevel, $new - 1)){ if($newY > 0 && !$this->isLocBlocked($pmfLevel, $new - 1)){
if(!$this->avoidFallDamage){ if(!$this->avoidFallDamage){
@ -108,60 +108,59 @@ class TileNavigator
if($this->isLocBlocked($pmfLevel, $new - 2)){ if($this->isLocBlocked($pmfLevel, $new - 2)){
$new -= 1; $new -= 1;
$newY -= 1; $newY -= 1;
}else if($this->isLocBlocked($pmfLevel, $new - 3)){ }elseif($this->isLocBlocked($pmfLevel, $new - 3)){
$new -= 2; $new -= 2;
$newY -= 2; $newY -= 2;
}else if($this->isLocBlocked($pmfLevel, $new - 4)){ }elseif($this->isLocBlocked($pmfLevel, $new - 4)){
$new -= 3; $new -= 3;
$newY -= 3; $newY -= 3;
}else{ }else{
continue; continue;
} }
} }
} }
$dist = ($fromX - $newX)*($fromX - $newX) + ($fromY - $newY)*($fromY - $newY) + ($fromZ - $newZ)*($fromZ - $newZ); $dist = ($fromX - $newX) * ($fromX - $newX) + ($fromY - $newY) * ($fromY - $newY) + ($fromZ - $newZ) * ($fromZ - $newZ);
if($dist < -$maxDist || $dist > $maxDist){ if($dist < -$maxDist || $dist > $maxDist){
continue; continue;
} }
$points[] = $new; $points[] = $new;
}else if(!$this->isLocBlocked($pmfLevel, $current+1) && !$this->isLocBlocked($pmfLevel, $new+1)){ }elseif(!$this->isLocBlocked($pmfLevel, $current + 1) && !$this->isLocBlocked($pmfLevel, $new + 1)){
$new += 1; $new += 1;
$newY += 1; $newY += 1;
$dist = ($fromX - $newX)*($fromX - $newX) + ($fromY - $newY)*($fromY - $newY) + ($fromZ - $newZ)*($fromZ - $newZ); $dist = ($fromX - $newX) * ($fromX - $newX) + ($fromY - $newY) * ($fromY - $newY) + ($fromZ - $newZ) * ($fromZ - $newZ);
if($dist < -$maxDist || $dist > $maxDist){ if($dist < -$maxDist || $dist > $maxDist){
continue; continue;
} }
$points[] = $new; $points[] = $new;
} }
} }
foreach($points as $neighbor) foreach($points as $neighbor)
{ {
if(isset($visited[$neighbor])){ if(isset($visited[$neighbor])){
continue; continue;
} }
$visited[$neighbor] = true; $visited[$neighbor] = true;
$diffX = ($toX - ($neighbor >> 16 & 0xff)); $diffX = ($toX - ($neighbor >> 16 & 0xff));
$diffY = ($toY - ($neighbor & 0xff)); $diffY = ($toY - ($neighbor & 0xff));
$diffZ = ($toZ - ($neighbor >> 8 & 0xff)); $diffZ = ($toZ - ($neighbor >> 8 & 0xff));
$targetDist = $diffX*$diffX + $diffY*$diffY + $diffZ*$diffZ; $targetDist = $diffX * $diffX + $diffY * $diffY + $diffZ * $diffZ;
$diffX = ($currentX - ($neighbor >> 16 & 0xff)); $diffX = ($currentX - ($neighbor >> 16 & 0xff));
$diffY = ($currentY - ($neighbor & 0xff)); $diffY = ($currentY - ($neighbor & 0xff));
$diffZ = ($currentZ - ($neighbor >> 8 & 0xff)); $diffZ = ($currentZ - ($neighbor >> 8 & 0xff));
$distbetweenCost = $diffX*$diffX + $diffY*$diffY + $diffZ*$diffZ; $distbetweenCost = $diffX * $diffX + $diffY * $diffY + $diffZ * $diffZ;
$tentativeG = $gScore[$current] + $distbetweenCost; $tentativeG = $gScore[$current] + $distbetweenCost;
if (!isset($has[$neighbor])) if (!isset($has[$neighbor]))
{ {
//if(isset($open[-$tentativeG])) console("overwriting $tentativeG"); //if(isset($open[-$tentativeG])) console("overwriting $tentativeG");
//$open[-$tentativeG] = $neighbor; //$open[-$tentativeG] = $neighbor;
$open->insert($neighbor, -$tentativeG); $open->insert($neighbor, -$tentativeG);
$has[$neighbor] = true; $has[$neighbor] = true;
} }
@ -171,26 +170,25 @@ class TileNavigator
} }
if(!isset($gScore[$neighbor]) || $distbetweenCost < $gScore[$neighbor]){ if(!isset($gScore[$neighbor]) || $distbetweenCost < $gScore[$neighbor]){
$path[$neighbor] = $current; $path[$neighbor] = $current;
if($targetDist < $closestToTargetDist){ if($targetDist < $closestToTargetDist){
//console("found new best to target: $neighbor($closestToTargetDist -> $targetDist)"); //console("found new best to target: $neighbor($closestToTargetDist -> $targetDist)");
$closestToTarget = $neighbor; $closestToTarget = $neighbor;
$closestToTargetDist = $targetDist; $closestToTargetDist = $targetDist;
} }
} }
$gScore[$neighbor] = $tentativeG; $gScore[$neighbor] = $tentativeG;
} }
} }
if($closestToTarget != null){ if($closestToTarget != null){
return $this->reconstructPath($path, $closestToTarget); return $this->reconstructPath($path, $closestToTarget);
} }
return null; return null;
} }
}
}

View file

@ -1,4 +1,5 @@
<?php <?php
set_time_limit(0); set_time_limit(0);
function parseOffset(string $offset) : string|false{ function parseOffset(string $offset) : string|false{

View file

@ -109,7 +109,6 @@ define("SOUL_SAND", 88);
define("GLOWSTONE", 89); define("GLOWSTONE", 89);
define("GLOWSTONE_BLOCK", 89); define("GLOWSTONE_BLOCK", 89);
define("LIT_PUMPKIN", 91); define("LIT_PUMPKIN", 91);
define("JACK_O_LANTERN", 91); define("JACK_O_LANTERN", 91);
define("CAKE_BLOCK", 92); define("CAKE_BLOCK", 92);

View file

@ -26,10 +26,10 @@ define("ENTITY_OBJECT", 3);
define("ENTITY_ITEM", 4); define("ENTITY_ITEM", 4);
define("ENTITY_ITEM_TYPE", 64); define("ENTITY_ITEM_TYPE", 64);
define("ENTITY_FALLING", 5); define("ENTITY_FALLING", 5);
define("FALLING_SAND", 66); define("FALLING_SAND", 66);
//TileEntities //TileEntities
define("TILE_SIGN", "Sign"); define("TILE_SIGN", "Sign");
define("TILE_CHEST", "Chest"); define("TILE_CHEST", "Chest");
@ -44,7 +44,7 @@ const CORRECT_ENTITY_CLASSES = [
MOB_COW => true, MOB_COW => true,
MOB_PIG => true, MOB_PIG => true,
MOB_SHEEP => true, MOB_SHEEP => true,
MOB_ZOMBIE => true, MOB_ZOMBIE => true,
MOB_SKELETON => true, MOB_SKELETON => true,
MOB_SPIDER => true, MOB_SPIDER => true,
@ -64,5 +64,5 @@ const CORRECT_ENTITY_CLASSES = [
ENTITY_FALLING => [ ENTITY_FALLING => [
FALLING_SAND => true FALLING_SAND => true
] ]
]; ];

View file

@ -103,7 +103,6 @@ require_once(FILE_PATH . "/src/pmf/PMF.php");
require_once(FILE_PATH . "/src/astarnavigator/TileNavigator.php"); require_once(FILE_PATH . "/src/astarnavigator/TileNavigator.php");
require_once(FILE_PATH . "/src/entity/ai/tasks/TaskBase.php"); require_once(FILE_PATH . "/src/entity/ai/tasks/TaskBase.php");
require_once(FILE_PATH . "/src/entity/Rideable.php"); require_once(FILE_PATH . "/src/entity/Rideable.php");
@ -138,8 +137,6 @@ require_once(FILE_PATH . "/src/world/generator/vanilla/feature/Feature.php");
require_all(FILE_PATH . "src/"); require_all(FILE_PATH . "src/");
$inc = get_included_files(); $inc = get_included_files();
$inc[] = array_shift($inc); $inc[] = array_shift($inc);
$srcdir = realpath(FILE_PATH . "src/"); $srcdir = realpath(FILE_PATH . "src/");

View file

@ -1,17 +1,15 @@
<?php <?php
abstract class Animal extends Creature implements Ageable, Breedable{ abstract class Animal extends Creature implements Ageable, Breedable{
public $parent; public $parent;
public $inLove; //do NOT add it into metadata, it doesnt send it to player public $inLove; //do NOT add it into metadata, it doesnt send it to player
public $age; public $age;
public $loveTimeout; public $loveTimeout;
public $closestPlayerThatCanFeedEID = false; public $closestPlayerThatCanFeedEID = false;
public $closestPlayerThatCanFeedDist = INF; public $closestPlayerThatCanFeedDist = INF;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){ public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setAge($data["Age"] ?? 0); $this->setAge($data["Age"] ?? 0);
@ -20,11 +18,11 @@ abstract class Animal extends Creature implements Ageable, Breedable{
} }
$this->searchForClosestPlayers = true; $this->searchForClosestPlayers = true;
} }
public function isPlayerValid(Player $player){ public function isPlayerValid(Player $player){
return $player->spawned && $this->isFood($player->getHeldItem()->id) && !$player->entity->dead; return $player->spawned && $this->isFood($player->getHeldItem()->id) && !$player->entity->dead;
} }
public function handlePrePlayerSearcher(){ public function handlePrePlayerSearcher(){
parent::handlePrePlayerSearcher(); parent::handlePrePlayerSearcher();
if($this->closestPlayerThatCanFeedEID !== false){ if($this->closestPlayerThatCanFeedEID !== false){
@ -33,15 +31,15 @@ abstract class Animal extends Creature implements Ageable, Breedable{
$this->closestPlayerThatCanFeedEID = false; $this->closestPlayerThatCanFeedEID = false;
$this->closestPlayerThatCanFeedDist = INF; $this->closestPlayerThatCanFeedDist = INF;
}else{ }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; $this->closestPlayerThatCanFeedDist = $dist;
} }
} }
} }
public function handlePlayerSearcher(Player $player, $dist){ public function handlePlayerSearcher(Player $player, $dist){
parent::handlePlayerSearcher($player, $dist); parent::handlePlayerSearcher($player, $dist);
if($this->closestPlayerThatCanFeedDist >= $dist){ if($this->closestPlayerThatCanFeedDist >= $dist){
if($this->isPlayerValid($player)){ if($this->isPlayerValid($player)){
$this->closestPlayerThatCanFeedDist = $dist; $this->closestPlayerThatCanFeedDist = $dist;
@ -49,18 +47,18 @@ abstract class Animal extends Creature implements Ageable, Breedable{
} }
} }
} }
public function harm($dmg, $cause = "generic", $force = false){ public function harm($dmg, $cause = "generic", $force = false){
$ret = parent::harm($dmg, $cause, $force); $ret = parent::harm($dmg, $cause, $force);
$this->inPanic |= ($ret && is_numeric($cause)); $this->inPanic |= ($ret && is_numeric($cause));
$this->inLove = false; $this->inLove = false;
return $ret; return $ret;
} }
public function isBaby(){ public function isBaby(){
return $this->getAge() < 0; return $this->getAge() < 0;
} }
public function breed(){ public function breed(){
if($this->server->dhandle("entity.animal.breed", ["parent" => $this]) !== false){ if($this->server->dhandle("entity.animal.breed", ["parent" => $this]) !== false){
$c = $this->spawnChild(); $c = $this->spawnChild();
@ -70,22 +68,22 @@ abstract class Animal extends Creature implements Ageable, Breedable{
} }
return false; return false;
} }
public function resetInLove(){ public function resetInLove(){
$this->inLove = 0; $this->inLove = 0;
} }
public function canMate($ent){ public function canMate($ent){
return $ent->eid != $this->eid && $this->type === $ent->type && $this->isInLove() && $ent->isInLove(); return $ent->eid != $this->eid && $this->type === $ent->type && $this->isInLove() && $ent->isInLove();
} }
public function update($now){ public function update($now){
parent::update($now); parent::update($now);
if($this->loveTimeout > 0){ if($this->loveTimeout > 0){
--$this->loveTimeout; --$this->loveTimeout;
} }
$age = $this->getAge() + 1; //100 - fast. debug, 1 - normal $age = $this->getAge() + 1; //100 - fast. debug, 1 - normal
if($age >= 0 && $this->isBaby()){ if($age >= 0 && $this->isBaby()){
$this->setAge($age); $this->setAge($age);
@ -99,15 +97,15 @@ abstract class Animal extends Creature implements Ageable, Breedable{
unset($this->level->entitiesInLove[$this->eid]); unset($this->level->entitiesInLove[$this->eid]);
} }
} }
public function getAge(){ public function getAge(){
return $this->age; return $this->age;
} }
public function setAge($i){ public function setAge($i){
$this->age = $i; $this->age = $i;
} }
public function spawnChild() public function spawnChild()
{ {
return $this->server->api->entity->add($this->level, $this->class, $this->type, [ return $this->server->api->entity->add($this->level, $this->class, $this->type, [
@ -118,24 +116,24 @@ abstract class Animal extends Creature implements Ageable, Breedable{
"Age" => -24000, "Age" => -24000,
]); ]);
} }
public function getMetadata(){ public function getMetadata(){
$d = parent::getMetadata(); $d = parent::getMetadata();
$d[14]["value"] = $this->isBaby(); $d[14]["value"] = $this->isBaby();
return $d; return $d;
} }
public function createSaveData(){ public function createSaveData(){
$data = parent::createSaveData(); $data = parent::createSaveData();
$data["IsBaby"] = $this->isBaby(); $data["IsBaby"] = $this->isBaby();
$data["Age"] = $this->getAge(); $data["Age"] = $this->getAge();
return $data; return $data;
} }
public function isInLove(){ public function isInLove(){
return $this->inLove > 0; return $this->inLove > 0;
} }
public function interactWith(Entity $e, $action){ public function interactWith(Entity $e, $action){
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){ if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem(); $slot = $e->player->getHeldItem();
@ -149,14 +147,14 @@ abstract class Animal extends Creature implements Ageable, Breedable{
} }
parent::interactWith($e, $action); parent::interactWith($e, $action);
} }
public function counterUpdate(){ public function counterUpdate(){
parent::counterUpdate(); parent::counterUpdate();
if($this->isInLove()){ if($this->isInLove()){
--$this->inLove; --$this->inLove;
} }
} }
public function getDrops(){ public function getDrops(){
if($this->isBaby()){ if($this->isBaby()){
return []; return [];

View file

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

View file

@ -2,12 +2,11 @@
abstract class Creature extends Living{ abstract class Creature extends Living{
const CLASS_TYPE = ENTITY_MOB; const CLASS_TYPE = ENTITY_MOB;
public $inPanic; public $inPanic;
public $closestPlayerEID = false; public $closestPlayerEID = false;
public $closestPlayerDist = INF; public $closestPlayerDist = INF;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){ public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->inPanic = false; //force for now $this->inPanic = false; //force for now
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
@ -15,13 +14,12 @@ abstract class Creature extends Living{
$this->enableAutojump = true; $this->enableAutojump = true;
$this->searchForClosestPlayers = true; $this->searchForClosestPlayers = true;
} }
public function update($now){ public function update($now){
$this->handlePrePlayerSearcher(); $this->handlePrePlayerSearcher();
return parent::update($now); return parent::update($now);
} }
public function handlePrePlayerSearcher(){ public function handlePrePlayerSearcher(){
parent::handlePrePlayerSearcher(); parent::handlePrePlayerSearcher();
if($this->closestPlayerEID !== false){ if($this->closestPlayerEID !== false){
@ -30,12 +28,12 @@ abstract class Creature extends Living{
$this->closestPlayerEID = false; $this->closestPlayerEID = false;
$this->closestPlayerDist = INF; $this->closestPlayerDist = INF;
}else{ }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; $this->closestPlayerDist = $dist;
} }
} }
} }
public function handlePlayerSearcher(Player $player, $dist){ public function handlePlayerSearcher(Player $player, $dist){
parent::handlePlayerSearcher($player, $dist); parent::handlePlayerSearcher($player, $dist);
if($this->closestPlayerDist >= $dist){ if($this->closestPlayerDist >= $dist){
@ -43,13 +41,13 @@ abstract class Creature extends Living{
$this->closestPlayerDist = $dist; $this->closestPlayerDist = $dist;
} }
} }
public function createSaveData(){ public function createSaveData(){
$data = parent::createSaveData(); $data = parent::createSaveData();
$data["State"] = @$this->getState(); $data["State"] = @$this->getState();
return $data; return $data;
} }
public function getSpeedModifer(){ public function getSpeedModifer(){
return 0.7; return 0.7;
} }
@ -71,19 +69,19 @@ abstract class Creature extends Living{
$pk->z = $this->z; $pk->z = $this->z;
$pk->yaw = $this->yaw; $pk->yaw = $this->yaw;
$pk->pitch = $this->pitch; $pk->pitch = $this->pitch;
$pk->metadata = $this->getMetadata(); $pk->metadata = $this->getMetadata();
$player->dataPacket($pk); $player->dataPacket($pk);
$pk = new SetEntityMotionPacket; $pk = new SetEntityMotionPacket;
$pk->eid = $this->eid; $pk->eid = $this->eid;
$pk->speedX = $this->speedX; $pk->speedX = $this->speedX;
$pk->speedY = $this->speedY; $pk->speedY = $this->speedY;
$pk->speedZ = $this->speedZ; $pk->speedZ = $this->speedZ;
$player->dataPacket($pk); $player->dataPacket($pk);
if($this->linkedEntity != 0 && $this->isRider){ if($this->linkedEntity != 0 && $this->isRider){
$player->eventHandler(["rider" => $this->eid, "riding" => $this->linkedEntity, "type" => 0], "entity.link"); $player->eventHandler(["rider" => $this->eid, "riding" => $this->linkedEntity, "type" => 0], "entity.link");
} }
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,12 +1,11 @@
<?php <?php
abstract class Living extends Entity implements Pathfindable{ abstract class Living extends Entity implements Pathfindable{
public static $despawnMobs, $despawnTimer, $entityPushing = false; public static $despawnMobs, $despawnTimer, $entityPushing = false;
public static $pathfinderTest = false; public static $pathfinderTest = false;
/** /**
* @var Entity $target * @var Entity $target
* @var EntityAI $ai * @var EntityAI $ai
@ -14,14 +13,14 @@ abstract class Living extends Entity implements Pathfindable{
public $target, $ai; public $target, $ai;
public $pathFinder, $path = null, $currentIndex = 0, $currentNode, $pathFollower; public $pathFinder, $path = null, $currentIndex = 0, $currentNode, $pathFollower;
public $ticksExisted = 0; public $ticksExisted = 0;
public $landMovementFactor = 0.1; public $landMovementFactor = 0.1;
public $jumpMovementFactor = 0.02; public $jumpMovementFactor = 0.02;
public $aiMoveSpeed; public $aiMoveSpeed;
public $renderYawOffset = 0.0; //used by head rotation, TODO better name public $renderYawOffset = 0.0; //used by head rotation, TODO better name
public $jumping, $jumpTicks; public $jumping, $jumpTicks;
public function __construct(Level $level, $eid, $class, $type = 0, $data = array()){ public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->target = false; $this->target = false;
$this->ai = new EntityAI($this); $this->ai = new EntityAI($this);
$this->pathFinder = new TileNavigator($this); $this->pathFinder = new TileNavigator($this);
@ -30,43 +29,43 @@ abstract class Living extends Entity implements Pathfindable{
$this->canBeAttacked = true; $this->canBeAttacked = true;
$this->hasGravity = true; $this->hasGravity = true;
$this->hasKnockback = true; $this->hasKnockback = true;
//if(self::$despawnMobs) $this->server->schedule(self::$despawnTimer, [$this, "close"]); //900*20 //if(self::$despawnMobs) $this->server->schedule(self::$despawnTimer, [$this, "close"]); //900*20
} }
public function isPickable(){ public function isPickable(){
return !$this->dead; return !$this->dead;
} }
public function fall(){ public function fall(){
$dmg = ceil($this->fallDistance - 3); $dmg = ceil($this->fallDistance - 3);
if($dmg > 0){ if($dmg > 0){
$this->harm($dmg, "fall"); $this->harm($dmg, "fall");
} }
} }
public function handlePlayerSearcher(Player $player, $dist){ public function handlePlayerSearcher(Player $player, $dist){
} }
public function getAIMoveSpeed(){ public function getAIMoveSpeed(){
return $this->aiMoveSpeed; return $this->aiMoveSpeed;
} }
public function getVerticalFaceSpeed(){ public function getVerticalFaceSpeed(){
return 40; //unused in 0.8 but may be useful in 0.9/0.10 return 40; //unused in 0.8 but may be useful in 0.9/0.10
} }
public function setAIMoveSpeed($speed){ public function setAIMoveSpeed($speed){
$this->aiMoveSpeed = $speed; $this->aiMoveSpeed = $speed;
$this->moveForward = $speed; $this->moveForward = $speed;
} }
public function hasPath(){ public function hasPath(){
return $this->path != null; return $this->path != null;
} }
public function eatGrass(){} public function eatGrass(){}
public function close(){ public function close(){
parent::close(); parent::close();
unset($this->pathFollower->entity); unset($this->pathFollower->entity);
@ -76,22 +75,22 @@ abstract class Living extends Entity implements Pathfindable{
unset($this->parent); unset($this->parent);
unset($this->pathFinder->entity); unset($this->pathFinder->entity);
} }
public function canBeShot(){ public function canBeShot(){
return true; return true;
} }
public function isPushable(){ public function isPushable(){
return !$this->dead; return !$this->dead;
} }
public function collideHandler(){ public function collideHandler(){
$bb = $this->boundingBox->expand(0.2, 0, 0.2); $bb = $this->boundingBox->expand(0.2, 0, 0.2);
$minChunkX = ((int)($bb->minX)) >> 4; $minChunkX = ((int) ($bb->minX)) >> 4;
$minChunkZ = ((int)($bb->minZ)) >> 4; $minChunkZ = ((int) ($bb->minZ)) >> 4;
$maxChunkX = ((int)($bb->minX)) >> 4; $maxChunkX = ((int) ($bb->minX)) >> 4;
$maxChunkZ = ((int)($bb->minZ)) >> 4; $maxChunkZ = ((int) ($bb->minZ)) >> 4;
//TODO also index by chunkY? //TODO also index by chunkY?
for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){ for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){
for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ){ for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ){
@ -106,14 +105,14 @@ abstract class Living extends Entity implements Pathfindable{
} }
} }
} }
public function update($now){ public function update($now){
if(self::$despawnMobs && ++$this->ticksExisted > self::$despawnTimer){ if(self::$despawnMobs && ++$this->ticksExisted > self::$despawnTimer){
$this->close(); $this->close();
return; return;
} }
if($this->closed) return; if($this->closed) return;
$check = $this->level->mobSpawner->checkDespawn($this); $check = $this->level->mobSpawner->checkDespawn($this);
if($check){ if($check){
$this->close(); $this->close();
@ -121,7 +120,7 @@ abstract class Living extends Entity implements Pathfindable{
} }
parent::update($now); parent::update($now);
} }
public $pathEIDS = []; public $pathEIDS = [];
private static $lastPathEID = 10000000; private static $lastPathEID = 10000000;
public static $pathfind = true; public static $pathfind = true;
@ -139,22 +138,21 @@ abstract class Living extends Entity implements Pathfindable{
} }
if(self::$pathfind){ if(self::$pathfind){
$this->path = $this->pathFinder->navigate( $this->path = $this->pathFinder->navigate(
$this->level, $this->level,
(int)$this->x, (int)$this->y, (int)$this->z, (int) $this->x, (int) $this->y, (int) $this->z,
//(int)$pl->entity->x, (int)$pl->entity->y, (int)$pl->entity->z, //(int)$pl->entity->x, (int)$pl->entity->y, (int)$pl->entity->z,
(int)$this->x + mt_rand(-16, 16), (int)$this->y, (int)$this->z + mt_rand(-16, 16), (int) $this->x + mt_rand(-16, 16), (int) $this->y, (int) $this->z + mt_rand(-16, 16),
16 16
); );
} }
/*if($this->path){ /*if($this->path){
console("Found path of length ".count($this->path)); console("Found path of length ".count($this->path));
foreach($this->path as $node){ foreach($this->path as $node){
$eid = self::$lastPathEID++; $eid = self::$lastPathEID++;
$this->pathEIDS[] = $eid; $this->pathEIDS[] = $eid;
$pk = new AddItemEntityPacket(); $pk = new AddItemEntityPacket();
$pk->eid = $eid; $pk->eid = $eid;
$pk->item = BlockAPI::getItem(GOLD_BLOCK, 0, 1); $pk->item = BlockAPI::getItem(GOLD_BLOCK, 0, 1);
@ -171,8 +169,7 @@ abstract class Living extends Entity implements Pathfindable{
} }
$this->pathFollower->followPath(); $this->pathFollower->followPath();
} }
//not exactly here //not exactly here
if($this->jumping){ if($this->jumping){
if(!$this->inWater && !$this->inLava){ if(!$this->inWater && !$this->inLava){
@ -186,12 +183,11 @@ abstract class Living extends Entity implements Pathfindable{
}else{ }else{
$this->jumpTicks = 0; $this->jumpTicks = 0;
} }
$this->ai->mobController->movementTick(); $this->ai->mobController->movementTick();
$this->ai->mobController->rotateTick(); $this->ai->mobController->rotateTick();
$this->ai->mobController->jumpTick(); $this->ai->mobController->jumpTick();
if(abs($this->speedX) < self::MIN_POSSIBLE_SPEED) $this->speedX = 0; 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->speedZ) < self::MIN_POSSIBLE_SPEED) $this->speedZ = 0;
if(abs($this->speedY) < self::MIN_POSSIBLE_SPEED) $this->speedY = 0; if(abs($this->speedY) < self::MIN_POSSIBLE_SPEED) $this->speedY = 0;
@ -203,24 +199,23 @@ abstract class Living extends Entity implements Pathfindable{
$this->landMovementFactor = $savedLandFactor; $this->landMovementFactor = $savedLandFactor;
//Yaw rotation in 1.5 is handled in a bit different place but hopefully this will work too //Yaw rotation in 1.5 is handled in a bit different place but hopefully this will work too
$this->ai->mobController->updateHeadYaw(); $this->ai->mobController->updateHeadYaw();
if(self::$entityPushing){ if(self::$entityPushing){
$this->collideHandler(); $this->collideHandler();
} }
} }
public function jump(){ public function jump(){
$this->speedY = 0.42; $this->speedY = 0.42;
//TODO also set AirBorne? //TODO also set AirBorne?
} }
public function counterUpdate(){ public function counterUpdate(){
parent::counterUpdate(); parent::counterUpdate();
if($this->jumpTicks > 0) --$this->jumpTicks; if($this->jumpTicks > 0) --$this->jumpTicks;
} }
public function moveEntityWithHeading($strafe, $forward){ public function moveEntityWithHeading($strafe, $forward){
if($this->inWater){ //also check is player, and can it fly or not if($this->inWater){ //also check is player, and can it fly or not
$prevPosY = $this->y; $prevPosY = $this->y;
@ -230,8 +225,7 @@ abstract class Living extends Entity implements Pathfindable{
$this->speedY *= 0.8; $this->speedY *= 0.8;
$this->speedZ *= 0.8; $this->speedZ *= 0.8;
$this->speedY -= 0.02; $this->speedY -= 0.02;
if($this->isCollidedHorizontally && $this->isFree($this->speedX, $this->speedY + 0.6 - $this->y + $prevPosY, $this->speedZ)){ if($this->isCollidedHorizontally && $this->isFree($this->speedX, $this->speedY + 0.6 - $this->y + $prevPosY, $this->speedZ)){
$this->speedY = 0.3; $this->speedY = 0.3;
} }
@ -243,69 +237,69 @@ abstract class Living extends Entity implements Pathfindable{
$this->speedY *= 0.5; $this->speedY *= 0.5;
$this->speedZ *= 0.5; $this->speedZ *= 0.5;
$this->speedY -= 0.02; $this->speedY -= 0.02;
if($this->isCollidedHorizontally && $this->isFree($this->speedX, $this->speedY + 0.6 - $this->y + $prevPosY, $this->speedZ)){ if($this->isCollidedHorizontally && $this->isFree($this->speedX, $this->speedY + 0.6 - $this->y + $prevPosY, $this->speedZ)){
$this->speedY = 0.3; $this->speedY = 0.3;
} }
}else{ }else{
$friction = 0.91; $friction = 0.91;
if($this->onGround){ if($this->onGround){
$friction = 0.546; $friction = 0.546;
$blockAt = $this->level->level->getBlockID(floor($this->x), floor($this->boundingBox->minY) - 1, floor($this->z)); $blockAt = $this->level->level->getBlockID(floor($this->x), floor($this->boundingBox->minY) - 1, floor($this->z));
if($blockAt > 0) $friction = StaticBlock::getSlipperiness($blockAt) * 0.91; if($blockAt > 0) $friction = StaticBlock::getSlipperiness($blockAt) * 0.91;
} }
$var8 = 0.16277 / ($friction*$friction*$friction); $var8 = 0.16277 / ($friction * $friction * $friction);
if($this->onGround){ if($this->onGround){
$var5 = $this->getAIMoveSpeed(); //in vanilla it returns either this.seed or calls getBaseSpeed(depending on useNewAi) $var5 = $this->getAIMoveSpeed(); //in vanilla it returns either this.seed or calls getBaseSpeed(depending on useNewAi)
$var5 *= $var8; //in vanilla it also multiplies by speedModifer $var5 *= $var8; //in vanilla it also multiplies by speedModifer
}else{ }else{
$var5 = $this->jumpMovementFactor; $var5 = $this->jumpMovementFactor;
} }
$this->moveFlying($strafe, $forward, $var5); $this->moveFlying($strafe, $forward, $var5);
//recalculating friction, might be not neccessary //recalculating friction, might be not neccessary
$friction = 0.91; $friction = 0.91;
if($this->onGround){ if($this->onGround){
$friction = 0.546; $friction = 0.546;
$blockAt = $this->level->level->getBlockID(floor($this->x), floor($this->boundingBox->minY) - 1, floor($this->z)); $blockAt = $this->level->level->getBlockID(floor($this->x), floor($this->boundingBox->minY) - 1, floor($this->z));
if($blockAt > 0) $friction = StaticBlock::getSlipperiness($blockAt) * 0.91; if($blockAt > 0) $friction = StaticBlock::getSlipperiness($blockAt) * 0.91;
} }
if($this->isOnLadder()){ if($this->isOnLadder()){
$speedY = $this->speedY; $speedY = $this->speedY;
$this->fallDistance = 0; $this->fallDistance = 0;
if($speedY < -0.15) $this->speedY = -0.15; if($speedY < -0.15) $this->speedY = -0.15;
} }
$this->move($this->speedX, $this->speedY, $this->speedZ); $this->move($this->speedX, $this->speedY, $this->speedZ);
if($this->isOnLadder() && $this->isCollidedHorizontally){ if($this->isOnLadder() && $this->isCollidedHorizontally){
$this->speedY = 0.2; $this->speedY = 0.2;
} }
$this->speedY -= 0.08; //gravity $this->speedY -= 0.08; //gravity
$this->speedY *= 0.98; $this->speedY *= 0.98;
$this->speedX *= $friction; $this->speedX *= $friction;
$this->speedZ *= $friction; $this->speedZ *= $friction;
if($this->isCollidedHorizontally && $this->enableAutojump){ if($this->isCollidedHorizontally && $this->enableAutojump){
$this->ai->mobController->setJumping(true); //non vanilla $this->ai->mobController->setJumping(true); //non vanilla
} }
} }
} }
public function sendMoveUpdate(){ public function sendMoveUpdate(){
if($this->counter % 3 != 0){ if($this->counter % 3 != 0){
return; return;
} }
parent::sendMoveUpdate(); parent::sendMoveUpdate();
} }
} }

View file

@ -1,17 +1,18 @@
<?php <?php
class Monster extends Creature{ class Monster extends Creature{
public $closestPlayerToAttackEID = false; public $closestPlayerToAttackEID = false;
public $closestPlayerToAttackDist = INF; public $closestPlayerToAttackDist = INF;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){ public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
} }
public function getAttackDamage(){ public function getAttackDamage(){
return 2; return 2;
} }
/** /**
* *
* @see Entity::attackEntity() * @see Entity::attackEntity()
*/ */
public function attackEntity($entity, $distance){ public function attackEntity($entity, $distance){
@ -22,11 +23,11 @@ class Monster extends Creature{
return false; return false;
} }
} }
public function isPlayerValid(Player $player){ public function isPlayerValid(Player $player){
return $player->spawned && !$player->entity->dead; return $player->spawned && !$player->entity->dead;
} }
public function handlePrePlayerSearcher(){ public function handlePrePlayerSearcher(){
parent::handlePrePlayerSearcher(); parent::handlePrePlayerSearcher();
if($this->closestPlayerToAttackEID !== false){ if($this->closestPlayerToAttackEID !== false){
@ -35,15 +36,15 @@ class Monster extends Creature{
$this->closestPlayerToAttackEID = false; $this->closestPlayerToAttackEID = false;
$this->closestPlayerToAttackDist = INF; $this->closestPlayerToAttackDist = INF;
}else{ }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->closestPlayerToAttackDist = $dist; $this->closestPlayerToAttackDist = $dist;
} }
} }
} }
public function handlePlayerSearcher(Player $player, $dist){ public function handlePlayerSearcher(Player $player, $dist){
parent::handlePlayerSearcher($player, $dist); parent::handlePlayerSearcher($player, $dist);
if($this->closestPlayerToAttackDist >= $dist){ if($this->closestPlayerToAttackDist >= $dist){
if($this->isPlayerValid($player)){ if($this->isPlayerValid($player)){
$this->closestPlayerToAttackDist = $dist; $this->closestPlayerToAttackDist = $dist;
@ -51,5 +52,5 @@ class Monster extends Creature{
} }
} }
} }
} }

View file

@ -1,4 +1,5 @@
<?php <?php
abstract class Projectile extends Entity{ abstract class Projectile extends Entity{
const CLASS_TYPE = ENTITY_OBJECT; const CLASS_TYPE = ENTITY_OBJECT;
public $shooterEID; public $shooterEID;
@ -7,13 +8,13 @@ abstract class Projectile extends Entity{
public $ticksInAir = 0, $ticksInGround = 0; public $ticksInAir = 0, $ticksInGround = 0;
public $xTile = 0, $yTile = 0, $zTile = 0; public $xTile = 0, $yTile = 0, $zTile = 0;
public $inTile = false; public $inTile = false;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []) public function __construct(Level $level, $eid, $class, $type = 0, $data = [])
{ {
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->gravity = 0.03; $this->gravity = 0.03;
$this->setSize(0.25, 0.25); $this->setSize(0.25, 0.25);
$this->x -= cos($this->yaw / 180 * M_PI) * 0.16; $this->x -= cos($this->yaw / 180 * M_PI) * 0.16;
$this->y -= 0.1; $this->y -= 0.1;
$this->z -= cos($this->yaw / 180 * M_PI) * 0.16; $this->z -= cos($this->yaw / 180 * M_PI) * 0.16;
@ -25,7 +26,7 @@ abstract class Projectile extends Entity{
$this->xTile = $data["xTile"] ?? $this->xTile; $this->xTile = $data["xTile"] ?? $this->xTile;
$this->yTile = $data["yTile"] ?? $this->yTile; $this->yTile = $data["yTile"] ?? $this->yTile;
$this->zTile = $data["zTile"] ?? $this->zTile; $this->zTile = $data["zTile"] ?? $this->zTile;
if($shooter instanceof Entity){ if($shooter instanceof Entity){
$this->shooterEID = $shooter->eid; $this->shooterEID = $shooter->eid;
if($shooter->isPlayer()){ if($shooter->isPlayer()){
@ -44,9 +45,9 @@ abstract class Projectile extends Entity{
$this->shoot(, , , $throwPower, 1.0);*/ $this->shoot(, , , $throwPower, 1.0);*/
} }
} }
} }
public function shoot($d, $d1, $d2, $f, $f1){ //unchecked, may be not same as arrow public function shoot($d, $d1, $d2, $f, $f1){ //unchecked, may be not same as arrow
$f2 = sqrt($d * $d + $d1 * $d1 + $d2 * $d2); $f2 = sqrt($d * $d + $d1 * $d1 + $d2 * $d2);
$d /= $f2; $d /= $f2;
@ -66,7 +67,7 @@ abstract class Projectile extends Entity{
$this->pitch = (atan2($d1, $f3) * 180) / M_PI; $this->pitch = (atan2($d1, $f3) * 180) / M_PI;
$this->updatePosition(); $this->updatePosition();
} }
public function update($now){ public function update($now){
$this->lastX = $this->x; $this->lastX = $this->x;
$this->lastY = $this->y; $this->lastY = $this->y;
@ -88,32 +89,32 @@ abstract class Projectile extends Entity{
$this->fire -= 4; $this->fire -= 4;
if($this->fire <= 0) $this->fire = 0; if($this->fire <= 0) $this->fire = 0;
} }
if($this->fire <= 0){ if($this->fire <= 0){
$this->updateMetadata(); $this->updateMetadata();
} }
} }
if($this->handleLavaMovement()){ if($this->handleLavaMovement()){
if(!$this->isImmuneToFire){ if(!$this->isImmuneToFire){
$this->harm(4, "fire"); $this->harm(4, "fire");
$oldOnFire = $this->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()){ if($this->isInVoid()){
$this->outOfWorld(); $this->outOfWorld();
} }
//Entity::update end //Entity::update end
if($this->shake > 0) --$this->shake; if($this->shake > 0) --$this->shake;
if(!$this->inGround){ if(!$this->inGround){
++$this->ticksInAir; ++$this->ticksInAir;
goto CHECK_COLLISIONS; //TODO dont use gotos goto CHECK_COLLISIONS; //TODO dont use gotos
} }
$blockID = $this->level->level->getBlockID($this->xTile, $this->yTile, $this->zTile); $blockID = $this->level->level->getBlockID($this->xTile, $this->yTile, $this->zTile);
if($this->inTile != $blockID){ if($this->inTile != $blockID){
$this->speedX += (lcg_value() * 0.2); $this->speedX += (lcg_value() * 0.2);
@ -122,7 +123,7 @@ abstract class Projectile extends Entity{
$this->inGround = false; $this->inGround = false;
$this->ticksInAir = $this->ticksInGround = 0; $this->ticksInAir = $this->ticksInGround = 0;
CHECK_COLLISIONS: CHECK_COLLISIONS:
$start = new Vector3($this->x, $this->y, $this->z); $start = new Vector3($this->x, $this->y, $this->z);
$end = new Vector3($this->x + $this->speedX, $this->y + $this->speedY, $this->z + $this->speedZ); $end = new Vector3($this->x + $this->speedX, $this->y + $this->speedY, $this->z + $this->speedZ);
/** /**
@ -135,44 +136,44 @@ abstract class Projectile extends Entity{
}else{ }else{
$end = new Vector3($this->x + $this->speedX, $this->y + $this->speedY, $this->z + $this->speedZ); $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)); $entities = $this->level->getEntitiesInAABB($this->boundingBox->addCoord($this->speedX, $this->speedY, $this->speedZ)->expand(1, 1, 1));
$bestDist = 0; $bestDist = 0;
$bestEnt = null; $bestEnt = null;
foreach($entities as $eid => $ent){ foreach($entities as $eid => $ent){
if($eid != $this->eid && $ent->isPickable() && ($eid != $this->shooterEID || $this->ticksInAir >= 5)){ if($eid != $this->eid && $ent->isPickable() && ($eid != $this->shooterEID || $this->ticksInAir >= 5)){
$v12 = $ent->boundingBox->expand(0.3, 0.3, 0.3); $v12 = $ent->boundingBox->expand(0.3, 0.3, 0.3);
$v13 = $v12->calculateIntercept($start, $end); $v13 = $v12->calculateIntercept($start, $end);
if($v13 != null){ if($v13 != null){
$dist = $start->distance($v13->hitVector); $dist = $start->distance($v13->hitVector);
if($dist < $bestDist || $bestDist == 0){ if($dist < $bestDist || $bestDist == 0){
$bestEnt = $ent; $bestEnt = $ent;
} }
} }
} }
} }
if($bestEnt != null){ if($bestEnt != null){
$v4 = MovingObjectPosition::fromEntity($bestEnt); $v4 = MovingObjectPosition::fromEntity($bestEnt);
} }
if($v4 != null){ if($v4 != null){
$this->onHit($v4); $this->onHit($v4);
} }
$this->x += $this->speedX; $this->x += $this->speedX;
$this->y += $this->speedY; $this->y += $this->speedY;
$this->z += $this->speedZ; $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->yaw = atan2($this->speedX, $this->speedZ) * 180 / M_PI;
$this->pitch = atan2($this->speedY, $v21) * 180 / M_PI; $this->pitch = atan2($this->speedY, $v21) * 180 / M_PI;
$this->pitch = $this->lastPitch + ($this->pitch - $this->lastPitch) * 0.2; $this->pitch = $this->lastPitch + ($this->pitch - $this->lastPitch) * 0.2;
$this->yaw = $this->lastYaw + ($this->yaw - $this->lastYaw) * 0.2; $this->yaw = $this->lastYaw + ($this->yaw - $this->lastYaw) * 0.2;
$v24 = $this->inWater ? 0.8 : 0.99; $v24 = $this->inWater ? 0.8 : 0.99;
$this->speedX *= $v24; $this->speedX *= $v24;
$this->speedY *= $v24; $this->speedY *= $v24;
@ -183,19 +184,19 @@ abstract class Projectile extends Entity{
$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->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);
} }
} }
public function onHit(MovingObjectPosition $hitResult){ public function onHit(MovingObjectPosition $hitResult){
} }
public function createSaveData(){ public function createSaveData(){
$data = parent::createSaveData(); $data = parent::createSaveData();
$data["inTile"] = $this->inTile; $data["inTile"] = $this->inTile;
$data["inGround"] = $this->inGround; $data["inGround"] = $this->inGround;
$data["xTile"] = $this->xTile; $data["xTile"] = $this->xTile;
$data["yTile"] = $this->yTile; $data["yTile"] = $this->yTile;
$data["zTile"] = $this->zTile; $data["zTile"] = $this->zTile;
return $data; return $data;
} }
public function spawn($player) public function spawn($player)
@ -212,5 +213,5 @@ abstract class Projectile extends Entity{
$pk->did = 0; $pk->did = 0;
$player->dataPacket($pk); $player->dataPacket($pk);
} }
} }

View file

@ -10,29 +10,27 @@ class EntityAI
* @var Living * @var Living
*/ */
public $entity; public $entity;
/** /**
* @var TaskBase[] * @var TaskBase[]
*/ */
protected $tasks; protected $tasks;
public $lastTask; public $lastTask;
public function __construct($entity){ public function __construct($entity){
$this->entity = $entity; $this->entity = $entity;
$this->tasks = []; $this->tasks = [];
$this->mobController = new MobController($entity); $this->mobController = new MobController($entity);
} }
public function canSee(Entity $entity){ public function canSee(Entity $entity){
//TODO caches //TODO caches
return $this->entity->canSee($entity); return $this->entity->canSee($entity);
} }
/** /**
* Add a task for entity * Add a task for entity
* @param TaskBase $task
*/ */
public function addTask(TaskBase $task){ public function addTask(TaskBase $task){
$this->tasks[$task->__toString()] = $task; $this->tasks[$task->__toString()] = $task;
@ -44,16 +42,16 @@ class EntityAI
} }
return false; return false;
} }
/** /**
* *
* @param mixed $id classname * @param mixed $id classname
* @return TaskBase | false * @return TaskBase | false
*/ */
public function getTask($id){ public function getTask($id){
return $this->tasks[$id] ?? false; return $this->tasks[$id] ?? false;
} }
public function isStarted($id){ public function isStarted($id){
$task = $this->getTask($id); $task = $this->getTask($id);
return $task instanceof TaskBase && $task->isStarted; return $task instanceof TaskBase && $task->isStarted;
@ -75,10 +73,10 @@ class EntityAI
} }
} }
} }
public function __destruct(){ public function __destruct(){
unset($this->entity); unset($this->entity);
} }
} }

View file

@ -14,24 +14,24 @@ class MobController
* @var Living * @var Living
*/ */
public $entity; public $entity;
public $finalYaw, $finalPitch, $finalHeadYaw; public $finalYaw, $finalPitch, $finalHeadYaw;
public $headYaw; public $headYaw;
public $someTicker = 0; public $someTicker = 0;
protected $jumping; protected $jumping;
public $moveToX, $moveToY, $moveToZ; public $moveToX, $moveToY, $moveToZ;
public $speedMultiplier; public $speedMultiplier;
public $updateMove = false; public $updateMove = false;
public $lookX, $lookY, $lookZ; public $lookX, $lookY, $lookZ;
public $deltaLookYaw, $deltaLookPitch; public $deltaLookYaw, $deltaLookPitch;
public $isLooking = false; public $isLooking = false;
public $headYawIsYaw = false; public $headYawIsYaw = false;
public function __construct($e){ public function __construct($e){
$this->entity = $e; $this->entity = $e;
} }
@ -41,11 +41,11 @@ class MobController
public function isJumping(){ public function isJumping(){
return $this->jumping; return $this->jumping;
} }
public function setJumping($b){ public function setJumping($b){
$this->jumping = $b; $this->jumping = $b;
} }
public function isRotationCompleted(){ public function isRotationCompleted(){
return $this->finalHeadYaw === $this->entity->headYaw; return $this->finalHeadYaw === $this->entity->headYaw;
} }
@ -56,7 +56,7 @@ class MobController
$this->speedMultiplier = $speed; $this->speedMultiplier = $speed;
$this->updateMove = true; $this->updateMove = true;
} }
public function setMovingOffset($x, $y, $z, $speed){ public function setMovingOffset($x, $y, $z, $speed){
$this->moveToX = $this->entity->x + ($x); $this->moveToX = $this->entity->x + ($x);
$this->moveToY = $this->entity->y + ($y); $this->moveToY = $this->entity->y + ($y);
@ -64,50 +64,50 @@ class MobController
$this->speedMultiplier = $speed; $this->speedMultiplier = $speed;
$this->updateMove = true; $this->updateMove = true;
} }
public function canJump(){ public function canJump(){
return $this->isJumping() && $this->jumpTimeout <= 0 && $this->entity->onGround; return $this->isJumping() && $this->jumpTimeout <= 0 && $this->entity->onGround;
} }
public static function limitAngle2($old, $newA, $limit){ public static function limitAngle2($old, $newA, $limit){
$v4 = Utils::wrapAngleTo180($old - $newA); $v4 = Utils::wrapAngleTo180($old - $newA);
if($v4 < -$limit) $v4 = -$limit; if($v4 < -$limit) $v4 = -$limit;
if($v4 >= $limit) $v4 = $limit; if($v4 >= $limit) $v4 = $limit;
return $old - $v4; return $old - $v4;
} }
public static function limitAngle($old, $newA, $limit){ public static function limitAngle($old, $newA, $limit){
$v4 = Utils::wrapAngleTo180($newA - $old); $v4 = Utils::wrapAngleTo180($newA - $old);
if($v4 > $limit) $v4 = $limit; if($v4 > $limit) $v4 = $limit;
if($v4 < -$limit) $v4 = -$limit; if($v4 < -$limit) $v4 = -$limit;
return $old + $v4; return $old + $v4;
} }
public function jumpTick(){ public function jumpTick(){
$this->entity->jumping = $this->jumping; $this->entity->jumping = $this->jumping;
$this->jumping = false; $this->jumping = false;
} }
public function movementTick(){ public function movementTick(){
$this->entity->moveForward = 0; $this->entity->moveForward = 0;
if($this->updateMove){ if($this->updateMove){
$this->updateMove = false; $this->updateMove = false;
$v1 = floor($this->entity->boundingBox->minY + 0.5); $v1 = floor($this->entity->boundingBox->minY + 0.5);
$diffX = $this->moveToX - $this->entity->x; $diffX = $this->moveToX - $this->entity->x;
$diffZ = $this->moveToZ - $this->entity->z; $diffZ = $this->moveToZ - $this->entity->z;
$diffY = $this->moveToY - $v1; $diffY = $this->moveToY - $v1;
$v8 = $diffX*$diffX + $diffY*$diffY + $diffZ*$diffZ; $v8 = $diffX * $diffX + $diffY * $diffY + $diffZ * $diffZ;
if($v8 >= 0.00000025){ if($v8 >= 0.00000025){
$v10 = (atan2($diffZ, $diffX) * 180 / M_PI) - 90; $v10 = (atan2($diffZ, $diffX) * 180 / M_PI) - 90;
$this->entity->yaw = self::limitAngle($this->entity->yaw, $v10, 30); $this->entity->yaw = self::limitAngle($this->entity->yaw, $v10, 30);
$this->entity->setAIMoveSpeed($this->speedMultiplier * $this->entity->getSpeed() * $this->entity->getSpeedModifer()); $this->entity->setAIMoveSpeed($this->speedMultiplier * $this->entity->getSpeed() * $this->entity->getSpeedModifer());
if($diffY > 0 && $diffX*$diffX + $diffZ*$diffZ < 1) $this->setJumping(true); if($diffY > 0 && $diffX * $diffX + $diffZ * $diffZ < 1) $this->setJumping(true);
} }
} }
//TODO handle jumps somewhere //TODO handle jumps somewhere
@ -117,11 +117,11 @@ class MobController
//} //}
//if($this->jumpTimeout > 0) --$this->jumpTimeout; //if($this->jumpTimeout > 0) --$this->jumpTimeout;
} }
public function updateHeadYaw(){ public function updateHeadYaw(){
$diffX = $this->entity->x - $this->entity->lastX; $diffX = $this->entity->x - $this->entity->lastX;
$diffZ = $this->entity->z - $this->entity->lastZ; $diffZ = $this->entity->z - $this->entity->lastZ;
if(($diffX*$diffX + $diffZ*$diffZ) > 0.00000025){ if(($diffX * $diffX + $diffZ * $diffZ) > 0.00000025){
$this->entity->renderYawOffset = $this->entity->yaw; $this->entity->renderYawOffset = $this->entity->yaw;
$this->entity->headYaw = self::limitAngle2($this->entity->renderYawOffset, $this->entity->headYaw, 75); $this->entity->headYaw = self::limitAngle2($this->entity->renderYawOffset, $this->entity->headYaw, 75);
$this->headYaw = $this->entity->headYaw; $this->headYaw = $this->entity->headYaw;
@ -133,7 +133,7 @@ class MobController
$this->headYaw = $this->entity->headYaw; $this->headYaw = $this->entity->headYaw;
}else{ }else{
++$this->someTicker; ++$this->someTicker;
if($this->someTicker > 10){ if($this->someTicker > 10){
$v5 = max(1 - ($this->someTicker - 10) / 10, 0) * 75; $v5 = max(1 - ($this->someTicker - 10) / 10, 0) * 75;
} }
@ -141,53 +141,53 @@ class MobController
$this->entity->renderYawOffset = self::limitAngle2($this->entity->headYaw, $this->entity->renderYawOffset, $v5); $this->entity->renderYawOffset = self::limitAngle2($this->entity->headYaw, $this->entity->renderYawOffset, $v5);
} }
} }
public function rotateTick(){ //TODO handle more rotation public function rotateTick(){ //TODO handle more rotation
$this->entity->pitch = 0; $this->entity->pitch = 0;
if($this->isLooking){ if($this->isLooking){
$this->isLooking = false; $this->isLooking = false;
$diffX = $this->lookX - $this->entity->x; $diffX = $this->lookX - $this->entity->x;
$diffY = $this->lookY - ($this->entity->y + $this->entity->getEyeHeight()); $diffY = $this->lookY - ($this->entity->y + $this->entity->getEyeHeight());
$diffZ = $this->lookZ - $this->entity->z; $diffZ = $this->lookZ - $this->entity->z;
$distance = sqrt($diffX*$diffX + $diffZ*$diffZ); $distance = sqrt($diffX * $diffX + $diffZ * $diffZ);
$v9 = (atan2($diffZ, $diffX)*180 / M_PI) - 90; $v9 = (atan2($diffZ, $diffX) * 180 / M_PI) - 90;
$v10 = -(atan2($diffY, $distance)*180 / M_PI); $v10 = -(atan2($diffY, $distance) * 180 / M_PI);
$this->entity->pitch = self::limitAngle($this->entity->pitch, $v10, $this->deltaLookPitch); $this->entity->pitch = self::limitAngle($this->entity->pitch, $v10, $this->deltaLookPitch);
$this->entity->headYaw = self::limitAngle($this->entity->headYaw, $v9, $this->deltaLookYaw); $this->entity->headYaw = self::limitAngle($this->entity->headYaw, $v9, $this->deltaLookYaw);
}else{ }else{
$this->entity->headYaw = self::limitAngle($this->entity->headYaw, $this->entity->renderYawOffset, 10); $this->entity->headYaw = self::limitAngle($this->entity->headYaw, $this->entity->renderYawOffset, 10);
} }
if($this->headYawIsYaw) $this->entity->yaw = $this->entity->headYaw; if($this->headYawIsYaw) $this->entity->yaw = $this->entity->headYaw;
$this->headYawIsYaw = false; $this->headYawIsYaw = false;
/* Some stuff for pathfinder - nc doesnt have it now /* Some stuff for pathfinder - nc doesnt have it now
* float var11 = MathHelper.wrapAngleTo180_float(this.entity.rotationYawHead - this.entity.renderYawOffset); * float var11 = MathHelper.wrapAngleTo180_float(this.entity.rotationYawHead - this.entity.renderYawOffset);
if (!this.entity.getNavigator().noPath()) if (!this.entity.getNavigator().noPath())
{ {
if (var11 < -75.0F) if (var11 < -75.0F)
{ {
this.entity.rotationYawHead = this.entity.renderYawOffset - 75.0F; this.entity.rotationYawHead = this.entity.renderYawOffset - 75.0F;
} }
if (var11 > 75.0F) if (var11 > 75.0F)
{ {
this.entity.rotationYawHead = this.entity.renderYawOffset + 75.0F; this.entity.rotationYawHead = this.entity.renderYawOffset + 75.0F;
} }
} }
*/ */
//$this->entity->lastHeadYaw = $this->entity->headYaw; //$this->entity->lastHeadYaw = $this->entity->headYaw;
//$w180 = Utils::wrapAngleTo180($this->finalHeadYaw - $this->entity->headYaw); //$w180 = Utils::wrapAngleTo180($this->finalHeadYaw - $this->entity->headYaw);
//$w180min = min(abs($w180), 20)*Utils::getSign($w180); //$w180min = min(abs($w180), 20)*Utils::getSign($w180);
//$this->entity->headYaw = Utils::wrapAngleTo360($this->entity->headYaw + $w180min); //$this->entity->headYaw = Utils::wrapAngleTo360($this->entity->headYaw + $w180min);
} }
public function setLookPosition($posX, $posY, $posZ, $lookYaw, $lookPitch){ public function setLookPosition($posX, $posY, $posZ, $lookYaw, $lookPitch){
$this->lookX = $posX; $this->lookX = $posX;
$this->lookY = $posY; $this->lookY = $posY;
@ -196,9 +196,9 @@ class MobController
$this->deltaLookPitch = $lookPitch; $this->deltaLookPitch = $lookPitch;
$this->isLooking = true; $this->isLooking = true;
} }
public function faceEntity($x, $y, $z){ public function faceEntity($x, $y, $z){
$len = sqrt($x*$x + $z*$z + $y*$y); $len = sqrt($x * $x + $z * $z + $y * $y);
//$d = $len == 0 ?//$v->subtract($this->entity)->normalize(); //$d = $len == 0 ?//$v->subtract($this->entity)->normalize();
if($len == 0){ if($len == 0){
$dx = 0; $dx = 0;
@ -207,38 +207,37 @@ class MobController
$dx = $x / $len; $dx = $x / $len;
$dz = $z / $len; $dz = $z / $len;
} }
$tan = $dz == 0 ? ($dx < 0 ? 180 : 0) : (90 - rad2deg(atan($dx / $dz)));
$tan = $dz == 0 ? ($dx < 0 ? 180 : 0) : (90 - rad2deg(atan($dx / $dz)));
$thetaOffset = $dz < 0 ? 90 : 270; $thetaOffset = $dz < 0 ? 90 : 270;
$calcYaw = ($thetaOffset + $tan); $calcYaw = ($thetaOffset + $tan);
$this->finalHeadYaw = $this->entity->yaw = Utils::wrapAngleTo360($calcYaw); $this->finalHeadYaw = $this->entity->yaw = Utils::wrapAngleTo360($calcYaw);
} }
public function lookOffset($x, $y, $z, $pitch = true){ public function lookOffset($x, $y, $z, $pitch = true){
$tan = $z == 0 ? ($x < 0 ? 180 : 0) : (90 - rad2deg(atan($x / $z))); /*arctan(infinity) = pi/2 = (90deg) - 90 = 0*/ $tan = $z == 0 ? ($x < 0 ? 180 : 0) : (90 - rad2deg(atan($x / $z))); /*arctan(infinity) = pi/2 = (90deg) - 90 = 0*/
$thetaOffset = $z < 0 ? 90 : 270; $thetaOffset = $z < 0 ? 90 : 270;
$calcYaw = $tan + $thetaOffset; $calcYaw = $tan + $thetaOffset;
$this->entity->yaw = $this->finalHeadYaw = Utils::wrapAngleTo360($calcYaw); $this->entity->yaw = $this->finalHeadYaw = Utils::wrapAngleTo360($calcYaw);
if($pitch){ if($pitch){
$diff = sqrt($x * $x + $z * $z); $diff = sqrt($x * $x + $z * $z);
$calcPitch = $diff == 0 ? ($y < 0 ? -90 : 90) : rad2deg(atan($y / $diff)); $calcPitch = $diff == 0 ? ($y < 0 ? -90 : 90) : rad2deg(atan($y / $diff));
$this->entity->pitch = $calcPitch; $this->entity->pitch = $calcPitch;
} }
//$this->entity->server->query("UPDATE entities SET pitch = ".$this->entity->pitch.", yaw = ".$this->entity->yaw." WHERE EID = ".$this->entity->eid.";"); //$this->entity->server->query("UPDATE entities SET pitch = ".$this->entity->pitch.", yaw = ".$this->entity->yaw." WHERE EID = ".$this->entity->eid.";");
return true; return true;
} }
public function lookOn($x, $y = 0, $z = 0, $pitch = true){ public function lookOn($x, $y = 0, $z = 0, $pitch = true){
if($x instanceof Vector3){ if($x instanceof Vector3){
return $this->lookOn($x->x, $x->y + $x->getEyeHeight(), $x->z, $pitch); return $this->lookOn($x->x, $x->y + $x->getEyeHeight(), $x->z, $pitch);
} }
return $this->lookOffset($x - $this->entity->x, ($this->entity->y + $this->entity->height) - $y, $z - $this->entity->z, $pitch); return $this->lookOffset($x - $this->entity->x, ($this->entity->y + $this->entity->height) - $y, $z - $this->entity->z, $pitch);
} }
public function __destruct(){ public function __destruct(){
unset($this->entity); unset($this->entity);
} }

View file

@ -5,16 +5,16 @@ class PathFollower{
* @var Living * @var Living
*/ */
public $entity; public $entity;
public function __construct(Living $entity){ public function __construct(Living $entity){
$this->entity = $entity; $this->entity = $entity;
} }
public function followPath(){ public function followPath(){
if(!isset($this->entity) || !($this->entity instanceof Living)) return; if(!isset($this->entity) || !($this->entity instanceof Living)) return;
if(!$this->entity->hasPath()) return; if(!$this->entity->hasPath()) return;
if($this->entity->currentNode == null){ if($this->entity->currentNode == null){
$this->entity->currentNode = $this->entity->path[$this->entity->currentIndex]; $this->entity->currentNode = $this->entity->path[$this->entity->currentIndex];
} }
@ -27,14 +27,13 @@ class PathFollower{
//console("next"); //console("next");
$this->entity->currentNode = null; $this->entity->currentNode = null;
} }
if($this->entity->currentIndex >= count($this->entity->path)){ if($this->entity->currentIndex >= count($this->entity->path)){
console("path finished."); console("path finished.");
$this->entity->currentNode = null; $this->entity->currentNode = null;
$this->entity->path = null; $this->entity->path = null;
$this->entity->currentIndex = 0; $this->entity->currentIndex = 0;
/*foreach($this->entity->pathEIDS as $eid){ /*foreach($this->entity->pathEIDS as $eid){
$pk = new RemoveEntityPacket(); $pk = new RemoveEntityPacket();
$pk->eid = $eid; $pk->eid = $eid;
@ -42,9 +41,9 @@ class PathFollower{
$player->dataPacket($pk); $player->dataPacket($pk);
} }
}*/ }*/
} }
} }
} }

View file

@ -4,20 +4,19 @@ class TaskAttackPlayer extends TaskBase
{ {
public $speedMultiplier; public $speedMultiplier;
public $rangeSquared; public $rangeSquared;
public $attackCounter; public $attackCounter;
public function __construct($speed, $range){ public function __construct($speed, $range){
$this->speedMultiplier = $speed; $this->speedMultiplier = $speed;
$this->rangeSquared = $range*$range; $this->rangeSquared = $range * $range;
} }
public function onStart(EntityAI $ai) public function onStart(EntityAI $ai)
{ {
$this->selfCounter = 1; $this->selfCounter = 1;
} }
public function onUpdate(EntityAI $ai) public function onUpdate(EntityAI $ai)
{ {
if(!$this->isTargetValid($ai)){ if(!$this->isTargetValid($ai)){
@ -27,7 +26,7 @@ class TaskAttackPlayer extends TaskBase
} }
$ai->mobController->setMovingTarget($ai->entity->target->x, $ai->entity->target->y, $ai->entity->target->z, $this->speedMultiplier); $ai->mobController->setMovingTarget($ai->entity->target->x, $ai->entity->target->y, $ai->entity->target->z, $this->speedMultiplier);
$ai->mobController->setLookPosition($ai->entity->target->x, $ai->entity->target->y + 0.12, $ai->entity->target->z, 10, $ai->entity->getVerticalFaceSpeed()); $ai->mobController->setLookPosition($ai->entity->target->x, $ai->entity->target->y + 0.12, $ai->entity->target->z, 10, $ai->entity->getVerticalFaceSpeed());
--$this->attackCounter; --$this->attackCounter;
$v1 = $ai->entity->width * $ai->entity->width * 4; $v1 = $ai->entity->width * $ai->entity->width * 4;
if($ai->entity instanceof Creeper){ if($ai->entity instanceof Creeper){
@ -38,16 +37,15 @@ class TaskAttackPlayer extends TaskBase
$xDiff = ($t->x - $e->x); $xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y); $yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z); $zDiff = ($t->z - $e->z);
$dist = ($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff); $dist = ($xDiff * $xDiff + $yDiff * $yDiff + $zDiff * $zDiff);
if($dist <= $v1){ if($dist <= $v1){
if($this->attackCounter <= 0){ if($this->attackCounter <= 0){
$this->attackCounter = $e->attackEntity($t, sqrt($dist)) ? 20 : 0; $this->attackCounter = $e->attackEntity($t, sqrt($dist)) ? 20 : 0;
} }
} }
} }
public function isTargetValid(EntityAI $ai){ public function isTargetValid(EntityAI $ai){
$e = $ai->entity; $e = $ai->entity;
if($e->target instanceof Entity && !$e->target->closed && !$e->target->dead){ if($e->target instanceof Entity && !$e->target->closed && !$e->target->dead){
@ -55,11 +53,11 @@ class TaskAttackPlayer extends TaskBase
$xDiff = ($t->x - $e->x); $xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y); $yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z); $zDiff = ($t->z - $e->z);
return ($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff) <= $this->rangeSquared; return ($xDiff * $xDiff + $yDiff * $yDiff + $zDiff * $zDiff) <= $this->rangeSquared;
} }
return false; return false;
} }
public function tryTargeting(EntityAI $ai){ public function tryTargeting(EntityAI $ai){
$e = $ai->entity; $e = $ai->entity;
if($e->target instanceof Entity){ if($e->target instanceof Entity){
@ -67,25 +65,25 @@ class TaskAttackPlayer extends TaskBase
$xDiff = ($t->x - $e->x); $xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y); $yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z); $zDiff = ($t->z - $e->z);
if(($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff) <= $this->rangeSquared){ if(($xDiff * $xDiff + $yDiff * $yDiff + $zDiff * $zDiff) <= $this->rangeSquared){
return true; return true;
} }
} }
$closestTarget = $e->closestPlayerToAttackDist <= $this->rangeSquared ? $e->level->entityList[$e->closestPlayerToAttackEID] : null; $closestTarget = $e->closestPlayerToAttackDist <= $this->rangeSquared ? $e->level->entityList[$e->closestPlayerToAttackEID] : null;
if($closestTarget != null){ if($closestTarget != null){
$e->target = $closestTarget; //TODO dont save entity object ? $e->target = $closestTarget; //TODO dont save entity object ?
return true; return true;
} }
return false; return false;
} }
public function canBeExecuted(EntityAI $ai) public function canBeExecuted(EntityAI $ai)
{ {
return $this->tryTargeting($ai); return $this->tryTargeting($ai);
} }
public function onEnd(EntityAI $ai) public function onEnd(EntityAI $ai)
{ {
$ai->entity->target = false; $ai->entity->target = false;

View file

@ -3,45 +3,41 @@
abstract class TaskBase abstract class TaskBase
{ {
public $isStarted = false, $selfCounter = 0; public $isStarted = false, $selfCounter = 0;
public function __construct(){} public function __construct(){}
/** /**
* Executed when entity starts task. It is recommended to set counter here. * Executed when entity starts task. It is recommended to set counter here.
* @param EntityAI $ai
*/ */
abstract function onStart(EntityAI $ai); abstract function onStart(EntityAI $ai);
/** /**
* Every tick until counter will be not equal to 0. It is recommended to update value of counter here. * Every tick until counter will be not equal to 0. It is recommended to update value of counter here.
* @param EntityAI $ai
*/ */
abstract function onUpdate(EntityAI $ai); abstract function onUpdate(EntityAI $ai);
/** /**
* On task end. * On task end.
* @param EntityAI $ai
*/ */
abstract function onEnd(EntityAI $ai); abstract function onEnd(EntityAI $ai);
/** /**
* Can start the task * Can start the task
* @param EntityAI $ai
*/ */
abstract function canBeExecuted(EntityAI $ai); abstract function canBeExecuted(EntityAI $ai);
/** /**
* @return number ticks * @return number ticks
*/ */
function getIdleTimeAfterEnd(){ function getIdleTimeAfterEnd(){
return 0; return 0;
} }
function reset(){ function reset(){
$this->isStarted = false; $this->isStarted = false;
$this->selfCounter = 0; $this->selfCounter = 0;
} }
final function __toString(){ final function __toString(){
return get_class($this); return get_class($this);
} }

View file

@ -10,7 +10,7 @@ class TaskEatTileGoal extends TaskBase
public function onEnd(EntityAI $ai) public function onEnd(EntityAI $ai)
{ {
} }
public function onUpdate(EntityAI $ai) public function onUpdate(EntityAI $ai)
@ -18,7 +18,7 @@ class TaskEatTileGoal extends TaskBase
if($ai->isStarted("TaskPanic")){ if($ai->isStarted("TaskPanic")){
$this->reset(); $this->reset();
return false; return false;
} }
if (--$this->selfCounter == 4) if (--$this->selfCounter == 4)
{ {
@ -27,7 +27,7 @@ class TaskEatTileGoal extends TaskBase
if($id === TALL_GRASS){ if($id === TALL_GRASS){
$ai->entity->level->fastSetBlockUpdate($ai->entity->x, $ai->entity->y, $ai->entity->z, AIR, 0); $ai->entity->level->fastSetBlockUpdate($ai->entity->x, $ai->entity->y, $ai->entity->z, AIR, 0);
$ai->entity->eatGrass(); $ai->entity->eatGrass();
}elseif($idb === GRASS){ }elseif($idb === GRASS){
$ai->entity->level->fastSetBlockUpdate($ai->entity->x, $ai->entity->y - 1, $ai->entity->z, DIRT, 0); $ai->entity->level->fastSetBlockUpdate($ai->entity->x, $ai->entity->y - 1, $ai->entity->z, DIRT, 0);
$ai->entity->eatGrass(); $ai->entity->eatGrass();

View file

@ -5,7 +5,7 @@ class TaskFollowParent extends TaskBase
public function __construct($speed){ public function __construct($speed){
$this->speedMultiplier = $speed; $this->speedMultiplier = $speed;
} }
public function onStart(EntityAI $ai) public function onStart(EntityAI $ai)
{ {
$this->selfCounter = 1; $this->selfCounter = 1;
@ -23,19 +23,19 @@ class TaskFollowParent extends TaskBase
$ai->entity->parent = null; $ai->entity->parent = null;
return false; return false;
} }
$dist = $ai->entity->distanceSquared($ai->entity->parent); $dist = $ai->entity->distanceSquared($ai->entity->parent);
if($dist > 256 || $dist < 9){ //3-16 blocks if($dist > 256 || $dist < 9){ //3-16 blocks
$this->reset(); $this->reset();
return false; return false;
} }
$parent = $ai->entity->parent; $parent = $ai->entity->parent;
$ai->mobController->setLookPosition($parent->x, $parent->y + $parent->getEyeHeight(), $parent->z, 10, $ai->entity->getVerticalFaceSpeed()); $ai->mobController->setLookPosition($parent->x, $parent->y + $parent->getEyeHeight(), $parent->z, 10, $ai->entity->getVerticalFaceSpeed());
$ai->mobController->setMovingTarget($parent->x, $parent->y, $parent->z, $this->speedMultiplier); $ai->mobController->setMovingTarget($parent->x, $parent->y, $parent->z, $this->speedMultiplier);
} }
public function canBeExecuted(EntityAI $ai) public function canBeExecuted(EntityAI $ai)
{ {
return $ai->entity->isBaby() && ($ai->entity->parent instanceof Entity) && !$ai->entity->parent->dead; //TODO find a new parent if the current one is dead return $ai->entity->isBaby() && ($ai->entity->parent instanceof Entity) && !$ai->entity->parent->dead; //TODO find a new parent if the current one is dead

View file

@ -3,7 +3,7 @@
class TaskLookAround extends TaskBase class TaskLookAround extends TaskBase
{ {
public $lookOffsetX, $lookOffsetZ; public $lookOffsetX, $lookOffsetZ;
public function onStart(EntityAI $ai) public function onStart(EntityAI $ai)
{ {
$this->selfCounter = 20 + lcg_value(); $this->selfCounter = 20 + lcg_value();
@ -19,9 +19,9 @@ class TaskLookAround extends TaskBase
public function canBeExecuted(EntityAI $ai) public function canBeExecuted(EntityAI $ai)
{ {
return !$ai->entity->inPanic && !$ai->entity->isMoving() && lcg_value() < 0.02 && !$ai->isStarted("TaskLookAtPlayer") && !$ai->isStarted("TaskAttackPlayer") && !$ai->isStarted("TaskMate") && !$ai->isStarted("TaskTempt") && !$ai->entity->hasPath(); /*Vanilla value*/ return !$ai->entity->inPanic && !$ai->entity->isMoving() && lcg_value() < 0.02 && !$ai->isStarted("TaskLookAtPlayer") && !$ai->isStarted("TaskAttackPlayer") && !$ai->isStarted("TaskMate") && !$ai->isStarted("TaskTempt") && !$ai->entity->hasPath(); /*Vanilla value*/
} }
public function onUpdate(EntityAI $ai) public function onUpdate(EntityAI $ai)
{ {
--$this->selfCounter; --$this->selfCounter;

View file

@ -6,13 +6,13 @@ class TaskLookAtPlayer extends TaskBase{
public function __construct($distance){ public function __construct($distance){
$this->distance = $distance; $this->distance = $distance;
} }
public function canBeExecuted(EntityAI $ai){ public function canBeExecuted(EntityAI $ai){
return !$ai->entity->inPanic && lcg_value() < 0.02 && !$ai->entity->isMovingHorizontally() && !$ai->isStarted("TaskMate") && !$ai->isStarted("TaskLookAround") && !$ai->isStarted("TaskTempt") && !$ai->isStarted("TaskPanic") && !$ai->entity->hasPath(); return !$ai->entity->inPanic && lcg_value() < 0.02 && !$ai->entity->isMovingHorizontally() && !$ai->isStarted("TaskMate") && !$ai->isStarted("TaskLookAround") && !$ai->isStarted("TaskTempt") && !$ai->isStarted("TaskPanic") && !$ai->entity->hasPath();
} }
protected function findTarget(Creature $e, $r){ protected function findTarget(Creature $e, $r){
return $e->closestPlayerDist > $r*$r ? null : $e->level->entityList[$e->closestPlayerEID]; return $e->closestPlayerDist > $r * $r ? null : $e->level->entityList[$e->closestPlayerEID];
} }
public function onStart(EntityAI $ai){ public function onStart(EntityAI $ai){
@ -22,7 +22,7 @@ class TaskLookAtPlayer extends TaskBase{
$this->onEnd($ai); $this->onEnd($ai);
return; return;
} }
$this->selfCounter = mt_rand(20, 60); $this->selfCounter = mt_rand(20, 60);
} }
@ -35,7 +35,7 @@ class TaskLookAtPlayer extends TaskBase{
$ai->mobController->setLookPosition($this->target->x, $this->target->y + $this->target->getEyeHeight(), $this->target->z, 10, $ai->entity->getVerticalFaceSpeed()); $ai->mobController->setLookPosition($this->target->x, $this->target->y + $this->target->getEyeHeight(), $this->target->z, 10, $ai->entity->getVerticalFaceSpeed());
$this->selfCounter--; $this->selfCounter--;
} }
public function onEnd(EntityAI $ai){ public function onEnd(EntityAI $ai){
unset($this->target); unset($this->target);
$ai->entity->pitch = 0; $ai->entity->pitch = 0;

View file

@ -5,9 +5,9 @@ class TaskMate extends TaskBase
public function __construct($speed){ public function __construct($speed){
$this->speedMultiplier = $speed; $this->speedMultiplier = $speed;
} }
public $targetMateID; public $targetMateID;
public function onStart(EntityAI $ai) public function onStart(EntityAI $ai)
{ {
$this->selfCounter = 60; $this->selfCounter = 60;
@ -27,17 +27,16 @@ class TaskMate extends TaskBase
$this->onEnd($ai); $this->onEnd($ai);
return; return;
} }
$ai->mobController->setLookPosition($movTo->x, $movTo->y + $movTo->getEyeHeight(), $movTo->z, 10, $ai->entity->getVerticalFaceSpeed()); $ai->mobController->setLookPosition($movTo->x, $movTo->y + $movTo->getEyeHeight(), $movTo->z, 10, $ai->entity->getVerticalFaceSpeed());
$ai->mobController->setMovingTarget($movTo->x, $movTo->y, $movTo->z, $this->speedMultiplier); $ai->mobController->setMovingTarget($movTo->x, $movTo->y, $movTo->z, $this->speedMultiplier);
--$this->selfCounter; --$this->selfCounter;
if($this->selfCounter <= 0 && $ai->entity->distanceSquared($movTo) < 9){ if($this->selfCounter <= 0 && $ai->entity->distanceSquared($movTo) < 9){
$this->createBaby($ai, $movTo); $this->createBaby($ai, $movTo);
} }
} }
public function createBaby(EntityAI $ai, Entity $entpar2){ public function createBaby(EntityAI $ai, Entity $entpar2){
/** /**
* @var Animal $baby * @var Animal $baby
@ -45,20 +44,20 @@ class TaskMate extends TaskBase
$baby = $ai->entity->breed(); $baby = $ai->entity->breed();
//this.theAnimal.setGrowingAge(6000); TODO growing age? //this.theAnimal.setGrowingAge(6000); TODO growing age?
//this.targetMate.setGrowingAge(6000); //this.targetMate.setGrowingAge(6000);
$ai->entity->loveTimeout = 6000; $ai->entity->loveTimeout = 6000;
$entpar2->loveTimeout = 6000; $entpar2->loveTimeout = 6000;
$ai->entity->resetInLove(); $ai->entity->resetInLove();
$entpar2->resetInLove(); $entpar2->resetInLove();
$baby->setAge(-24000); $baby->setAge(-24000);
} }
public function findMate(EntityAI $ai){ public function findMate(EntityAI $ai){
$distance = 8.0*8.0; $distance = 8.0 * 8.0;
$minDist = $distance; //TODO check bb intersection? $minDist = $distance; //TODO check bb intersection?
$matedEID = null; $matedEID = null;
foreach($ai->entity->level->entitiesInLove as $eid => $_){ foreach($ai->entity->level->entitiesInLove as $eid => $_){
$e = $ai->entity->level->entityList[$eid] ?? false; $e = $ai->entity->level->entityList[$eid] ?? false;
if($e instanceof Entity){ if($e instanceof Entity){
@ -71,7 +70,7 @@ class TaskMate extends TaskBase
} }
return $matedEID; return $matedEID;
} }
public function canBeExecuted(EntityAI $ai) public function canBeExecuted(EntityAI $ai)
{ {
return $ai->entity->isInLove() && ($this->targetMateID = $this->findMate($ai)) != null; return $ai->entity->isInLove() && ($this->targetMateID = $this->findMate($ai)) != null;

View file

@ -3,12 +3,12 @@
class TaskPanic extends TaskBase class TaskPanic extends TaskBase
{ {
protected $randX = 2, $randZ = 2; protected $randX = 2, $randZ = 2;
public $speedMultiplier; public $speedMultiplier;
public function __construct($speedMultiplier){ public function __construct($speedMultiplier){
$this->speedMultiplier = $speedMultiplier; $this->speedMultiplier = $speedMultiplier;
} }
public function onStart(EntityAI $ai) public function onStart(EntityAI $ai)
{ {
$this->selfCounter = 60; $this->selfCounter = 60;
@ -20,16 +20,16 @@ class TaskPanic extends TaskBase
$ai->entity->inPanic = false; $ai->entity->inPanic = false;
$this->reset(); $this->reset();
} }
public function regenerateRandXZ(){ public function regenerateRandXZ(){
$this->randX = (mt_rand(0, 1) ? -1 : 1); $this->randX = (mt_rand(0, 1) ? -1 : 1);
$this->randZ = (mt_rand(0, 1) ? -1 : 1); $this->randZ = (mt_rand(0, 1) ? -1 : 1);
} }
public function reset(){ public function reset(){
$this->randX = $this->randZ = 2; $this->randX = $this->randZ = 2;
} }
public function onUpdate(EntityAI $ai) public function onUpdate(EntityAI $ai)
{ {
--$this->selfCounter; --$this->selfCounter;
@ -42,6 +42,5 @@ class TaskPanic extends TaskBase
return $ai->entity instanceof Animal && $ai->entity->inPanic && $ai->entity->knockbackTime <= 0; return $ai->entity instanceof Animal && $ai->entity->inPanic && $ai->entity->knockbackTime <= 0;
} }
}
}

View file

@ -7,7 +7,7 @@ class TaskRandomWalk extends TaskBase
public function __construct($speedMultiplier){ public function __construct($speedMultiplier){
$this->speedMultiplier = $speedMultiplier; $this->speedMultiplier = $speedMultiplier;
} }
public function onStart(EntityAI $ai) public function onStart(EntityAI $ai)
{ {
$this->x = mt_rand(-1, 1); $this->x = mt_rand(-1, 1);
@ -30,7 +30,7 @@ class TaskRandomWalk extends TaskBase
$this->reset(); $this->reset();
return false; //TODO Better way: block movement return false; //TODO Better way: block movement
} }
--$this->selfCounter; --$this->selfCounter;
$ai->mobController->setMovingOffset($this->x, 0, $this->z, $this->speedMultiplier); $ai->mobController->setMovingOffset($this->x, 0, $this->z, $this->speedMultiplier);
} }
@ -40,8 +40,7 @@ class TaskRandomWalk extends TaskBase
if(($ai->entity instanceof Creeper && $ai->entity->isIgnited()) || $ai->entity->hasPath() || $ai->isStarted("TaskTempt") || $ai->isStarted("TaskAttackPlayer") || $ai->isStarted("TaskRangedAttack")) { if(($ai->entity instanceof Creeper && $ai->entity->isIgnited()) || $ai->entity->hasPath() || $ai->isStarted("TaskTempt") || $ai->isStarted("TaskAttackPlayer") || $ai->isStarted("TaskRangedAttack")) {
return false; return false;
} // i really need mutexBits } // i really need mutexBits
return !$ai->entity->inPanic && !$ai->isStarted("TaskMate") && !$ai->isStarted("TaskEatTileGoal") && !$ai->isStarted("TaskLookAround") && !$ai->isStarted("TaskFollowParent") && !$ai->isStarted("TaskLookAtPlayer") && mt_rand(0, 120) == 0; return !$ai->entity->inPanic && !$ai->isStarted("TaskMate") && !$ai->isStarted("TaskEatTileGoal") && !$ai->isStarted("TaskLookAround") && !$ai->isStarted("TaskFollowParent") && !$ai->isStarted("TaskLookAtPlayer") && mt_rand(0, 120) == 0;
} }
}
}

View file

@ -7,10 +7,10 @@ class TaskRangedAttack extends \TaskBase
public $seenTicks = 0; public $seenTicks = 0;
public function __construct($speed, $range){ public function __construct($speed, $range){
$this->speedMultiplier = $speed; $this->speedMultiplier = $speed;
$this->rangeSquared = $range*$range; $this->rangeSquared = $range * $range;
$this->server = ServerAPI::request(); $this->server = ServerAPI::request();
} }
public function onStart(EntityAI $ai) public function onStart(EntityAI $ai)
{ {
$this->selfCounter = 1; $this->selfCounter = 1;
@ -20,7 +20,7 @@ class TaskRangedAttack extends \TaskBase
public function onEnd(EntityAI $ai) public function onEnd(EntityAI $ai)
{ {
$ai->entity->target = false; $ai->entity->target = false;
} }
public function onUpdate(EntityAI $ai) public function onUpdate(EntityAI $ai)
@ -36,24 +36,23 @@ class TaskRangedAttack extends \TaskBase
}else{ }else{
$this->seenTicks = 0; $this->seenTicks = 0;
} }
$dist = $ai->entity->distanceSquared($ai->entity->target); $dist = $ai->entity->distanceSquared($ai->entity->target);
if($dist > 100 || $this->seenTicks < 20){ if($dist > 100 || $this->seenTicks < 20){
$ai->mobController->setMovingTarget($ai->entity->target->x, $ai->entity->target->y, $ai->entity->target->z, $this->speedMultiplier); $ai->mobController->setMovingTarget($ai->entity->target->x, $ai->entity->target->y, $ai->entity->target->z, $this->speedMultiplier);
}else{ }else{
$ai->mobController->headYawIsYaw = true; $ai->mobController->headYawIsYaw = true;
} }
$ai->mobController->setLookPosition($ai->entity->target->x, $ai->entity->target->y + 0.12, $ai->entity->target->z, 10, $ai->entity->getVerticalFaceSpeed()); $ai->mobController->setLookPosition($ai->entity->target->x, $ai->entity->target->y + 0.12, $ai->entity->target->z, 10, $ai->entity->getVerticalFaceSpeed());
if($this->attackCounter <= 0 && $this->seenTicks > 0){ if($this->attackCounter <= 0 && $this->seenTicks > 0){
$this->rangedAttack($ai->entity, $ai->entity->target); $this->rangedAttack($ai->entity, $ai->entity->target);
$this->attackCounter = 60; $this->attackCounter = 60;
} }
} }
public function rangedAttack($selfEntity, $target){ public function rangedAttack($selfEntity, $target){
$d = [ $d = [
"x" => $selfEntity->x, "x" => $selfEntity->x,
@ -88,8 +87,7 @@ class TaskRangedAttack extends \TaskBase
$this->server->api->entity->spawnToAll($arrow); $this->server->api->entity->spawnToAll($arrow);
} }
} }
public function isTargetValid(EntityAI $ai){ public function isTargetValid(EntityAI $ai){
$e = $ai->entity; $e = $ai->entity;
if($e->target instanceof Entity && !$e->target->closed && !$e->target->dead){ if($e->target instanceof Entity && !$e->target->closed && !$e->target->dead){
@ -97,11 +95,11 @@ class TaskRangedAttack extends \TaskBase
$xDiff = ($t->x - $e->x); $xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y); $yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z); $zDiff = ($t->z - $e->z);
return ($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff) <= $this->rangeSquared; return ($xDiff * $xDiff + $yDiff * $yDiff + $zDiff * $zDiff) <= $this->rangeSquared;
} }
return false; return false;
} }
public function tryTargeting(EntityAI $ai){ public function tryTargeting(EntityAI $ai){
$e = $ai->entity; $e = $ai->entity;
if($e->target instanceof Entity){ if($e->target instanceof Entity){
@ -109,21 +107,20 @@ class TaskRangedAttack extends \TaskBase
$xDiff = ($t->x - $e->x); $xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y); $yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z); $zDiff = ($t->z - $e->z);
if(($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff) <= $this->rangeSquared){ if(($xDiff * $xDiff + $yDiff * $yDiff + $zDiff * $zDiff) <= $this->rangeSquared){
return true; return true;
} }
} }
$closestTarget = $e->closestPlayerToAttackDist <= $this->rangeSquared ? $e->level->entityList[$e->closestPlayerToAttackEID] : null; $closestTarget = $e->closestPlayerToAttackDist <= $this->rangeSquared ? $e->level->entityList[$e->closestPlayerToAttackEID] : null;
if($closestTarget != null){ if($closestTarget != null){
$e->target = $closestTarget; //TODO dont save entity object ? $e->target = $closestTarget; //TODO dont save entity object ?
return true; return true;
} }
return false; return false;
} }
public function canBeExecuted(EntityAI $ai) public function canBeExecuted(EntityAI $ai)
{ {
return $this->tryTargeting($ai); return $this->tryTargeting($ai);

View file

@ -9,7 +9,7 @@ class TaskSwimming extends TaskBase
public function onEnd(EntityAI $ai) public function onEnd(EntityAI $ai)
{ {
} }
public function onUpdate(EntityAI $ai) public function onUpdate(EntityAI $ai)
@ -18,12 +18,12 @@ class TaskSwimming extends TaskBase
$this->reset(); $this->reset();
return; return;
} }
if(lcg_value() < 0.8){ #1.5.2 method if(lcg_value() < 0.8){ #1.5.2 method
$ai->mobController->setJumping(true); $ai->mobController->setJumping(true);
} }
} }
public function canBeExecuted(EntityAI $ai) public function canBeExecuted(EntityAI $ai)
{ {
return $ai->entity->inWater || $ai->entity->inLava; return $ai->entity->inWater || $ai->entity->inLava;

View file

@ -4,19 +4,19 @@ class TaskTempt extends TaskBase
{ {
public function __construct($speed){ public function __construct($speed){
$this->speedMultiplier = $speed; $this->speedMultiplier = $speed;
$this->targetDistance = 10*10; $this->targetDistance = 10 * 10;
} }
public function onStart(EntityAI $ai) public function onStart(EntityAI $ai)
{ {
$this->selfCounter = 1; $this->selfCounter = 1;
} }
public function onEnd(EntityAI $ai) public function onEnd(EntityAI $ai)
{ {
$ai->entity->target = false; $ai->entity->target = false;
} }
public function onUpdate(EntityAI $ai) public function onUpdate(EntityAI $ai)
{ {
if(!$this->isTargetValid($ai) || $ai->entity->inPanic || $ai->isStarted("TaskMate")){ if(!$this->isTargetValid($ai) || $ai->entity->inPanic || $ai->isStarted("TaskMate")){
@ -24,22 +24,21 @@ class TaskTempt extends TaskBase
$this->onEnd($ai); $this->onEnd($ai);
return false; return false;
} }
$target = $ai->entity->target; $target = $ai->entity->target;
$xdiff = ($target->x - $ai->entity->x); $xdiff = ($target->x - $ai->entity->x);
$ydiff = ($target->y - $ai->entity->y); $ydiff = ($target->y - $ai->entity->y);
$zdiff = ($target->z - $ai->entity->z); $zdiff = ($target->z - $ai->entity->z);
$dist = $xdiff*$xdiff + $ydiff*$ydiff + $zdiff*$zdiff; $dist = $xdiff * $xdiff + $ydiff * $ydiff + $zdiff * $zdiff;
$ai->mobController->setLookPosition($target->x, $target->y + $target->getEyeHeight(), $target->z, 30, $ai->entity->getVerticalFaceSpeed()); $ai->mobController->setLookPosition($target->x, $target->y + $target->getEyeHeight(), $target->z, 30, $ai->entity->getVerticalFaceSpeed());
if($dist >= 6.25){ if($dist >= 6.25){
$ai->mobController->setMovingTarget($target->x, $target->y, $target->z, $this->speedMultiplier); $ai->mobController->setMovingTarget($target->x, $target->y, $target->z, $this->speedMultiplier);
}else{ }else{
$ai->mobController->headYawIsYaw = true; $ai->mobController->headYawIsYaw = true;
} }
} }
public function isTargetValid(EntityAI $ai){ public function isTargetValid(EntityAI $ai){
$e = $ai->entity; $e = $ai->entity;
if($e->target instanceof Entity && !$e->target->closed && $e->isFood($e->target->player->getHeldItem()->id)){ if($e->target instanceof Entity && !$e->target->closed && $e->isFood($e->target->player->getHeldItem()->id)){
@ -47,16 +46,16 @@ class TaskTempt extends TaskBase
$xDiff = ($t->x - $e->x); $xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y); $yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z); $zDiff = ($t->z - $e->z);
return ($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff) <= $this->targetDistance; return ($xDiff * $xDiff + $yDiff * $yDiff + $zDiff * $zDiff) <= $this->targetDistance;
} }
return false; return false;
} }
public function canBeExecuted(EntityAI $ai) public function canBeExecuted(EntityAI $ai)
{ {
return !$ai->entity->inPanic && !$ai->isStarted("TaskMate") && $this->tryTargeting($ai); return !$ai->entity->inPanic && !$ai->isStarted("TaskMate") && $this->tryTargeting($ai);
} }
public function tryTargeting(EntityAI $ai){ public function tryTargeting(EntityAI $ai){
$e = $ai->entity; $e = $ai->entity;
if($e->target instanceof Entity){ if($e->target instanceof Entity){
@ -64,13 +63,13 @@ class TaskTempt extends TaskBase
$xDiff = ($t->x - $e->x); $xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y); $yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z); $zDiff = ($t->z - $e->z);
if(($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff) <= $this->targetDistance){ if(($xDiff * $xDiff + $yDiff * $yDiff + $zDiff * $zDiff) <= $this->targetDistance){
return true; return true;
} }
} }
$closestTarget = $e->closestPlayerThatCanFeedDist <= $this->targetDistance ? $e->level->entityList[$e->closestPlayerThatCanFeedEID] : null; $closestTarget = $e->closestPlayerThatCanFeedDist <= $this->targetDistance ? $e->level->entityList[$e->closestPlayerThatCanFeedEID] : null;
if($closestTarget != null){ if($closestTarget != null){
$e->target = $closestTarget; //TODO dont save entity object ? $e->target = $closestTarget; //TODO dont save entity object ?
return true; return true;

View file

@ -10,7 +10,7 @@ class Chicken extends Animal{
$this->setHealth($this->data["Health"] ?? 4, "generic"); $this->setHealth($this->data["Health"] ?? 4, "generic");
$this->setName('Chicken'); $this->setName('Chicken');
$this->setSpeed(0.25); $this->setSpeed(0.25);
$this->ai->addTask(new TaskRandomWalk(1.0)); $this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAtPlayer(6)); $this->ai->addTask(new TaskLookAtPlayer(6));
$this->ai->addTask(new TaskPanic(1.5)); $this->ai->addTask(new TaskPanic(1.5));
@ -23,27 +23,27 @@ class Chicken extends Animal{
public function isFood($id){ public function isFood($id){
return $id === PUMPKIN_SEEDS || $id === MELON_SEEDS || $id === BEETROOT_SEEDS || $id === WHEAT_SEEDS; return $id === PUMPKIN_SEEDS || $id === MELON_SEEDS || $id === BEETROOT_SEEDS || $id === WHEAT_SEEDS;
} }
public function updateEntityMovement(){ public function updateEntityMovement(){
parent::updateEntityMovement(); parent::updateEntityMovement();
if(!$this->onGround && $this->speedY < 0) $this->speedY *= 0.6; if(!$this->onGround && $this->speedY < 0) $this->speedY *= 0.6;
if($this->timeUntilEgg-- <= 0 && !$this->isBaby()){ if($this->timeUntilEgg-- <= 0 && !$this->isBaby()){
$this->dropAnEgg(); $this->dropAnEgg();
$this->timeUntilEgg = mt_rand(0,6000) + 6000; $this->timeUntilEgg = mt_rand(0,6000) + 6000;
} }
} }
public function fall(){} //chickens have no fall dmg? public function fall(){} //chickens have no fall dmg?
public function dropAnEgg(){ public function dropAnEgg(){
if($this->closed){ if($this->closed){
return; return;
} }
ServerAPI::request()->api->entity->drop(new Position($this->x + 0.5, $this->y, $this->z + 0.5, $this->level), BlockAPI::getItem(EGG, 0, 1)); ServerAPI::request()->api->entity->drop(new Position($this->x + 0.5, $this->y, $this->z + 0.5, $this->level), BlockAPI::getItem(EGG, 0, 1));
} }
public function getDrops(){ public function getDrops(){
return $this->isBaby() ? parent::getDrops() : [ return $this->isBaby() ? parent::getDrops() : [
[FEATHER, 0, mt_rand(0,2)], [FEATHER, 0, mt_rand(0,2)],

View file

@ -17,11 +17,11 @@ class Cow extends Animal{
$this->ai->addTask(new TaskMate(1.0)); $this->ai->addTask(new TaskMate(1.0));
$this->ai->addTask(new TaskFollowParent(1.1)); $this->ai->addTask(new TaskFollowParent(1.1));
} }
public function isFood($id){ public function isFood($id){
return $id === WHEAT; return $id === WHEAT;
} }
public function interactWith(Entity $e, $action){ public function interactWith(Entity $e, $action){
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){ if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem(); $slot = $e->player->getHeldItem();
@ -33,9 +33,9 @@ class Cow extends Animal{
} }
parent::interactWith($e, $action); parent::interactWith($e, $action);
} }
public function getDrops(){ public function getDrops(){
return $this->isBaby() ? parent::getDrops() : [ return $this->isBaby() ? parent::getDrops() : [
[LEATHER, 0, mt_rand(0,2)], [LEATHER, 0, mt_rand(0,2)],
[($this->fire > 0 ? STEAK : BEEF), 0, mt_rand(0, 3)] [($this->fire > 0 ? STEAK : BEEF), 0, mt_rand(0, 3)]
]; ];

View file

@ -1,7 +1,8 @@
<?php <?php
class Pig extends Animal implements Rideable{ class Pig extends Animal implements Rideable{
const TYPE = MOB_PIG; const TYPE = MOB_PIG;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){ public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.9, 0.9); $this->setSize(0.9, 0.9);
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
@ -9,7 +10,7 @@ class Pig extends Animal implements Rideable{
$this->server = ServerAPI::request(); $this->server = ServerAPI::request();
$this->setName("Pig"); $this->setName("Pig");
$this->setSpeed(0.25); $this->setSpeed(0.25);
$this->ai->addTask(new TaskRandomWalk(1.0)); $this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAtPlayer(6)); $this->ai->addTask(new TaskLookAtPlayer(6));
$this->ai->addTask(new TaskPanic(1.5)); $this->ai->addTask(new TaskPanic(1.5));
@ -25,18 +26,18 @@ class Pig extends Animal implements Rideable{
public function isSaddled(){ public function isSaddled(){
return (boolean) $this->getState(); return (boolean) $this->getState();
} }
/** /**
* @param boolean $value * @param boolean $value
*/ */
public function setSaddled($value = null){ public function setSaddled($value = null){
$this->setState($value === null ? !$this->getState() : $value); $this->setState($value === null ? !$this->getState() : $value);
} }
public function canRide($e){ public function canRide($e){
return $this->isSaddled() && $this->linkedEntity == 0 && $e->linkedEntity == 0; return $this->isSaddled() && $this->linkedEntity == 0 && $e->linkedEntity == 0;
} }
public function updateEntityMovement(){ public function updateEntityMovement(){
/*if($this->linkedEntity != 0){ /*if($this->linkedEntity != 0){
$e = $this->level->entityList[$this->linkedEntity] ?? false; $e = $this->level->entityList[$this->linkedEntity] ?? false;
@ -47,10 +48,10 @@ class Pig extends Animal implements Rideable{
$this->yaw = $e->headYaw; $this->yaw = $e->headYaw;
} }
}*/ }*/
parent::updateEntityMovement(); parent::updateEntityMovement();
} }
public function interactWith(Entity $e, $action) public function interactWith(Entity $e, $action)
{ {
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){ if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
@ -59,7 +60,7 @@ class Pig extends Animal implements Rideable{
$e->setRiding($this); $e->setRiding($this);
return true; return true;
} }
if($slot->getID() === SADDLE){ if($slot->getID() === SADDLE){
if(!$this->isSaddled()){ if(!$this->isSaddled()){
$e->player->removeItem($slot->getID(), 0, 1); $e->player->removeItem($slot->getID(), 0, 1);
@ -67,15 +68,15 @@ class Pig extends Animal implements Rideable{
} }
return true; //avoid further interactions return true; //avoid further interactions
} }
} }
return parent::interactWith($e, $action); return parent::interactWith($e, $action);
} }
public function isFood($id){ public function isFood($id){
return $id === POTATO || $id === CARROT || $id === BEETROOT; return $id === POTATO || $id === CARROT || $id === BEETROOT;
} }
public function getDrops(){ public function getDrops(){
return $this->isBaby() ? parent::getDrops() : ($this->isSaddled() ? [ return $this->isBaby() ? parent::getDrops() : ($this->isSaddled() ? [
[($this->fire > 0 ? COOKED_PORKCHOP : RAW_PORKCHOP), 0, mt_rand(0,2)], [($this->fire > 0 ? COOKED_PORKCHOP : RAW_PORKCHOP), 0, mt_rand(0,2)],

View file

@ -3,7 +3,7 @@
class Sheep extends Animal{ class Sheep extends Animal{
public $color; public $color;
const TYPE = MOB_SHEEP; const TYPE = MOB_SHEEP;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.9, 1.3); $this->setSize(0.9, 1.3);
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
@ -12,7 +12,7 @@ class Sheep extends Animal{
$this->data["Sheared"] = $this->data["Sheared"] ?? 0; $this->data["Sheared"] = $this->data["Sheared"] ?? 0;
$this->data["Color"] = $this->data["Color"] ?? $this->sheepColor(); $this->data["Color"] = $this->data["Color"] ?? $this->sheepColor();
$this->setSpeed(0.25); $this->setSpeed(0.25);
$this->ai->addTask(new TaskRandomWalk(1.0)); $this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAtPlayer(6)); $this->ai->addTask(new TaskLookAtPlayer(6));
$this->ai->addTask(new TaskPanic(1.5)); $this->ai->addTask(new TaskPanic(1.5));
@ -23,14 +23,14 @@ class Sheep extends Animal{
$this->ai->addTask(new TaskMate(1.0)); $this->ai->addTask(new TaskMate(1.0));
$this->ai->addTask(new TaskFollowParent(1.0)); $this->ai->addTask(new TaskFollowParent(1.0));
} }
public function createSaveData(){ public function createSaveData(){
$data = parent::createSaveData(); $data = parent::createSaveData();
$data["Color"] = @$this->data["Color"]; $data["Color"] = @$this->data["Color"];
$data["Sheared"] = @$this->data["Sheared"]; $data["Sheared"] = @$this->data["Sheared"];
return $data; return $data;
} }
public function eatGrass(){ public function eatGrass(){
$this->setSheared(0); $this->setSheared(0);
if($this->isBaby()){ if($this->isBaby()){
@ -39,24 +39,24 @@ class Sheep extends Animal{
$this->setAge($age); $this->setAge($age);
} }
} }
public function setSheared($v = null){ public function setSheared($v = null){
$this->data["Sheared"] = $v === null ? !$this->isSheared() : $v; $this->data["Sheared"] = $v === null ? !$this->isSheared() : $v;
$this->updateMetadata(); $this->updateMetadata();
} }
public function isSheared(){ public function isSheared(){
return $this->data["Sheared"]; return $this->data["Sheared"];
} }
public function getColor(){ public function getColor(){
return $this->data["Color"]; //color === 16 -> color = 0, color === 17 -> color = 1 ... return $this->data["Color"]; //color === 16 -> color = 0, color === 17 -> color = 1 ...
} }
public function switchColorMeta($meta){ public function switchColorMeta($meta){
return abs($meta - 15); return abs($meta - 15);
} }
public function setColor($meta){ public function setColor($meta){
$this->data["Color"] = $meta; $this->data["Color"] = $meta;
} }
@ -65,11 +65,11 @@ class Sheep extends Animal{
[WOOL, $this->getColor(), 1] [WOOL, $this->getColor(), 1]
]; ];
} }
public function isFood($id){ public function isFood($id){
return $id === WHEAT; return $id === WHEAT;
} }
public function interactWith(Entity $e, $action){ public function interactWith(Entity $e, $action){
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){ if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem(); $slot = $e->player->getHeldItem();
@ -79,7 +79,7 @@ class Sheep extends Animal{
$this->setSheared(1); $this->setSheared(1);
$speedX = (lcg_value() * 0.2 - 0.1) + (lcg_value() - lcg_value()) * 0.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; $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); $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()){ if($slot->getMetadata() >= $slot->getMaxDurability()){
$e->player->removeItem($slot->getID(), $slot->getMetadata(), $slot->count, true); $e->player->removeItem($slot->getID(), $slot->getMetadata(), $slot->count, true);
@ -90,7 +90,7 @@ class Sheep extends Animal{
return true; return true;
}elseif($slot->getID() === DYE){ }elseif($slot->getID() === DYE){
$this->setColor($this->switchColorMeta($slot->getMetadata())); $this->setColor($this->switchColorMeta($slot->getMetadata()));
if(($e->player->gamemode & 0x01) === SURVIVAL){ if(($e->player->gamemode & 0x01) === SURVIVAL){
$e->player->removeItem($slot->getID(), $slot->getMetadata(), 1, true); $e->player->removeItem($slot->getID(), $slot->getMetadata(), 1, true);
} }
@ -98,7 +98,7 @@ class Sheep extends Animal{
} }
return parent::interactWith($e, $action); return parent::interactWith($e, $action);
} }
public function getMetadata(){ public function getMetadata(){
$d = parent::getMetadata(); $d = parent::getMetadata();
if(!isset($this->data["Sheared"])){ if(!isset($this->data["Sheared"])){
@ -107,7 +107,7 @@ class Sheep extends Animal{
$d[16]["value"] = ($this->data["Sheared"] << 4) | ($this->getColor() & 0x0F); $d[16]["value"] = ($this->data["Sheared"] << 4) | ($this->getColor() & 0x0F);
return $d; return $d;
} }
public function sheepColor(){ //a method from 0.8.1 public function sheepColor(){ //a method from 0.8.1
$c = mt_rand(0,100); $c = mt_rand(0,100);
if($c <= 4){ if($c <= 4){

View file

@ -1,4 +1,5 @@
<?php <?php
class Creeper extends Monster{ class Creeper extends Monster{
const TYPE = MOB_CREEPER; const TYPE = MOB_CREEPER;
const EXPL_TIME = 30; const EXPL_TIME = 30;
@ -12,30 +13,28 @@ class Creeper extends Monster{
$this->ignited = 0; $this->ignited = 0;
$this->setSpeed(0.25); $this->setSpeed(0.25);
$this->timeUntilExplode = $this->isIgnited() ? self::EXPL_TIME : 0; $this->timeUntilExplode = $this->isIgnited() ? self::EXPL_TIME : 0;
$this->ai->addTask(new TaskRandomWalk(1.0)); $this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskAttackPlayer(1.25, 16)); $this->ai->addTask(new TaskAttackPlayer(1.25, 16));
$this->ai->addTask(new TaskLookAround()); $this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming()); $this->ai->addTask(new TaskSwimming());
} }
public function getAttackDamage(){ public function getAttackDamage(){
return 0; return 0;
} }
public function setIgnited($v = null){ public function setIgnited($v = null){
$this->setState($v === null ? !$this->getState() : $v); $this->setState($v === null ? !$this->getState() : $v);
} }
/** /**
* @return boolean * @return boolean
*/ */
public function isIgnited(){ public function isIgnited(){
return $this->getState() > 0; return $this->getState() > 0;
} }
public function interactWith(Entity $e, $action){ public function interactWith(Entity $e, $action){
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){ if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem(); $slot = $e->player->getHeldItem();
@ -51,12 +50,12 @@ class Creeper extends Monster{
} }
return parent::interactWith($e, $action); return parent::interactWith($e, $action);
} }
public function ignite(){ public function ignite(){
$this->setIgnited(1); $this->setIgnited(1);
$this->timeUntilExplode = self::EXPL_TIME; $this->timeUntilExplode = self::EXPL_TIME;
} }
public function attackEntity($entity, $distance){ public function attackEntity($entity, $distance){
if(Utils::distance_noroot($entity, $this) <= 49 && !$this->isIgnited() && $this->ai->canSee($entity)){ if(Utils::distance_noroot($entity, $this) <= 49 && !$this->isIgnited() && $this->ai->canSee($entity)){
$this->ignite(); $this->ignite();
@ -88,7 +87,7 @@ class Creeper extends Monster{
$this->close(); $this->close();
$explosion->explode(); $explosion->explode();
} }
public function getDrops(){ public function getDrops(){
return [ return [
[GUNPOWDER, 0, mt_rand(0,2)] [GUNPOWDER, 0, mt_rand(0,2)]

View file

@ -1,4 +1,5 @@
<?php <?php
class PigZombie extends Monster{ //TODO extends zombie class PigZombie extends Monster{ //TODO extends zombie
const TYPE = MOB_PIGMAN; const TYPE = MOB_PIGMAN;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){

View file

@ -1,4 +1,5 @@
<?php <?php
class Skeleton extends Monster{ class Skeleton extends Monster{
const TYPE = MOB_SKELETON; const TYPE = MOB_SKELETON;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
@ -8,31 +9,31 @@ class Skeleton extends Monster{
$this->setName("Skeleton"); $this->setName("Skeleton");
$this->ai->removeTask("TaskAttackPlayer"); $this->ai->removeTask("TaskAttackPlayer");
$this->setSpeed(0.25); $this->setSpeed(0.25);
$this->ai->addTask(new TaskRandomWalk(1.0)); $this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAround()); $this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming()); $this->ai->addTask(new TaskSwimming());
$this->ai->addTask(new TaskRangedAttack(1.0, 16)); $this->ai->addTask(new TaskRangedAttack(1.0, 16));
} }
public function getAttackDamage(){ public function getAttackDamage(){
return 0; return 0;
} }
public function updateBurning(){ public function updateBurning(){
if($this->fire > 0 || !$this->level->isDay() || $this->inWater){ if($this->fire > 0 || !$this->level->isDay() || $this->inWater){
return false; return false;
} }
//bad fix for burning in water //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){ if($block == WATER || $block == STILL_WATER){
$v16 = ((int)$this->y + 1) - LiquidBlock::getPercentAir($meta); $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))){ 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; return false;
} }
} }
for($y = (int)$this->y; $y < 129; $y++){ for($y = (int) $this->y; $y < 129; $y++){
$block = $this->level->level->getBlockID($this->x, $y, $this->z); $block = $this->level->level->getBlockID($this->x, $y, $this->z);
if(StaticBlock::getIsSolid($block)){ if(StaticBlock::getIsSolid($block)){
return false; return false;
@ -49,12 +50,12 @@ class Skeleton extends Monster{
return false; return false;
} }
} }
public function updateEntityMovement(){ public function updateEntityMovement(){
$this->updateBurning(); $this->updateBurning();
return parent::updateEntityMovement(); return parent::updateEntityMovement();
} }
public function getDrops(){ public function getDrops(){
return [ return [
[ARROW, 0, mt_rand(0,2)], [ARROW, 0, mt_rand(0,2)],

View file

@ -1,8 +1,9 @@
<?php <?php
class Spider extends Monster{ class Spider extends Monster{
const TYPE = MOB_SPIDER; const TYPE = MOB_SPIDER;
function __construct(Level $level, $eid, $class, $type = 0, $data = array()){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(1.4, 0.9); $this->setSize(1.4, 0.9);
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth($this->data["Health"] ?? 8, "generic"); $this->setHealth($this->data["Health"] ?? 8, "generic");
@ -11,35 +12,35 @@ class Spider extends Monster{
$this->ai->addTask(new TaskRandomWalk(1.2)); $this->ai->addTask(new TaskRandomWalk(1.2));
$this->ai->addTask(new TaskLookAround()); $this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming()); $this->ai->addTask(new TaskSwimming());
$this->ai->addTask(new TaskAttackPlayer(1.2, 16)); $this->ai->addTask(new TaskAttackPlayer(1.2, 16));
} }
public function getAttackDamage(){ public function getAttackDamage(){
return 2; return 2;
} }
public function attackEntity($entity, $distance){ public function attackEntity($entity, $distance){
if($distance > 2.0 && $distance < 6.0){ if($distance > 2.0 && $distance < 6.0){
if($this->onGround){ if($this->onGround){
$diffX = $entity->x - $this->x; $diffX = $entity->x - $this->x;
$diffZ = $entity->z - $this->z; $diffZ = $entity->z - $this->z;
$dist = sqrt($diffX*$diffX + $diffZ*$diffZ); $dist = sqrt($diffX * $diffX + $diffZ * $diffZ);
$this->speedX = $diffX / $dist*0.5*0.8 + $this->speedX*0.2; $this->speedX = $diffX / $dist * 0.5 * 0.8 + $this->speedX * 0.2;
$this->speedZ = $diffZ / $dist*0.5*0.8 + $this->speedZ*0.2; $this->speedZ = $diffZ / $dist * 0.5 * 0.8 + $this->speedZ * 0.2;
$this->speedY = 0.4; $this->speedY = 0.4;
} }
return false; return false;
}else{ }else{
return parent::attackEntity($entity, $distance); return parent::attackEntity($entity, $distance);
} }
} }
public function isOnLadder(){ public function isOnLadder(){
return $this->isCollidedHorizontally; return $this->isCollidedHorizontally;
} }
public function getDrops(){ public function getDrops(){
return [ return [
[STRING, 0, mt_rand(0,2)] [STRING, 0, mt_rand(0,2)]

View file

@ -1,37 +1,38 @@
<?php <?php
class Zombie extends Monster{ class Zombie extends Monster{
const TYPE = MOB_ZOMBIE; const TYPE = MOB_ZOMBIE;
function __construct(Level $level, $eid, $class, $type = 0, $data = array()){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.6, 1.85); $this->setSize(0.6, 1.85);
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth($this->data["Health"] ?? 12, "generic"); $this->setHealth($this->data["Health"] ?? 12, "generic");
$this->setName("Zombie"); $this->setName("Zombie");
$this->setSpeed(0.23); $this->setSpeed(0.23);
$this->ai->addTask(new TaskRandomWalk(1.0)); $this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAround()); $this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming()); $this->ai->addTask(new TaskSwimming());
$this->ai->addTask(new TaskAttackPlayer(1.0, 16)); $this->ai->addTask(new TaskAttackPlayer(1.0, 16));
} }
public function getArmorValue(){ public function getArmorValue(){
return 2; return 2;
} }
public function updateBurning(){ public function updateBurning(){
if($this->fire > 0 || !$this->level->isDay() || $this->inWater){ if($this->fire > 0 || !$this->level->isDay() || $this->inWater){
return false; return false;
} }
//bad fix for burning in water //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){ if($block == WATER || $block == STILL_WATER){
$v16 = ((int)$this->y + 1) - LiquidBlock::getPercentAir($meta); $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))){ 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; return false;
} }
} }
for($y = (int)$this->y; $y < 129; $y++){ for($y = (int) $this->y; $y < 129; $y++){
$block = $this->level->level->getBlockID($this->x, $y, $this->z); $block = $this->level->level->getBlockID($this->x, $y, $this->z);
if(StaticBlock::getIsSolid($block)){ if(StaticBlock::getIsSolid($block)){
return false; return false;
@ -48,7 +49,7 @@ class Zombie extends Monster{
return false; return false;
} }
} }
public function getAttackDamage(){ public function getAttackDamage(){
return 4; return 4;
} }
@ -57,7 +58,7 @@ class Zombie extends Monster{
$this->updateBurning(); $this->updateBurning();
return parent::updateEntityMovement(); return parent::updateEntityMovement();
} }
public function getDrops(){ public function getDrops(){
return [ return [
[CARROT, 0, Utils::chance(0.83) ? 1 : 0], [CARROT, 0, Utils::chance(0.83) ? 1 : 0],

View file

@ -3,7 +3,7 @@
class Arrow extends Entity{ class Arrow extends Entity{
const TYPE = OBJECT_ARROW; const TYPE = OBJECT_ARROW;
const CLASS_TYPE = ENTITY_OBJECT; const CLASS_TYPE = ENTITY_OBJECT;
public $shooterEID = 0; public $shooterEID = 0;
public $xTile, $yTile, $zTile; public $xTile, $yTile, $zTile;
public $inTile, $inData; public $inTile, $inData;
@ -13,7 +13,7 @@ class Arrow extends Entity{
public $criticial = false; public $criticial = false;
public $groundTicks = 0; public $groundTicks = 0;
public $shotByPlayer = false; public $shotByPlayer = false;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->gravity = 0.05; $this->gravity = 0.05;
@ -32,12 +32,12 @@ class Arrow extends Entity{
$this->yTile = $data["yTile"] ?? $this->yTile; $this->yTile = $data["yTile"] ?? $this->yTile;
$this->zTile = $data["zTile"] ?? $this->zTile; $this->zTile = $data["zTile"] ?? $this->zTile;
$this->shotByPlayer = $data["shotByPlayer"] ?? $this->shotByPlayer; $this->shotByPlayer = $data["shotByPlayer"] ?? $this->shotByPlayer;
//$this->server->schedule(1210, array($this, "update")); //Despawn //$this->server->schedule(1210, array($this, "update")); //Despawn
} }
public function createSaveData(){ public function createSaveData(){
$data = parent::createSaveData(); $data = parent::createSaveData();
$data["inTile"] = $this->inTile; $data["inTile"] = $this->inTile;
$data["inData"] = $this->inData; $data["inData"] = $this->inData;
$data["inGround"] = $this->inGround; $data["inGround"] = $this->inGround;
@ -57,7 +57,7 @@ class Arrow extends Entity{
$pk->pitch = $this->pitch; $pk->pitch = $this->pitch;
$this->server->api->player->broadcastPacket($this->level->players, $pk); $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 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); $f2 = sqrt($d * $d + $d1 * $d1 + $d2 * $d2);
$d /= $f2; $d /= $f2;
@ -79,7 +79,7 @@ class Arrow extends Entity{
//$this->update(); //$this->update();
$this->groundTicks = 0; $this->groundTicks = 0;
} }
public function update($now){ public function update($now){
$this->lastX = $this->x; $this->lastX = $this->x;
$this->lastY = $this->y; $this->lastY = $this->y;
@ -101,40 +101,39 @@ class Arrow extends Entity{
$this->fire -= 4; $this->fire -= 4;
if($this->fire <= 0) $this->fire = 0; if($this->fire <= 0) $this->fire = 0;
} }
if($this->fire <= 0){ if($this->fire <= 0){
$this->updateMetadata(); $this->updateMetadata();
} }
} }
if($this->handleLavaMovement()){ if($this->handleLavaMovement()){
if(!$this->isImmuneToFire){ if(!$this->isImmuneToFire){
$this->harm(4, "fire"); $this->harm(4, "fire");
$oldOnFire = $this->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()){ if($this->isInVoid()){
$this->outOfWorld(); $this->outOfWorld();
} }
//Entity::update end //Entity::update end
if($this->lastPitch == $this->lastYaw && $this->lastYaw == 0){ 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->lastYaw = $this->yaw = atan2($this->speedX, $this->speedZ) * 180 / M_PI;
$this->lastPitch = $this->pitch = atan2($this->speedY, $v1) * 180 / M_PI; $this->lastPitch = $this->pitch = atan2($this->speedY, $v1) * 180 / M_PI;
} }
if($this->shake > 0){ if($this->shake > 0){
--$this->shake; --$this->shake;
} }
if($this->inGround){ if($this->inGround){
[$blockID, $blockMeta] = $this->level->level->getBlock($this->xTile, $this->yTile, $this->zTile); [$blockID, $blockMeta] = $this->level->level->getBlock($this->xTile, $this->yTile, $this->zTile);
$this->speedZ = $this->speedX = $this->speedY = 0; $this->speedZ = $this->speedX = $this->speedY = 0;
if($blockID == $this->inTile && $blockMeta == $this->inData){ if($blockID == $this->inTile && $blockMeta == $this->inData){
++$this->groundTicks; ++$this->groundTicks;
if($this->groundTicks >= 1200){ //TODO customizeable? if($this->groundTicks >= 1200){ //TODO customizeable?
@ -147,7 +146,7 @@ class Arrow extends Entity{
$this->speedZ *= lcg_value() * 0.2; $this->speedZ *= lcg_value() * 0.2;
$this->groundTicks = $this->airTicks = 0; $this->groundTicks = $this->airTicks = 0;
} }
}else{ }else{
++$this->airTicks; ++$this->airTicks;
$start = new Vector3($this->x, $this->y, $this->z); $start = new Vector3($this->x, $this->y, $this->z);
@ -162,42 +161,40 @@ class Arrow extends Entity{
}else{ }else{
$end = new Vector3($this->x + $this->speedX, $this->y + $this->speedY, $this->z + $this->speedZ); $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)); $entities = $this->level->getEntitiesInAABB($this->boundingBox->addCoord($this->speedX, $this->speedY, $this->speedZ)->expand(1, 1, 1));
$bestDist = 0; $bestDist = 0;
$bestEnt = null; $bestEnt = null;
foreach($entities as $eid => $ent){ foreach($entities as $eid => $ent){
if($eid != $this->eid && $ent->isPickable() && ($eid != $this->shooterEID || $this->airTicks >= 5)){ if($eid != $this->eid && $ent->isPickable() && ($eid != $this->shooterEID || $this->airTicks >= 5)){
$v12 = $ent->boundingBox->expand(0.3, 0.3, 0.3); $v12 = $ent->boundingBox->expand(0.3, 0.3, 0.3);
$v13 = $v12->calculateIntercept($start, $end); $v13 = $v12->calculateIntercept($start, $end);
if($v13 != null){ if($v13 != null){
$dist = $start->distance($v13->hitVector); $dist = $start->distance($v13->hitVector);
if($dist < $bestDist || $bestDist == 0){ if($dist < $bestDist || $bestDist == 0){
$bestEnt = $ent; $bestEnt = $ent;
} }
} }
} }
} }
if($bestEnt != null){ if($bestEnt != null){
$v4 = MovingObjectPosition::fromEntity($bestEnt); $v4 = MovingObjectPosition::fromEntity($bestEnt);
} }
if($v4 != null){ if($v4 != null){
if($v4->entityHit != null){ if($v4->entityHit != null){
$v49 = sqrt($this->speedY*$this->speedY + $this->speedX*$this->speedX + $this->speedZ*$this->speedZ); $v49 = sqrt($this->speedY * $this->speedY + $this->speedX * $this->speedX + $this->speedZ * $this->speedZ);
$damage = ceil($v49+$v49); $damage = ceil($v49 + $v49);
if($this->criticial){ if($this->criticial){
$damage += mt_rand(0, $damage / 2 + 1); $damage += mt_rand(0, $damage / 2 + 1);
} }
if($v4->entityHit->harm($damage, $this->eid)){ if($v4->entityHit->harm($damage, $this->eid)){
//vanilla seems to increase arrow count if $v4->entity is mob //vanilla seems to increase arrow count if $v4->entity is mob
$this->close(); $this->close();
@ -213,36 +210,36 @@ class Arrow extends Entity{
$this->xTile = $v4->blockX; $this->xTile = $v4->blockX;
$this->yTile = $v4->blockY; $this->yTile = $v4->blockY;
$this->zTile = $v4->blockZ; $this->zTile = $v4->blockZ;
[$this->inTile, $this->inData] = $this->level->level->getBlock($this->xTile, $this->yTile, $this->zTile); [$this->inTile, $this->inData] = $this->level->level->getBlock($this->xTile, $this->yTile, $this->zTile);
$this->speedX = $v4->hitVector->x - $this->x; $this->speedX = $v4->hitVector->x - $this->x;
$this->speedY = $v4->hitVector->y - $this->y; $this->speedY = $v4->hitVector->y - $this->y;
$this->speedZ = $v4->hitVector->z - $this->z; $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){ if($v21 != 0){
$this->x -= $this->speedX / $v21 * 0.05; $this->x -= $this->speedX / $v21 * 0.05;
$this->y -= $this->speedY / $v21 * 0.05; $this->y -= $this->speedY / $v21 * 0.05;
$this->z -= $this->speedZ / $v21 * 0.05; $this->z -= $this->speedZ / $v21 * 0.05;
} }
$this->inGround = true; $this->inGround = true;
$this->shake = 7; $this->shake = 7;
$this->criticial = false; $this->criticial = false;
} }
} }
$this->x += $this->speedX; $this->x += $this->speedX;
$this->y += $this->speedY; $this->y += $this->speedY;
$this->z += $this->speedZ; $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->yaw = atan2($this->speedX, $this->speedZ) * 180 / M_PI;
$this->pitch = atan2($this->speedY, $v21) * 180 / M_PI; $this->pitch = atan2($this->speedY, $v21) * 180 / M_PI;
$this->pitch = $this->lastPitch + ($this->pitch - $this->lastPitch) * 0.2; $this->pitch = $this->lastPitch + ($this->pitch - $this->lastPitch) * 0.2;
$this->yaw = $this->lastYaw + ($this->yaw - $this->lastYaw) * 0.2; $this->yaw = $this->lastYaw + ($this->yaw - $this->lastYaw) * 0.2;
$v24 = $this->inWater ? 0.8 : 0.99; $v24 = $this->inWater ? 0.8 : 0.99;
$this->speedX *= $v24; $this->speedX *= $v24;
$this->speedY *= $v24; $this->speedY *= $v24;
@ -252,14 +249,12 @@ class Arrow extends Entity{
$v7 = $this->width / 2; $v7 = $this->width / 2;
$v8 = $this->height; $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->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(); $this->doBlocksCollision();
} }
} }
public function spawn($player){ public function spawn($player){
if($this->type === OBJECT_ARROW){ if($this->type === OBJECT_ARROW){
$pk = new AddEntityPacket; $pk = new AddEntityPacket;
@ -268,7 +263,7 @@ class Arrow extends Entity{
$pk->x = $this->x; $pk->x = $this->x;
$pk->y = $this->y; $pk->y = $this->y;
$pk->z = $this->z; $pk->z = $this->z;
$pk->did = 1; $pk->did = 1;
$pk->speedX = $this->speedX; $pk->speedX = $this->speedX;
$pk->speedY = $this->speedY; $pk->speedY = $this->speedY;
$pk->speedZ = $this->speedZ; $pk->speedZ = $this->speedZ;

View file

@ -3,9 +3,9 @@
class FallingSand extends Entity{ class FallingSand extends Entity{
const TYPE = FALLING_SAND; const TYPE = FALLING_SAND;
const CLASS_TYPE = ENTITY_FALLING; const CLASS_TYPE = ENTITY_FALLING;
public $fallTime = 0; public $fallTime = 0;
public function __construct($level, $eid, $class, $type = 0, $data = []){ public function __construct($level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(PHP_INT_MAX, "generic"); $this->setHealth(PHP_INT_MAX, "generic");
@ -15,14 +15,14 @@ class FallingSand extends Entity{
$this->hasGravity = true; $this->hasGravity = true;
$this->gravity = 0.04; $this->gravity = 0.04;
} }
public function isPickable(){ public function isPickable(){
return !$this->dead; return !$this->dead;
} }
public function update($now){ public function update($now){
if($this->closed) return; if($this->closed) return;
if( $this->data["Tile"] == AIR) { if( $this->data["Tile"] == AIR) {
$this->close(); $this->close();
return; return;
@ -33,15 +33,15 @@ class FallingSand extends Entity{
++$this->fallTime; ++$this->fallTime;
$this->speedY -= 0.04; $this->speedY -= 0.04;
$this->move($this->speedX, $this->speedY, $this->speedZ); $this->move($this->speedX, $this->speedY, $this->speedZ);
$this->speedX *= 0.98; $this->speedX *= 0.98;
$this->speedY *= 0.98; $this->speedY *= 0.98;
$this->speedZ *= 0.98; $this->speedZ *= 0.98;
$x = floor($this->x); $x = floor($this->x);
$y = floor($this->y); $y = floor($this->y);
$z = floor($this->z); $z = floor($this->z);
if($this->onGround){ if($this->onGround){
$this->speedX *= 0.7; $this->speedX *= 0.7;
$this->speedZ *= 0.7; $this->speedZ *= 0.7;

View file

@ -4,10 +4,10 @@ class ItemEntity extends Entity{
const TYPE = ENTITY_ITEM_TYPE; const TYPE = ENTITY_ITEM_TYPE;
const CLASS_TYPE = ENTITY_ITEM; const CLASS_TYPE = ENTITY_ITEM;
public static $searchRadiusX = 0.5, $searchRadiusY = 0.0, $searchRadiusZ = 0.5; public static $searchRadiusX = 0.5, $searchRadiusY = 0.0, $searchRadiusZ = 0.5;
public $meta, $stack, $itemID; public $meta, $stack, $itemID;
public function __construct(Level $level, $eid, $class, $type = 0, $data = array()) public function __construct(Level $level, $eid, $class, $type = 0, $data = [])
{ {
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setSize(0.25, 0.25); $this->setSize(0.25, 0.25);
@ -27,21 +27,21 @@ class ItemEntity extends Entity{
$this->delayBeforePickup = 40; //in vanilla it is 0 by default $this->delayBeforePickup = 40; //in vanilla it is 0 by default
$this->stepHeight = 0; $this->stepHeight = 0;
} }
public function counterUpdate(){ public function counterUpdate(){
parent::counterUpdate(); parent::counterUpdate();
if($this->delayBeforePickup > 0) --$this->delayBeforePickup; if($this->delayBeforePickup > 0) --$this->delayBeforePickup;
} }
public function searchForOtherItemsNearby(){ public function searchForOtherItemsNearby(){
$ents = $this->level->getEntitiesInAABBOfType($this->boundingBox->expand(self::$searchRadiusX, self::$searchRadiusY, self::$searchRadiusZ), ENTITY_ITEM); $ents = $this->level->getEntitiesInAABBOfType($this->boundingBox->expand(self::$searchRadiusX, self::$searchRadiusY, self::$searchRadiusZ), ENTITY_ITEM);
foreach($ents as $e){ foreach($ents as $e){
$this->tryCombining($e); $this->tryCombining($e);
} }
} }
public function spawn($player) public function spawn($player)
{ {
$pk = new AddItemEntityPacket(); $pk = new AddItemEntityPacket();
@ -55,7 +55,7 @@ class ItemEntity extends Entity{
$pk->item = BlockAPI::getItem($this->itemID, $this->meta, $this->stack); $pk->item = BlockAPI::getItem($this->itemID, $this->meta, $this->stack);
$pk->metadata = $this->getMetadata(); $pk->metadata = $this->getMetadata();
$player->dataPacket($pk); $player->dataPacket($pk);
$pk = new SetEntityMotionPacket(); $pk = new SetEntityMotionPacket();
$pk->eid = $this->eid; $pk->eid = $this->eid;
$pk->speedX = $this->speedX; $pk->speedX = $this->speedX;
@ -63,16 +63,15 @@ class ItemEntity extends Entity{
$pk->speedZ = $this->speedZ; $pk->speedZ = $this->speedZ;
$player->dataPacket($pk); $player->dataPacket($pk);
} }
public function tryCombining(Entity $another){ public function tryCombining(Entity $another){
if($another->eid == $this->eid) return false; if($another->eid == $this->eid) return false;
if(!$another->closed && !$this->closed){ if(!$another->closed && !$this->closed){
if($another->itemID == $this->itemID && $another->meta == $this->meta){ if($another->itemID == $this->itemID && $another->meta == $this->meta){
if(($another->stack + $this->stack) > 64) return false; //TODO dynamic stack size if(($another->stack + $this->stack) > 64) return false; //TODO dynamic stack size
$another->stack += $this->stack; $another->stack += $this->stack;
$another->age = min($this->age, $another->age); $another->age = min($this->age, $another->age);
$this->close(); $this->close();
@ -84,29 +83,29 @@ class ItemEntity extends Entity{
$xFloor = floor($x); $xFloor = floor($x);
$yFloor = floor($y); $yFloor = floor($y);
$zFloor = floor($z); $zFloor = floor($z);
$id = $this->level->level->getBlockID($xFloor, $yFloor, $zFloor); $id = $this->level->level->getBlockID($xFloor, $yFloor, $zFloor);
if(StaticBlock::getIsSolid($id)){ if(StaticBlock::getIsSolid($id)){
$xDiff = $x - $xFloor; $xDiff = $x - $xFloor;
$id = $this->level->level->getBlockID($xFloor - 1, $yFloor, $zFloor); $id = $this->level->level->getBlockID($xFloor - 1, $yFloor, $zFloor);
$xNeg = StaticBlock::getIsSolid($id); $xNeg = StaticBlock::getIsSolid($id);
$id = $this->level->level->getBlockID($xFloor + 1, $yFloor, $zFloor); $id = $this->level->level->getBlockID($xFloor + 1, $yFloor, $zFloor);
$xPos = StaticBlock::getIsSolid($id); $xPos = StaticBlock::getIsSolid($id);
$id = $this->level->level->getBlockID($xFloor, $yFloor - 1, $zFloor); $id = $this->level->level->getBlockID($xFloor, $yFloor - 1, $zFloor);
$yNeg = StaticBlock::getIsSolid($id); $yNeg = StaticBlock::getIsSolid($id);
$id = $this->level->level->getBlockID($xFloor, $yFloor + 1, $zFloor); $id = $this->level->level->getBlockID($xFloor, $yFloor + 1, $zFloor);
$yPos = StaticBlock::getIsSolid($id); $yPos = StaticBlock::getIsSolid($id);
$id = $this->level->level->getBlockID($xFloor - 1, $yFloor, $zFloor - 1); $id = $this->level->level->getBlockID($xFloor - 1, $yFloor, $zFloor - 1);
$zNeg = StaticBlock::getIsSolid($id); $zNeg = StaticBlock::getIsSolid($id);
$zPos = $this->level->level->getBlockID($xFloor + 1, $yFloor, $zFloor + 1); $zPos = $this->level->level->getBlockID($xFloor + 1, $yFloor, $zFloor + 1);
if($xNeg || $xDiff >= 9999.0){ //TODO not needed check? if($xNeg || $xDiff >= 9999.0){ //TODO not needed check?
$v15 = 9999.0; $v15 = 9999.0;
$v16 = -1; $v16 = -1;
@ -114,22 +113,22 @@ class ItemEntity extends Entity{
$v15 = $xDiff; $v15 = $xDiff;
$v16 = 0; $v16 = 0;
} }
if(!$xPos){ if(!$xPos){
$v17 = 1 - $xDiff; $v17 = 1 - $xDiff;
if($v17 < $v15){ if($v17 < $v15){
$v15 = $v17; $v15 = $v17;
$v16 = 1; $v16 = 1;
} }
} }
$yDiff = $y - $yFloor; $yDiff = $y - $yFloor;
if(!$yNeg && $yDiff < $v15){ if(!$yNeg && $yDiff < $v15){
$v15 = $yDiff; $v15 = $yDiff;
$v16 = 2; $v16 = 2;
} }
if(!$yPos){ if(!$yPos){
$v19 = 1.0 - $yDiff; $v19 = 1.0 - $yDiff;
if($v19 < $v15){ if($v19 < $v15){
@ -137,17 +136,17 @@ class ItemEntity extends Entity{
$v16 = 3; $v16 = 3;
} }
} }
$zDiff = $z - $zFloor; $zDiff = $z - $zFloor;
if(!$zNeg && $zDiff < $v15){ if(!$zNeg && $zDiff < $v15){
$v15 = $zDiff; $v15 = $zDiff;
$v16 = 4; $v16 = 4;
} }
if(!StaticBlock::getIsSolid($zPos) && ((1.0 - $zDiff) < $v15)){ if(!StaticBlock::getIsSolid($zPos) && ((1.0 - $zDiff) < $v15)){
$v16 = 5; $v16 = 5;
} }
$v21 = lcg_value() * 0.2 + 0.1; $v21 = lcg_value() * 0.2 + 0.1;
switch($v16){ switch($v16){
case 0: case 0:
@ -166,24 +165,24 @@ class ItemEntity extends Entity{
$this->speedZ = $v21; $this->speedZ = $v21;
return 0; return 0;
} }
return 0; return 0;
} }
} }
public function handleWaterMovement(){ public function handleWaterMovement(){
return $this->level->handleMaterialAcceleration($this->boundingBox, 0, $this); return $this->level->handleMaterialAcceleration($this->boundingBox, 0, $this);
} }
public function updateEntityMovement(){ public function updateEntityMovement(){
//TODO custom update( method //TODO custom update( method
$this->speedY -= 0.04; $this->speedY -= 0.04;
//$this->noClip = false; //$this->noClip = false;
$this->checkInTile($this->x, $this->y, $this->z); $this->checkInTile($this->x, $this->y, $this->z);
$this->move($this->speedX, $this->speedY, $this->speedZ); $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){ if($var1 || $this->counter % 25 == 0){
$blockIDAt = $this->level->level->getBlockID(floor($this->x), floor($this->y), floor($this->z)); $blockIDAt = $this->level->level->getBlockID(floor($this->x), floor($this->y), floor($this->z));
if($blockIDAt == LAVA || $blockIDAt == STILL_LAVA){ if($blockIDAt == LAVA || $blockIDAt == STILL_LAVA){
@ -191,30 +190,30 @@ class ItemEntity extends Entity{
$this->speedX = (lcg_value() - lcg_value()) * 0.2; $this->speedX = (lcg_value() - lcg_value()) * 0.2;
$this->speedZ = (lcg_value() - lcg_value()) * 0.2; $this->speedZ = (lcg_value() - lcg_value()) * 0.2;
} }
//$this->searchForOtherItemsNearby(); //not in vanilla 0.8.1 //$this->searchForOtherItemsNearby(); //not in vanilla 0.8.1
} }
if($this->closed) return; if($this->closed) return;
$friction = 0.98; $friction = 0.98;
if($this->onGround){ if($this->onGround){
$friction = 0.588; $friction = 0.588;
$v3 = $this->level->level->getBlockID($this->x, floor($this->boundingBox->minY) - 1, $this->z); $v3 = $this->level->level->getBlockID($this->x, floor($this->boundingBox->minY) - 1, $this->z);
if($v3 > 0) $friction = StaticBlock::getSlipperiness($v3); if($v3 > 0) $friction = StaticBlock::getSlipperiness($v3);
} }
$this->speedX *= $friction; $this->speedX *= $friction;
$this->speedY *= 0.98; $this->speedY *= 0.98;
$this->speedZ *= $friction; $this->speedZ *= $friction;
if($this->onGround) $this->speedY *= -0.5; if($this->onGround) $this->speedY *= -0.5;
if(abs($this->speedX) < self::MIN_POSSIBLE_SPEED) $this->speedX = 0; 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->speedZ) < self::MIN_POSSIBLE_SPEED) $this->speedZ = 0;
if(abs($this->speedY) < self::MIN_POSSIBLE_SPEED) $this->speedY = 0; if(abs($this->speedY) < self::MIN_POSSIBLE_SPEED) $this->speedY = 0;
++$this->age; ++$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; const TYPE = OBJECT_MINECART;
/** /**
* A minecart rotation matrix * A minecart rotation matrix
* @var int[][][] * @var int[][][]
*/ */
private static $matrix = [ private static $matrix = [
[ [
@ -48,14 +48,14 @@ class Minecart extends Vehicle{
[1, 0, 0] [1, 0, 0]
] ]
]; ];
private $hurtTime = 0; //syncentdata 17 int private $hurtTime = 0; //syncentdata 17 int
private $damage = 0; //syncentdata 19 float private $damage = 0; //syncentdata 19 float
private $minecartX = 0, $minecartY = 0, $minecartZ = 0; private $minecartX = 0, $minecartY = 0, $minecartZ = 0;
private $turnProgress = 0; private $turnProgress = 0;
public $isInReverse = false; public $isInReverse = false;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->canBeAttacked = true; $this->canBeAttacked = true;
@ -67,76 +67,76 @@ class Minecart extends Vehicle{
$this->yOffset = $this->height / 2; $this->yOffset = $this->height / 2;
$this->stepHeight = 0; $this->stepHeight = 0;
} }
public function isPickable(){ public function isPickable(){
return !$this->dead; return !$this->dead;
} }
public function getDrops(){ public function getDrops(){
return [ return [
[MINECART, 0, 1] [MINECART, 0, 1]
]; ];
} }
public function getPos($x, $y, $z){ public function getPos($x, $y, $z){
$blockX = floor($x); $blockX = floor($x);
$blockY = floor($y); $blockY = floor($y);
$blockZ = floor($z); $blockZ = floor($z);
if(RailBaseBlock::isRailBlock($this->level, $blockX, $blockY - 1, $blockZ)) --$blockY; if(RailBaseBlock::isRailBlock($this->level, $blockX, $blockY - 1, $blockZ)) --$blockY;
[$id, $meta] = $this->level->level->getBlock($blockX, $blockY, $blockZ); [$id, $meta] = $this->level->level->getBlock($blockX, $blockY, $blockZ);
if(RailBaseBlock::isRailID($id)){ if(RailBaseBlock::isRailID($id)){
if($id == POWERED_RAIL) $meta &= 7; if($id == POWERED_RAIL) $meta &= 7;
$mat = self::$matrix[$meta]; $mat = self::$matrix[$meta];
$v13 = 0; $v13 = 0;
$v15 = $blockX + 0.5 + $mat[0][0] * 0.5; $v15 = $blockX + 0.5 + $mat[0][0] * 0.5;
$v17 = $blockY + 0.5 + $mat[0][1] * 0.5; $v17 = $blockY + 0.5 + $mat[0][1] * 0.5;
$v19 = $blockZ + 0.5 + $mat[0][2] * 0.5; $v19 = $blockZ + 0.5 + $mat[0][2] * 0.5;
$v21 = $blockX + 0.5 + $mat[1][0] * 0.5; $v21 = $blockX + 0.5 + $mat[1][0] * 0.5;
$v23 = $blockY + 0.5 + $mat[1][1] * 0.5; $v23 = $blockY + 0.5 + $mat[1][1] * 0.5;
$v25 = $blockZ + 0.5 + $mat[1][2] * 0.5; $v25 = $blockZ + 0.5 + $mat[1][2] * 0.5;
$v27 = $v21 - $v15; $v27 = $v21 - $v15;
$v29 = ($v23 - $v17) * 2; $v29 = ($v23 - $v17) * 2;
$v31 = $v25 - $v19; $v31 = $v25 - $v19;
if($v27 == 0){ if($v27 == 0){
$x = $blockX + 0.5; $x = $blockX + 0.5;
$v13 = $z - $blockZ; $v13 = $z - $blockZ;
}else if($v31 == 0){ }elseif($v31 == 0){
$z = $blockZ + 0.5; $z = $blockZ + 0.5;
$v13 = $x - $blockX; $v13 = $x - $blockX;
}else{ }else{
$v33 = $x - $v15; $v33 = $x - $v15;
$v35 = $z - $v19; $v35 = $z - $v19;
$v13 = ($v33*$v27 + $v35*$v31) * 2; $v13 = ($v33 * $v27 + $v35 * $v31) * 2;
} }
$x = $v15 + $v27 * $v13; $x = $v15 + $v27 * $v13;
$y = $v17 + $v29 * $v13; $y = $v17 + $v29 * $v13;
$z = $v19 + $v31 * $v13; $z = $v19 + $v31 * $v13;
if($v29 < 0) ++$y; if($v29 < 0) ++$y;
if($v29 > 0) $y += 0.5; if($v29 > 0) $y += 0.5;
return [$x, $y, $z]; return [$x, $y, $z];
} }
return false; return false;
} }
public function moveAlongTrack($x, $y, $z, $maxSpeed, $boost, $id, $meta){ public function moveAlongTrack($x, $y, $z, $maxSpeed, $boost, $id, $meta){
$this->fallDistance = 0; $this->fallDistance = 0;
$vec = $this->getPos($this->x, $this->y, $this->z); $vec = $this->getPos($this->x, $this->y, $this->z);
$this->y = $y; $this->y = $y;
if($id == POWERED_RAIL) $meta &= 7; if($id == POWERED_RAIL) $meta &= 7;
if($meta >= 2 && $meta <= 5) $this->y = $y + 1; if($meta >= 2 && $meta <= 5) $this->y = $y + 1;
switch($meta){ switch($meta){
case 2: case 2:
$this->speedX -= $boost; $this->speedX -= $boost;
@ -151,53 +151,53 @@ class Minecart extends Vehicle{
$this->speedZ -= $boost; $this->speedZ -= $boost;
break; break;
} }
$mat = self::$matrix[$meta]; $mat = self::$matrix[$meta];
$matXDiff = $mat[1][0] - $mat[0][0]; $matXDiff = $mat[1][0] - $mat[0][0];
$matZDiff = $mat[1][2] - $mat[0][2]; $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){ if(($this->speedZ * $matZDiff + $this->speedX * $matXDiff) < 0){
$matXDiff = -$matXDiff; $matXDiff = -$matXDiff;
$matZDiff = -$matZDiff; $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; if($speedTotal > 2) $speedTotal = 2;
$this->speedX = ($speedTotal * $matXDiff) / $matDiffTotal; $this->speedX = ($speedTotal * $matXDiff) / $matDiffTotal;
$this->speedZ = ($speedTotal * $matZDiff) / $matDiffTotal; $this->speedZ = ($speedTotal * $matZDiff) / $matDiffTotal;
if($this->linkedEntity != 0 && !$this->isRider){ if($this->linkedEntity != 0 && !$this->isRider){
$rider = $this->level->entityList[$this->linkedEntity] ?? false; $rider = $this->level->entityList[$this->linkedEntity] ?? false;
if($rider instanceof Entity && ($rider->isPlayer() || $rider->class == ENTITY_MOB)){ if($rider instanceof Entity && ($rider->isPlayer() || $rider->class == ENTITY_MOB)){
if($rider->moveForward > 0){ if($rider->moveForward > 0){
$v32 = sin($this->yaw * M_PI / 180); $v32 = sin($this->yaw * M_PI / 180);
$v33 = cos($this->yaw * M_PI / 180); $v33 = cos($this->yaw * M_PI / 180);
if($this->speedZ*$this->speedZ + $this->speedX*$this->speedX < 0.01){ if($this->speedZ * $this->speedZ + $this->speedX * $this->speedX < 0.01){
$this->speedX -= $v32*0.1; $this->speedX -= $v32 * 0.1;
$this->speedZ += $v33*0.1; $this->speedZ += $v33 * 0.1;
} }
} }
} }
} }
$v38 = ($x + 0.5) + ($mat[0][0] * 0.5); $v38 = ($x + 0.5) + ($mat[0][0] * 0.5);
$v39 = ($z + 0.5) + ($mat[0][2] * 0.5); $v39 = ($z + 0.5) + ($mat[0][2] * 0.5);
$v40 = (($x + 0.5) + ($mat[1][0] * 0.5)) - $v38; $v40 = (($x + 0.5) + ($mat[1][0] * 0.5)) - $v38;
$v41 = (($z + 0.5) + ($mat[1][2] * 0.5)) - $v39; $v41 = (($z + 0.5) + ($mat[1][2] * 0.5)) - $v39;
if($v40 == 0){ if($v40 == 0){
$v42 = $this->z - $z; $v42 = $this->z - $z;
}else if($v41 == 0){ }elseif($v41 == 0){
$v42 = $this->x - $x; $v42 = $this->x - $x;
}else{ }else{
$v44 = (($this->z - $v39) * $v41) + (($this->x - $v38) * $v40); $v44 = (($this->z - $v39) * $v41) + (($this->x - $v38) * $v40);
$v42 = $v44 + $v44; $v42 = $v44 + $v44;
} }
$this->x = $v38 + ($v40 * $v42); $this->x = $v38 + ($v40 * $v42);
$this->z = $v39 + ($v41 * $v42); $this->z = $v39 + ($v41 * $v42);
$this->setPos($this->x, $this->y + $this->yOffset + 0.00001, $this->z); $this->setPos($this->x, $this->y + $this->yOffset + 0.00001, $this->z);
$dx = $this->speedX; $dx = $this->speedX;
$dz = $this->speedZ; $dz = $this->speedZ;
@ -205,55 +205,55 @@ class Minecart extends Vehicle{
$dx *= 0.75; $dx *= 0.75;
$dz *= 0.75; $dz *= 0.75;
} }
if($dx < -$maxSpeed) $dx = -$maxSpeed; if($dx < -$maxSpeed) $dx = -$maxSpeed;
else if($dx > $maxSpeed) $dx = $maxSpeed; elseif($dx > $maxSpeed) $dx = $maxSpeed;
if($dz < -$maxSpeed) $dz = -$maxSpeed; if($dz < -$maxSpeed) $dz = -$maxSpeed;
else if($dz > $maxSpeed) $dz = $maxSpeed; elseif($dz > $maxSpeed) $dz = $maxSpeed;
$this->move($dx, 0, $dz); $this->move($dx, 0, $dz);
if($mat[0][1]){ if($mat[0][1]){
if((floor($this->x) - $x) == $mat[0][0] && (floor($this->z) - $z) == $mat[0][2]){ 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); $this->setPos($this->x, $mat[0][1] + $this->y, $this->z);
}else if($mat[1][1]){ }elseif($mat[1][1]){
goto mat_1_1; goto mat_1_1;
} }
}else if($mat[1][1]){ }elseif($mat[1][1]){
mat_1_1: mat_1_1:
if((floor($this->x) - $x) == $mat[1][0] && (floor($this->z) - $z) == $mat[1][2]){ 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->setPos($this->x, $mat[1][1] + $this->y, $this->z);
} }
} }
$this->applyNaturalSlowdown(); $this->applyNaturalSlowdown();
$vec2 = $this->getPos($this->x, $this->y, $this->z); $vec2 = $this->getPos($this->x, $this->y, $this->z);
if($vec2 !== false && $vec !== false){ if($vec2 !== false && $vec !== false){
$yDiff = ($vec[1] - $vec2[1]) * 0.05; $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){ if($totalSpeed > 0){
$this->speedX = ($this->speedX / $totalSpeed) * ($totalSpeed + $yDiff); $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); $this->setPos($this->x, $vec2[1], $this->z);
} }
if(floor($this->x) != $x || floor($this->z) != $z){ //this breaks everything 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->speedX = (floor($this->x) - $x) * $totalSpeed;
$this->speedZ = (floor($this->z) - $z) * $totalSpeed; $this->speedZ = (floor($this->z) - $z) * $totalSpeed;
} }
if($id == POWERED_RAIL){ 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){ if($totalSpeed > 0.01){
$this->speedX += (($this->speedX / $totalSpeed) * 0.06); $this->speedX += (($this->speedX / $totalSpeed) * 0.06);
$this->speedZ += (($this->speedZ / $totalSpeed) * 0.06); $this->speedZ += (($this->speedZ / $totalSpeed) * 0.06);
return; return;
} }
if($meta == 1){ if($meta == 1){
//TODO Level::isSolidBlockingTile //TODO Level::isSolidBlockingTile
if(StaticBlock::getIsSolid($this->level->level->getBlockID($x - 1, $y, $z))){ if(StaticBlock::getIsSolid($this->level->level->getBlockID($x - 1, $y, $z))){
@ -265,7 +265,7 @@ class Minecart extends Vehicle{
$v63 = -0.02; $v63 = -0.02;
} }
$this->speedX = $v63; $this->speedX = $v63;
}else if($meta == 0){ }elseif($meta == 0){
//TODO Level::isSolidBlockingTile //TODO Level::isSolidBlockingTile
if(StaticBlock::getIsSolid($this->level->level->getBlockID($x, $y, $z - 1))){ if(StaticBlock::getIsSolid($this->level->level->getBlockID($x, $y, $z - 1))){
return; return;
@ -278,58 +278,57 @@ class Minecart extends Vehicle{
$this->speedZ = $v64; $this->speedZ = $v64;
} }
} }
} }
public function applyNaturalSlowdown(){ public function applyNaturalSlowdown(){
$mult = $this->linkedEntity != 0 && !$this->isRider ? 0.997 : 0.96; $mult = $this->linkedEntity != 0 && !$this->isRider ? 0.997 : 0.96;
$this->speedX *= $mult; $this->speedX *= $mult;
$this->speedY = 0; $this->speedY = 0;
$this->speedZ *= $mult; $this->speedZ *= $mult;
} }
public function comeOffTrack($topSpeed){ public function comeOffTrack($topSpeed){
if($this->speedX < -$topSpeed) $this->speedX = -$topSpeed; if($this->speedX < -$topSpeed) $this->speedX = -$topSpeed;
else if($this->speedX > $topSpeed) $this->speedX = $topSpeed; elseif($this->speedX > $topSpeed) $this->speedX = $topSpeed;
if($this->speedZ < -$topSpeed) $this->speedZ = -$topSpeed; if($this->speedZ < -$topSpeed) $this->speedZ = -$topSpeed;
else if($this->speedZ > $topSpeed) $this->speedZ = $topSpeed; elseif($this->speedZ > $topSpeed) $this->speedZ = $topSpeed;
if($this->onGround){ if($this->onGround){
$this->speedX *= 0.5; $this->speedX *= 0.5;
$this->speedY *= 0.5; $this->speedY *= 0.5;
$this->speedZ *= 0.5; $this->speedZ *= 0.5;
} }
$this->move($this->speedX, $this->speedY, $this->speedZ); $this->move($this->speedX, $this->speedY, $this->speedZ);
if(!$this->onGround){ if(!$this->onGround){
$this->speedX *= 0.95; $this->speedX *= 0.95;
$this->speedY *= 0.95; $this->speedY *= 0.95;
$this->speedZ *= 0.95; $this->speedZ *= 0.95;
} }
} }
public function applyCollision(Entity $collided){ public function applyCollision(Entity $collided){
$diffX = $collided->x - $this->x; $diffX = $collided->x - $this->x;
$diffZ = $collided->z - $this->z; $diffZ = $collided->z - $this->z;
$dist = $diffX*$diffX + $diffZ*$diffZ; $dist = $diffX * $diffX + $diffZ * $diffZ;
if($dist >= 0.0001){ if($dist >= 0.0001){
$sqrtMax = sqrt($dist); $sqrtMax = sqrt($dist);
$diffX /= $sqrtMax; $diffX /= $sqrtMax;
$diffZ /= $sqrtMax; $diffZ /= $sqrtMax;
$col = (($v = 1 / $sqrtMax) > 1 ? 1 : $v); $col = (($v = 1 / $sqrtMax) > 1 ? 1 : $v);
$diffX *= $col; $diffX *= $col;
$diffZ *= $col; $diffZ *= $col;
$diffX *= 0.1; $diffX *= 0.1;
$diffZ *= 0.1; $diffZ *= 0.1;
$diffX *= 0.5; $diffX *= 0.5;
$diffZ *= 0.5; $diffZ *= 0.5;
$this->addVelocity(-$diffX, 0, -$diffZ); $this->addVelocity(-$diffX, 0, -$diffZ);
$collided->addVelocity($diffX / 4, 0, $diffZ / 4); $collided->addVelocity($diffX / 4, 0, $diffZ / 4);
} }
@ -341,18 +340,18 @@ class Minecart extends Vehicle{
} }
$this->updateLast(); $this->updateLast();
//$this->updatePosition(); //$this->updatePosition();
$this->speedY -= 0.04; $this->speedY -= 0.04;
//TODO port stuff //TODO port stuff
$blockX = floor($this->x); $blockX = floor($this->x);
$blockY = floor($this->y); $blockY = floor($this->y);
$blockZ = floor($this->z); $blockZ = floor($this->z);
if(RailBaseBlock::isRailBlock($this->level, $blockX, $blockY - 1, $blockZ)){ if(RailBaseBlock::isRailBlock($this->level, $blockX, $blockY - 1, $blockZ)){
--$blockY; --$blockY;
} }
[$id, $meta] = $this->level->level->getBlock($blockX, $blockY, $blockZ); [$id, $meta] = $this->level->level->getBlock($blockX, $blockY, $blockZ);
if(RailBaseBlock::isRailID($id)){ if(RailBaseBlock::isRailID($id)){
$this->moveAlongTrack($blockX, $blockY, $blockZ, 0.4, 0.0078125, $id, $meta); $this->moveAlongTrack($blockX, $blockY, $blockZ, 0.4, 0.0078125, $id, $meta);
@ -362,32 +361,32 @@ class Minecart extends Vehicle{
} }
$this->doBlocksCollision(); $this->doBlocksCollision();
$this->pitch = 0; $this->pitch = 0;
$diffX = $this->lastX - $this->x; $diffX = $this->lastX - $this->x;
$diffZ = $this->lastZ - $this->z; $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; $this->yaw = atan2($diffZ, $diffX) * 180 / M_PI;
if($this->isInReverse) $this->yaw += 180; if($this->isInReverse) $this->yaw += 180;
} }
$yw = fmod($this->yaw - $this->lastYaw, 360); $yw = fmod($this->yaw - $this->lastYaw, 360);
if($yw >= 180) $yw -= 360; if($yw >= 180) $yw -= 360;
if($yw < 180) $yw += 360; if($yw < 180) $yw += 360;
if($yw < -170 || $yw >= 170){ if($yw < -170 || $yw >= 170){
$this->isInReverse = !$this->isInReverse; $this->isInReverse = !$this->isInReverse;
$this->yaw = $this->yaw + 180; $this->yaw = $this->yaw + 180;
} }
$bb = $this->boundingBox->expand(0.2, 0, 0.2); $bb = $this->boundingBox->expand(0.2, 0, 0.2);
$minChunkX = ((int)($bb->minX - 2)) >> 4; $minChunkX = ((int) ($bb->minX - 2)) >> 4;
$minChunkZ = ((int)($bb->minZ - 2)) >> 4; $minChunkZ = ((int) ($bb->minZ - 2)) >> 4;
$maxChunkX = ((int)($bb->minX + 2)) >> 4; $maxChunkX = ((int) ($bb->minX + 2)) >> 4;
$maxChunkZ = ((int)($bb->minZ + 2)) >> 4; $maxChunkZ = ((int) ($bb->minZ + 2)) >> 4;
//TODO also index by chunkY? //TODO also index by chunkY?
for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){ for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){
for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ){ for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ){
@ -401,14 +400,14 @@ class Minecart extends Vehicle{
}else{ }else{
$e->applyCollision($this); $e->applyCollision($this);
} }
} }
} }
} }
} }
} }
} }
public function close() public function close()
{ {
parent::close(); parent::close();
@ -421,11 +420,11 @@ class Minecart extends Vehicle{
} }
} }
} }
public function isPushable(){ public function isPushable(){
return false; //TODO replace with true return false; //TODO replace with true
} }
public function spawn($player){ public function spawn($player){
$pk = new AddEntityPacket; $pk = new AddEntityPacket;
$pk->eid = $this->eid; $pk->eid = $this->eid;
@ -436,7 +435,7 @@ class Minecart extends Vehicle{
$pk->yaw = $this->yaw; $pk->yaw = $this->yaw;
$pk->pitch = $this->pitch; $pk->pitch = $this->pitch;
$player->dataPacket($pk); $player->dataPacket($pk);
$pk = new SetEntityMotionPacket; $pk = new SetEntityMotionPacket;
$pk->eid = $this->eid; $pk->eid = $this->eid;
$pk->speedX = $this->speedX; $pk->speedX = $this->speedX;
@ -444,7 +443,7 @@ class Minecart extends Vehicle{
$pk->speedZ = $this->speedZ; $pk->speedZ = $this->speedZ;
$player->dataPacket($pk); $player->dataPacket($pk);
} }
public function interactWith(Entity $e, $action){ public function interactWith(Entity $e, $action){
if($action === InteractPacket::ACTION_HOLD && $e->isPlayer() && $this->canRide($e)){ if($action === InteractPacket::ACTION_HOLD && $e->isPlayer() && $this->canRide($e)){
$e->setRiding($this); $e->setRiding($this);

View file

@ -3,23 +3,23 @@
class Painting extends Entity{ class Painting extends Entity{
const CLASS_TYPE = ENTITY_OBJECT; const CLASS_TYPE = ENTITY_OBJECT;
const TYPE = OBJECT_PAINTING; const TYPE = OBJECT_PAINTING;
public $motive; public $motive;
public $direction; public $direction;
public $xPos, $yPos, $zPos; public $xPos, $yPos, $zPos;
public $isValid = true; public $isValid = true;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){ public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->x = $this->data["TileX"] ?? $this->x; $this->x = $this->data["TileX"] ?? $this->x;
$this->y = $this->data["TileY"] ?? $this->y; $this->y = $this->data["TileY"] ?? $this->y;
$this->z = $this->data["TileZ"] ?? $this->z; $this->z = $this->data["TileZ"] ?? $this->z;
$this->xPos = $this->data["xPos"] ?? (int)$this->x; $this->xPos = $this->data["xPos"] ?? (int) $this->x;
$this->zPos = $this->data["zPos"] ?? (int)$this->z; $this->zPos = $this->data["zPos"] ?? (int) $this->z;
$this->yPos = $this->data["yPos"] ?? (int)$this->y; $this->yPos = $this->data["yPos"] ?? (int) $this->y;
$this->health = 1; $this->health = 1;
$this->canBeAttacked = true; $this->canBeAttacked = true;
$this->width = 1; $this->width = 1;
@ -30,30 +30,30 @@ class Painting extends Entity{
if($dir === false){ if($dir === false){
$dir = floor($this->yaw / 90); $dir = floor($this->yaw / 90);
} }
if($mot === false){ if($mot === false){
$this->setRandomMotive($dir); $this->setRandomMotive($dir);
}else{ }else{
$this->motive = $mot; $this->motive = $mot;
$this->direction = $dir; $this->direction = $dir;
$this->setDirection($dir); $this->setDirection($dir);
} }
} }
public $counter = 0; public $counter = 0;
public function update($now){ public function update($now){
if($this->closed === true){ if($this->closed === true){
return false; return false;
} }
if(++$this->counter >= 100){ if(++$this->counter >= 100){
$this->counter = 0; $this->counter = 0;
if(!$this->survives() && !$this->dead){ //maybe dont check entity collision? if(!$this->survives() && !$this->dead){ //maybe dont check entity collision?
$this->makeDead("nosurvive"); $this->makeDead("nosurvive");
} }
} }
return true; return true;
} }
@ -62,34 +62,34 @@ class Painting extends Entity{
foreach(PaintingItem::$motives as $name => $motive){ foreach(PaintingItem::$motives as $name => $motive){
$this->motive = $name; $this->motive = $name;
$this->setDirection($dir); $this->setDirection($dir);
if($this->survives()){ if($this->survives()){
$tochoose[] = $name; $tochoose[] = $name;
} }
} }
if(count($tochoose) > 0){ if(count($tochoose) > 0){
$ind = mt_rand(0, count($tochoose)-1); $ind = mt_rand(0, count($tochoose) - 1);
}else{ }else{
$this->isValid = false; $this->isValid = false;
return; return;
} }
$this->motive = $tochoose[$ind]; $this->motive = $tochoose[$ind];
$this->setDirection($dir); $this->setDirection($dir);
} }
public static function offs($n){ public static function offs($n){
if($n == 32 || $n == 64) return 0.5; if($n == 32 || $n == 64) return 0.5;
return 0; return 0;
} }
const DIRECTION_OPPOSITE = [2, 3, 0, 1]; const DIRECTION_OPPOSITE = [2, 3, 0, 1];
public function setDirection($dir){ public function setDirection($dir){
$this->direction = $dir; $this->direction = $dir;
$this->lastYaw = $this->yaw = $dir * 90; $this->lastYaw = $this->yaw = $dir * 90;
$size = PaintingItem::$motives[$this->motive] ?? array(1, 1); $size = PaintingItem::$motives[$this->motive] ?? [1, 1];
$width = $size[0]*16; $width = $size[0] * 16;
$height = $size[1]*16; $height = $size[1] * 16;
if($dir == 2 || $dir == 0){ if($dir == 2 || $dir == 0){
$v10 = 2; $v10 = 2;
$v9 = $width; $v9 = $width;
@ -98,28 +98,28 @@ class Painting extends Entity{
$v9 = 2; $v9 = 2;
$v10 = $width; $v10 = $width;
} }
$v12 = $v9 * 0.03125; $v12 = $v9 * 0.03125;
$v13 = $height * 0.03125; $v13 = $height * 0.03125;
$v14 = $v10 * 0.03125; $v14 = $v10 * 0.03125;
$v15 = $this->xPos + 0.5; $v15 = $this->xPos + 0.5;
$v16 = $this->yPos + 0.5; $v16 = $this->yPos + 0.5;
$v17 = $this->zPos + 0.5; //XXX check $v17 = $this->zPos + 0.5; //XXX check
if($dir == 2){ if($dir == 2){
$v17 = $v17 - 0.5625; $v17 = $v17 - 0.5625;
$v15 = $v15 - self::offs($width); $v15 = $v15 - self::offs($width);
}else if($dir == 1){ }elseif($dir == 1){
$v15 = $v15 - 0.5625; $v15 = $v15 - 0.5625;
$v17 = $v17 + self::offs($width); $v17 = $v17 + self::offs($width);
}else if($dir == 3){ }elseif($dir == 3){
$v15 = $v15 + 0.5625; $v15 = $v15 + 0.5625;
$v17 = $v17 - self::offs($width); $v17 = $v17 - self::offs($width);
}else{ }else{
$v17 = $v17 + 0.5625; $v17 = $v17 + 0.5625;
$v15 = $v15 + self::offs($width); $v15 = $v15 + self::offs($width);
} }
$v23 = $v16 + self::offs($height); $v23 = $v16 + self::offs($height);
$this->setPos($v15, $v23, $v17); $this->setPos($v15, $v23, $v17);
$this->boundingBox->minX = ($v15 - $v12) + 0.03125; $this->boundingBox->minX = ($v15 - $v12) + 0.03125;
@ -129,35 +129,35 @@ class Painting extends Entity{
$this->boundingBox->maxY = ($v23 + $v13) - 0.03125; $this->boundingBox->maxY = ($v23 + $v13) - 0.03125;
$this->boundingBox->maxZ = ($v17 + $v14) - 0.03125; $this->boundingBox->maxZ = ($v17 + $v14) - 0.03125;
} }
public function getDrops(){ public function getDrops(){
return [ return [
[PAINTING, 0, 1] [PAINTING, 0, 1]
]; ];
} }
public function isPickable(){ public function isPickable(){
return true; return true;
} }
public function survives(){ public function survives(){
$cubes = $this->level->getCubes($this, $this->boundingBox); $cubes = $this->level->getCubes($this, $this->boundingBox);
if(count($cubes) == 0){ if(count($cubes) == 0){
$size = PaintingItem::$motives[$this->motive] ?? array(1, 1); $size = PaintingItem::$motives[$this->motive] ?? [1, 1];
$width = $size[0]; $width = $size[0];
$width2 = $width*16/32; $width2 = $width * 16 / 32;
$height = $size[1]; $height = $size[1];
$height2 = $height*16/32; $height2 = $height * 16 / 32;
if($width < 1) $width = 1; if($width < 1) $width = 1;
if($height < 1) $height = 1; if($height < 1) $height = 1;
$positionX = $this->xPos; $positionX = $this->xPos;
$positionZ = $this->zPos; $positionZ = $this->zPos;
if($this->direction == 2 || $this->direction == 0) $positionX = floor($this->x - $width2); if($this->direction == 2 || $this->direction == 0) $positionX = floor($this->x - $width2);
if($this->direction == 1 || $this->direction == 3) $positionZ = floor($this->z - $width2); if($this->direction == 1 || $this->direction == 3) $positionZ = floor($this->z - $width2);
$minY = floor($this->y - $height2); $minY = floor($this->y - $height2);
for($off = 0; $off < $width; ++$off){ for($off = 0; $off < $width; ++$off){
for($yoff = 0; $yoff < $height; ++$yoff){ for($yoff = 0; $yoff < $height; ++$yoff){
$y = $minY + $yoff; $y = $minY + $yoff;
@ -166,13 +166,13 @@ class Painting extends Entity{
}else{ }else{
$id = $this->level->level->getBlockId($positionX + $off, $y, $this->zPos); $id = $this->level->level->getBlockId($positionX + $off, $y, $this->zPos);
} }
if(!StaticBlock::getIsSolid($id)){ if(!StaticBlock::getIsSolid($id)){
return false; return false;
} }
} }
} }
$ents = $this->level->getEntitiesInAABBOfType($this->boundingBox, ENTITY_OBJECT); $ents = $this->level->getEntitiesInAABBOfType($this->boundingBox, ENTITY_OBJECT);
foreach($ents as $e){ foreach($ents as $e){
if($e->eid == $this->eid) continue; if($e->eid == $this->eid) continue;
@ -182,13 +182,13 @@ class Painting extends Entity{
} }
return true; return true;
} }
return false; return false;
} }
public function createSaveData(){ public function createSaveData(){
$data = parent::createSaveData(); $data = parent::createSaveData();
$data["Motive"] = $this->motive; $data["Motive"] = $this->motive;
$data["Direction"] = $this->direction; $data["Direction"] = $this->direction;
$data["xPos"] = $this->xPos; $data["xPos"] = $this->xPos;

View file

@ -14,11 +14,11 @@ class PrimedTNT extends Entity{
$this->yOffset = $this->height / 2; $this->yOffset = $this->height / 2;
$this->setHealth(10000000, "generic"); $this->setHealth(10000000, "generic");
} }
public function isPickable(){ public function isPickable(){
return !$this->dead; return !$this->dead;
} }
public function getMetadata(){ public function getMetadata(){
$d = parent::getMetadata(); $d = parent::getMetadata();
$d[16]["value"] = (int) $this->data["fuse"]; $d[16]["value"] = (int) $this->data["fuse"];
@ -26,34 +26,34 @@ class PrimedTNT extends Entity{
} }
public function createSaveData(){ public function createSaveData(){
$data = parent::createSaveData(); $data = parent::createSaveData();
$data["fuse"] = $this->data["fuse"]; $data["fuse"] = $this->data["fuse"];
$data["power"] = $this->data["power"]; $data["power"] = $this->data["power"];
return $data; return $data;
} }
public function update($now){ public function update($now){
if($this->closed) return; if($this->closed) return;
$this->lastX = $this->x; $this->lastX = $this->x;
$this->lastY = $this->y; $this->lastY = $this->y;
$this->lastZ = $this->z; $this->lastZ = $this->z;
$this->speedY -= 0.04; $this->speedY -= 0.04;
$this->move($this->speedX, $this->speedY, $this->speedZ); $this->move($this->speedX, $this->speedY, $this->speedZ);
$this->speedX *- 0.98; $this->speedX * -0.98;
$this->speedY *= 0.98; $this->speedY *= 0.98;
$this->speedZ *= 0.98; $this->speedZ *= 0.98;
if($this->onGround){ if($this->onGround){
$this->speedX *= 0.7; $this->speedX *= 0.7;
$this->speedZ *= 0.7; $this->speedZ *= 0.7;
$this->speedY *= -0.5; $this->speedY *= -0.5;
} }
$tickDiff = ($now - $this->lastUpdate) / 0.05; $tickDiff = ($now - $this->lastUpdate) / 0.05;
$this->data["fuse"] -= $tickDiff; $this->data["fuse"] -= $tickDiff;
$this->updateMetadata(); $this->updateMetadata();
if($this->data["fuse"] <= 0){ if($this->data["fuse"] <= 0){
@ -61,10 +61,10 @@ class PrimedTNT extends Entity{
$explosion = new Explosion($this, $this->data["power"]); $explosion = new Explosion($this, $this->data["power"]);
$explosion->explode(); $explosion->explode();
} }
$this->lastUpdate = $now; $this->lastUpdate = $now;
} }
public function spawn($player){ public function spawn($player){
$pk = new AddEntityPacket; $pk = new AddEntityPacket;
$pk->eid = $this->eid; $pk->eid = $this->eid;

View file

@ -1,32 +1,32 @@
<?php <?php
class ThrownEgg extends Projectile{ class ThrownEgg extends Projectile{
const TYPE = OBJECT_EGG; const TYPE = OBJECT_EGG;
public function onHit(MovingObjectPosition $hitResult){ public function onHit(MovingObjectPosition $hitResult){
if($hitResult->typeOfHit == 1){ if($hitResult->typeOfHit == 1){
$hitResult->entityHit->harm(0, $this->eid); $hitResult->entityHit->harm(0, $this->eid);
} }
$rand = mt_rand(0, 7); $rand = mt_rand(0, 7);
if($rand == 0){ if($rand == 0){
$count = mt_rand(0, 31) == 0 ? 4 : 1; $count = mt_rand(0, 31) == 0 ? 4 : 1;
$data = [ $data = [
"x" => $this->x, "x" => $this->x,
"y" => $this->y, "y" => $this->y,
"z" => $this->z, "z" => $this->z,
"yaw" => $this->yaw, "yaw" => $this->yaw,
"pitch" => 0, "pitch" => 0,
"IsBaby" => true "IsBaby" => true
]; ];
for($i = 0; $i < $count; ++$i){ for($i = 0; $i < $count; ++$i){
$chicken = $this->server->api->entity->add($this->level, ENTITY_MOB, MOB_CHICKEN, $data); $chicken = $this->server->api->entity->add($this->level, ENTITY_MOB, MOB_CHICKEN, $data);
$this->server->api->entity->spawnToAll($chicken); $this->server->api->entity->spawnToAll($chicken);
} }
} }
$this->close(); $this->close();
} }
}
}

View file

@ -1,11 +1,12 @@
<?php <?php
class ThrownSnowball extends Projectile{ class ThrownSnowball extends Projectile{
const TYPE = OBJECT_SNOWBALL; const TYPE = OBJECT_SNOWBALL;
public function onHit(MovingObjectPosition $hitResult){ public function onHit(MovingObjectPosition $hitResult){
if($hitResult->typeOfHit == 1){ if($hitResult->typeOfHit == 1){
$hitResult->entityHit->harm(0, $this->eid); $hitResult->entityHit->harm(0, $this->eid);
} }
$this->close(); $this->close();
} }
} }

View file

@ -2,16 +2,16 @@
class TripodCamera extends Entity{ class TripodCamera extends Entity{
const TYPE = OBJECT_TRIPOD_CAMERA; const TYPE = OBJECT_TRIPOD_CAMERA;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){ function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data); parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(PHP_INT_MAX, "generic"); $this->setHealth(PHP_INT_MAX, "generic");
} }
public function isPickable(){ public function isPickable(){
return !$this->dead; return !$this->dead;
} }
public function interactWith(Entity $e, $action){ public function interactWith(Entity $e, $action){
if($e->isPlayer() and $action === InteractPacket::ACTION_HOLD){ if($e->isPlayer() and $action === InteractPacket::ACTION_HOLD){
//todo //todo

View file

@ -1,8 +1,8 @@
<?php <?php
class EntityRegistry{ class EntityRegistry{
public static $entityList; public static $entityList;
/*Register all entities*/ /*Register all entities*/
public static function registerEntities(){ public static function registerEntities(){
ConsoleAPI::info("Registering entities..."); ConsoleAPI::info("Registering entities...");
@ -25,13 +25,13 @@ class EntityRegistry{
self::registerEntity(ThrownEgg::class); self::registerEntity(ThrownEgg::class);
self::registerEntity(ThrownSnowball::class); self::registerEntity(ThrownSnowball::class);
} }
/*Register an Entity*/ /*Register an Entity*/
public static function registerEntity($className){ public static function registerEntity($className){
$class = new \ReflectionClass($className); $class = new \ReflectionClass($className);
if(is_a($className, Entity::class, true) and !$class->isAbstract()){ if(is_a($className, Entity::class, true) and !$class->isAbstract()){
//self::$entityList[$className::TYPE] = $className; //self::$entityList[$className::TYPE] = $className;
self::$entityList->addEntity(new PropertyEntity($className::CLASS_TYPE, $className::TYPE, $className)); self::$entityList->addEntity(new PropertyEntity($className::CLASS_TYPE, $className::TYPE, $className));
//self::$shortNames[$className] = $class->getShortName(); what is this even supposed to do? //self::$shortNames[$className] = $class->getShortName(); what is this even supposed to do?
//console("[INFO] Registered a ".$className); //console("[INFO] Registered a ".$className);

View file

@ -2,13 +2,13 @@
class PropertyEntity{ class PropertyEntity{
private $class,$type,$name; private $class,$type,$name;
function __construct($class, $type, $name){ function __construct($class, $type, $name){
$this->class = $class; $this->class = $class;
$this->type = $type; $this->type = $type;
$this->name = $name; $this->name = $name;
} }
public function getEntityClass(){ public function getEntityClass(){
return $this->class; return $this->class;
} }

View file

@ -16,7 +16,7 @@ abstract class EventHandler{
}else{ }else{
return BaseEvent::ALLOW; return BaseEvent::ALLOW;
} }
} }
} }
} }

View file

@ -2,11 +2,11 @@
/** /**
* *
* ____ _ _ __ __ _ __ __ ____ * ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by * it under the terms of the GNU Lesser General Public License as published by
@ -15,7 +15,7 @@
* *
* @author PocketMine Team * @author PocketMine Team
* @link http://www.pocketmine.net/ * @link http://www.pocketmine.net/
* *
* *
*/ */
@ -44,9 +44,9 @@ abstract class EventPriority{
const HIGHEST = 1; const HIGHEST = 1;
/** /**
* Event is listened to purely for monitoring the outcome of an event. * Event is listened to purely for monitoring the outcome of an event.
* *
* No modifications to the event should be made under this priority * No modifications to the event should be made under this priority
*/ */
const MONITOR = 0; const MONITOR = 0;
} }

View file

@ -1,6 +1,5 @@
<?php <?php
/** /**
* Plugins that create events must use this class as the base * Plugins that create events must use this class as the base
*/ */

View file

@ -2,11 +2,11 @@
/** /**
* *
* ____ _ _ __ __ _ __ __ ____ * ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by * it under the terms of the GNU Lesser General Public License as published by
@ -15,7 +15,7 @@
* *
* @author PocketMine Team * @author PocketMine Team
* @link http://www.pocketmine.net/ * @link http://www.pocketmine.net/
* *
* *
*/ */

View file

@ -2,11 +2,11 @@
/** /**
* *
* ____ _ _ __ __ _ __ __ ____ * ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by * it under the terms of the GNU Lesser General Public License as published by
@ -15,26 +15,26 @@
* *
* @author PocketMine Team * @author PocketMine Team
* @link http://www.pocketmine.net/ * @link http://www.pocketmine.net/
* *
* *
*/ */
class DataPacketReceiveEvent extends ServerEvent implements CancellableEvent{ class DataPacketReceiveEvent extends ServerEvent implements CancellableEvent{
public static $handlers; public static $handlers;
public static $handlerPriority; public static $handlerPriority;
private $packet; private $packet;
private $player; private $player;
public function __construct(Player $player, RakNetDataPacket $packet){ public function __construct(Player $player, RakNetDataPacket $packet){
$this->packet = $packet; $this->packet = $packet;
$this->player = $player; $this->player = $player;
} }
public function getPacket(){ public function getPacket(){
return $this->packet; return $this->packet;
} }
public function getPlayer(){ public function getPlayer(){
return $this->player; return $this->player;
} }

View file

@ -2,11 +2,11 @@
/** /**
* *
* ____ _ _ __ __ _ __ __ ____ * ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by * it under the terms of the GNU Lesser General Public License as published by
@ -15,26 +15,26 @@
* *
* @author PocketMine Team * @author PocketMine Team
* @link http://www.pocketmine.net/ * @link http://www.pocketmine.net/
* *
* *
*/ */
class DataPacketSendEvent extends ServerEvent implements CancellableEvent{ class DataPacketSendEvent extends ServerEvent implements CancellableEvent{
public static $handlers; public static $handlers;
public static $handlerPriority; public static $handlerPriority;
private $packet; private $packet;
private $player; private $player;
public function __construct(Player $player, RakNetDataPacket $packet){ public function __construct(Player $player, RakNetDataPacket $packet){
$this->packet = $packet; $this->packet = $packet;
$this->player = $player; $this->player = $player;
} }
public function getPacket(){ public function getPacket(){
return $this->packet; return $this->packet;
} }
public function getPlayer(){ public function getPlayer(){
return $this->player; return $this->player;
} }

View file

@ -2,11 +2,11 @@
/** /**
* *
* ____ _ _ __ __ _ __ __ ____ * ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by * it under the terms of the GNU Lesser General Public License as published by
@ -15,21 +15,20 @@
* *
* @author PocketMine Team * @author PocketMine Team
* @link http://www.pocketmine.net/ * @link http://www.pocketmine.net/
* *
* *
*/ */
class PacketReceiveEvent extends ServerEvent implements CancellableEvent{ class PacketReceiveEvent extends ServerEvent implements CancellableEvent{
public static $handlers; public static $handlers;
public static $handlerPriority; public static $handlerPriority;
private $packet; private $packet;
public function __construct(Packet $packet){ public function __construct(Packet $packet){
$this->packet = $packet; $this->packet = $packet;
} }
public function getPacket(){ public function getPacket(){
return $this->packet; return $this->packet;
} }

View file

@ -2,11 +2,11 @@
/** /**
* *
* ____ _ _ __ __ _ __ __ ____ * ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by * it under the terms of the GNU Lesser General Public License as published by
@ -15,21 +15,20 @@
* *
* @author PocketMine Team * @author PocketMine Team
* @link http://www.pocketmine.net/ * @link http://www.pocketmine.net/
* *
* *
*/ */
class PacketSendEvent extends ServerEvent implements CancellableEvent{ class PacketSendEvent extends ServerEvent implements CancellableEvent{
public static $handlers; public static $handlers;
public static $handlerPriority; public static $handlerPriority;
private $packet; private $packet;
public function __construct(Packet $packet){ public function __construct(Packet $packet){
$this->packet = $packet; $this->packet = $packet;
} }
public function getPacket(){ public function getPacket(){
return $this->packet; return $this->packet;
} }

View file

@ -11,7 +11,6 @@ if(!function_exists("cli_set_process_title")){
} }
} }
function dummy(){ function dummy(){
} }
@ -69,8 +68,6 @@ function nullsafe(&$a, $null){
return $a ?? $null; return $a ?? $null;
} }
function require_all($path, &$count = 0){ function require_all($path, &$count = 0){
$dir = dir($path . "/"); $dir = dir($path . "/");
$dirs = []; $dirs = [];

View file

@ -8,7 +8,7 @@
const DEFAULT_MEMORY = 128; const DEFAULT_MEMORY = 128;
const DEFAULT_PLAYERS = 20; const DEFAULT_PLAYERS = 20;
const DEFAULT_GAMEMODE = SURVIVAL; const DEFAULT_GAMEMODE = SURVIVAL;
private $lang, $config; private $lang, $config;
public function __construct(){ public function __construct(){
echo "[*] NostalgiaCore set-up wizard\n"; echo "[*] NostalgiaCore set-up wizard\n";
@ -25,8 +25,8 @@
} }
}while($lang == false); }while($lang == false);
$this->lang = new InstallerLang($lang); $this->lang = new InstallerLang($lang);
echo "[*] ".$this->lang->language_has_been_selected."\n"; echo "[*] " . $this->lang->language_has_been_selected . "\n";
echo "[?] ".$this->lang->skip_installer." (y/N): "; echo "[?] " . $this->lang->skip_installer . " (y/N): ";
if(strtolower($this->getInput()) === "y"){ if(strtolower($this->getInput()) === "y"){
return; return;
} }
@ -34,14 +34,14 @@
$this->welcome(); $this->welcome();
$this->generateBaseConfig(); $this->generateBaseConfig();
$this->generateUserFiles(); $this->generateUserFiles();
$this->networkFunctions(); $this->networkFunctions();
$this->endWizard(); $this->endWizard();
} }
private function welcome(){ private function welcome(){
echo $this->lang->welcome_to_pocketmine."\n"; echo $this->lang->welcome_to_pocketmine . "\n";
echo <<<LICENSE echo <<<LICENSE
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
@ -50,44 +50,44 @@
(at your option) any later version. (at your option) any later version.
LICENSE; LICENSE;
echo "\n[?] ".$this->lang->accept_license." (y/N): "; echo "\n[?] " . $this->lang->accept_license . " (y/N): ";
if(strtolower($this->getInput("n")) != "y"){ if(strtolower($this->getInput("n")) != "y"){
echo "[!] ".$this->lang->you_have_to_accept_the_license."\n"; echo "[!] " . $this->lang->you_have_to_accept_the_license . "\n";
sleep(5); sleep(5);
exit(0); exit(0);
} }
echo "[*] ".$this->lang->setting_up_server_now."\n"; echo "[*] " . $this->lang->setting_up_server_now . "\n";
echo "[*] ".$this->lang->default_values_info."\n"; echo "[*] " . $this->lang->default_values_info . "\n";
echo "[*] ".$this->lang->server_properties."\n"; echo "[*] " . $this->lang->server_properties . "\n";
} }
private function generateBaseConfig(){ private function generateBaseConfig(){
$config = new Config(DATA_PATH . "server.properties", CONFIG_PROPERTIES); $config = new Config(DATA_PATH . "server.properties", CONFIG_PROPERTIES);
echo "[?] ".$this->lang->name_your_server." (".self::DEFAULT_NAME."): "; echo "[?] " . $this->lang->name_your_server . " (" . self::DEFAULT_NAME . "): ";
$config->set("server-name", $this->getInput(self::DEFAULT_NAME)); $config->set("server-name", $this->getInput(self::DEFAULT_NAME));
echo "[*] ".$this->lang->port_warning."\n"; echo "[*] " . $this->lang->port_warning . "\n";
do{ do{
echo "[?] ".$this->lang->server_port." (".self::DEFAULT_PORT."): "; echo "[?] " . $this->lang->server_port . " (" . self::DEFAULT_PORT . "): ";
$port = (int) $this->getInput(self::DEFAULT_PORT); $port = (int) $this->getInput(self::DEFAULT_PORT);
if($port <= 0 or $port > 65535){ if($port <= 0 or $port > 65535){
echo "[!] ".$this->lang->invalid_port."\n"; echo "[!] " . $this->lang->invalid_port . "\n";
} }
}while($port <= 0 or $port > 65535); }while($port <= 0 or $port > 65535);
$config->set("server-port", $port); $config->set("server-port", $port);
echo "[*] ".$this->lang->ram_warning."\n"; echo "[*] " . $this->lang->ram_warning . "\n";
echo "[?] ".$this->lang->server_ram." (".self::DEFAULT_MEMORY."): "; echo "[?] " . $this->lang->server_ram . " (" . self::DEFAULT_MEMORY . "): ";
$config->set("memory-limit", ((int) $this->getInput(self::DEFAULT_MEMORY))."M"); $config->set("memory-limit", ((int) $this->getInput(self::DEFAULT_MEMORY)) . "M");
echo "[*] ".$this->lang->gamemode_info."\n"; echo "[*] " . $this->lang->gamemode_info . "\n";
do{ do{
echo "[?] ".$this->lang->default_gamemode.": (".self::DEFAULT_GAMEMODE."): "; echo "[?] " . $this->lang->default_gamemode . ": (" . self::DEFAULT_GAMEMODE . "): ";
$gamemode = (int) $this->getInput(self::DEFAULT_GAMEMODE); $gamemode = (int) $this->getInput(self::DEFAULT_GAMEMODE);
}while($gamemode < 0 or $gamemode > 3); }while($gamemode < 0 or $gamemode > 3);
$config->set("gamemode", $gamemode); $config->set("gamemode", $gamemode);
echo "[?] ".$this->lang->max_players." (".self::DEFAULT_PLAYERS."): "; echo "[?] " . $this->lang->max_players . " (" . self::DEFAULT_PLAYERS . "): ";
$config->set("max-players", (int) $this->getInput(self::DEFAULT_PLAYERS)); $config->set("max-players", (int) $this->getInput(self::DEFAULT_PLAYERS));
echo "[*] ".$this->lang->spawn_protection_info."\n"; echo "[*] " . $this->lang->spawn_protection_info . "\n";
echo "[?] ".$this->lang->spawn_protection." (Y/n): "; echo "[?] " . $this->lang->spawn_protection . " (Y/n): ";
if(strtolower($this->getInput("y")) == "n"){ if(strtolower($this->getInput("y")) == "n"){
$config->set("spawn-protection", -1); $config->set("spawn-protection", -1);
}else{ }else{
@ -95,82 +95,80 @@ LICENSE;
} }
$config->save(); $config->save();
} }
private function generateUserFiles(){ private function generateUserFiles(){
echo "[*] ".$this->lang->op_info."\n"; echo "[*] " . $this->lang->op_info . "\n";
echo "[?] ".$this->lang->op_who.": "; echo "[?] " . $this->lang->op_who . ": ";
$op = strtolower($this->getInput("")); $op = strtolower($this->getInput(""));
if($op === ""){ if($op === ""){
echo "[!] ".$this->lang->op_warning."\n"; echo "[!] " . $this->lang->op_warning . "\n";
}else{ }else{
$ops = new Config(DATA_PATH."ops.txt", CONFIG_LIST); $ops = new Config(DATA_PATH . "ops.txt", CONFIG_LIST);
$ops->set($op, true); $ops->set($op, true);
$ops->save(); $ops->save();
} }
echo "[*] ".$this->lang->whitelist_info."\n"; echo "[*] " . $this->lang->whitelist_info . "\n";
echo "[?] ".$this->lang->whitelist_enable." (y/N): "; echo "[?] " . $this->lang->whitelist_enable . " (y/N): ";
$config = new Config(DATA_PATH . "server.properties", CONFIG_PROPERTIES); $config = new Config(DATA_PATH . "server.properties", CONFIG_PROPERTIES);
if(strtolower($this->getInput("n")) === "y"){ if(strtolower($this->getInput("n")) === "y"){
echo "[!] ".$this->lang->whitelist_warning."\n"; echo "[!] " . $this->lang->whitelist_warning . "\n";
$config->set("white-list", true); $config->set("white-list", true);
}else{ }else{
$config->set("white-list", false); $config->set("white-list", false);
} }
$config->save(); $config->save();
} }
private function networkFunctions(){ private function networkFunctions(){
$config = new Config(DATA_PATH . "server.properties", CONFIG_PROPERTIES); $config = new Config(DATA_PATH . "server.properties", CONFIG_PROPERTIES);
echo "[!] ".$this->lang->query_warning1."\n"; echo "[!] " . $this->lang->query_warning1 . "\n";
echo "[!] ".$this->lang->query_warning2."\n"; echo "[!] " . $this->lang->query_warning2 . "\n";
echo "[?] ".$this->lang->query_disable." (y/N): "; echo "[?] " . $this->lang->query_disable . " (y/N): ";
if(strtolower($this->getInput("n")) === "y"){ if(strtolower($this->getInput("n")) === "y"){
$config->set("enable-query", false); $config->set("enable-query", false);
}else{ }else{
$config->set("enable-query", true); $config->set("enable-query", true);
} }
echo "[*] ".$this->lang->rcon_info."\n"; echo "[*] " . $this->lang->rcon_info . "\n";
echo "[?] ".$this->lang->rcon_enable." (y/N): "; echo "[?] " . $this->lang->rcon_enable . " (y/N): ";
if(strtolower($this->getInput("n")) === "y"){ if(strtolower($this->getInput("n")) === "y"){
$config->set("enable-rcon", true); $config->set("enable-rcon", true);
$password = substr(base64_encode(Utils::getRandomBytes(20, false)), 3, 10); $password = substr(base64_encode(Utils::getRandomBytes(20, false)), 3, 10);
$config->set("rcon.password", $password); $config->set("rcon.password", $password);
echo "[*] ".$this->lang->rcon_password.": ".$password."\n"; echo "[*] " . $this->lang->rcon_password . ": " . $password . "\n";
}else{ }else{
$config->set("enable-rcon", false); $config->set("enable-rcon", false);
} }
$config->save(); $config->save();
echo "[*] " . $this->lang->ip_get . "\n";
echo "[*] ".$this->lang->ip_get."\n";
$externalIP = Utils::getIP(); $externalIP = Utils::getIP();
$internalIP = gethostbyname(trim(`hostname`)); $internalIP = gethostbyname(trim(`hostname`));
echo "[!] ".$this->lang->get("ip_warning", array("{{EXTERNAL_IP}}", "{{INTERNAL_IP}}"), array($externalIP, $internalIP))."\n"; echo "[!] " . $this->lang->get("ip_warning", ["{{EXTERNAL_IP}}", "{{INTERNAL_IP}}"], [$externalIP, $internalIP]) . "\n";
echo "[!] ".$this->lang->ip_confirm; echo "[!] " . $this->lang->ip_confirm;
$this->getInput(); $this->getInput();
} }
private function endWizard(){ private function endWizard(){
echo "[*] ".$this->lang->you_have_finished."\n"; echo "[*] " . $this->lang->you_have_finished . "\n";
echo "[*] ".$this->lang->pocketmine_plugins."\n"; echo "[*] " . $this->lang->pocketmine_plugins . "\n";
echo "[*] ".$this->lang->pocketmine_will_start."\n\n\n"; echo "[*] " . $this->lang->pocketmine_will_start . "\n\n\n";
sleep(4); sleep(4);
} }
private function getInput($default = ""){ private function getInput($default = ""){
$input = trim(fgets(STDIN)); $input = trim(fgets(STDIN));
return $input === "" ? $default:$input; return $input === "" ? $default:$input;
} }
} }
class InstallerLang{ class InstallerLang{
public static $languages = array( public static $languages = [
"ru" => "Pyccĸий", "ru" => "Pyccĸий",
"en" => "English", "en" => "English",
"es" => "Español", "es" => "Español",
@ -180,7 +178,7 @@ LICENSE;
//"vi" => "Tiếng Việt", //"vi" => "Tiếng Việt",
"ko" => "한국어", "ko" => "한국어",
"fr" => "Français", "fr" => "Français",
"it" => "Italiano", "it" => "Italiano",
//"lv" => "Latviešu", //"lv" => "Latviešu",
"nl" => "Nederlands", "nl" => "Nederlands",
//"pt" => "Português", //"pt" => "Português",
@ -189,18 +187,18 @@ LICENSE;
"tr" => "Türkçe", "tr" => "Türkçe",
"uk" => "Український" "uk" => "Український"
//"et" => "Eesti", //"et" => "Eesti",
); ];
private $texts = array(); private $texts = [];
private $lang; private $lang;
private $langfile; private $langfile;
public function __construct($lang = ""){ public function __construct($lang = ""){
if(file_exists(FILE_PATH."src/lang/Installer/".$lang.".ini")){ if(file_exists(FILE_PATH . "src/lang/Installer/" . $lang . ".ini")){
$this->lang = $lang; $this->lang = $lang;
$this->langfile = FILE_PATH."src/lang/Installer/".$lang.".ini"; $this->langfile = FILE_PATH . "src/lang/Installer/" . $lang . ".ini";
}else{ }else{
$l = glob(FILE_PATH."src/lang/Installer/".$lang."_*.ini"); $l = glob(FILE_PATH . "src/lang/Installer/" . $lang . "_*.ini");
if(count($l) > 0){ if(count($l) > 0){
$files = array(); $files = [];
foreach($l as $file){ foreach($l as $file){
$files[$file] = filesize($file); $files[$file] = filesize($file);
} }
@ -209,38 +207,38 @@ LICENSE;
$l = key($files); $l = key($files);
$l = substr($l, strrpos($l, "/") + 1, -4); $l = substr($l, strrpos($l, "/") + 1, -4);
$this->lang = isset(self::$languages[$l]) ? $l:$lang; $this->lang = isset(self::$languages[$l]) ? $l:$lang;
$this->langfile = FILE_PATH."src/lang/Installer/".$l.".ini"; $this->langfile = FILE_PATH . "src/lang/Installer/" . $l . ".ini";
}else{ }else{
$this->lang = "en"; $this->lang = "en";
$this->langfile = FILE_PATH."src/lang/Installer/en.ini"; $this->langfile = FILE_PATH . "src/lang/Installer/en.ini";
} }
} }
$this->loadLang(FILE_PATH."src/lang/Installer/en.ini", "en"); $this->loadLang(FILE_PATH . "src/lang/Installer/en.ini", "en");
if($this->lang !== "en"){ if($this->lang !== "en"){
$this->loadLang($this->langfile, $this->lang); $this->loadLang($this->langfile, $this->lang);
} }
} }
public function getLang(){ public function getLang(){
return ($this->lang); return ($this->lang);
} }
public function loadLang($langfile, $lang = "en"){ public function loadLang($langfile, $lang = "en"){
$this->texts[$lang] = array(); $this->texts[$lang] = [];
$texts = explode("\n", str_replace(array("\r", "\/\/"), array("", "//"), file_get_contents($langfile))); $texts = explode("\n", str_replace(["\r", "\/\/"], ["", "//"], file_get_contents($langfile)));
foreach($texts as $line){ foreach($texts as $line){
$line = trim($line); $line = trim($line);
if($line === ""){ if($line === ""){
continue; continue;
} }
$line = explode("=", $line); $line = explode("=", $line);
$this->texts[$lang][array_shift($line)] = str_replace(array("\\n", "\\N",), "\n", implode("=", $line)); $this->texts[$lang][array_shift($line)] = str_replace(["\\n", "\\N",], "\n", implode("=", $line));
} }
} }
public function get($name, $search = array(), $replace = array()){ public function get($name, $search = [], $replace = []){
if(!isset($this->texts[$this->lang][$name])){ if(!isset($this->texts[$this->lang][$name])){
if($this->lang !== "en" and isset($this->texts["en"][$name])){ if($this->lang !== "en" and isset($this->texts["en"][$name])){
return $this->texts["en"][$name]; return $this->texts["en"][$name];
@ -253,10 +251,10 @@ LICENSE;
return $this->texts[$this->lang][$name]; return $this->texts[$this->lang][$name];
} }
} }
public function __get($name){ public function __get($name){
return $this->get($name); return $this->get($name);
} }
} }
/***REM_END***/ /***REM_END***/

View file

@ -1,138 +1,138 @@
<?php <?php
abstract class Block extends Position{ abstract class Block extends Position{
public static $class = array( public static $class = [
AIR => "AirBlock", AIR => "AirBlock",
STONE => "StoneBlock", STONE => "StoneBlock",
GRASS => "GrassBlock", GRASS => "GrassBlock",
DIRT => "DirtBlock", DIRT => "DirtBlock",
COBBLESTONE => "CobblestoneBlock", COBBLESTONE => "CobblestoneBlock",
PLANKS => "PlanksBlock", PLANKS => "PlanksBlock",
SAPLING => "SaplingBlock", SAPLING => "SaplingBlock",
BEDROCK => "BedrockBlock", BEDROCK => "BedrockBlock",
WATER => "WaterBlock", WATER => "WaterBlock",
STILL_WATER => "StillWaterBlock", STILL_WATER => "StillWaterBlock",
LAVA => "LavaBlock", LAVA => "LavaBlock",
STILL_LAVA => "StillLavaBlock", STILL_LAVA => "StillLavaBlock",
SAND => "SandBlock", SAND => "SandBlock",
GRAVEL => "GravelBlock", GRAVEL => "GravelBlock",
GOLD_ORE => "GoldOreBlock", GOLD_ORE => "GoldOreBlock",
IRON_ORE => "IronOreBlock", IRON_ORE => "IronOreBlock",
COAL_ORE => "CoalOreBlock", COAL_ORE => "CoalOreBlock",
WOOD => "WoodBlock", WOOD => "WoodBlock",
LEAVES => "LeavesBlock", LEAVES => "LeavesBlock",
SPONGE => "SpongeBlock", SPONGE => "SpongeBlock",
GLASS => "GlassBlock", GLASS => "GlassBlock",
LAPIS_ORE => "LapisOreBlock", LAPIS_ORE => "LapisOreBlock",
LAPIS_BLOCK => "LapisBlock", LAPIS_BLOCK => "LapisBlock",
SANDSTONE => "SandstoneBlock", SANDSTONE => "SandstoneBlock",
BED_BLOCK => "BedBlock", BED_BLOCK => "BedBlock",
POWERED_RAIL => "PoweredRailBlock", POWERED_RAIL => "PoweredRailBlock",
COBWEB => "CobwebBlock", COBWEB => "CobwebBlock",
TALL_GRASS => "TallGrassBlock", TALL_GRASS => "TallGrassBlock",
DEAD_BUSH => "DeadBushBlock", DEAD_BUSH => "DeadBushBlock",
WOOL => "WoolBlock", WOOL => "WoolBlock",
DANDELION => "DandelionBlock", DANDELION => "DandelionBlock",
CYAN_FLOWER => "CyanFlowerBlock", CYAN_FLOWER => "CyanFlowerBlock",
BROWN_MUSHROOM => "BrownMushroomBlock", BROWN_MUSHROOM => "BrownMushroomBlock",
RED_MUSHROOM => "RedMushRoomBlock", RED_MUSHROOM => "RedMushRoomBlock",
GOLD_BLOCK => "GoldBlock", GOLD_BLOCK => "GoldBlock",
IRON_BLOCK => "IronBlock", IRON_BLOCK => "IronBlock",
DOUBLE_SLAB => "DoubleSlabBlock", DOUBLE_SLAB => "DoubleSlabBlock",
SLAB => "SlabBlock", SLAB => "SlabBlock",
BRICKS_BLOCK => "BricksBlock", BRICKS_BLOCK => "BricksBlock",
TNT => "TNTBlock", TNT => "TNTBlock",
BOOKSHELF => "BookshelfBlock", BOOKSHELF => "BookshelfBlock",
MOSS_STONE => "MossStoneBlock", MOSS_STONE => "MossStoneBlock",
OBSIDIAN => "ObsidianBlock", OBSIDIAN => "ObsidianBlock",
TORCH => "TorchBlock", TORCH => "TorchBlock",
FIRE => "FireBlock", FIRE => "FireBlock",
WOOD_STAIRS => "WoodStairsBlock", WOOD_STAIRS => "WoodStairsBlock",
CHEST => "ChestBlock", CHEST => "ChestBlock",
DIAMOND_ORE => "DiamondOreBlock", DIAMOND_ORE => "DiamondOreBlock",
DIAMOND_BLOCK => "DiamondBlock", DIAMOND_BLOCK => "DiamondBlock",
WORKBENCH => "WorkbenchBlock", WORKBENCH => "WorkbenchBlock",
WHEAT_BLOCK => "WheatBlock", WHEAT_BLOCK => "WheatBlock",
FARMLAND => "FarmlandBlock", FARMLAND => "FarmlandBlock",
FURNACE => "FurnaceBlock", FURNACE => "FurnaceBlock",
BURNING_FURNACE => "BurningFurnaceBlock", BURNING_FURNACE => "BurningFurnaceBlock",
SIGN_POST => "SignPostBlock", SIGN_POST => "SignPostBlock",
WOOD_DOOR_BLOCK => "WoodDoorBlock", WOOD_DOOR_BLOCK => "WoodDoorBlock",
LADDER => "LadderBlock", LADDER => "LadderBlock",
RAIL => "RailBlock", RAIL => "RailBlock",
COBBLESTONE_STAIRS => "CobblestoneStairsBlock", COBBLESTONE_STAIRS => "CobblestoneStairsBlock",
WALL_SIGN => "WallSignBlock", WALL_SIGN => "WallSignBlock",
IRON_DOOR_BLOCK => "IronDoorBlock", IRON_DOOR_BLOCK => "IronDoorBlock",
REDSTONE_ORE => "RedstoneOreBlock", REDSTONE_ORE => "RedstoneOreBlock",
GLOWING_REDSTONE_ORE => "GlowingRedstoneOreBlock", GLOWING_REDSTONE_ORE => "GlowingRedstoneOreBlock",
SNOW_LAYER => "SnowLayerBlock", SNOW_LAYER => "SnowLayerBlock",
ICE => "IceBlock", ICE => "IceBlock",
SNOW_BLOCK => "SnowBlock", SNOW_BLOCK => "SnowBlock",
CACTUS => "CactusBlock", CACTUS => "CactusBlock",
CLAY_BLOCK => "ClayBlock", CLAY_BLOCK => "ClayBlock",
SUGARCANE_BLOCK => "SugarcaneBlock", SUGARCANE_BLOCK => "SugarcaneBlock",
FENCE => "FenceBlock", FENCE => "FenceBlock",
PUMPKIN => "PumpkinBlock", PUMPKIN => "PumpkinBlock",
NETHERRACK => "NetherrackBlock", NETHERRACK => "NetherrackBlock",
SOUL_SAND => "SoulSandBlock", SOUL_SAND => "SoulSandBlock",
GLOWSTONE_BLOCK => "GlowstoneBlock", GLOWSTONE_BLOCK => "GlowstoneBlock",
LIT_PUMPKIN => "LitPumpkinBlock", LIT_PUMPKIN => "LitPumpkinBlock",
INVISIBLE_BEDROCK => "InvisibleBedrockBlock", INVISIBLE_BEDROCK => "InvisibleBedrockBlock",
CAKE_BLOCK => "CakeBlock",
TRAPDOOR => "TrapdoorBlock",
STONE_BRICKS => "StoneBricksBlock", CAKE_BLOCK => "CakeBlock",
IRON_BARS => "IronBarsBlock", TRAPDOOR => "TrapdoorBlock",
GLASS_PANE => "GlassPaneBlock",
MELON_BLOCK => "MelonBlock",
PUMPKIN_STEM => "PumpkinStemBlock",
MELON_STEM => "MelonStemBlock",
FENCE_GATE => "FenceGateBlock", STONE_BRICKS => "StoneBricksBlock",
BRICK_STAIRS => "BrickStairsBlock",
STONE_BRICK_STAIRS => "StoneBrickStairsBlock",
NETHER_BRICKS => "NetherBricksBlock", IRON_BARS => "IronBarsBlock",
GLASS_PANE => "GlassPaneBlock",
MELON_BLOCK => "MelonBlock",
PUMPKIN_STEM => "PumpkinStemBlock",
MELON_STEM => "MelonStemBlock",
NETHER_BRICKS_STAIRS => "NetherBricksStairsBlock", FENCE_GATE => "FenceGateBlock",
BRICK_STAIRS => "BrickStairsBlock",
STONE_BRICK_STAIRS => "StoneBrickStairsBlock",
SANDSTONE_STAIRS => "SandstoneStairsBlock", NETHER_BRICKS => "NetherBricksBlock",
SPRUCE_WOOD_STAIRS => "SpruceWoodStairsBlock",
BIRCH_WOOD_STAIRS => "BirchWoodStairsBlock",
JUNGLE_WOOD_STAIRS => "JungleWoodStairsBlock",
STONE_WALL => "StoneWallBlock",
CARROT_BLOCK => "CarrotBlock",
POTATO_BLOCK => "PotatoBlock",
QUARTZ_BLOCK => "QuartzBlock", NETHER_BRICKS_STAIRS => "NetherBricksStairsBlock",
QUARTZ_STAIRS => "QuartzStairsBlock",
DOUBLE_WOOD_SLAB => "DoubleWoodSlabBlock", SANDSTONE_STAIRS => "SandstoneStairsBlock",
WOOD_SLAB => "WoodSlabBlock",
SPRUCE_WOOD_STAIRS => "SpruceWoodStairsBlock",
HAY_BALE => "HayBaleBlock", BIRCH_WOOD_STAIRS => "BirchWoodStairsBlock",
CARPET => "CarpetBlock", JUNGLE_WOOD_STAIRS => "JungleWoodStairsBlock",
STONE_WALL => "StoneWallBlock",
COAL_BLOCK => "CoalBlock",
CARROT_BLOCK => "CarrotBlock",
BEETROOT_BLOCK => "BeetrootBlock", POTATO_BLOCK => "PotatoBlock",
STONECUTTER => "StonecutterBlock",
GLOWING_OBSIDIAN => "GlowingObsidianBlock", QUARTZ_BLOCK => "QuartzBlock",
NETHER_REACTOR => "NetherReactorBlock", QUARTZ_STAIRS => "QuartzStairsBlock",
INFO_UPDATE => "InfoUpdateBlock", DOUBLE_WOOD_SLAB => "DoubleWoodSlabBlock",
INFO_UPDATE2 => "InfoUpdate2Block", WOOD_SLAB => "WoodSlabBlock",
RESERVED6 => "Reserved6Block",
); 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",
];
public $id; public $id;
public $meta; public $meta;
public $name; public $name;
@ -155,50 +155,50 @@ abstract class Block extends Position{
public $z = 0; public $z = 0;
public $slipperiness; public $slipperiness;
public static function interact(Level $level, $x, $y, $z, Player $player){} 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 neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){}
public static function getAABB(Level $level, $x, $y, $z){ public static function getAABB(Level $level, $x, $y, $z){
return StaticBlock::getAABB(static::$blockID, $x, $y, $z); return StaticBlock::getAABB(static::$blockID, $x, $y, $z);
} }
public static function containsX($id, $v){ 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]; 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){ 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]; 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){ 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]; 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 updateShape(Level $level, $x, $y, $z){
} }
public static function clip(Level $level, $x, $y, $z, Vector3 $start, Vector3 $end){ public static function clip(Level $level, $x, $y, $z, Vector3 $start, Vector3 $end){
static::updateShape($level, $x, $y, $z); static::updateShape($level, $x, $y, $z);
$id = $level->level->getBlockID($x, $y, $z); $id = $level->level->getBlockID($x, $y, $z);
$start = $start->subtract($x, $y, $z); $start = $start->subtract($x, $y, $z);
$end = $end->subtract($x, $y, $z); $end = $end->subtract($x, $y, $z);
$v7 = $start->clipX($end, StaticBlock::$minXs[$id]); $v7 = $start->clipX($end, StaticBlock::$minXs[$id]);
$v8 = $start->clipX($end, StaticBlock::$maxXs[$id]); $v8 = $start->clipX($end, StaticBlock::$maxXs[$id]);
$v9 = $start->clipY($end, StaticBlock::$minYs[$id]); $v9 = $start->clipY($end, StaticBlock::$minYs[$id]);
$v10 = $start->clipY($end, StaticBlock::$maxYs[$id]); $v10 = $start->clipY($end, StaticBlock::$maxYs[$id]);
$v11 = $start->clipZ($end, StaticBlock::$minZs[$id]); $v11 = $start->clipZ($end, StaticBlock::$minZs[$id]);
$v12 = $start->clipZ($end, StaticBlock::$maxZs[$id]); $v12 = $start->clipZ($end, StaticBlock::$maxZs[$id]);
if(!self::containsX($id, $v7)) $v7 = null; if(!self::containsX($id, $v7)) $v7 = null;
if(!self::containsX($id, $v8)) $v8 = null; if(!self::containsX($id, $v8)) $v8 = null;
if(!self::containsY($id, $v9)) $v9 = null; if(!self::containsY($id, $v9)) $v9 = null;
if(!self::containsY($id, $v10)) $v10 = null; if(!self::containsY($id, $v10)) $v10 = null;
if(!self::containsZ($id, $v11)) $v11 = null; if(!self::containsZ($id, $v11)) $v11 = null;
if(!self::containsZ($id, $v12)) $v12 = null; if(!self::containsZ($id, $v12)) $v12 = null;
$v13 = null; $v13 = null;
if($v7 != null && ($v13 == null || $start->distanceSquared($v7) < $start->distanceSquared($v13))) $v13 = $v7; 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; if($v8 != null && ($v13 == null || $start->distanceSquared($v8) < $start->distanceSquared($v13))) $v13 = $v8;
@ -206,9 +206,9 @@ abstract class Block extends Position{
if($v10 != null && ($v13 == null || $start->distanceSquared($v10) < $start->distanceSquared($v13))) $v13 = $v10; 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($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($v12 != null && ($v13 == null || $start->distanceSquared($v12) < $start->distanceSquared($v13))) $v13 = $v12;
if($v13 == null) return null; if($v13 == null) return null;
$v14 = -1; $v14 = -1;
if($v13 == $v7) $v14 = 4; if($v13 == $v7) $v14 = 4;
if($v13 == $v8) $v14 = 5; if($v13 == $v8) $v14 = 5;
@ -216,10 +216,10 @@ abstract class Block extends Position{
if($v13 == $v10) $v14 = 1; if($v13 == $v10) $v14 = 1;
if($v13 == $v11) $v14 = 2; if($v13 == $v11) $v14 = 2;
if($v13 == $v12) $v14 = 3; if($v13 == $v12) $v14 = 3;
return MovingObjectPosition::fromBlock($x, $y, $z, $v14, $v13->add($x, $y, $z)); return MovingObjectPosition::fromBlock($x, $y, $z, $v14, $v13->add($x, $y, $z));
} }
public static function onPlace(Level $level, $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 addVelocityToEntity(Level $level, $x, $y, $z, Entity $entity, Vector3 $velocityVector){}
public static function onRandomTick(Level $level, $x, $y, $z){} public static function onRandomTick(Level $level, $x, $y, $z){}
@ -229,8 +229,7 @@ abstract class Block extends Position{
return [static::getAABB($level, $x, $y, $z)]; return [static::getAABB($level, $x, $y, $z)];
} }
public static function onEntityCollidedWithBlock(Level $level, $x, $y, $z, Entity $entity){} public static function onEntityCollidedWithBlock(Level $level, $x, $y, $z, Entity $entity){}
public function __construct($id, $meta = 0, $name = "Unknown"){ public function __construct($id, $meta = 0, $name = "Unknown"){
$this->id = (int) $id; $this->id = (int) $id;
$this->meta = (int) $meta; $this->meta = (int) $meta;
@ -240,15 +239,15 @@ abstract class Block extends Position{
$this->slipperiness = 0.6; $this->slipperiness = 0.6;
$this->boundingBox = new AxisAlignedBB($this->x, $this->y, $this->z, $this->x + 1, $this->y + 1, $this->z + 1); $this->boundingBox = new AxisAlignedBB($this->x, $this->y, $this->z, $this->x + 1, $this->y + 1, $this->z + 1);
} }
final public function getHardness(){ final public function getHardness(){
return ($this->hardness); return ($this->hardness);
} }
final public function getName(){ final public function getName(){
return $this->name; return $this->name;
} }
final public function getID(){ final public function getID(){
return $this->id; return $this->id;
} }
@ -258,7 +257,7 @@ abstract class Block extends Position{
final public function getMetadata(){ final public function getMetadata(){
return $this->meta & 0x0F; return $this->meta & 0x0F;
} }
final public function position(Position $v){ final public function position(Position $v){
$this->level = $v->level; $this->level = $v->level;
$this->x = (int) $v->x; $this->x = (int) $v->x;
@ -266,24 +265,24 @@ abstract class Block extends Position{
$this->z = (int) $v->z; $this->z = (int) $v->z;
$this->boundingBox->setBounds($this->x, $this->y, $this->z, $this->x + 1, $this->y + 1, $this->z + 1); $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){ public function getDrops(Item $item, Player $player){
if(!isset(Block::$class[$this->id])){ //Unknown blocks if(!isset(Block::$class[$this->id])){ //Unknown blocks
return array(); return [];
}else{ }else{
return array( return [
array($this->id, $this->meta, 1), [$this->id, $this->meta, 1],
); ];
} }
} }
public function getBreakTime(Item $item, Player $player){ public function getBreakTime(Item $item, Player $player){
if(($player->gamemode & 0x01) === 0x01){ if(($player->gamemode & 0x01) === 0x01){
return 0.15; return 0.15;
} }
return $this->breakTime; return $this->breakTime;
} }
public function getSide($side, $step = 1){ public function getSide($side, $step = 1){
$v = parent::getSide($side, $step); $v = parent::getSide($side, $step);
if($this->level instanceof Level){ if($this->level instanceof Level){
@ -291,17 +290,17 @@ abstract class Block extends Position{
} }
return $v; return $v;
} }
final public function __toString(){ final public function __toString(){
return "Block ". $this->name ." (".$this->id.":".$this->meta.")"; return "Block " . $this->name . " (" . $this->id . ":" . $this->meta . ")";
} }
abstract function isBreakable(Item $item, Player $player); abstract function isBreakable(Item $item, Player $player);
abstract function onBreak(Item $item, Player $player); abstract function onBreak(Item $item, Player $player);
abstract function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz); abstract function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz);
abstract function onActivate(Item $item, Player $player); abstract function onActivate(Item $item, Player $player);
} }

View file

@ -5,12 +5,12 @@ class Item{
const TOOL_PICKAXE = 1; const TOOL_PICKAXE = 1;
const TOOL_AXE = 2; const TOOL_AXE = 2;
const TOOL_SHOVEL = 3; const TOOL_SHOVEL = 3;
const TOOL_HOE = 4; const TOOL_HOE = 4;
const DEF_DAMAGE = 1; const DEF_DAMAGE = 1;
public static $class = array( public static $class = [
//armor //armor
LEATHER_CAP => "LeatherCapItem", LEATHER_CAP => "LeatherCapItem",
LEATHER_TUNIC => "LeatherTunicItem", LEATHER_TUNIC => "LeatherTunicItem",
@ -32,7 +32,7 @@ class Item{
GOLDEN_CHESTPLATE => "GoldenChestplateItem", GOLDEN_CHESTPLATE => "GoldenChestplateItem",
GOLDEN_LEGGINGS => "GoldenLeggingsItem", GOLDEN_LEGGINGS => "GoldenLeggingsItem",
GOLDEN_BOOTS => "GoldenBootsItem", GOLDEN_BOOTS => "GoldenBootsItem",
//food //food
APPLE => "AppleItem", APPLE => "AppleItem",
MUSHROOM_STEW => "MushroomStewItem", MUSHROOM_STEW => "MushroomStewItem",
@ -51,7 +51,7 @@ class Item{
PUMPKIN_PIE => "PumpkinPieItem", PUMPKIN_PIE => "PumpkinPieItem",
BEETROOT => "BeetrootItem", BEETROOT => "BeetrootItem",
BEETROOT_SOUP => "BeetrootSoupItem", BEETROOT_SOUP => "BeetrootSoupItem",
//generic //generic
ARROW => "ArrowItem", ARROW => "ArrowItem",
COAL => "CoalItem", COAL => "CoalItem",
@ -95,7 +95,7 @@ class Item{
QUARTZ => "QuartzItem", QUARTZ => "QuartzItem",
CAMERA => "CameraItem", CAMERA => "CameraItem",
BEETROOT_SEEDS => "BeetrootSeedsItem", BEETROOT_SEEDS => "BeetrootSeedsItem",
//tool //tool
IRON_SHOVEL => "IronShovelItem", IRON_SHOVEL => "IronShovelItem",
IRON_PICKAXE => "IronPickaxeItem", IRON_PICKAXE => "IronPickaxeItem",
@ -127,21 +127,21 @@ class Item{
COMPASS => "CompassItem", COMPASS => "CompassItem",
CLOCK => "ClockItem", CLOCK => "ClockItem",
SHEARS => "ShearsItem", SHEARS => "ShearsItem",
); ];
public $block; public $block;
public $id; public $id;
public $meta; public $meta;
public $count; public $count;
/** /**
* @var int * @var int
* Max stack size of the item. Use Item::getMaxStackSize to get stack size for specific item. * Max stack size of the item. Use Item::getMaxStackSize to get stack size for specific item.
*/ */
public $maxStackSize = 64; public $maxStackSize = 64;
public $durability = 0; public $durability = 0;
public $name; public $name;
public $isActivable = false; public $isActivable = false;
public function __construct($id, $meta = 0, $count = 1, $name = "Unknown"){ public function __construct($id, $meta = 0, $count = 1, $name = "Unknown"){
$this->id = (int) $id; $this->id = (int) $id;
$this->meta = (int) $meta; $this->meta = (int) $meta;
@ -155,19 +155,19 @@ class Item{
$this->maxStackSize = 1; $this->maxStackSize = 1;
} }
} }
public function isPickaxe(){ public function isPickaxe(){
return false; return false;
} }
public function getName(){ public function getName(){
return $this->name; return $this->name;
} }
public function isPlaceable(){ public function isPlaceable(){
return (($this->block instanceof Block) and $this->block->isPlaceable === true); return (($this->block instanceof Block) and $this->block->isPlaceable === true);
} }
public function getBlock(){ public function getBlock(){
if($this->block instanceof Block){ if($this->block instanceof Block){
return $this->block; return $this->block;
@ -175,23 +175,23 @@ class Item{
return BlockAPI::get(AIR); return BlockAPI::get(AIR);
} }
} }
public function getID(){ public function getID(){
return $this->id; return $this->id;
} }
public function getMetadata(){ public function getMetadata(){
return $this->meta; return $this->meta;
} }
public function isArmor(){ public function isArmor(){
return false; return false;
} }
public function getMaxStackSize(){ public function getMaxStackSize(){
return $this->maxStackSize; return $this->maxStackSize;
} }
public function getFuelTime(){ public function getFuelTime(){
if(!isset(FuelData::$duration[$this->id])){ if(!isset(FuelData::$duration[$this->id])){
return false; return false;
@ -201,24 +201,24 @@ class Item{
} }
return false; return false;
} }
public function getSmeltItem(){ public function getSmeltItem(){
if(!isset(SmeltingData::$product[$this->id])){ if(!isset(SmeltingData::$product[$this->id])){
return false; return false;
} }
if(isset(SmeltingData::$product[$this->id][0]) and !is_array(SmeltingData::$product[$this->id][0])){ 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]); return BlockAPI::getItem(SmeltingData::$product[$this->id][0], SmeltingData::$product[$this->id][1]);
} }
if(!isset(SmeltingData::$product[$this->id][$this->meta])){ if(!isset(SmeltingData::$product[$this->id][$this->meta])){
return false; return false;
} }
return BlockAPI::getItem(SmeltingData::$product[$this->id][$this->meta][0], SmeltingData::$product[$this->id][$this->meta][1]); return BlockAPI::getItem(SmeltingData::$product[$this->id][$this->meta][0], SmeltingData::$product[$this->id][$this->meta][1]);
} }
public function useOn($object, $force = false){ public function useOn($object, $force = false){
if($force){ if($force){
if(($object instanceof Entity) and !$this->isSword()){ if(($object instanceof Entity) and !$this->isSword()){
@ -230,16 +230,16 @@ class Item{
} }
return false; return false;
} }
public function isTool(){ public function isTool(){
return false; return false;
} }
public function getMaxDurability(){ public function getMaxDurability(){
if(!$this->isTool() and $this->id !== BOW){ if(!$this->isTool() and $this->id !== BOW){
return false; return false;
} }
$levels = [ //TODO rewrite(item usage too) $levels = [ //TODO rewrite(item usage too)
2 => 33, //GOLD 2 => 33, //GOLD
1 => 60, //WOODEN 1 => 60, //WOODEN
@ -256,14 +256,14 @@ class Item{
} }
return $levels[$type]; return $levels[$type];
} }
public function getLevel(){ public function getLevel(){
return false; return false;
} }
//TODO remove? //TODO remove?
public function getPickaxeLevel(){ //Returns false or level of the pickaxe public function getPickaxeLevel(){ //Returns false or level of the pickaxe
return match ($this->id) { return match ($this->id) {
WOODEN_PICKAXE => 1, WOODEN_PICKAXE => 1,
GOLDEN_PICKAXE => 2, GOLDEN_PICKAXE => 2,
STONE_PICKAXE => 3, STONE_PICKAXE => 3,
@ -272,7 +272,7 @@ class Item{
default => false, default => false,
}; };
} }
public function isAxe(){ public function isAxe(){
return false; return false;
} }
@ -280,11 +280,11 @@ class Item{
public function isSword(){ public function isSword(){
return false; return false;
} }
public function isShovel(){ public function isShovel(){
return false; return false;
} }
public function isHoe(){ public function isHoe(){
return false; return false;
} }
@ -292,23 +292,23 @@ class Item{
public function isShears(){ public function isShears(){
return ($this->id === SHEARS); return ($this->id === SHEARS);
} }
public function __toString(){ public function __toString(){
return "Item ". $this->name ." (".$this->id.":".$this->meta.")"; return "Item " . $this->name . " (" . $this->id . ":" . $this->meta . ")";
} }
public function getDamageAgainstOf($e){ public function getDamageAgainstOf($e){
return Item::DEF_DAMAGE; return Item::DEF_DAMAGE;
} }
public function getDestroySpeed(Block $block, Player $player){ public function getDestroySpeed(Block $block, Player $player){
return 1; return 1;
} }
public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
return false; return false;
} }
public static function getFoodHeal($id){ public static function getFoodHeal($id){
return match($id){ return match($id){
APPLE => 4, APPLE => 4,
@ -328,9 +328,9 @@ class Item{
POTATO => 1, POTATO => 1,
BAKED_POTATO => 6, BAKED_POTATO => 6,
BEETROOT => 1, BEETROOT => 1,
default => 0 default => 0
}; };
} }
} }

View file

@ -1,4 +1,5 @@
<?php <?php
/*value - durability*/ /*value - durability*/
class Material{ class Material{
const LEATHER = 5; //when enums const LEATHER = 5; //when enums

View file

@ -6,7 +6,7 @@ class StaticBlock
{ {
const DEFAULT_SLIPPERINESS = 0.6; const DEFAULT_SLIPPERINESS = 0.6;
const DEFAULT_HARDNESS = 0; const DEFAULT_HARDNESS = 0;
private static $NULL_BOUNDS; private static $NULL_BOUNDS;
public static $prealloc = []; public static $prealloc = [];
public static $isSolid = []; public static $isSolid = [];
@ -17,18 +17,18 @@ class StaticBlock
public static $hasPhysics = []; public static $hasPhysics = [];
public static $isLiquid = []; public static $isLiquid = [];
public static $isFullBlock = []; public static $isFullBlock = [];
public static $hardness = []; public static $hardness = [];
public static $slipperiness = []; public static $slipperiness = [];
public static $boundingBoxes = []; public static $boundingBoxes = [];
public static $minXs = [], $minYs = [], $minZs = [], $maxXs = [], $maxYs = [], $maxZs = []; public static $minXs = [], $minYs = [], $minZs = [], $maxXs = [], $maxYs = [], $maxZs = [];
public static function init(){ public static function init(){
self::$NULL_BOUNDS = new AxisAlignedBB(0, 0, 0, 0, 0, 0); self::$NULL_BOUNDS = new AxisAlignedBB(0, 0, 0, 0, 0, 0);
foreach(Block::$class as $nonstaticname){ foreach(Block::$class as $nonstaticname){
/**@var Block $b*/ /**@var Block $b*/
$b = new $nonstaticname(); $b = new $nonstaticname();
self::$isSolid[$b->getID()] = $b->isSolid; self::$isSolid[$b->getID()] = $b->isSolid;
self::$isTransparent[$b->getID()] = $b->isTransparent; self::$isTransparent[$b->getID()] = $b->isTransparent;
self::$isFlowable[$b->getID()] = $b->isFlowable; self::$isFlowable[$b->getID()] = $b->isFlowable;
@ -45,7 +45,7 @@ class StaticBlock
FireBlock::setFlammabilityAndCatchingChance($b->getID(), 0, 0); FireBlock::setFlammabilityAndCatchingChance($b->getID(), 0, 0);
self::setBlockBounds($b->getID(), 0, 0, 0, 1, 1, 1); self::setBlockBounds($b->getID(), 0, 0, 0, 1, 1, 1);
} }
self::setBlockBounds(BED_BLOCK, 0, 0, 0, 1, 0.5625, 1); self::setBlockBounds(BED_BLOCK, 0, 0, 0, 1, 0.5625, 1);
//Cake: has bounds based on world state //Cake: has bounds based on world state
//Chest: has bounds based on world state //Chest: has bounds based on world state
@ -68,16 +68,16 @@ class StaticBlock
self::setBlockBounds(SLAB, 0, 0, 0, 1, 0.5, 1); self::setBlockBounds(SLAB, 0, 0, 0, 1, 0.5, 1);
self::setBlockBounds(RAIL, 0, 0, 0, 1, 0.125, 1); self::setBlockBounds(RAIL, 0, 0, 0, 1, 0.125, 1);
self::setBlockBounds(POWERED_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(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(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(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(SNOW_LAYER, 0, 0, 0, 1, 0.125, 1);
self::setBlockBounds(CARPET, 0, 0, 0, 1, 0, 1); self::setBlockBounds(CARPET, 0, 0, 0, 1, 0, 1);
//Stairs: based on different factors //Stairs: based on different factors
//Stone wall: based on state //Stone wall: based on state
//Fire related stuff //Fire related stuff
FireBlock::setFlammabilityAndCatchingChance(PLANKS, 5, 20); FireBlock::setFlammabilityAndCatchingChance(PLANKS, 5, 20);
FireBlock::setFlammabilityAndCatchingChance(DOUBLE_WOOD_SLAB, 5, 20); FireBlock::setFlammabilityAndCatchingChance(DOUBLE_WOOD_SLAB, 5, 20);
@ -101,29 +101,29 @@ class StaticBlock
FireBlock::setFlammabilityAndCatchingChance(HAY_BALE, 60, 20); FireBlock::setFlammabilityAndCatchingChance(HAY_BALE, 60, 20);
FireBlock::setFlammabilityAndCatchingChance(SPONGE, 30, 60); FireBlock::setFlammabilityAndCatchingChance(SPONGE, 30, 60);
} }
public static function setBlockBounds($blockID, $minX, $minY, $minZ, $maxX, $maxY, $maxZ){ public static function setBlockBounds($blockID, $minX, $minY, $minZ, $maxX, $maxY, $maxZ){
self::$maxXs[$blockID] = $maxX; self::$maxXs[$blockID] = $maxX;
self::$maxYs[$blockID] = $maxY; self::$maxYs[$blockID] = $maxY;
self::$maxZs[$blockID] = $maxZ; self::$maxZs[$blockID] = $maxZ;
self::$minXs[$blockID] = $minX; self::$minXs[$blockID] = $minX;
self::$minYs[$blockID] = $minY; self::$minYs[$blockID] = $minY;
self::$minZs[$blockID] = $minZ; self::$minZs[$blockID] = $minZ;
} }
public static function getAABB($id, $x, $y, $z){ 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 ? 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){ public static function getBlock($id){
return self::$prealloc[$id] ?? self::$prealloc[0]; //accessing preallocated instances is faster Block::$class[$id] ?? Block::$class[0]; return self::$prealloc[$id] ?? self::$prealloc[0]; //accessing preallocated instances is faster Block::$class[$id] ?? Block::$class[0];
} }
public static function getHardness($id){ 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 //TODO: use static block min/max
public static function getBoundingBoxForBlockCoords($id, $x, $y, $z){ public static function getBoundingBoxForBlockCoords($id, $x, $y, $z){
/**@var AxisAlignedBB $bb*/ /**@var AxisAlignedBB $bb*/
@ -134,40 +134,39 @@ class StaticBlock
$bb = clone $bb; $bb = clone $bb;
return $bb->setBounds($x + $bb->minX, $y + $bb->minY, $z + $bb->minZ, $x + $bb->maxX, $y + $bb->maxY, $z + $bb->maxZ); 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){ public static function getSlipperiness($id){
return self::$slipperiness[$id] ?? StaticBlock::DEFAULT_SLIPPERINESS; return self::$slipperiness[$id] ?? StaticBlock::DEFAULT_SLIPPERINESS;
} }
public static function getIsSolid($id){ public static function getIsSolid($id){
return self::$isSolid[$id] ?? false; return self::$isSolid[$id] ?? false;
} }
public static function getIsTransparent($id){ public static function getIsTransparent($id){
return self::$isTransparent[$id] ?? false; return self::$isTransparent[$id] ?? false;
} }
public static function getIsFlowable($id){ public static function getIsFlowable($id){
return self::$isFlowable[$id] ?? false; return self::$isFlowable[$id] ?? false;
} }
public static function getIsReplaceable($id){ public static function getIsReplaceable($id){
return self::$isReplaceable[$id] ?? false; return self::$isReplaceable[$id] ?? false;
} }
public static function getIsPlaceable($id){ public static function getIsPlaceable($id){
return self::$isPlaceable[$id] ?? false; return self::$isPlaceable[$id] ?? false;
} }
public static function getHasPhysics($id){ public static function getHasPhysics($id){
return self::$hasPhysics[$id] ?? false; return self::$hasPhysics[$id] ?? false;
} }
public static function getIsLiquid($id){ public static function getIsLiquid($id){
return self::$isLiquid[$id] ?? false; return self::$isLiquid[$id] ?? false;
} }
public static function getIsFullBlock($id){ public static function getIsFullBlock($id){
return self::$isFullBlock[$id] ?? false; return self::$isFullBlock[$id] ?? false;
} }

View file

@ -86,14 +86,13 @@ class DoorBlock extends TransparentBlock{
} }
break; break;
} }
return [$aabb->offset($x, $y, $z)]; return [$aabb->offset($x, $y, $z)];
} }
public static function getCompositeData(Level $level, $x, $y, $z){ public static function getCompositeData(Level $level, $x, $y, $z){
$myMeta = $level->level->getBlockDamage($x, $y, $z); $myMeta = $level->level->getBlockDamage($x, $y, $z);
if(($myMeta & 8) != 0){ if(($myMeta & 8) != 0){
$metaLower = $level->level->getBlockDamage($x, $y - 1, $z); $metaLower = $level->level->getBlockDamage($x, $y - 1, $z);
$metaUpper = $myMeta; $metaUpper = $myMeta;
@ -101,19 +100,18 @@ class DoorBlock extends TransparentBlock{
$metaLower = $myMeta; $metaLower = $myMeta;
$metaUpper = $level->level->getBlockDamage($x, $y + 1, $z); $metaUpper = $level->level->getBlockDamage($x, $y + 1, $z);
} }
return $metaLower & 7 | (($myMeta & 8) != 0 ? 8 : 0) | (($metaUpper & 1 != 0) ? 16 : 0); 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){ 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){ //Replace with common break method
$level->fastSetBlockUpdate($x, $y, $z, 0, 0); $level->fastSetBlockUpdate($x, $y, $z, 0, 0);
$id = $level->level->getBlockID($x, $y, $z); $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)); 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)); elseif($id == 71) ServerAPI::request()->api->entity->drop(new Position($x + 0.5, $y, $z + 0.5, $level), BlockAPI::getItem(330, 0, 1));
$top = $level->level->getBlockID($x, $y + 1, $z); $top = $level->level->getBlockID($x, $y + 1, $z);
if($top == IRON_DOOR_BLOCK || $top == DOOR_BLOCK){ if($top == IRON_DOOR_BLOCK || $top == DOOR_BLOCK){
$level->fastSetBlockUpdate($x, $y + 1, $z, 0, 0); $level->fastSetBlockUpdate($x, $y + 1, $z, 0, 0);
@ -121,12 +119,7 @@ class DoorBlock extends TransparentBlock{
} }
} }
/** /**
* @param Item $item
* @param Player $player
* @param Block $block
* @param Block $target
* @param integer $face * @param integer $face
* @param integer $fx * @param integer $fx
* @param integer $fy * @param integer $fy
@ -142,12 +135,12 @@ class DoorBlock extends TransparentBlock{
return false; return false;
} }
$direction = $player->entity->getDirection(); $direction = $player->entity->getDirection();
$face = array( $face = [
0 => 3, 0 => 3,
1 => 4, 1 => 4,
2 => 2, 2 => 2,
3 => 5, 3 => 5,
); ];
$next = $this->getSide($face[(($direction + 2) % 4)]); $next = $this->getSide($face[(($direction + 2) % 4)]);
$next2 = $this->getSide($face[$direction]); $next2 = $this->getSide($face[$direction]);
$metaUp = 0x08; $metaUp = 0x08;
@ -155,17 +148,15 @@ class DoorBlock extends TransparentBlock{
$metaUp |= 0x01; $metaUp |= 0x01;
} }
$this->level->setBlock($blockUp, BlockAPI::get($this->id, $metaUp), true, false, true); //Top $this->level->setBlock($blockUp, BlockAPI::get($this->id, $metaUp), true, false, true); //Top
$this->meta = $direction & 0x03; $this->meta = $direction & 0x03;
$this->level->setBlock($block, $this, true, false, true); //Bottom $this->level->setBlock($block, $this, true, false, true); //Bottom
return true; return true;
} }
return false; return false;
} }
/** /**
* @param Item $item
* @param Player $player
* *
* @return boolean * @return boolean
*/ */
@ -186,8 +177,6 @@ class DoorBlock extends TransparentBlock{
} }
/** /**
* @param Item $item
* @param Player $player
* *
* @return boolean * @return boolean
*/ */

View file

@ -12,10 +12,6 @@ class FallableBlock extends SolidBlock{
} }
/** /**
* @param Item $item
* @param Player $player
* @param Block $block
* @param Block $target
* @param int $face * @param int $face
* @param int $fx * @param int $fx
* @param int $fy * @param int $fy

View file

@ -1,6 +1,5 @@
<?php <?php
class GenericBlock extends Block{ class GenericBlock extends Block{
/** /**
* @param int $id * @param int $id
@ -12,10 +11,6 @@ class GenericBlock extends Block{
} }
/** /**
* @param Item $item
* @param Player $player
* @param Block $block
* @param Block $target
* @param integer $face * @param integer $face
* @param integer $fx * @param integer $fx
* @param integer $fy * @param integer $fy
@ -28,8 +23,6 @@ class GenericBlock extends Block{
} }
/** /**
* @param Item $item
* @param Player $player
* *
* @return boolean * @return boolean
*/ */
@ -38,8 +31,6 @@ class GenericBlock extends Block{
} }
/** /**
* @param Item $item
* @param Player $player
* *
* @return mixed * @return mixed
*/ */
@ -55,26 +46,25 @@ class GenericBlock extends Block{
parent::onPlace($level, $x, $y, $z); parent::onPlace($level, $x, $y, $z);
} }
} }
public static function onUpdate(Level $level, $x, $y, $z, $type){ public static function onUpdate(Level $level, $x, $y, $z, $type){
[$id, $meta] = $level->level->getBlock($x, $y, $z); [$id, $meta] = $level->level->getBlock($x, $y, $z);
$down = $level->level->getBlockID($x, $y - 1, $z); $down = $level->level->getBlockID($x, $y - 1, $z);
if($down == AIR || StaticBlock::getIsLiquid($down)){ if($down == AIR || StaticBlock::getIsLiquid($down)){
$data = array( $data = [
"x" => $x + 0.5, "x" => $x + 0.5,
"y" => $y - 0.5, "y" => $y - 0.5,
"z" => $z + 0.5, "z" => $z + 0.5,
"Tile" => $id, "Tile" => $id,
); ];
$server = ServerAPI::request(); $server = ServerAPI::request();
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
$e = $server->api->entity->add($level, ENTITY_FALLING, FALLING_SAND, $data); $e = $server->api->entity->add($level, ENTITY_FALLING, FALLING_SAND, $data);
$server->api->entity->spawnToAll($e); $server->api->entity->spawnToAll($e);
} }
} }
/** /**
* @param integer $type
* *
* @return boolean * @return boolean
*/ */
@ -86,8 +76,6 @@ class GenericBlock extends Block{
} }
/** /**
* @param Item $item
* @param Player $player
* *
* @return boolean * @return boolean
*/ */

View file

@ -21,14 +21,14 @@ class LiquidBlock extends TransparentBlock{
return match(static::$blockID){ return match(static::$blockID){
WATER, STILL_WATER => $id == WATER || $id == STILL_WATER ? $meta : -1, WATER, STILL_WATER => $id == WATER || $id == STILL_WATER ? $meta : -1,
LAVA, STILL_LAVA => $id == LAVA || $id == STILL_LAVA ? $meta : -1, LAVA, STILL_LAVA => $id == LAVA || $id == STILL_LAVA ? $meta : -1,
default=> -1 default => -1
}; };
} }
public static function onPlace(Level $level, $x, $y, $z){ public static function onPlace(Level $level, $x, $y, $z){
static::updateLiquid($level, $x, $y, $z); static::updateLiquid($level, $x, $y, $z);
} }
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
static::updateLiquid($level, $x, $y, $z); static::updateLiquid($level, $x, $y, $z);
} }
@ -40,10 +40,10 @@ class LiquidBlock extends TransparentBlock{
$f = ($meta + 1) / 9; $f = ($meta + 1) / 9;
return $f; return $f;
} }
public static function getRenderedDepth(Level $level, $x, $y, $z){ public static function getRenderedDepth(Level $level, $x, $y, $z){
[$id, $meta] = $level->level->getBlock($x, $y, $z); [$id, $meta] = $level->level->getBlock($x, $y, $z);
$cond = match($id){ $cond = match($id){
WATER, STILL_WATER => static::$blockID == WATER || static::$blockID == STILL_WATER, WATER, STILL_WATER => static::$blockID == WATER || static::$blockID == STILL_WATER,
LAVA, STILL_LAVA => static::$blockID == LAVA || static::$blockID == STILL_LAVA, LAVA, STILL_LAVA => static::$blockID == LAVA || static::$blockID == STILL_LAVA,
@ -52,23 +52,23 @@ class LiquidBlock extends TransparentBlock{
if(!$cond) return -1; if(!$cond) return -1;
return $meta >= 8 ? 0 : $meta; return $meta >= 8 ? 0 : $meta;
} }
public static function shouldRenderFace(Level $level, $x, $y, $z, $face){ public static function shouldRenderFace(Level $level, $x, $y, $z, $face){
$id = $level->level->getBlockID($x, $y, $z); $id = $level->level->getBlockID($x, $y, $z);
if($id == ICE) return false; if($id == ICE) return false;
if((($id == WATER || $id == STILL_WATER) && (static::$blockID == WATER || static::$blockID == STILL_WATER))) return false; if((($id == WATER || $id == STILL_WATER) && (static::$blockID == WATER || static::$blockID == STILL_WATER))) return false;
if((($id == LAVA || $id == STILL_LAVA) && (static::$blockID == LAVA || static::$blockID == STILL_LAVA))) return false; if((($id == LAVA || $id == STILL_LAVA) && (static::$blockID == LAVA || static::$blockID == STILL_LAVA))) return false;
if($face == 1) return true; if($face == 1) return true;
return StaticBlock::getIsSolid($id); return StaticBlock::getIsSolid($id);
//return parent::shouldRenderFace($level, $x, $y, $z, $face); //return parent::shouldRenderFace($level, $x, $y, $z, $face);
} }
public static function getFlow(Level $level, $x, $y, $z){ public static function getFlow(Level $level, $x, $y, $z){
$flowVector = new Vector3(0, 0, 0); $flowVector = new Vector3(0, 0, 0);
$v6 = static::getRenderedDepth($level, $x, $y, $z); $v6 = static::getRenderedDepth($level, $x, $y, $z);
for($v7 = 0; $v7 < 4; ++$v7){ for($v7 = 0; $v7 < 4; ++$v7){
$v8 = $x; $v8 = $x;
$v10 = $z; $v10 = $z;
@ -86,12 +86,12 @@ class LiquidBlock extends TransparentBlock{
++$v10; ++$v10;
break; break;
} }
$v11 = static::getRenderedDepth($level, $v8, $y, $v10); $v11 = static::getRenderedDepth($level, $v8, $y, $v10);
if($v11 < 0){ if($v11 < 0){
if(!StaticBlock::getIsSolid($level->level->getBlockID($v8, $y, $v10))){ //TODO material.blocksMovement if(!StaticBlock::getIsSolid($level->level->getBlockID($v8, $y, $v10))){ //TODO material.blocksMovement
$v11 = static::getRenderedDepth($level, $v8, $y - 1, $v10); $v11 = static::getRenderedDepth($level, $v8, $y - 1, $v10);
if($v11 >= 0){ if($v11 >= 0){
$v12 = $v11 - ($v6 - 8); $v12 = $v11 - ($v6 - 8);
$flowVector->x += ($v8 - $x) * $v12; $flowVector->x += ($v8 - $x) * $v12;
@ -99,29 +99,29 @@ class LiquidBlock extends TransparentBlock{
$flowVector->z += ($v10 - $z) * $v12; $flowVector->z += ($v10 - $z) * $v12;
} }
} }
}else if($v11 >= 0){ }elseif($v11 >= 0){
$v12 = $v11 - $v6; $v12 = $v11 - $v6;
$flowVector->x += ($v8 - $x) * $v12; $flowVector->x += ($v8 - $x) * $v12;
$flowVector->y += ($y - $y) * $v12; $flowVector->y += ($y - $y) * $v12;
$flowVector->z += ($v10 - $z) * $v12; $flowVector->z += ($v10 - $z) * $v12;
} }
} }
$meta = $level->level->getBlockDamage($x, $y, $z); $meta = $level->level->getBlockDamage($x, $y, $z);
if($meta >= 8){ if($meta >= 8){
$v13 = //TODO more vanilla way to do it $v13 = //TODO more vanilla way to do it
static::shouldRenderFace($level, $x, $y, $z - 1, 2) || static::shouldRenderFace($level, $x, $y, $z - 1, 2) ||
static::shouldRenderFace($level, $x, $y, $z + 1, 3) || static::shouldRenderFace($level, $x, $y, $z + 1, 3) ||
static::shouldRenderFace($level, $x - 1, $y, $z, 4) || static::shouldRenderFace($level, $x - 1, $y, $z, 4) ||
static::shouldRenderFace($level, $x + 1, $y, $z, 5) || static::shouldRenderFace($level, $x + 1, $y, $z, 5) ||
static::shouldRenderFace($level, $x, $y + 1, $z - 1, 2) || static::shouldRenderFace($level, $x, $y + 1, $z - 1, 2) ||
static::shouldRenderFace($level, $x, $y + 1, $z + 1, 3) || static::shouldRenderFace($level, $x, $y + 1, $z + 1, 3) ||
static::shouldRenderFace($level, $x - 1, $y + 1, $z, 4) || static::shouldRenderFace($level, $x - 1, $y + 1, $z, 4) ||
static::shouldRenderFace($level, $x + 1, $y + 1, $z, 5) static::shouldRenderFace($level, $x + 1, $y + 1, $z, 5)
; ;
if($v13){ if($v13){
$ln = $flowVector->length(); $ln = $flowVector->length();
if($ln){ if($ln){
@ -141,37 +141,37 @@ class LiquidBlock extends TransparentBlock{
}else{ }else{
$flowVector->x = $flowVector->y = $flowVector->z = 0; $flowVector->x = $flowVector->y = $flowVector->z = 0;
} }
return $flowVector; return $flowVector;
} }
public static function addVelocityToEntity(Level $level, $x, $y, $z, Entity $entity, Vector3 $velocityVector){ public static function addVelocityToEntity(Level $level, $x, $y, $z, Entity $entity, Vector3 $velocityVector){
$flow = static::getFlow($level, $x, $y, $z); $flow = static::getFlow($level, $x, $y, $z);
$velocityVector->x += $flow->x * 0.5; $velocityVector->x += $flow->x * 0.5;
$velocityVector->y += $flow->y * 0.5; $velocityVector->y += $flow->y * 0.5;
$velocityVector->z += $flow->z * 0.5; $velocityVector->z += $flow->z * 0.5;
} }
public static function getTickDelay(){ public static function getTickDelay(){
throw new RuntimeException("If you see this, something bad happened"); throw new RuntimeException("If you see this, something bad happened");
} }
public static function updateLiquid(Level $level, $x, $y, $z){ public static function updateLiquid(Level $level, $x, $y, $z){
[$id, $meta] = $level->level->getBlock($x, $y, $z); [$id, $meta] = $level->level->getBlock($x, $y, $z);
if($id != LAVA && $id != STILL_LAVA) return; if($id != LAVA && $id != STILL_LAVA) return;
$zNeg = $level->level->getBlockID($x, $y, $z - 1); $zNeg = $level->level->getBlockID($x, $y, $z - 1);
$zPos = $level->level->getBlockID($x, $y, $z + 1); $zPos = $level->level->getBlockID($x, $y, $z + 1);
$xNeg = $level->level->getBlockID($x - 1, $y, $z); $xNeg = $level->level->getBlockID($x - 1, $y, $z);
$xPos = $level->level->getBlockID($x + 1, $y, $z); $xPos = $level->level->getBlockID($x + 1, $y, $z);
$yPos = $level->level->getBlockID($x, $y + 1, $z); $yPos = $level->level->getBlockID($x, $y + 1, $z);
if( if(
$zNeg == WATER || $zNeg == STILL_WATER $zNeg == WATER || $zNeg == STILL_WATER
|| $zPos == WATER || $zPos == STILL_WATER || $zPos == WATER || $zPos == STILL_WATER
|| $xNeg == WATER || $xNeg == STILL_WATER || $xNeg == WATER || $xNeg == STILL_WATER
|| $xPos == WATER || $xPos == STILL_WATER || $xPos == WATER || $xPos == STILL_WATER
|| $yPos == WATER || $yPos == STILL_WATER || $yPos == WATER || $yPos == STILL_WATER
) { ) {
if($meta){ if($meta){
//if($meta > 4) -> fizz & ret //if($meta > 4) -> fizz & ret
@ -179,17 +179,16 @@ class LiquidBlock extends TransparentBlock{
}else{ }else{
$replacement = OBSIDIAN; $replacement = OBSIDIAN;
} }
$level->fastSetBlockUpdate($x, $y, $z, $replacement, true); $level->fastSetBlockUpdate($x, $y, $z, $replacement, true);
} }
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return array(); return [];
} }
public function getLiquidHeight(){ public function getLiquidHeight(){
return (($this->meta >= 8 ? 0 : $this->meta)+1) / 9; return (($this->meta >= 8 ? 0 : $this->meta) + 1) / 9;
} }
} }

View file

@ -11,7 +11,7 @@ class SolidBlock extends GenericBlock{
$this->isSolid = true; $this->isSolid = true;
$this->isFullBlock = true; $this->isFullBlock = true;
} }
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return [new AxisAlignedBB($x, $y, $z, $x + 1, $y + 1, $z + 1)]; return [new AxisAlignedBB($x, $y, $z, $x + 1, $y + 1, $z + 1)];
} }

View file

@ -15,26 +15,26 @@ class StairBlock extends TransparentBlock{
} }
$this->hardness = 30; $this->hardness = 30;
} }
public static function isBlocksStairsID($id){ public static function isBlocksStairsID($id){
return $id > 0 && StaticBlock::getBlock($id) instanceof StairBlock; return $id > 0 && StaticBlock::getBlock($id) instanceof StairBlock;
} }
public static function isStairsAtXYZAndAreTheirMetadataSame(Level $level, $x, $y, $z, $meta){ public static function isStairsAtXYZAndAreTheirMetadataSame(Level $level, $x, $y, $z, $meta){
$block = $level->level->getBlock($x, $y, $z); $block = $level->level->getBlock($x, $y, $z);
return self::isBlocksStairsID($block[0]) && $block[1] == $meta; return self::isBlocksStairsID($block[0]) && $block[1] == $meta;
} }
public static function setBaseShape(Level $level, $x, $y, $z){ public static function setBaseShape(Level $level, $x, $y, $z){
$meta = $level->level->getBlockDamage($x, $y, $z); $meta = $level->level->getBlockDamage($x, $y, $z);
if(($meta & 4) != 0){ if(($meta & 4) != 0){
return new AxisAlignedBB(0, 0.5, 0, 1, 1, 1); return new AxisAlignedBB(0, 0.5, 0, 1, 1, 1);
}else{ }else{
return new AxisAlignedBB(0, 0, 0, 1, 0.5, 1); return new AxisAlignedBB(0, 0, 0, 1, 0.5, 1);
} }
} }
const DEAD_SAPCES = [ const DEAD_SAPCES = [
[2, 6], [2, 6],
[3, 7], [3, 7],
@ -45,72 +45,72 @@ class StairBlock extends TransparentBlock{
[0, 1], [0, 1],
[4, 5] [4, 5]
]; ];
public static function updateShape(Level $level, $x, $y, $z){ public static function updateShape(Level $level, $x, $y, $z){
if(self::$complexState){ if(self::$complexState){
$id = $level->level->getBlockID($x, $y, $z); $id = $level->level->getBlockID($x, $y, $z);
$cid = self::$complexStateID; $cid = self::$complexStateID;
StaticBlock::setBlockBounds($id, StaticBlock::setBlockBounds($id,
0.5 * ($cid % 2), 0.5 * ($cid % 2),
0.5 * ((int)($cid / 2) % 2), 0.5 * ((int) ($cid / 2) % 2),
0.5 * ((int)($cid / 4) % 2), 0.5 * ((int) ($cid / 4) % 2),
0.5 + 0.5 * ($cid % 2), 0.5 + 0.5 * ($cid % 2),
0.5 + 0.5 * ((int)($cid / 2) % 2), 0.5 + 0.5 * ((int) ($cid / 2) % 2),
0.5 + 0.5 * ((int)($cid / 4) % 2) 0.5 + 0.5 * ((int) ($cid / 4) % 2)
); );
}else{ }else{
StaticBlock::setBlockBounds($level->level->getBlockID($x, $y, $z), 0, 0, 0, 1, 1, 1); StaticBlock::setBlockBounds($level->level->getBlockID($x, $y, $z), 0, 0, 0, 1, 1, 1);
} }
} }
static $complexState = false; static $complexState = false;
static $complexStateID = 0; static $complexStateID = 0;
public static function clip(Level $level, $x, $y, $z, Vector3 $start, Vector3 $end){ public static function clip(Level $level, $x, $y, $z, Vector3 $start, Vector3 $end){
$v7 = []; $v7 = [];
$v8 = $level->level->getBlockDamage($x, $y, $z); $v8 = $level->level->getBlockDamage($x, $y, $z);
$v9 = $v8 & 3; $v9 = $v8 & 3;
$v10 = ($v8 & 4) == 4; $v10 = ($v8 & 4) == 4;
$v11 = self::DEAD_SAPCES[$v9 + ($v10 ? 4 : 0)]; $v11 = self::DEAD_SAPCES[$v9 + ($v10 ? 4 : 0)];
self::$complexState = true; self::$complexState = true;
for($v12 = 0; $v12 < 8; ++$v12){ for($v12 = 0; $v12 < 8; ++$v12){
self::$complexStateID = $v12; self::$complexStateID = $v12;
for($v15 = 0; $v15 < /*count($v11}*/ 2; ++$v15){ for($v15 = 0; $v15 < /*count($v11}*/ 2; ++$v15){
$v16 = $v11[$v15]; $v16 = $v11[$v15];
if($v16 == $v12){ if($v16 == $v12){
//wat //wat
} }
} }
$v7[$v12] = parent::clip($level, $x, $y, $z, $start, $end); $v7[$v12] = parent::clip($level, $x, $y, $z, $start, $end);
} }
for($v14 = 0; $v14 < /*count($v11}*/ 2; ++$v14){ for($v14 = 0; $v14 < /*count($v11}*/ 2; ++$v14){
$v15 = $v11[$v14]; $v15 = $v11[$v14];
$v7[$v15] = null; $v7[$v15] = null;
} }
$v24 = 0; $v24 = 0;
$v22 = null; $v22 = null;
for($v17 = 0; $v17 < count($v7); ++$v17){ for($v17 = 0; $v17 < count($v7); ++$v17){
$v18 = $v7[$v17]; $v18 = $v7[$v17];
if($v18 != null){ if($v18 != null){
$v19 = $v18->hitVector->distanceSquared($end); $v19 = $v18->hitVector->distanceSquared($end);
if($v19 > $v24){ if($v19 > $v24){
$v22 = $v18; $v22 = $v18;
$v24 = $v19; $v24 = $v19;
} }
} }
} }
return $v22; return $v22;
} }
public static function setStepShape(Level $level, $x, $y, $z){ public static function setStepShape(Level $level, $x, $y, $z){
$blockMeta = $level->level->getBlockDamage($x, $y, $z); $blockMeta = $level->level->getBlockDamage($x, $y, $z);
$metaAnd3 = $blockMeta & 3; $metaAnd3 = $blockMeta & 3;
@ -120,13 +120,13 @@ class StairBlock extends TransparentBlock{
$minY = 0.0; $minY = 0.0;
$maxY = 0.5; $maxY = 0.5;
} }
$minX = 0; $minX = 0;
$maxX = 1; $maxX = 1;
$minZ = 0; $minZ = 0;
$maxZ = 0.5; $maxZ = 0.5;
$v13 = true; $v13 = true;
switch($metaAnd3){ switch($metaAnd3){
case 0: case 0:
$minX = 0.5; $minX = 0.5;
@ -134,10 +134,10 @@ class StairBlock extends TransparentBlock{
$blockNearby = $level->level->getBlock($x + 1, $y, $z); $blockNearby = $level->level->getBlock($x + 1, $y, $z);
$blockIDNearby = $blockNearby[0]; $blockIDNearby = $blockNearby[0];
$blockMetaNearby = $blockNearby[1]; $blockMetaNearby = $blockNearby[1];
if(self::isBlocksStairsID($blockIDNearby) && (($blockMeta & 4) == ($blockMetaNearby & 4))){ if(self::isBlocksStairsID($blockIDNearby) && (($blockMeta & 4) == ($blockMetaNearby & 4))){
$blockMetaNearbyAnd3 = $blockMetaNearby & 3; $blockMetaNearbyAnd3 = $blockMetaNearby & 3;
if($blockMetaNearbyAnd3 == 3 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x, $y, $z + 1, $blockMeta)){ if($blockMetaNearbyAnd3 == 3 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x, $y, $z + 1, $blockMeta)){
$maxZ = 0.5; $maxZ = 0.5;
$v13 = false; $v13 = false;
@ -153,10 +153,10 @@ class StairBlock extends TransparentBlock{
$blockNearby = $level->level->getBlock($x - 1, $y, $z); $blockNearby = $level->level->getBlock($x - 1, $y, $z);
$blockIDNearby = $blockNearby[0]; $blockIDNearby = $blockNearby[0];
$blockMetaNearby = $blockNearby[1]; $blockMetaNearby = $blockNearby[1];
if(self::isBlocksStairsID($blockIDNearby) && (($blockMeta & 4) == ($blockMetaNearby & 4))){ if(self::isBlocksStairsID($blockIDNearby) && (($blockMeta & 4) == ($blockMetaNearby & 4))){
$blockMetaNearbyAnd3 = $blockMetaNearby & 3; $blockMetaNearbyAnd3 = $blockMetaNearby & 3;
if($blockMetaNearbyAnd3 == 3 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x, $y, $z + 1, $blockMeta)){ if($blockMetaNearbyAnd3 == 3 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x, $y, $z + 1, $blockMeta)){
$maxZ = 0.5; $maxZ = 0.5;
$v13 = false; $v13 = false;
@ -172,10 +172,10 @@ class StairBlock extends TransparentBlock{
$blockNearby = $level->level->getBlock($x, $y, $z + 1); $blockNearby = $level->level->getBlock($x, $y, $z + 1);
$blockIDNearby = $blockNearby[0]; $blockIDNearby = $blockNearby[0];
$blockMetaNearby = $blockNearby[1]; $blockMetaNearby = $blockNearby[1];
if(self::isBlocksStairsID($blockIDNearby) && (($blockMeta & 4) == ($blockMetaNearby & 4))){ if(self::isBlocksStairsID($blockIDNearby) && (($blockMeta & 4) == ($blockMetaNearby & 4))){
$blockMetaNearbyAnd3 = $blockMetaNearby & 3; $blockMetaNearbyAnd3 = $blockMetaNearby & 3;
if($blockMetaNearbyAnd3 == 1 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x + 1, $y, $z, $blockMeta)){ if($blockMetaNearbyAnd3 == 1 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x + 1, $y, $z, $blockMeta)){
$maxX = 0.5; $maxX = 0.5;
$v13 = false; $v13 = false;
@ -191,7 +191,7 @@ class StairBlock extends TransparentBlock{
$blockMetaNearby = $blockNearby[1]; $blockMetaNearby = $blockNearby[1];
if(self::isBlocksStairsID($blockIDNearby) && (($blockMeta & 4) == ($blockMetaNearby & 4))){ if(self::isBlocksStairsID($blockIDNearby) && (($blockMeta & 4) == ($blockMetaNearby & 4))){
$blockMetaNearbyAnd3 = $blockMetaNearby & 3; $blockMetaNearbyAnd3 = $blockMetaNearby & 3;
if($blockMetaNearbyAnd3 == 1 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x + 1, $y, $z, $blockMeta)){ if($blockMetaNearbyAnd3 == 1 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x + 1, $y, $z, $blockMeta)){
$maxX = 0.5; $maxX = 0.5;
$v13 = false; $v13 = false;
@ -203,34 +203,34 @@ class StairBlock extends TransparentBlock{
break; break;
} }
return [new AxisAlignedBB($minX, $minY, $minZ, $maxX, $maxY, $maxZ), $v13]; return [new AxisAlignedBB($minX, $minY, $minZ, $maxX, $maxY, $maxZ), $v13];
} }
public static function setInnerPieceShape(Level $level, $x, $y, $z){ public static function setInnerPieceShape(Level $level, $x, $y, $z){
$meta = $level->level->getBlockDamage($x, $y, $z); $meta = $level->level->getBlockDamage($x, $y, $z);
$metaAnd3 = $meta & 3; $metaAnd3 = $meta & 3;
$minY = 0.5; $minY = 0.5;
$maxY = 1.0; $maxY = 1.0;
if(($meta & 4) != 0){ if(($meta & 4) != 0){
$minY = 0.0; $minY = 0.0;
$maxY = 0.5; $maxY = 0.5;
} }
$minX = 0.0; $minX = 0.0;
$maxX = 0.5; $maxX = 0.5;
$minZ = 0.5; $minZ = 0.5;
$maxZ = 1.0; $maxZ = 1.0;
$v13 = false; $v13 = false;
switch($metaAnd3){ switch($metaAnd3){
case 0: case 0:
$idNearby = $level->level->getBlockID($x - 1, $y, $z); $idNearby = $level->level->getBlockID($x - 1, $y, $z);
$metaNearby = $level->level->getBlockDamage($x - 1, $y, $z); $metaNearby = $level->level->getBlockDamage($x - 1, $y, $z);
if(self::isBlocksStairsID($idNearby) && ($meta & 4) == ($metaNearby & 4)){ if(self::isBlocksStairsID($idNearby) && ($meta & 4) == ($metaNearby & 4)){
$metaNearbyAnd3 = $metaNearby & 3; $metaNearbyAnd3 = $metaNearby & 3;
if($metaNearbyAnd3 == 3 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x, $y, $z - 1, $meta)){ if($metaNearbyAnd3 == 3 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x, $y, $z - 1, $meta)){
$minZ = 0; $minZ = 0;
$maxZ = 0.5; $maxZ = 0.5;
@ -245,7 +245,7 @@ class StairBlock extends TransparentBlock{
case 1: case 1:
$idNearby = $level->level->getBlockID($x + 1, $y, $z); $idNearby = $level->level->getBlockID($x + 1, $y, $z);
$metaNearby = $level->level->getBlockDamage($x + 1, $y, $z); $metaNearby = $level->level->getBlockDamage($x + 1, $y, $z);
if(self::isBlocksStairsID($idNearby) && ($meta & 4) == ($metaNearby & 4)){ if(self::isBlocksStairsID($idNearby) && ($meta & 4) == ($metaNearby & 4)){
$minX = 0.5; $minX = 0.5;
$maxX = 1.0; $maxX = 1.0;
@ -261,17 +261,17 @@ class StairBlock extends TransparentBlock{
$v13 = true; $v13 = true;
} }
} }
break; break;
case 2: case 2:
$idNearby = $level->level->getBlockID($x, $y, $z - 1); $idNearby = $level->level->getBlockID($x, $y, $z - 1);
$metaNearby = $level->level->getBlockDamage($x, $y, $z - 1); $metaNearby = $level->level->getBlockDamage($x, $y, $z - 1);
if(self::isBlocksStairsID($idNearby) && ($meta & 4) == ($metaNearby & 4)){ if(self::isBlocksStairsID($idNearby) && ($meta & 4) == ($metaNearby & 4)){
$minZ = 0; $minZ = 0;
$maxZ = 0.5; $maxZ = 0.5;
$metaNearbyAnd3 = $metaNearby & 3; $metaNearbyAnd3 = $metaNearby & 3;
if($metaNearbyAnd3 == 1 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x - 1, $y, $z, $meta)){ if($metaNearbyAnd3 == 1 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x - 1, $y, $z, $meta)){
$v13 = true; $v13 = true;
}elseif($metaNearbyAnd3 == 0 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x + 1, $y, $z, $meta)){ }elseif($metaNearbyAnd3 == 0 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x + 1, $y, $z, $meta)){
@ -280,16 +280,16 @@ class StairBlock extends TransparentBlock{
$v13 = true; $v13 = true;
} }
} }
break; break;
case 3: case 3:
$idNearby = $level->level->getBlockID($x, $y, $z + 1); $idNearby = $level->level->getBlockID($x, $y, $z + 1);
$metaNearby = $level->level->getBlockDamage($x, $y, $z + 1); $metaNearby = $level->level->getBlockDamage($x, $y, $z + 1);
if(self::isBlocksStairsID($idNearby) && ($meta & 4) == ($metaNearby & 4)){ if(self::isBlocksStairsID($idNearby) && ($meta & 4) == ($metaNearby & 4)){
$metaNearbyAnd3 = $metaNearby & 3; $metaNearbyAnd3 = $metaNearby & 3;
if($metaNearbyAnd3 == 1 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x - 1, $y, $z, $meta)){ if($metaNearbyAnd3 == 1 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x - 1, $y, $z, $meta)){
$v13 = true; $v13 = true;
}elseif($metaNearbyAnd3 == 0 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x + 1, $y, $z, $meta)){ }elseif($metaNearbyAnd3 == 0 && !self::isStairsAtXYZAndAreTheirMetadataSame($level, $x + 1, $y, $z, $meta)){
@ -300,10 +300,10 @@ class StairBlock extends TransparentBlock{
} }
break; break;
} }
return [new AxisAlignedBB($minX, $minY, $minZ, $maxX, $maxY, $maxZ), $v13]; return [new AxisAlignedBB($minX, $minY, $minZ, $maxX, $maxY, $maxZ), $v13];
} }
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
$bbs = [self::setBaseShape($level, $x, $y, $z)->offset($x, $y, $z)]; $bbs = [self::setBaseShape($level, $x, $y, $z)->offset($x, $y, $z)];
$ret = self::setStepShape($level, $x, $y, $z); $ret = self::setStepShape($level, $x, $y, $z);
@ -314,15 +314,11 @@ class StairBlock extends TransparentBlock{
$bbs[] = $ret2[0]->offset($x, $y, $z); $bbs[] = $ret2[0]->offset($x, $y, $z);
} }
} }
return $bbs; return $bbs;
} }
/** /**
* @param Item $item
* @param Player $player
* @param Block $block
* @param Block $target
* @param int $face * @param int $face
* @param int $fx * @param int $fx
* @param int $fy * @param int $fy
@ -331,12 +327,12 @@ class StairBlock extends TransparentBlock{
* @return bool|mixed * @return bool|mixed
*/ */
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$faces = array( $faces = [
0 => 0, 0 => 0,
1 => 2, 1 => 2,
2 => 1, 2 => 1,
3 => 3, 3 => 3,
); ];
$this->meta = $faces[$player->entity->getDirection()] & 0x03; $this->meta = $faces[$player->entity->getDirection()] & 0x03;
if(($fy > 0.5 and $face !== 1) or $face === 0){ if(($fy > 0.5 and $face !== 1) or $face === 0){
$this->meta |= 0x04; //Upside-down stairs $this->meta |= 0x04; //Upside-down stairs
@ -346,18 +342,16 @@ class StairBlock extends TransparentBlock{
} }
/** /**
* @param Item $item
* @param Player $player
* *
* @return array * @return array
*/ */
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
if($item->getPickaxeLevel() >= 1){ if($item->getPickaxeLevel() >= 1){
return array( return [
array($this->id, 0, 1), [$this->id, 0, 1],
); ];
}else{ }else{
return array(); return [];
} }
} }
} }

View file

@ -13,11 +13,11 @@ class TransparentBlock extends GenericBlock{
$this->isFlowable = false; $this->isFlowable = false;
$this->isTransparent = true; $this->isTransparent = true;
$this->isReplaceable = false; $this->isReplaceable = false;
$this->isPlaceable = true; $this->isPlaceable = true;
$this->isSolid = true; $this->isSolid = true;
$this->boundingBox->setBounds($this->x, $this->y, $this->z, $this->x + 1, $this->y + 1, $this->z + 1); $this->boundingBox->setBounds($this->x, $this->y, $this->z, $this->x + 1, $this->y + 1, $this->z + 1);
} }
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return []; return [];
} }

View file

@ -4,7 +4,7 @@ class LadderBlock extends TransparentBlock{
public static $blockID; public static $blockID;
public static function getAABB(Level $level, $x, $y, $z){ public static function getAABB(Level $level, $x, $y, $z){
[$id, $meta] = $level->level->getBlock($x, $y, $z); [$id, $meta] = $level->level->getBlock($x, $y, $z);
switch($meta){ switch($meta){
case 2: case 2:
StaticBlock::setBlockBounds($id, 0.0, 0.0, 0.875, 1.0, 1.0, 1.0); StaticBlock::setBlockBounds($id, 0.0, 0.0, 0.875, 1.0, 1.0, 1.0);
@ -18,9 +18,9 @@ class LadderBlock extends TransparentBlock{
case 5: case 5:
StaticBlock::setBlockBounds($id, 0, 0.0, 0.0, 0.125, 1.0, 1.0); StaticBlock::setBlockBounds($id, 0, 0.0, 0.0, 0.125, 1.0, 1.0);
break; break;
} }
return parent::getAABB($level, $x, $y, $z); return parent::getAABB($level, $x, $y, $z);
} }
public function __construct($meta = 0){ public function __construct($meta = 0){
@ -43,7 +43,7 @@ class LadderBlock extends TransparentBlock{
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
$side = $level->level->getBlockDamage($x, $y, $z); $side = $level->level->getBlockDamage($x, $y, $z);
$attached = match($side){ $attached = match($side){
3 => $level->level->getBlockID($x, $y, $z - 1), 3 => $level->level->getBlockID($x, $y, $z - 1),
2 => $level->level->getBlockID($x, $y, $z + 1), 2 => $level->level->getBlockID($x, $y, $z + 1),
@ -51,7 +51,7 @@ class LadderBlock extends TransparentBlock{
4 => $level->level->getBlockID($x + 1, $y, $z), 4 => $level->level->getBlockID($x + 1, $y, $z),
default => 0 //TODO default => 0 //TODO
}; };
if($attached == AIR){ //Replace with common break method if($attached == AIR){ //Replace with common break method
ServerAPI::request()->api->entity->drop(new Position($x, $y, $z, $level), BlockAPI::getItem(LADDER, 0, 1)); ServerAPI::request()->api->entity->drop(new Position($x, $y, $z, $level), BlockAPI::getItem(LADDER, 0, 1));
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
@ -59,8 +59,8 @@ class LadderBlock extends TransparentBlock{
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return array( return [
array($this->id, 0, 1), [$this->id, 0, 1],
); ];
} }
} }

View file

@ -17,7 +17,7 @@ class SignPostBlock extends TransparentBlock{
$this->isFullBlock = false; $this->isFullBlock = false;
$this->hardness = 5; $this->hardness = 5;
} }
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ 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) && $face !== 0){
if(!isset(self::$faces[$face])){ if(!isset(self::$faces[$face])){
@ -32,7 +32,7 @@ class SignPostBlock extends TransparentBlock{
} }
return false; return false;
} }
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ 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){ //Replace with common break method
ServerAPI::request()->api->entity->drop(new Position($x, $y, $z, $level), BlockAPI::getItem(SIGN, 0, 1)); ServerAPI::request()->api->entity->drop(new Position($x, $y, $z, $level), BlockAPI::getItem(SIGN, 0, 1));
@ -40,15 +40,15 @@ class SignPostBlock extends TransparentBlock{
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true, true); $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true, true);
} }
} }
public function onBreak(Item $item, Player $player){ public function onBreak(Item $item, Player $player){
$this->level->setBlock($this, new AirBlock(), true, true, true); $this->level->setBlock($this, new AirBlock(), true, true, true);
return true; return true;
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return array( return [
array(SIGN, 0, 1), [SIGN, 0, 1],
); ];
} }
} }

View file

@ -6,15 +6,15 @@ class TorchBlock extends FlowableBlock implements LightingBlock{
parent::__construct(TORCH, $meta, "Torch"); parent::__construct(TORCH, $meta, "Torch");
$this->hardness = 0; $this->hardness = 0;
} }
public function getMaxLightValue(){ public function getMaxLightValue(){
return 15; return 15;
} }
public static function getAABB(Level $level, $x, $y, $z){ public static function getAABB(Level $level, $x, $y, $z){
return null; return null;
} }
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
$side = $level->level->getBlockDamage($x, $y, $z); $side = $level->level->getBlockDamage($x, $y, $z);
$attach = match($side){ $attach = match($side){
@ -22,9 +22,9 @@ class TorchBlock extends FlowableBlock implements LightingBlock{
2 => $level->level->getBlockID($x + 1, $y, $z), 2 => $level->level->getBlockID($x + 1, $y, $z),
3 => $level->level->getBlockID($x, $y, $z - 1), 3 => $level->level->getBlockID($x, $y, $z - 1),
4 => $level->level->getBlockID($x, $y, $z + 1), 4 => $level->level->getBlockID($x, $y, $z + 1),
default => $level->level->getBlockID($x, $y - 1, $z) default => $level->level->getBlockID($x, $y - 1, $z)
}; };
if(StaticBlock::getIsTransparent($attach) && !($side === 0 && $attach === FENCE)){ //Replace with common break method if(StaticBlock::getIsTransparent($attach) && !($side === 0 && $attach === FENCE)){ //Replace with common break method
ServerAPI::request()->api->entity->drop(new Position($x, $y, $z, $level), BlockAPI::getItem(TORCH, 0, 1)); ServerAPI::request()->api->entity->drop(new Position($x, $y, $z, $level), BlockAPI::getItem(TORCH, 0, 1));
$level->fastSetBlockUpdate($x, $y, $z, 0, 0); $level->fastSetBlockUpdate($x, $y, $z, 0, 0);
@ -33,13 +33,13 @@ class TorchBlock extends FlowableBlock implements LightingBlock{
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
if($target->isTransparent === false and $face !== 0){ if($target->isTransparent === false and $face !== 0){
$faces = array( $faces = [
1 => 5, 1 => 5,
2 => 4, 2 => 4,
3 => 3, 3 => 3,
4 => 2, 4 => 2,
5 => 1, 5 => 1,
); ];
$this->meta = $faces[$face]; $this->meta = $faces[$face];
$this->level->setBlock($block, $this, true, false, true); $this->level->setBlock($block, $this, true, false, true);
return true; return true;
@ -51,8 +51,8 @@ class TorchBlock extends FlowableBlock implements LightingBlock{
return false; return false;
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return array( return [
array($this->id, 0, 1), [$this->id, 0, 1],
); ];
} }
} }

View file

@ -17,25 +17,25 @@ class TrapdoorBlock extends TransparentBlock{
$id = $target->getID(); $id = $target->getID();
return $id === SLAB || $id === GLOWSTONE || $id === SLAB || $id === WOOD_SLAB || (!$target->isTransparent || $target instanceof StairBlock); return $id === SLAB || $id === GLOWSTONE || $id === SLAB || $id === WOOD_SLAB || (!$target->isTransparent || $target instanceof StairBlock);
} }
public static function isOpen($meta){ public static function isOpen($meta){
return ($meta >> 2) & 1; return ($meta >> 2) & 1;
} }
public static function getAABB(Level $level, $x, $y, $z){ public static function getAABB(Level $level, $x, $y, $z){
static::updateShape($level, $x, $y, $z); static::updateShape($level, $x, $y, $z);
return StaticBlock::getAABB(static::$blockID, $x, $y, $z); return StaticBlock::getAABB(static::$blockID, $x, $y, $z);
} }
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return [static::getAABB($level, $x, $y, $z)]; return [static::getAABB($level, $x, $y, $z)];
} }
public static function updateShape(Level $level, $x, $y, $z){ public static function updateShape(Level $level, $x, $y, $z){
[$id, $meta] = $level->level->getBlock($x, $y, $z); [$id, $meta] = $level->level->getBlock($x, $y, $z);
StaticBlock::setBlockBounds($id, 0.0, 0.0, 0.0, 1.0, 0.1875, 1.0); StaticBlock::setBlockBounds($id, 0.0, 0.0, 0.0, 1.0, 0.1875, 1.0);
if(static::isOpen($meta)){ if(static::isOpen($meta)){
$facing = $meta & 3; $facing = $meta & 3;
switch($facing){ switch($facing){
@ -56,24 +56,24 @@ class TrapdoorBlock extends TransparentBlock{
} }
} }
} }
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
if(($this->canAttachTo($target)) and $face !== 0 and $face !== 1){ if(($this->canAttachTo($target)) and $face !== 0 and $face !== 1){
$faces = array( $faces = [
2 => 0, 2 => 0,
3 => 1, 3 => 1,
4 => 2, 4 => 2,
5 => 3, 5 => 3,
); ];
$this->meta = $faces[$face] & 0x03; $this->meta = $faces[$face] & 0x03;
$this->level->setBlock($block, $this, true, false, true); $this->level->setBlock($block, $this, true, false, true);
return true; return true;
} }
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return array( return [
array($this->id, 0, 1), [$this->id, 0, 1],
); ];
} }
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
$attach = match($level->level->getBlockDamage($x, $y, $z)){ $attach = match($level->level->getBlockDamage($x, $y, $z)){
@ -83,13 +83,13 @@ class TrapdoorBlock extends TransparentBlock{
3, 7 => $level->level->getBlockID($x - 1, $y, $z), 3, 7 => $level->level->getBlockID($x - 1, $y, $z),
default => 0 default => 0
}; };
if($attach == AIR){ //Replace with common break method if($attach == AIR){ //Replace with common break method
ServerAPI::request()->api->entity->drop(new Position($x, $y, $z, $level), BlockAPI::getItem(TRAPDOOR, 0, 1)); ServerAPI::request()->api->entity->drop(new Position($x, $y, $z, $level), BlockAPI::getItem(TRAPDOOR, 0, 1));
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
} }
} }
public function onActivate(Item $item, Player $player){ public function onActivate(Item $item, Player $player){
$this->meta ^= 0x04; $this->meta ^= 0x04;
$this->level->setBlock($this, $this, true, false, true); $this->level->setBlock($this, $this, true, false, true);

View file

@ -10,7 +10,7 @@ class WallSignBlock extends SignPostBlock{
TransparentBlock::__construct(WALL_SIGN, $meta, "Wall Sign"); TransparentBlock::__construct(WALL_SIGN, $meta, "Wall Sign");
$this->isSolid = false; $this->isSolid = false;
} }
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
$attached = match($level->level->getBlockDamage($x, $y, $z)){ $attached = match($level->level->getBlockDamage($x, $y, $z)){
2 => $level->level->getBlockID($x, $y, $z + 1), 2 => $level->level->getBlockID($x, $y, $z + 1),
@ -19,7 +19,7 @@ class WallSignBlock extends SignPostBlock{
5 => $level->level->getBlockID($x - 1, $y, $z), 5 => $level->level->getBlockID($x - 1, $y, $z),
default => WALL_SIGN default => WALL_SIGN
}; };
if(!StaticBlock::getIsSolid($attached) && $attached != SIGN_POST && $attached != WALL_SIGN){ if(!StaticBlock::getIsSolid($attached) && $attached != SIGN_POST && $attached != WALL_SIGN){
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true, true); $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)); (ServerAPI::request())->api->entity->drop(new Position($x + 0.5, $y + 0.5, $z + 0.5, $level), BlockAPI::getItem(SIGN, 0, 1));

View file

@ -1,4 +1,5 @@
<?php <?php
require_once("LiquidBlockDynamic.php"); //TODO class loader? require_once("LiquidBlockDynamic.php"); //TODO class loader?
class LavaBlock extends LiquidBlockDynamic implements LightingBlock{ class LavaBlock extends LiquidBlockDynamic implements LightingBlock{
@ -7,16 +8,16 @@ class LavaBlock extends LiquidBlockDynamic implements LightingBlock{
parent::__construct(LAVA, $meta, "Lava"); parent::__construct(LAVA, $meta, "Lava");
$this->hardness = 500; $this->hardness = 500;
} }
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$ret = $this->level->setBlock($this, $this, true, false, true); $ret = $this->level->setBlock($this, $this, true, false, true);
return $ret; return $ret;
} }
public static function getTickDelay(){ public static function getTickDelay(){
return 30; return 30;
} }
public function getMaxLightValue(){ public function getMaxLightValue(){
return 15; return 15;
} }

View file

@ -4,55 +4,55 @@ class LiquidBlockDynamic extends LiquidBlock{
public function __construct($id, $meta = 0, $name = "Unknown"){ public function __construct($id, $meta = 0, $name = "Unknown"){
parent::__construct($id, $meta, $name); parent::__construct($id, $meta, $name);
} }
public static $blockID = 0; public static $blockID = 0;
public static $sourcesAround = 0; public static $sourcesAround = 0;
public static $spread = [0, 0, 0, 0]; public static $spread = [0, 0, 0, 0];
public static function getHighest(Level $level, $x, $y, $z, $highest){ public static function getHighest(Level $level, $x, $y, $z, $highest){
$depth = static::getDepth($level, $x, $y, $z); $depth = static::getDepth($level, $x, $y, $z);
if($depth < 0) return $highest; if($depth < 0) return $highest;
if($depth == 0) ++static::$sourcesAround; if($depth == 0) ++static::$sourcesAround;
if($depth >= 8) $depth = 0; if($depth >= 8) $depth = 0;
return $highest >= 0 && $depth >= $highest ? $highest : $depth; return $highest >= 0 && $depth >= $highest ? $highest : $depth;
} }
public static function setStatic(Level $level, $x, $y, $z){ public static function setStatic(Level $level, $x, $y, $z){
$meta = $level->level->getBlockDamage($x, $y, $z); $meta = $level->level->getBlockDamage($x, $y, $z);
$level->fastSetBlockUpdate($x, $y, $z, static::$blockID + 1, $meta); $level->fastSetBlockUpdate($x, $y, $z, static::$blockID + 1, $meta);
} }
public static function isWaterBlocking(Level $level, $x, $y, $z){ public static function isWaterBlocking(Level $level, $x, $y, $z){
$id = $level->level->getBlockID($x, $y, $z); $id = $level->level->getBlockID($x, $y, $z);
if($id == AIR) return false; if($id == AIR) return false;
if($id == DOOR_BLOCK || $id == SIGN_POST || $id == WALL_SIGN || $id == LADDER || $id == SUGARCANE_BLOCK) return true; 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 if($id == CARPET || $id == SNOW_LAYER || $id == RAIL || $id == POWERED_RAIL) return false; //TODO Tile::getThickness() > 0
//TODO materials //TODO materials
//if(!StaticBlock::getIsFlowable($id)) return true; //if(!StaticBlock::getIsFlowable($id)) return true;
return StaticBlock::getIsSolid($id); return StaticBlock::getIsSolid($id);
} }
public static function canSpreadTo(Level $level, $x, $y, $z){ public static function canSpreadTo(Level $level, $x, $y, $z){
$id = $level->level->getBlockID($x, $y, $z); $id = $level->level->getBlockID($x, $y, $z);
if($id == LAVA || $id == STILL_LAVA) return false; if($id == LAVA || $id == STILL_LAVA) return false;
if((static::$blockID == WATER) && ($id == WATER || $id == STILL_WATER)) return false; if((static::$blockID == WATER) && ($id == WATER || $id == STILL_WATER)) return false;
return static::isWaterBlocking($level, $x, $y, $z) ^ 1; return static::isWaterBlocking($level, $x, $y, $z) ^ 1;
} }
public static function getSpread(Level $level, $x, $y, $z){ public static function getSpread(Level $level, $x, $y, $z){
for($i = 0; $i < 4; ++$i){ for($i = 0; $i < 4; ++$i){
static::$spread[$i] = 1000; static::$spread[$i] = 1000;
$xs = $x; $xs = $x;
$ys = $y; $ys = $y;
$zs = $z; $zs = $z;
switch($i){ switch($i){
case 0: case 0:
--$xs; --$xs;
@ -67,13 +67,13 @@ class LiquidBlockDynamic extends LiquidBlock{
++$zs; ++$zs;
break; break;
} }
if(static::isWaterBlocking($level, $xs, $ys, $zs)) continue; if(static::isWaterBlocking($level, $xs, $ys, $zs)) continue;
[$id, $meta] = $level->level->getBlock($xs, $ys, $zs); [$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){ if(((static::$blockID == WATER && ($id == WATER || $id == STILL_WATER)) || (static::$blockID == LAVA && ($id == LAVA || $id == STILL_LAVA))) && $meta == 0){
continue; continue;
} }
if(!static::isWaterBlocking($level, $xs, $ys - 1, $zs)) static::$spread[$i] = 0; if(!static::isWaterBlocking($level, $xs, $ys - 1, $zs)) static::$spread[$i] = 0;
else static::$spread[$i] = static::getSlopeDistance($level, $xs, $ys, $zs, 1, $i); 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]); for($i = 0; $i < 4; ++$i) $ba[$i] = ($i1 == static::$spread[$i]);
return $ba; return $ba;
} }
public static function getSlopeDistance(Level $level, $x, $y, $z, $l, $i1){ public static function getSlopeDistance(Level $level, $x, $y, $z, $l, $i1){
$j1 = 1000; $j1 = 1000;
for($k1 = 0; $k1 < 4; ++$k1){ 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; continue;
} }
$xs = $x; $xs = $x;
$ys = $y; $ys = $y;
$zs = $z; $zs = $z;
switch($k1){ switch($k1){
case 0: case 0:
--$xs; --$xs;
@ -111,10 +111,10 @@ class LiquidBlockDynamic extends LiquidBlock{
++$zs; ++$zs;
break; break;
} }
if(static::isWaterBlocking($level, $xs, $ys, $zs)) continue; if(static::isWaterBlocking($level, $xs, $ys, $zs)) continue;
[$id, $meta] = $level->level->getBlock($xs, $ys, $zs); [$id, $meta] = $level->level->getBlock($xs, $ys, $zs);
if( if(
((static::$blockID == WATER && ($id == WATER || $id == STILL_WATER)) || ((static::$blockID == WATER && ($id == WATER || $id == STILL_WATER)) ||
(static::$blockID == LAVA && ($id == LAVA || $id == STILL_LAVA))) && (static::$blockID == LAVA && ($id == LAVA || $id == STILL_LAVA))) &&
@ -122,20 +122,20 @@ class LiquidBlockDynamic extends LiquidBlock{
){ ){
continue; continue;
} }
if(!static::isWaterBlocking($level, $xs, $ys - 1, $zs)) return $l; if(!static::isWaterBlocking($level, $xs, $ys - 1, $zs)) return $l;
if($l >= 4) continue; if($l >= 4) continue;
$k2 = static::getSlopeDistance($level, $xs, $ys, $zs, $l + 1, $k1); $k2 = static::getSlopeDistance($level, $xs, $ys, $zs, $l + 1, $k1);
if($k2 < $j1) $j1 = $k2; if($k2 < $j1) $j1 = $k2;
} }
return $j1; return $j1;
} }
public static function trySpreadTo(Level $level, $x, $y, $z, $meta){ public static function trySpreadTo(Level $level, $x, $y, $z, $meta){
if(static::canSpreadTo($level, $x, $y, $z)){ if(static::canSpreadTo($level, $x, $y, $z)){
[$id, $meta2] = $level->level->getBlock($x, $y, $z); [$id, $meta2] = $level->level->getBlock($x, $y, $z);
if($id > 0){ if($id > 0){
if(($id == LAVA || $id == STILL_LAVA) && (static::$blockID == LAVA || static::$blockID == STILL_LAVA)); //fizz if(($id == LAVA || $id == STILL_LAVA) && (static::$blockID == LAVA || static::$blockID == STILL_LAVA)); //fizz
else{ else{
@ -147,23 +147,23 @@ class LiquidBlockDynamic extends LiquidBlock{
} }
} }
} }
$level->fastSetBlockUpdate($x, $y, $z, static::$blockID, $meta, true); $level->fastSetBlockUpdate($x, $y, $z, static::$blockID, $meta, true);
} }
} }
public static function onPlace(Level $level, $x, $y, $z){ public static function onPlace(Level $level, $x, $y, $z){
static::updateLiquid($level, $x, $y, $z); static::updateLiquid($level, $x, $y, $z);
$id = $level->level->getBlockID($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()); 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){ public static function onUpdate(Level $level, $x, $y, $z, $type){
$id = $level->level->getBlockID($x, $y, $z); $id = $level->level->getBlockID($x, $y, $z);
$depth = static::getDepth($level, $x, $y, $z); $depth = static::getDepth($level, $x, $y, $z);
$flowAdd = (static::$blockID == LAVA) ? 2 : 1; $flowAdd = (static::$blockID == LAVA) ? 2 : 1;
$flag = true; $flag = true;
if($depth > 0){ if($depth > 0){
static::$sourcesAround = 0; static::$sourcesAround = 0;
$highest = static::getHighest($level, $x - 1, $y, $z, -100); $highest = static::getHighest($level, $x - 1, $y, $z, -100);
@ -174,19 +174,19 @@ class LiquidBlockDynamic extends LiquidBlock{
if($j1 >= 8 || $highest < 0) $j1 = -1; if($j1 >= 8 || $highest < 0) $j1 = -1;
$l1 = static::getDepth($level, $x, $y + 1, $z); $l1 = static::getDepth($level, $x, $y + 1, $z);
if($l1 >= 0) $j1 = ($l1 >= 8 ? $l1 : $l1 + 8); if($l1 >= 0) $j1 = ($l1 >= 8 ? $l1 : $l1 + 8);
if(static::$sourcesAround >= 2 && static::$blockID == WATER){ if(static::$sourcesAround >= 2 && static::$blockID == WATER){
$idBot = $level->level->getBlockID($x, $y - 1, $z); $idBot = $level->level->getBlockID($x, $y - 1, $z);
if($idBot > 0){ if($idBot > 0){
if(StaticBlock::getIsSolid($idBot) || (($idBot == WATER || $idBot == STILL_WATER) && $level->level->getBlockDamage($x, $y, $z) == 0)) $j1 = 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 //if(static::$blockID == LAVA && $depth < 8 && $j1 < 8 && $j1 > $depth && mt_rand(0, 4) != 0){ TODO fix later
// $j1 = $depth; // $j1 = $depth;
// $flag = false; // $flag = false;
//} //}
if($j1 != $depth){ if($j1 != $depth){
$depth = $j1; $depth = $j1;
if($depth < 0) $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); 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()); 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 $level->updateNeighborsAt($x, $y, $z, static::$blockID); //TODO check is needed
} }
}else if($flag){ }elseif($flag){
static::setStatic($level, $x, $y, $z); static::setStatic($level, $x, $y, $z);
} }
}else{ }else{
static::setStatic($level, $x, $y, $z); static::setStatic($level, $x, $y, $z);
} }
if(static::canSpreadTo($level, $x, $y - 1, $z)){ if(static::canSpreadTo($level, $x, $y - 1, $z)){
$level->fastSetBlockUpdate($x, $y - 1, $z, static::$blockID, ($depth >= 8 ? $depth : $depth + 8) & 0xf, true); $level->fastSetBlockUpdate($x, $y - 1, $z, static::$blockID, ($depth >= 8 ? $depth : $depth + 8) & 0xf, true);
}else if($depth >= 0 && ($depth == 0 || static::isWaterBlocking($level, $x, $y - 1, $z))){ }elseif($depth >= 0 && ($depth == 0 || static::isWaterBlocking($level, $x, $y - 1, $z))){
$flags = static::getSpread($level, $x, $y, $z); $flags = static::getSpread($level, $x, $y, $z);
$k1 = $depth >= 8 ? 1 : ($depth + $flowAdd); $k1 = $depth >= 8 ? 1 : ($depth + $flowAdd);
if($k1 >= 8) return; if($k1 >= 8) return;

View file

@ -6,13 +6,13 @@ class LiquidBlockStatic extends LiquidBlock{
} }
public static $blockID = 0; public static $blockID = 0;
//TODO: tick: try spread fire if lava //TODO: tick: try spread fire if lava
public static function setDynamic(Level $level, $x, $y, $z){ public static function setDynamic(Level $level, $x, $y, $z){
[$id, $meta] = $level->level->getBlock($x, $y, $z); [$id, $meta] = $level->level->getBlock($x, $y, $z);
$dynamicID = $id - 1; //very unsafe $dynamicID = $id - 1; //very unsafe
$level->fastSetBlockUpdate($x, $y, $z, $dynamicID, $meta); $level->fastSetBlockUpdate($x, $y, $z, $dynamicID, $meta);
} }
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
$oldID = $level->level->getBlockID($x, $y, $z); $oldID = $level->level->getBlockID($x, $y, $z);
static::updateLiquid($level, $x, $y, $z); static::updateLiquid($level, $x, $y, $z);
@ -21,6 +21,5 @@ class LiquidBlockStatic extends LiquidBlock{
static::setDynamic($level, $x, $y, $z); static::setDynamic($level, $x, $y, $z);
} }
} }
}
}

View file

@ -1,4 +1,5 @@
<?php <?php
require_once("LiquidBlockStatic.php"); //TODO class loader? require_once("LiquidBlockStatic.php"); //TODO class loader?
class StillLavaBlock extends LiquidBlockStatic{ class StillLavaBlock extends LiquidBlockStatic{
@ -7,9 +8,9 @@ class StillLavaBlock extends LiquidBlockStatic{
parent::__construct(STILL_LAVA, $meta, "Still Lava"); parent::__construct(STILL_LAVA, $meta, "Still Lava");
$this->hardness = 500; $this->hardness = 500;
} }
public static function getTickDelay(){ public static function getTickDelay(){
return 30; return 30;
} }
} }

View file

@ -1,6 +1,5 @@
<?php <?php
/***REM_START***/ /***REM_START***/
require_once("WaterBlock.php"); //TODO class loader? require_once("WaterBlock.php"); //TODO class loader?
require_once("LiquidBlockStatic.php"); //TODO class loader? require_once("LiquidBlockStatic.php"); //TODO class loader?
@ -13,7 +12,7 @@ class StillWaterBlock extends LiquidBlockStatic{
LiquidBlock::__construct(STILL_WATER, $meta, "Still Water"); LiquidBlock::__construct(STILL_WATER, $meta, "Still Water");
$this->hardness = 500; $this->hardness = 500;
} }
public static function getTickDelay(){ public static function getTickDelay(){
return 5; return 5;
} }

View file

@ -1,19 +1,20 @@
<?php <?php
require_once("LiquidBlockDynamic.php"); //TODO class loader? require_once("LiquidBlockDynamic.php"); //TODO class loader?
class WaterBlock extends LiquidBlockDynamic{ class WaterBlock extends LiquidBlockDynamic{
public static $blockID = WATER; public static $blockID = WATER;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(WATER, $meta, "Water"); parent::__construct(WATER, $meta, "Water");
$this->hardness = 500; $this->hardness = 500;
} }
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$ret = $this->level->setBlock($this, $this, true, false, true); $ret = $this->level->setBlock($this, $this, true, false, true);
return $ret; return $ret;
} }
public static function getTickDelay(){ public static function getTickDelay(){
return 5; return 5;
} }

View file

@ -2,7 +2,7 @@
class AirBlock extends TransparentBlock{ class AirBlock extends TransparentBlock{
public static $blockID; public static $blockID;
public function __construct(){ public function __construct(){
parent::__construct(AIR, 0, "Air"); parent::__construct(AIR, 0, "Air");
$this->isActivable = false; $this->isActivable = false;
@ -15,7 +15,7 @@ class AirBlock extends TransparentBlock{
$this->isSolid = false; $this->isSolid = false;
$this->isFullBlock = true; $this->isFullBlock = true;
$this->hardness = 0; $this->hardness = 0;
} }
} }

View file

@ -20,37 +20,37 @@ class BedBlock extends TransparentBlock{
$this->isFullBlock = false; $this->isFullBlock = false;
$this->hardness = 1; $this->hardness = 1;
} }
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return [static::getAABB($level, $x, $y, $z)]; return [static::getAABB($level, $x, $y, $z)];
} }
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
$meta = $level->level->getBlockDamage($x, $y, $z); $meta = $level->level->getBlockDamage($x, $y, $z);
$dir = $meta & 3; $dir = $meta & 3;
$isHead = ($meta >> 3) & 1; $isHead = ($meta >> 3) & 1;
$offX = self::HEAD_DIRECTION_OFFSETS[$dir][0]; $offX = self::HEAD_DIRECTION_OFFSETS[$dir][0];
$offZ = self::HEAD_DIRECTION_OFFSETS[$dir][1]; $offZ = self::HEAD_DIRECTION_OFFSETS[$dir][1];
if($isHead){ if($isHead){
if($level->level->getBlockID($x - $offX, $y, $z - $offZ) != BED_BLOCK){ if($level->level->getBlockID($x - $offX, $y, $z - $offZ) != BED_BLOCK){
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
} }
}else if($level->level->getBlockID($x + $offX, $y, $z + $offZ) != BED_BLOCK){ }elseif($level->level->getBlockID($x + $offX, $y, $z + $offZ) != BED_BLOCK){
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
ServerAPI::request()->api->entity->dropRawPos( ServerAPI::request()->api->entity->dropRawPos(
$level, $level,
$x + (lcg_value() * 0.7) + 0.15, $x + (lcg_value() * 0.7) + 0.15,
$y + (lcg_value() * 0.7) + 0.15, $y + (lcg_value() * 0.7) + 0.15,
$z + (lcg_value() * 0.7) + 0.15, $z + (lcg_value() * 0.7) + 0.15,
BlockAPI::getItem(BED, 0, 1), BlockAPI::getItem(BED, 0, 1),
lcg_value() * 0.2 - 0.1, 0.2, lcg_value() * 0.2 - 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){ public static function findStandUpPosition(Level $level, $x, $y, $z){
$blockMeta = $level->level->getBlockDamage($x, $y, $z); $blockMeta = $level->level->getBlockDamage($x, $y, $z);
@ -60,7 +60,7 @@ class BedBlock extends TransparentBlock{
$minZ = $z - self::HEAD_DIRECTION_OFFSETS[$direction][1] * $v7 - 1; $minZ = $z - self::HEAD_DIRECTION_OFFSETS[$direction][1] * $v7 - 1;
$maxX = $minX + 2; $maxX = $minX + 2;
$maxZ = $minZ + 2; $maxZ = $minZ + 2;
for($xCheck = $minX; $xCheck <= $maxX; ++$xCheck){ for($xCheck = $minX; $xCheck <= $maxX; ++$xCheck){
for($zCheck = $minZ; $zCheck <= $maxZ; ++$zCheck){ for($zCheck = $minZ; $zCheck <= $maxZ; ++$zCheck){
$idCheck = $level->level->getBlockID($xCheck, $y - 1, $zCheck); $idCheck = $level->level->getBlockID($xCheck, $y - 1, $zCheck);
@ -70,10 +70,10 @@ class BedBlock extends TransparentBlock{
} }
} }
} }
return null; return null;
} }
public function onActivate(Item $item, Player $player){ public function onActivate(Item $item, Player $player){
if(ServerAPI::request()->api->time->getPhase($player->level) !== "night"){ if(ServerAPI::request()->api->time->getPhase($player->level) !== "night"){
$pk = new ChatPacket; $pk = new ChatPacket;
@ -81,12 +81,12 @@ class BedBlock extends TransparentBlock{
$player->dataPacket($pk); $player->dataPacket($pk);
return true; return true;
} }
$blockNorth = $this->getSide(2); //Gets the blocks around them $blockNorth = $this->getSide(2); //Gets the blocks around them
$blockSouth = $this->getSide(3); $blockSouth = $this->getSide(3);
$blockEast = $this->getSide(5); $blockEast = $this->getSide(5);
$blockWest = $this->getSide(4); $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; $b = $this;
}else{ //Bottom Part of Bed }else{ //Bottom Part of Bed
if($blockNorth->getID() === $this->id and ($blockNorth->meta & 0x08) === 0x08){ if($blockNorth->getID() === $this->id and ($blockNorth->meta & 0x08) === 0x08){
@ -112,11 +112,11 @@ class BedBlock extends TransparentBlock{
} }
return true; return true;
} }
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$down = $this->getSide(0); $down = $this->getSide(0);
if($down->isTransparent === false){ if($down->isTransparent === false){
$d = $player->entity->getDirection(); $d = $player->entity->getDirection();
$next = $this->getSide(self::$faces[(($d + 3) % 4)]); $next = $this->getSide(self::$faces[(($d + 3) % 4)]);
$downNext = $next->getSide(0); $downNext = $next->getSide(0);
@ -128,15 +128,15 @@ class BedBlock extends TransparentBlock{
} }
} }
return false; return false;
} }
public function onBreak(Item $item, Player $player){ public function onBreak(Item $item, Player $player){
$blockNorth = $this->getSide(2); //Gets the blocks around them $blockNorth = $this->getSide(2); //Gets the blocks around them
$blockSouth = $this->getSide(3); $blockSouth = $this->getSide(3);
$blockEast = $this->getSide(5); $blockEast = $this->getSide(5);
$blockWest = $this->getSide(4); $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){ switch($this->meta & 0x7){
case 0: case 0:
if($blockNorth->id === $this->id) $this->level->setBlock($blockNorth, new AirBlock(), true, false, true); if($blockNorth->id === $this->id) $this->level->setBlock($blockNorth, new AirBlock(), true, false, true);
@ -170,11 +170,11 @@ class BedBlock extends TransparentBlock{
$this->level->setBlock($this, new AirBlock(), true, false, true); $this->level->setBlock($this, new AirBlock(), true, false, true);
return true; return true;
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return array( return [
array(BED, 0, 1), [BED, 0, 1],
); ];
} }
} }

View file

@ -4,7 +4,7 @@ class FireBlock extends FlowableBlock implements LightingBlock{
public static $blockID; public static $blockID;
public static $flammability = []; public static $flammability = [];
public static $fireCatchingChance = []; public static $fireCatchingChance = [];
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(FIRE, $meta, "Fire"); parent::__construct(FIRE, $meta, "Fire");
$this->isReplaceable = true; $this->isReplaceable = true;
@ -19,39 +19,39 @@ class FireBlock extends FlowableBlock implements LightingBlock{
self::$flammability[$blockID] = $flammability; self::$flammability[$blockID] = $flammability;
self::$fireCatchingChance[$blockID] = $v; self::$fireCatchingChance[$blockID] = $v;
} }
public static function canBurn(Level $level, $x, $y, $z){ public static function canBurn(Level $level, $x, $y, $z){
return self::$flammability[$level->level->getBlockID($x, $y, $z)] > 0; return self::$flammability[$level->level->getBlockID($x, $y, $z)] > 0;
} }
public static function onRandomTick(Level $level, $x, $y, $z){ public static function onRandomTick(Level $level, $x, $y, $z){
if($level->level->getBlockID($x, $y - 1, $z) !== NETHERRACK){ if($level->level->getBlockID($x, $y - 1, $z) !== NETHERRACK){
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
} }
} }
public static function onPlace(Level $level, $x, $y, $z){ public static function onPlace(Level $level, $x, $y, $z){
ServerAPI::request()->api->block->scheduleBlockUpdateXYZ($level, $x, $y, $z, BLOCK_UPDATE_SCHEDULED, 30); ServerAPI::request()->api->block->scheduleBlockUpdateXYZ($level, $x, $y, $z, BLOCK_UPDATE_SCHEDULED, 30);
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return array(); return [];
} }
public function getMaxLightValue(){ public function getMaxLightValue(){
return 15; return 15;
} }
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){
$b = $level->level->getBlockID($x, $y - 1, $z); $b = $level->level->getBlockID($x, $y - 1, $z);
if(!StaticBlock::getIsSolid($b)) $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); //TODO more vanilla later? if(!StaticBlock::getIsSolid($b)) $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); //TODO more vanilla later?
} }
public static function onUpdate(Level $level, $x, $y, $z, $type){ public static function onUpdate(Level $level, $x, $y, $z, $type){
if($type === BLOCK_UPDATE_SCHEDULED){ if($type === BLOCK_UPDATE_SCHEDULED){
$idBelow = $level->level->getBlockID($x, $y - 1, $z); $idBelow = $level->level->getBlockID($x, $y - 1, $z);
[$id, $meta] = $level->level->getBlock($x, $y, $z); [$id, $meta] = $level->level->getBlock($x, $y, $z);
$alwaysBurn = $idBelow == NETHERRACK; $alwaysBurn = $idBelow == NETHERRACK;
if($meta < 15){ if($meta < 15){
$newMeta = $meta + 1; //TODO better formula $newMeta = $meta + 1; //TODO better formula
if($newMeta > 15) $newMeta = 15; if($newMeta > 15) $newMeta = 15;
@ -65,20 +65,19 @@ class FireBlock extends FlowableBlock implements LightingBlock{
} }
} }
$chance = self::$fireCatchingChance[$idBelow]; $chance = self::$fireCatchingChance[$idBelow];
if(mt_rand(0, 249) < $chance){ if(mt_rand(0, 249) < $chance){
//TODO ignite tnt //TODO ignite tnt
$level->fastSetBlockUpdate($x, $y - 1, $z, 0, 0, true); $level->fastSetBlockUpdate($x, $y - 1, $z, 0, 0, true);
goto REMOVE_FIRE; goto REMOVE_FIRE;
} }
ServerAPI::request()->api->block->scheduleBlockUpdateXYZ($level, $x, $y, $z, BLOCK_UPDATE_SCHEDULED, 30); //TODO looks like it also adds mt_rand(0, 9) to it ServerAPI::request()->api->block->scheduleBlockUpdateXYZ($level, $x, $y, $z, BLOCK_UPDATE_SCHEDULED, 30); //TODO looks like it also adds mt_rand(0, 9) to it
} }
} }
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
parent::place($item, $player, $block, $target, $face, $fx, $fy, $fz); parent::place($item, $player, $block, $target, $face, $fx, $fy, $fz);
$this->level->scheduleBlockUpdate($this, 30, BLOCK_UPDATE_SCHEDULED); $this->level->scheduleBlockUpdate($this, 30, BLOCK_UPDATE_SCHEDULED);
} }
} }

View file

@ -7,7 +7,7 @@ class NetherReactorBlock extends SolidBlock{
parent::__construct(NETHER_REACTOR, $meta, "Nether Reactor"); parent::__construct(NETHER_REACTOR, $meta, "Nether Reactor");
$this->isActivable = true; $this->isActivable = true;
} }
public function onActivate(Item $item, Player $player){ public function onActivate(Item $item, Player $player){
//if(($item->getID() === IRON_SWORD || $item->getID() === WOODEN_SWORD || $item->getID() === STONE_SWORD || $item->getID() === DIAMOND_SWORD || $item->getID() === GOLD_SWORD) /*&& $player->gamemode === 0*/){ //if(($item->getID() === IRON_SWORD || $item->getID() === WOODEN_SWORD || $item->getID() === STONE_SWORD || $item->getID() === DIAMOND_SWORD || $item->getID() === GOLD_SWORD) /*&& $player->gamemode === 0*/){
if($this->getMetadata() === 0 && $this->isCorrect($this->getX(),$this->getY(),$this->getZ()) && $this->getY() < 101 && NetherReactorBlock::$enableReactor){ if($this->getMetadata() === 0 && $this->isCorrect($this->getX(),$this->getY(),$this->getZ()) && $this->getY() < 101 && NetherReactorBlock::$enableReactor){
@ -15,58 +15,58 @@ class NetherReactorBlock extends SolidBlock{
$this->meta = 1; $this->meta = 1;
$this->level->setBlock($this,$this); $this->level->setBlock($this,$this);
$server = ServerAPI::request(); $server = ServerAPI::request();
$server->schedule(40, array($this, "glow"), 1); $server->schedule(40, [$this, "glow"], 1);
$server->schedule(60, array($this, "glow"), 2); $server->schedule(60, [$this, "glow"], 2);
$server->schedule(80, array($this, "glow"), 3); $server->schedule(80, [$this, "glow"], 3);
$server->schedule(140, array($this, "glow"), 4); $server->schedule(140, [$this, "glow"], 4);
$server->schedule(200, array($this, "spawnItems"), [0,15,2,true]); //200 $server->schedule(200, [$this, "spawnItems"], [0,15,2,true]); //200
$server->schedule(260, array($this, "spawnItems"), [0,15,"checkPigmen",true]); $server->schedule(260, [$this, "spawnItems"], [0,15,"checkPigmen",true]);
$server->schedule(300, array($this, "spawnItems"), [0,15,"checkPigmen",true]); $server->schedule(300, [$this, "spawnItems"], [0,15,"checkPigmen",true]);
$server->schedule(340, array($this, "spawnItems"), [11,20,"checkPigmen",false]); $server->schedule(340, [$this, "spawnItems"], [11,20,"checkPigmen",false]);
$server->schedule(400, array($this, "spawnItems"), [0,10,"checkPigmen",false]); $server->schedule(400, [$this, "spawnItems"], [0,10,"checkPigmen",false]);
$server->schedule(500, array($this, "spawnItems"), [17,32, "checkPigmen",false]); //500 $server->schedule(500, [$this, "spawnItems"], [17,32, "checkPigmen",false]); //500
$server->schedule(580, array($this, "spawnItems"), [17,32, "checkPigmen",false]); $server->schedule(580, [$this, "spawnItems"], [17,32, "checkPigmen",false]);
$server->schedule(620, array($this, "spawnItems"), [1,32, "checkPigmen",false]); $server->schedule(620, [$this, "spawnItems"], [1,32, "checkPigmen",false]);
$server->schedule(660, array($this, "spawnItems"), [1,32,"checkPigmen",false]); $server->schedule(660, [$this, "spawnItems"], [1,32,"checkPigmen",false]);
$server->schedule(700, array($this, "spawnItems"), [1,32,"checkPigmen",false]); $server->schedule(700, [$this, "spawnItems"], [1,32,"checkPigmen",false]);
$server->schedule(860, array($this, "glow"), 5); $server->schedule(860, [$this, "glow"], 5);
$server->schedule(880, array($this, "glow"), 6); $server->schedule(880, [$this, "glow"], 6);
$server->schedule(900, array($this, "glow"), 7); $server->schedule(900, [$this, "glow"], 7);
$server->schedule(920, array($this, "destroy")); $server->schedule(920, [$this, "destroy"]);
return true; return true;
} }
//} //}
} }
public function destroy(){ public function destroy(){
$this->level->setBlock(new Vector3($this->x, $this->y, $this->z),new NetherReactorBlock(2)); $this->level->setBlock(new Vector3($this->x, $this->y, $this->z),new NetherReactorBlock(2));
$this->decay($this->x-8, $this->y-3, $this->z-8, 0, 17, 16, 2, 34, 1, 0, 17, 1); $this->decay($this->x - 8, $this->y - 3, $this->z - 8, 0, 17, 16, 2, 34, 1, 0, 17, 1);
$this->decay($this->x-8, $this->y-3, $this->z-8, 1, 16, 1, 2, 34, 1, 0, 17, 16); $this->decay($this->x - 8, $this->y - 3, $this->z - 8, 1, 16, 1, 2, 34, 1, 0, 17, 16);
$this->decay($this->x-8, $this->y-3, $this->z-8, 3, 14, 10, 8, 34, 1, 3, 14, 1); $this->decay($this->x - 8, $this->y - 3, $this->z - 8, 3, 14, 10, 8, 34, 1, 3, 14, 1);
$this->decay($this->x-8, $this->y-3, $this->z-8, 4, 13, 1, 8, 34, 1, 3, 14, 10); $this->decay($this->x - 8, $this->y - 3, $this->z - 8, 4, 13, 1, 8, 34, 1, 3, 14, 10);
$this->decay($this->x-8, $this->y-3, $this->z-8, 5, 12, 6, 14, 34, 1, 5, 12, 1); $this->decay($this->x - 8, $this->y - 3, $this->z - 8, 5, 12, 6, 14, 34, 1, 5, 12, 1);
$this->decay($this->x-8, $this->y-3, $this->z-8, 6, 11, 1, 14, 34, 1, 5, 12, 16); $this->decay($this->x - 8, $this->y - 3, $this->z - 8, 6, 11, 1, 14, 34, 1, 5, 12, 16);
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
if($item->getPickaxeLevel() >= 1){ if($item->getPickaxeLevel() >= 1){
return [[NETHER_REACTOR, 0, 1]]; return [[NETHER_REACTOR, 0, 1]];
} }
} }
private function decay($x, $y, $z, $aOne, $aTwo, $aThree, $bOne, $bTwo, $bThree, $cOne, $cTwo, $cThree) { private function decay($x, $y, $z, $aOne, $aTwo, $aThree, $bOne, $bTwo, $bThree, $cOne, $cTwo, $cThree) {
for($a = $aOne; $a < $aTwo; $a += $aThree) { for($a = $aOne; $a < $aTwo; $a += $aThree) {
for($b = $bOne; $b < $bTwo; $b += $bThree) { for($b = $bOne; $b < $bTwo; $b += $bThree) {
for($c = $cOne; $c < $cTwo; $c += $cThree) { for($c = $cOne; $c < $cTwo; $c += $cThree) {
if ($this->level->level->getBlockID($x+$a, $y+$b, $z+$c) === NETHERRACK && lcg_value() > 0.75){ if ($this->level->level->getBlockID($x + $a, $y + $b, $z + $c) === NETHERRACK && lcg_value() > 0.75){
$this->level->fastSetBlockUpdate($x+$a, $y+$b, $z+$c, 0, 0); $this->level->fastSetBlockUpdate($x + $a, $y + $b, $z + $c, 0, 0);
} }
} }
} }
} }
} }
private function pigmenCheck($x,$y,$z) { private function pigmenCheck($x,$y,$z) {
$pigCount = 0; $pigCount = 0;
$server = ServerAPI::request(); $server = ServerAPI::request();
@ -88,28 +88,28 @@ class NetherReactorBlock extends SolidBlock{
$forceAmount = $data[3]; $forceAmount = $data[3];
$server = ServerAPI::request(); $server = ServerAPI::request();
if(!$forceAmount){ if(!$forceAmount){
$spawnNumber = $minAmount + floor(lcg_value()*($maxAmount-$minAmount+1)); $spawnNumber = $minAmount + floor(lcg_value() * ($maxAmount - $minAmount + 1));
} }
else{ else{
$spawnNumber = $maxAmount; $spawnNumber = $maxAmount;
} }
for($i = 0; $i < $spawnNumber; $i++) { for($i = 0; $i < $spawnNumber; $i++) {
$randomRange = floor(lcg_value()*5+3); $randomRange = floor(lcg_value() * 5 + 3);
$shiftX = cos(floor(lcg_value()*360)*(pi()/180)); $shiftX = cos(floor(lcg_value() * 360) * (pi() / 180));
$shiftZ = sin(floor(lcg_value()*360)*(pi()/180)); $shiftZ = sin(floor(lcg_value() * 360) * (pi() / 180));
if(Utils::chance(5)) $randomID = $this->rarePossibleLoot[array_rand($this->rarePossibleLoot)]; if(Utils::chance(5)) $randomID = $this->rarePossibleLoot[array_rand($this->rarePossibleLoot)];
else $randomID = $this->possibleLoot[array_rand($this->possibleLoot)]; else $randomID = $this->possibleLoot[array_rand($this->possibleLoot)];
$server->api->entity->drop(new Position($x+($shiftX*$randomRange)+0.5, $y, $z+($shiftZ*$randomRange)+0.5, $this->level), BlockAPI::getItem($randomID, 0, 1)); $server->api->entity->drop(new Position($x + ($shiftX * $randomRange) + 0.5, $y, $z + ($shiftZ * $randomRange) + 0.5, $this->level), BlockAPI::getItem($randomID, 0, 1));
} }
for($i = 0; $i < $pigmen; $i++) { for($i = 0; $i < $pigmen; $i++) {
$randomRange = floor(lcg_value()*5+3); $randomRange = floor(lcg_value() * 5 + 3);
$shiftX = cos(floor(lcg_value()*360)*(pi()/180)); $shiftX = cos(floor(lcg_value() * 360) * (pi() / 180));
$shiftZ = sin(floor(lcg_value()*360)*(pi()/180)); $shiftZ = sin(floor(lcg_value() * 360) * (pi() / 180));
$data = array( $data = [
"x" => $x+($shiftX*$randomRange)+0.5, "x" => $x + ($shiftX * $randomRange) + 0.5,
"y" => $y, "y" => $y,
"z" => $z+($shiftZ*$randomRange)+0.5, "z" => $z + ($shiftZ * $randomRange) + 0.5,
); ];
$e = $server->api->entity->add($this->level, ENTITY_MOB, MOB_PIGMAN, $data); $e = $server->api->entity->add($this->level, ENTITY_MOB, MOB_PIGMAN, $data);
$server->api->entity->spawnToAll($e); $server->api->entity->spawnToAll($e);
} }
@ -120,63 +120,63 @@ class NetherReactorBlock extends SolidBlock{
$z = $this->z; $z = $this->z;
switch($part){ switch($part){
case 1: case 1:
$this->level->setBlock(new Vector3($x, $y-1, $z),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x, $y - 1, $z),new GlowingObsidianBlock);
$this->level->setBlock(new Vector3($x+1, $y-1, $z),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y - 1, $z),new GlowingObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y-1, $z),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y - 1, $z),new GlowingObsidianBlock);
$this->level->setBlock(new Vector3($x, $y-1, $z+1),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x, $y - 1, $z + 1),new GlowingObsidianBlock);
$this->level->setBlock(new Vector3($x, $y-1, $z-1),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x, $y - 1, $z - 1),new GlowingObsidianBlock);
break; break;
case 2: case 2:
$this->level->setBlock(new Vector3($x+1, $y, $z+1),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y, $z + 1),new GlowingObsidianBlock);
$this->level->setBlock(new Vector3($x+1, $y, $z-1),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y, $z - 1),new GlowingObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y, $z+1),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y, $z + 1),new GlowingObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y, $z-1),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y, $z - 1),new GlowingObsidianBlock);
break; break;
case 3: case 3:
$this->level->setBlock(new Vector3($x, $y+1, $z),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x, $y + 1, $z),new GlowingObsidianBlock);
$this->level->setBlock(new Vector3($x+1, $y+1, $z),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y + 1, $z),new GlowingObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y+1, $z),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y + 1, $z),new GlowingObsidianBlock);
$this->level->setBlock(new Vector3($x, $y+1, $z+1),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x, $y + 1, $z + 1),new GlowingObsidianBlock);
$this->level->setBlock(new Vector3($x, $y+1, $z-1),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x, $y + 1, $z - 1),new GlowingObsidianBlock);
break; break;
case 4: case 4:
$this->level->setBlock(new Vector3($x+1, $y-1, $z+1),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y - 1, $z + 1),new GlowingObsidianBlock);
$this->level->setBlock(new Vector3($x+1, $y-1, $z-1),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y - 1, $z - 1),new GlowingObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y-1, $z+1),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y - 1, $z + 1),new GlowingObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y-1, $z-1),new GlowingObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y - 1, $z - 1),new GlowingObsidianBlock);
break; break;
case 5: case 5:
$this->level->setBlock(new Vector3($x, $y+1, $z),new ObsidianBlock); $this->level->setBlock(new Vector3($x, $y + 1, $z),new ObsidianBlock);
$this->level->setBlock(new Vector3($x+1, $y+1, $z),new ObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y + 1, $z),new ObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y+1, $z),new ObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y + 1, $z),new ObsidianBlock);
$this->level->setBlock(new Vector3($x, $y+1, $z+1),new ObsidianBlock); $this->level->setBlock(new Vector3($x, $y + 1, $z + 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x, $y+1, $z-1),new ObsidianBlock); $this->level->setBlock(new Vector3($x, $y + 1, $z - 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x+1, $y+1, $z+1),new ObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y + 1, $z + 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x+1, $y+1, $z-1),new ObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y + 1, $z - 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y+1, $z+1),new ObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y + 1, $z + 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y+1, $z-1),new ObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y + 1, $z - 1),new ObsidianBlock);
break; break;
case 6: case 6:
$this->level->setBlock(new Vector3($x, $y, $z), new NetherReactorBlock(2)); $this->level->setBlock(new Vector3($x, $y, $z), new NetherReactorBlock(2));
$this->level->setBlock(new Vector3($x+1, $y, $z),new ObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y, $z),new ObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y, $z),new ObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y, $z),new ObsidianBlock);
$this->level->setBlock(new Vector3($x, $y, $z+1),new ObsidianBlock); $this->level->setBlock(new Vector3($x, $y, $z + 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x, $y, $z-1),new ObsidianBlock); $this->level->setBlock(new Vector3($x, $y, $z - 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x+1, $y, $z+1),new ObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y, $z + 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x+1, $y, $z-1),new ObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y, $z - 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y, $z+1),new ObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y, $z + 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y, $z-1),new ObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y, $z - 1),new ObsidianBlock);
break; break;
case 7: case 7:
$this->level->setBlock(new Vector3($x, $y-1, $z),new ObsidianBlock); $this->level->setBlock(new Vector3($x, $y - 1, $z),new ObsidianBlock);
$this->level->setBlock(new Vector3($x+1, $y-1, $z),new ObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y - 1, $z),new ObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y-1, $z),new ObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y - 1, $z),new ObsidianBlock);
$this->level->setBlock(new Vector3($x, $y-1, $z+1),new ObsidianBlock); $this->level->setBlock(new Vector3($x, $y - 1, $z + 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x, $y-1, $z-1),new ObsidianBlock); $this->level->setBlock(new Vector3($x, $y - 1, $z - 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x+1, $y-1, $z+1),new ObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y - 1, $z + 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x+1, $y-1, $z-1),new ObsidianBlock); $this->level->setBlock(new Vector3($x + 1, $y - 1, $z - 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y-1, $z+1),new ObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y - 1, $z + 1),new ObsidianBlock);
$this->level->setBlock(new Vector3($x-1, $y-1, $z-1),new ObsidianBlock); $this->level->setBlock(new Vector3($x - 1, $y - 1, $z - 1),new ObsidianBlock);
break; break;
} }
} }
@ -218,18 +218,18 @@ class NetherReactorBlock extends SolidBlock{
} }
return true; return true;
} }
private $possibleLoot = [ private $possibleLoot = [
GLOWSTONE_DUST, QUARTZ, CACTUS, SUGARCANE, BROWN_MUSHROOM, RED_MUSHROOM, PUMPKIN_SEEDS, MELON_SEEDS GLOWSTONE_DUST, QUARTZ, CACTUS, SUGARCANE, BROWN_MUSHROOM, RED_MUSHROOM, PUMPKIN_SEEDS, MELON_SEEDS
]; ];
private $rarePossibleLoot = [ private $rarePossibleLoot = [
BOW, BED, BOWL, ARROW, WOODEN_DOOR, FEATHER, PAINTING, BONE, DANDELION BOW, BED, BOWL, ARROW, WOODEN_DOOR, FEATHER, PAINTING, BONE, DANDELION
]; ];
private $core = [ private $core = [
-1 => ["GCG", "CCC", "GCG"], -1 => ["GCG", "CCC", "GCG"],
0 => ["C C", " R ", "C C",], 0 => ["C C", " R ", "C C",],
1 =>[" C ", "CCC", " C "] 1 => [" C ", "CCC", " C "]
]; ];
} }

View file

@ -7,19 +7,19 @@ class TNTBlock extends SolidBlock{
$this->hardness = 0; $this->hardness = 0;
$this->isActivable = true; $this->isActivable = true;
} }
public function onActivate(Item $item, Player $player){ public function onActivate(Item $item, Player $player){
if($item->getID() === FLINT_STEEL){ if($item->getID() === FLINT_STEEL){
if(($player->gamemode & 0x01) === 0){ if(($player->gamemode & 0x01) === 0){
$item->useOn($this); $item->useOn($this);
} }
$data = array( $data = [
"x" => $this->x + 0.5, "x" => $this->x + 0.5,
"y" => $this->y, "y" => $this->y,
"z" => $this->z + 0.5, "z" => $this->z + 0.5,
"power" => 3, "power" => 3,
"fuse" => 20 * 4, //4 seconds "fuse" => 20 * 4, //4 seconds
); ];
$this->level->fastSetBlockUpdate($this->x, $this->y, $this->z, 0, 0, true); $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); $e = ServerAPI::request()->api->entity->add($this->level, ENTITY_OBJECT, OBJECT_PRIMEDTNT, $data);
ServerAPI::request()->api->entity->spawnToAll($e); ServerAPI::request()->api->entity->spawnToAll($e);

View file

@ -9,18 +9,18 @@ class CakeBlock extends TransparentBlock{
$this->meta = $meta & 0x07; $this->meta = $meta & 0x07;
$this->hardness = 2.5; $this->hardness = 2.5;
} }
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){ public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
$data = $level->level->getBlockDamage($x, $y, $z); $data = $level->level->getBlockDamage($x, $y, $z);
return [new AxisAlignedBB($x + (2*$data + 1) * 0.0625, $y, $z + 0.0625, $x + 0.9375, $y + 0.5, $z + 0.9375)]; return [new AxisAlignedBB($x + (2 * $data + 1) * 0.0625, $y, $z + 0.0625, $x + 0.9375, $y + 0.5, $z + 0.9375)];
} }
public static function updateShape(Level $level, $x, $y, $z){ public static function updateShape(Level $level, $x, $y, $z){
[$id, $data] = $level->level->getBlock($x, $y, $z); [$id, $data] = $level->level->getBlock($x, $y, $z);
StaticBlock::setBlockBounds($id, (2 * $data + 1) * 0.0625, 0.0, 0.0625, 0.9375, 0.5, 0.9375); StaticBlock::setBlockBounds($id, (2 * $data + 1) * 0.0625, 0.0, 0.0625, 0.9375, 0.5, 0.9375);
} }
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){ public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$down = $this->getSide(0); $down = $this->getSide(0);
if($down->getID() !== AIR){ if($down->getID() !== AIR){
@ -29,17 +29,17 @@ class CakeBlock extends TransparentBlock{
} }
return false; return false;
} }
public static function neighborChanged(Level $level, $x, $y, $z, $nX, $nY, $nZ, $oldID){ 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){ //Replace with common break method
$level->fastSetBlockUpdate($x, $y, $z, 0, 0, true); $level->fastSetBlockUpdate($x, $y, $z, 0, 0, true);
} }
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return array(); return [];
} }
public function onActivate(Item $item, Player $player){ public function onActivate(Item $item, Player $player){
if($player->entity->getHealth() < 20){ if($player->entity->getHealth() < 20){
++$this->meta; ++$this->meta;
@ -53,5 +53,5 @@ class CakeBlock extends TransparentBlock{
} }
return false; return false;
} }
} }

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