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

@ -92,7 +92,6 @@ class AchievementAPI{
* 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 = []){
@ -185,14 +184,14 @@ class AchievementAPI{
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(){

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)){
@ -289,7 +289,7 @@ 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":
@ -311,7 +311,7 @@ class BlockAPI{
} }
$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] ?? "");
@ -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]));
@ -505,7 +504,7 @@ class BlockAPI{
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
} }
@ -541,8 +540,6 @@ class BlockAPI{
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){

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

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

@ -20,7 +20,6 @@ class EntityAPI{
$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,
@ -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)){
@ -82,7 +81,7 @@ class EntityAPI{
$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]);
@ -160,8 +159,8 @@ class EntityAPI{
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]);
@ -196,8 +195,8 @@ class EntityAPI{
$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])){
@ -223,10 +222,10 @@ class EntityAPI{
} }
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){

View file

@ -49,7 +49,6 @@ 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");

View file

@ -107,7 +107,7 @@ class PlayerAPI{
$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);

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,7 +149,7 @@ 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"])){
@ -159,13 +159,13 @@ class PluginAPI extends stdClass{
} }
$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");
@ -312,4 +312,3 @@ class RequiredPluginEntry{ //Use this as object of requirements array
} }
} }

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;
private $handCnt;
private $events;
private $eventsID;
private $handlers;
private $serverType;
private $lastTick;
private $memoryStats;
private $async = [];
private $asyncID = 0;
public $doTick, $levelData, $tiles, $entities, $schedule, $scheduleCnt, $whitelist, $spawn, $difficulty, $stop, $asyncThread; public $doTick;
public static $FORCE_20_TPS = false, $KEEP_CHUNKS_LOADED = true, $PACKET_READING_LIMIT = 100;
function __construct($name, $gamemode = SURVIVAL, $seed = false, $port = 19132, $serverip = "0.0.0.0"){ 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;
@ -26,8 +77,7 @@ class PocketMinecraftServer{
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...");
@ -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);
@ -230,8 +280,8 @@ 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, [
@ -244,15 +294,15 @@ class PocketMinecraftServer{
} }
} }
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,64 +419,64 @@ 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"]);
@ -439,8 +488,8 @@ class PocketMinecraftServer{
$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,8 +497,8 @@ 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;
} }
@ -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,17 +524,16 @@ 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;
} }
} }
@ -493,30 +541,30 @@ class PocketMinecraftServer{
$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);
} }
} }
@ -524,22 +572,21 @@ class PocketMinecraftServer{
} }
} }
} }
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,4 +1,5 @@
<?php <?php
class TileNavigator class TileNavigator
{ {
@ -21,9 +22,9 @@ class TileNavigator
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);
@ -57,7 +58,6 @@ class TileNavigator
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;
@ -71,12 +71,12 @@ class TileNavigator
$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;
@ -108,10 +108,10 @@ 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{
@ -119,17 +119,17 @@ class TileNavigator
} }
} }
} }
$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;
} }
@ -148,14 +148,13 @@ class TileNavigator
$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]))
{ {
@ -191,6 +190,5 @@ class TileNavigator
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

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

@ -7,8 +7,6 @@ abstract class Animal extends Creature implements Ageable, Breedable{
public $age; public $age;
public $loveTimeout; public $loveTimeout;
public $closestPlayerThatCanFeedEID = false; public $closestPlayerThatCanFeedEID = false;
public $closestPlayerThatCanFeedDist = INF; public $closestPlayerThatCanFeedDist = INF;
@ -33,7 +31,7 @@ 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;
} }
} }

View file

@ -7,7 +7,6 @@ abstract class Creature extends Living{
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);
@ -21,7 +20,6 @@ abstract class Creature extends Living{
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,7 +28,7 @@ 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;
} }
} }

View file

@ -3,9 +3,9 @@
class Entity extends Position class Entity extends Position
{ {
const TYPE = - 1; const TYPE = -1;
const CLASS_TYPE = - 1; const CLASS_TYPE = -1;
const MIN_POSSIBLE_SPEED = 1/8000; //anything below will send 0 to player const MIN_POSSIBLE_SPEED = 1 / 8000; //anything below will send 0 to player
public $searchForClosestPlayers = false; public $searchForClosestPlayers = false;
public $modifySpeedY = false; public $modifySpeedY = false;
@ -36,7 +36,7 @@ class Entity extends Position
public $delayBeforePickup; public $delayBeforePickup;
public $x, $y, $z; public $x, $y, $z;
public $speedX, $speedY, $speedZ, $speed; public $speedX, $speedY, $speedZ, $speed;
public $lastX = 0, $lastY = 0, $lastZ = 0, $lastYaw = 0, $lastPitch = 0, $lastTime = 0, $lastHeadYaw = 0, $lastSpeedX = 0, $lastSpeedY = 0, $lastSpeedZ = 0; public $lastX = 0, $lastY = 0, $lastZ = 0, $lastYaw = 0, $lastPitch = 0, $lastTime = 0, $lastHeadYaw = 0, $lastSpeedX = 0, $lastSpeedY = 0, $lastSpeedZ = 0;
/** /**
* 0 = lastX, * 0 = lastX,
* 1 = lastY, * 1 = lastY,
@ -65,7 +65,7 @@ class Entity extends Position
public $fallStart; public $fallStart;
private $state; private $state;
private $tickCounter; private $tickCounter;
private $speedMeasure = array(0, 0, 0, 0, 0, 0, 0); private $speedMeasure = [0, 0, 0, 0, 0, 0, 0];
public $server; public $server;
private $isStatic; private $isStatic;
public $level; public $level;
@ -131,7 +131,7 @@ class Entity extends Position
$this->status = 0; $this->status = 0;
$this->health = 20; $this->health = 20;
$this->hasGravity = false; $this->hasGravity = false;
$this->dmgcounter = array(0, 0, 0); $this->dmgcounter = [0, 0, 0];
$this->air = $this->maxAir; $this->air = $this->maxAir;
$this->fire = 0; $this->fire = 0;
$this->crouched = false; $this->crouched = false;
@ -154,14 +154,14 @@ class Entity extends Position
$this->yaw = isset($this->data["yaw"]) ? (float) $this->data["yaw"] : 0; $this->yaw = isset($this->data["yaw"]) ? (float) $this->data["yaw"] : 0;
$this->headYaw = $this->data["headYaw"] ?? $this->yaw; $this->headYaw = $this->data["headYaw"] ?? $this->yaw;
$this->pitch = isset($this->data["pitch"]) ? (float) $this->data["pitch"] : 0; $this->pitch = isset($this->data["pitch"]) ? (float) $this->data["pitch"] : 0;
$this->position = array( $this->position = [
"level" => $this->level, "level" => $this->level,
"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" => &$this->pitch "pitch" => &$this->pitch
); ];
$this->moveTime = 0; $this->moveTime = 0;
$this->lookTime = 0; $this->lookTime = 0;
$this->onGround = false; $this->onGround = false;
@ -345,26 +345,26 @@ class Entity extends Position
if(self::$keepInventory){ if(self::$keepInventory){
return []; return [];
} }
for($i = 0; $i < PLAYER_SURVIVAL_SLOTS; ++ $i){ for($i = 0; $i < PLAYER_SURVIVAL_SLOTS; ++$i){
$slot = $this->player->getSlot($i); $slot = $this->player->getSlot($i);
$this->player->setSlot($i, BlockAPI::getItem(AIR, 0, 0)); $this->player->setSlot($i, BlockAPI::getItem(AIR, 0, 0));
if($slot->getID() !== AIR and $slot->count > 0){ if($slot->getID() !== AIR and $slot->count > 0){
$inv[] = array( $inv[] = [
$slot->getID(), $slot->getID(),
$slot->getMetadata(), $slot->getMetadata(),
$slot->count $slot->count
); ];
} }
} }
for($re = 0; $re < 4; $re ++){ for($re = 0; $re < 4; $re++){
$slot = $this->player->getArmor($re); $slot = $this->player->getArmor($re);
$this->player->setArmor($re, BlockAPI::getItem(AIR, 0, 0)); $this->player->setArmor($re, BlockAPI::getItem(AIR, 0, 0));
if($slot->getID() !== AIR and $slot->count > 0){ if($slot->getID() !== AIR and $slot->count > 0){
$inv[] = array( $inv[] = [
$slot->getID(), $slot->getID(),
$slot->getMetadata(), $slot->getMetadata(),
$slot->count $slot->count
); ];
} }
} }
return $inv; return $inv;
@ -427,18 +427,18 @@ class Entity extends Position
foreach($this->server->api->entity->getRadius($this, 2, false) as $item){ foreach($this->server->api->entity->getRadius($this, 2, false) as $item){
if($item->class === ENTITY_ITEM && !$item->closed && $item->spawntime > 0 && $item->delayBeforePickup <= 0){ if($item->class === ENTITY_ITEM && !$item->closed && $item->spawntime > 0 && $item->delayBeforePickup <= 0){
if($item->boundingBox->intersectsWith($myBB)){ if($item->boundingBox->intersectsWith($myBB)){
if((($this->player->gamemode & 0x01) === 1 || $this->player->hasSpace($item->itemID, $item->meta, $item->stack) === true) && $this->server->api->dhandle("player.pickup", array( if((($this->player->gamemode & 0x01) === 1 || $this->player->hasSpace($item->itemID, $item->meta, $item->stack) === true) && $this->server->api->dhandle("player.pickup", [
"eid" => $this->player->eid, "eid" => $this->player->eid,
"player" => $this->player, "player" => $this->player,
"entity" => $item, "entity" => $item,
"block" => $item->itemID, "block" => $item->itemID,
"meta" => $item->meta, "meta" => $item->meta,
"target" => $item->eid "target" => $item->eid
)) !== false){ ]) !== false){
$item->close(); $item->close();
} }
} }
}else if($item->class == ENTITY_OBJECT && !$item->closed && $item->type == OBJECT_ARROW && $item->shotByPlayer && $item->inGround && $item->shake <= 0 && $item->boundingBox->intersectsWith($myBB)){ }elseif($item->class == ENTITY_OBJECT && !$item->closed && $item->type == OBJECT_ARROW && $item->shotByPlayer && $item->inGround && $item->shake <= 0 && $item->boundingBox->intersectsWith($myBB)){
if(($this->player->gamemode & 0x01) == 1 || $this->player->hasSpace(ARROW, 0, 1)){ if(($this->player->gamemode & 0x01) == 1 || $this->player->hasSpace(ARROW, 0, 1)){
$this->player->addItem(ARROW, 0, 1); $this->player->addItem(ARROW, 0, 1);
$item->close(); $item->close();
@ -487,7 +487,7 @@ class Entity extends Position
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
} }
} }
@ -533,7 +533,7 @@ class Entity extends Position
} }
public function moveFlying($strafe, $forward, $speed){ //TODO rename? public function moveFlying($strafe, $forward, $speed){ //TODO rename?
$v4 = $strafe*$strafe + $forward*$forward; $v4 = $strafe * $strafe + $forward * $forward;
if($v4 >= 0.0001){ if($v4 >= 0.0001){
$v4 = sqrt($v4); $v4 = sqrt($v4);
@ -543,11 +543,11 @@ class Entity extends Position
$strafe *= $v4; $strafe *= $v4;
$forward *= $v4; $forward *= $v4;
$v5 = sin($this->yaw * M_PI/180); $v5 = sin($this->yaw * M_PI / 180);
$v6 = cos($this->yaw * M_PI/180); $v6 = cos($this->yaw * M_PI / 180);
$this->speedX += $strafe*$v6 - $forward*$v5; $this->speedX += $strafe * $v6 - $forward * $v5;
$this->speedZ += $forward*$v6 + $strafe*$v5; $this->speedZ += $forward * $v6 + $strafe * $v5;
} }
} }
@ -589,14 +589,12 @@ class Entity extends Position
$this->speedX = $this->speedY = $this->speedZ = 0; $this->speedX = $this->speedY = $this->speedZ = 0;
} }
$savedDX = $dx; $savedDX = $dx;
$savedDY = $dy; $savedDY = $dy;
$savedDZ = $dz; $savedDZ = $dz;
$oldBB = clone $this->boundingBox; $oldBB = clone $this->boundingBox;
$aaBBs = $this->level->getCubes($this, $this->boundingBox->addCoord($dx, $dy, $dz)); $aaBBs = $this->level->getCubes($this, $this->boundingBox->addCoord($dx, $dy, $dz));
foreach($aaBBs as $bb){ foreach($aaBBs as $bb){
$dy = $bb->calculateYOffset($this->boundingBox, $dy); $dy = $bb->calculateYOffset($this->boundingBox, $dy);
@ -613,7 +611,6 @@ class Entity extends Position
} }
$this->boundingBox->offset(0, 0, $dz); $this->boundingBox->offset(0, 0, $dz);
$fallingFlag = $this->onGround || $savedDY != $dy && $savedDY < 0; $fallingFlag = $this->onGround || $savedDY != $dy && $savedDY < 0;
if($this->stepHeight > 0 && $fallingFlag && ($savedDX != $dx || $savedDZ != $dz)){ if($this->stepHeight > 0 && $fallingFlag && ($savedDX != $dx || $savedDZ != $dz)){
@ -644,7 +641,7 @@ class Entity extends Position
} }
$this->boundingBox->offset(0, 0, $dz); $this->boundingBox->offset(0, 0, $dz);
if ($cx*$cx + $cz*$cz >= $dx*$dx + $dz*$dz) if ($cx * $cx + $cz * $cz >= $dx * $dx + $dz * $dz)
{ {
$dx = $cx; $dx = $cx;
$dy = $cy; $dy = $cy;
@ -665,13 +662,10 @@ class Entity extends Position
$this->isCollided = $this->isCollidedHorizontally || $this->isCollidedVertically; $this->isCollided = $this->isCollidedHorizontally || $this->isCollidedVertically;
$this->updateFallState($this->speedY); $this->updateFallState($this->speedY);
if($savedDX != $dx) $this->speedX = 0; if($savedDX != $dx) $this->speedX = 0;
if($savedDY != $dy) $this->speedY = 0; if($savedDY != $dy) $this->speedY = 0;
if($savedDZ != $dz) $this->speedZ = 0; if($savedDZ != $dz) $this->speedZ = 0;
//TODO more stuff -> onEntityWalking //TODO more stuff -> onEntityWalking
$this->doBlocksCollision(); $this->doBlocksCollision();
@ -681,7 +675,7 @@ class Entity extends Position
$this->harm(1, "fire"); $this->harm(1, "fire");
if(!$this->inWater){ if(!$this->inWater){
++$this->fire; ++$this->fire;
if($this->fire == 0) $this->fire = 8*20; if($this->fire == 0) $this->fire = 8 * 20;
} }
}elseif($this->fire <= 0){ }elseif($this->fire <= 0){
$this->fire = -$this->fireResistance; $this->fire = -$this->fireResistance;
@ -801,7 +795,7 @@ class Entity extends Position
} }
} }
if($id == WATER || $id === STILL_WATER || $id === COBWEB || $id == LAVA || $id === STILL_LAVA){ if($id == WATER || $id === STILL_WATER || $id === COBWEB || $id == LAVA || $id === STILL_LAVA){
$this->notOnGroundTicks = 0; $this->notOnGroundTicks = 0;
} }
@ -828,7 +822,7 @@ class Entity extends Position
if($prevGroundState == $this->onGround && !$this->onGround && $this->player->isSleeping == false && !$this->dead){ //isSleeping may be a vector if($prevGroundState == $this->onGround && !$this->onGround && $this->player->isSleeping == false && !$this->dead){ //isSleeping may be a vector
++$this->notOnGroundTicks; ++$this->notOnGroundTicks;
}else if($this->onGround){ }elseif($this->onGround){
$this->notOnGroundTicks = 0; $this->notOnGroundTicks = 0;
} }
@ -840,7 +834,6 @@ class Entity extends Position
} }
} }
if($this->isOnLadder()){ if($this->isOnLadder()){
$this->fallDistance = 0; $this->fallDistance = 0;
$this->notOnGroundTicks = 0; $this->notOnGroundTicks = 0;
@ -851,7 +844,7 @@ class Entity extends Position
$this->fallStart = $this->y; $this->fallStart = $this->y;
} }
$this->updateFallState(($this->speedY <=> 0)*0.1); $this->updateFallState(($this->speedY <=> 0) * 0.1);
if($this->onGround) $this->fallDistance = 0; if($this->onGround) $this->fallDistance = 0;
if($handleCactus){ if($handleCactus){
@ -862,7 +855,7 @@ class Entity extends Position
$this->harm(1, "fire"); $this->harm(1, "fire");
if(!$this->inWater){ if(!$this->inWater){
++$this->fire; ++$this->fire;
if($this->fire == 0) $this->fire = 8*20; if($this->fire == 0) $this->fire = 8 * 20;
} }
}elseif($this->fire <= 0){ }elseif($this->fire <= 0){
$this->fire = -$this->fireResistance; $this->fire = -$this->fireResistance;
@ -880,7 +873,6 @@ class Entity extends Position
} }
} }
$this->counterUpdate(); $this->counterUpdate();
if($this->isPlayer()){ if($this->isPlayer()){
@ -895,9 +887,9 @@ class Entity extends Position
$this->lastUpdate = $now; $this->lastUpdate = $now;
} }
public function isOnLadder(){ public function isOnLadder(){
$x = (int)$this->x; $x = (int) $this->x;
$y = (int)$this->boundingBox->minY; $y = (int) $this->boundingBox->minY;
$z = (int)$this->z; $z = (int) $this->z;
return $this->level->level->getBlockID($x, $y, $z) === LADDER; return $this->level->level->getBlockID($x, $y, $z) === LADDER;
} }
@ -1059,7 +1051,7 @@ class Entity extends Position
], ],
1 => [ 1 => [
"type" => 1, "type" => 1,
"value" => (int)$this->air "value" => (int) $this->air
], ],
14 => [ 14 => [
"type" => 0, "type" => 0,
@ -1099,7 +1091,7 @@ class Entity extends Position
public function spawn($player) public function spawn($player)
{ {
if(! ($player instanceof Player)){ if(!($player instanceof Player)){
$player = $this->server->api->player->get($player); $player = $this->server->api->player->get($player);
} }
if($player->eid === $this->eid or $this->closed !== false or ($player->level !== $this->level and $this->class !== ENTITY_PLAYER)){ if($player->eid === $this->eid or $this->closed !== false or ($player->level !== $this->level and $this->class !== ENTITY_PLAYER)){
@ -1179,7 +1171,6 @@ class Entity extends Position
--$this->idleTime; --$this->idleTime;
} }
if($this->inAction){ if($this->inAction){
++$this->inActionCounter; ++$this->inActionCounter;
} }
@ -1251,7 +1242,7 @@ class Entity extends Position
} }
public function inBlockNonVector($x, $y, $z, $radius = 0.8) public function inBlockNonVector($x, $y, $z, $radius = 0.8)
{ {
return $y == ceil($this->y) || $y == (ceil($this->y)+1) && max(abs($x - ($this->x-0.5)), abs($z - ($this->z-0.5))); return $y == ceil($this->y) || $y == (ceil($this->y) + 1) && max(abs($x - ($this->x - 0.5)), abs($z - ($this->z - 0.5)));
} }
public function inBlock(Vector3 $block, $radius = 0.8) public function inBlock(Vector3 $block, $radius = 0.8)
{ {
@ -1275,7 +1266,7 @@ class Entity extends Position
{ {
$me = new Vector2($this->x - 0.5, $this->z - 0.5); $me = new Vector2($this->x - 0.5, $this->z - 0.5);
$diff = $this->y - $pos->y; $diff = $this->y - $pos->y;
if($me->distance(new Vector2($pos->x, $pos->z)) < $radius and $diff > - 0.7 and $diff < 1.6){ if($me->distance(new Vector2($pos->x, $pos->z)) < $radius and $diff > -0.7 and $diff < 1.6){
return true; return true;
} }
return false; return false;
@ -1283,7 +1274,7 @@ class Entity extends Position
public function resetSpeed() public function resetSpeed()
{ {
$this->speedMeasure = array(0, 0, 0, 0, 0, 0, 0); $this->speedMeasure = [0, 0, 0, 0, 0, 0, 0];
} }
public function getSpeed() public function getSpeed()
@ -1387,17 +1378,17 @@ class Entity extends Position
// $dmg = 0; // $dmg = 0;
// break; // break;
case 1: case 1:
$dmg = (int)($dmg / 3) + 1; $dmg = (int) ($dmg / 3) + 1;
break; break;
case 3: case 3:
$dmg = 3 * (int)($dmg / 2); $dmg = 3 * (int) ($dmg / 2);
break; break;
} }
} }
} }
$dmg = $this->applyArmor($dmg, $cause); $dmg = $this->applyArmor($dmg, $cause);
$ret = $this->setHealth(max(- 128, $this->getHealth() - ((int) $dmg)), $cause, $force); $ret = $this->setHealth(max(-128, $this->getHealth() - ((int) $dmg)), $cause, $force);
if($ret && is_numeric($cause) && ($entity = $this->server->api->entity->get($cause)) != false){ //TODO simplify if($ret && is_numeric($cause) && ($entity = $this->server->api->entity->get($cause)) != false){ //TODO simplify
$this->attackTimeout = 10; $this->attackTimeout = 10;
@ -1490,7 +1481,6 @@ class Entity extends Position
$this->server->api->dhandle("entity.link", ["rider" => $this->eid, "riding" => $e->eid, "type" => 0]); $this->server->api->dhandle("entity.link", ["rider" => $this->eid, "riding" => $e->eid, "type" => 0]);
} }
} }
public function isPlayer() public function isPlayer()
@ -1557,13 +1547,13 @@ class Entity extends Position
$harm = true; $harm = true;
} }
if($this->server->api->dhandle("entity.health.change", array( if($this->server->api->dhandle("entity.health.change", [
"entity" => $this, "entity" => $this,
"eid" => $this->eid, "eid" => $this->eid,
"health" => $health, "health" => $health,
"cause" => $cause "cause" => $cause
)) !== false or $force === true){ ]) !== false or $force === true){
$this->health = min(127, max(- 127, $health)); $this->health = min(127, max(-127, $health));
if($harm === true && $allowHarm){ if($harm === true && $allowHarm){
$pk = new EntityEventPacket; $pk = new EntityEventPacket;
$pk->eid = $this->eid; $pk->eid = $this->eid;
@ -1703,7 +1693,6 @@ class Entity extends Position
throw new Exception("Use getHeightOf or getWidthOf method instead of this."); throw new Exception("Use getHeightOf or getWidthOf method instead of this.");
} }
/** /**
* *
* @deprecated Use {@link getHeight} or {@link getWidth} instead * @deprecated Use {@link getHeight} or {@link getWidth} instead

View file

@ -6,7 +6,6 @@ abstract class Living extends Entity implements Pathfindable{
public static $pathfinderTest = false; public static $pathfinderTest = false;
/** /**
* @var Entity $target * @var Entity $target
* @var EntityAI $ai * @var EntityAI $ai
@ -21,7 +20,7 @@ abstract class Living extends Entity implements Pathfindable{
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);
@ -87,10 +86,10 @@ abstract class Living extends Entity implements Pathfindable{
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){
@ -140,14 +139,13 @@ 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));
@ -172,7 +170,6 @@ 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){
@ -187,7 +184,6 @@ abstract class Living extends Entity implements Pathfindable{
$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();
@ -220,7 +216,6 @@ abstract class Living extends Entity implements Pathfindable{
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;
@ -231,7 +226,6 @@ abstract class Living extends Entity implements Pathfindable{
$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;
} }
@ -257,7 +251,7 @@ abstract class Living extends Entity implements Pathfindable{
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)

View file

@ -1,4 +1,5 @@
<?php <?php
class Monster extends Creature{ class Monster extends Creature{
public $closestPlayerToAttackEID = false; public $closestPlayerToAttackEID = false;
@ -35,7 +36,7 @@ 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;
} }
} }

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;
@ -98,7 +99,7 @@ abstract class Projectile extends Entity{
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
} }
} }
@ -166,7 +167,7 @@ abstract class Projectile extends Entity{
$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;

View file

@ -24,7 +24,6 @@ class EntityAI
$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);
@ -32,7 +31,6 @@ class EntityAI
/** /**
* 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;

View file

@ -100,14 +100,14 @@ class MobController
$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
@ -121,7 +121,7 @@ class MobController
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;
@ -151,10 +151,10 @@ class MobController
$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);
@ -168,18 +168,18 @@ class MobController
/* 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;
@ -198,7 +198,7 @@ class MobController
} }
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;
@ -208,7 +208,6 @@ class MobController
$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);

View file

@ -28,7 +28,6 @@ class PathFollower{
$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;

View file

@ -9,7 +9,7 @@ class TaskAttackPlayer extends TaskBase
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)
@ -17,7 +17,6 @@ class TaskAttackPlayer extends TaskBase
$this->selfCounter = 1; $this->selfCounter = 1;
} }
public function onUpdate(EntityAI $ai) public function onUpdate(EntityAI $ai)
{ {
if(!$this->isTargetValid($ai)){ if(!$this->isTargetValid($ai)){
@ -38,7 +37,7 @@ 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;
@ -47,7 +46,6 @@ class TaskAttackPlayer extends TaskBase
} }
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,7 +53,7 @@ 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;
} }
@ -67,7 +65,7 @@ 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;
} }
} }

View file

@ -8,25 +8,21 @@ abstract class TaskBase
/** /**
* 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);

View file

@ -19,7 +19,7 @@ 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)

View file

@ -8,11 +8,11 @@ class TaskLookAtPlayer extends TaskBase{
} }
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){

View file

@ -28,7 +28,6 @@ class TaskMate extends TaskBase
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);
@ -55,7 +54,7 @@ class TaskMate extends TaskBase
} }
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;

View file

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

@ -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,7 +7,7 @@ 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();
} }
@ -37,7 +37,6 @@ class TaskRangedAttack extends \TaskBase
$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){
@ -89,7 +88,6 @@ class TaskRangedAttack extends \TaskBase
} }
} }
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,7 +95,7 @@ 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;
} }
@ -109,7 +107,7 @@ 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;
} }
} }
@ -123,7 +121,6 @@ class TaskRangedAttack extends \TaskBase
return false; return false;
} }
public function canBeExecuted(EntityAI $ai) public function canBeExecuted(EntityAI $ai)
{ {
return $this->tryTargeting($ai); return $this->tryTargeting($ai);

View file

@ -4,7 +4,7 @@ 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)
@ -29,7 +29,7 @@ class TaskTempt extends TaskBase
$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);
@ -37,7 +37,6 @@ class TaskTempt extends TaskBase
$ai->mobController->headYawIsYaw = true; $ai->mobController->headYawIsYaw = true;
} }
} }
public function isTargetValid(EntityAI $ai){ public function isTargetValid(EntityAI $ai){
@ -47,7 +46,7 @@ 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;
} }
@ -64,7 +63,7 @@ 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;
} }
} }

View file

@ -1,4 +1,5 @@
<?php <?php
class Pig extends Animal implements Rideable{ class Pig extends Animal implements Rideable{
const TYPE = MOB_PIG; const TYPE = MOB_PIG;

View file

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

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;
@ -27,8 +28,6 @@ class Creeper extends Monster{
$this->setState($v === null ? !$this->getState() : $v); $this->setState($v === null ? !$this->getState() : $v);
} }
/** /**
* @return boolean * @return boolean
*/ */

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 = []){
@ -24,15 +25,15 @@ class Skeleton extends Monster{
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;

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");
@ -23,10 +24,10 @@ class Spider extends Monster{
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;

View file

@ -1,7 +1,8 @@
<?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");
@ -23,15 +24,15 @@ class Zombie extends Monster{
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;

View file

@ -111,7 +111,7 @@ class Arrow extends Entity{
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
} }
} }
@ -120,9 +120,8 @@ class Arrow extends Entity{
} }
//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;
} }
@ -163,7 +162,6 @@ class Arrow extends Entity{
$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;
@ -190,14 +188,13 @@ class Arrow extends Entity{
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();
@ -220,7 +217,7 @@ class Arrow extends Entity{
$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;
@ -236,7 +233,7 @@ class Arrow extends Entity{
$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;
@ -256,8 +253,6 @@ class Arrow extends Entity{
$this->doBlocksCollision(); $this->doBlocksCollision();
} }
} }
public function spawn($player){ public function spawn($player){

View file

@ -7,7 +7,7 @@ class ItemEntity extends Entity{
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);
@ -64,7 +64,6 @@ class ItemEntity extends Entity{
$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;
@ -182,7 +181,7 @@ class ItemEntity extends Entity{
$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));

View file

@ -107,13 +107,13 @@ class Minecart extends Vehicle{
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;
@ -155,13 +155,13 @@ class Minecart extends Vehicle{
$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;
@ -173,9 +173,9 @@ class Minecart extends Vehicle{
$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;
} }
} }
} }
@ -188,7 +188,7 @@ class Minecart extends Vehicle{
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);
@ -207,20 +207,20 @@ class Minecart extends Vehicle{
} }
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);
@ -231,7 +231,7 @@ class Minecart extends Vehicle{
$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);
@ -241,13 +241,13 @@ class Minecart extends Vehicle{
} }
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);
@ -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;
@ -281,7 +281,6 @@ class Minecart extends Vehicle{
} }
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;
@ -292,10 +291,10 @@ class Minecart extends Vehicle{
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;
@ -315,7 +314,7 @@ class Minecart extends Vehicle{
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;
@ -367,7 +366,7 @@ class Minecart extends Vehicle{
$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;
@ -383,10 +382,10 @@ class Minecart extends Vehicle{
} }
$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){

View file

@ -16,9 +16,9 @@ class Painting extends Entity{
$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;
@ -43,9 +43,9 @@ class Painting extends Entity{
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;
@ -68,7 +68,7 @@ class Painting extends Entity{
} }
} }
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;
@ -87,9 +87,9 @@ class Painting extends Entity{
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;
@ -109,10 +109,10 @@ class Painting extends Entity{
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{
@ -144,11 +144,11 @@ class Painting extends Entity{
$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;

View file

@ -41,7 +41,7 @@ class PrimedTNT extends Entity{
$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;

View file

@ -1,4 +1,5 @@
<?php <?php
class ThrownEgg extends Projectile{ class ThrownEgg extends Projectile{
const TYPE = OBJECT_EGG; const TYPE = OBJECT_EGG;
@ -28,5 +29,4 @@ class ThrownEgg extends Projectile{
$this->close(); $this->close();
} }
}
}

View file

@ -1,4 +1,5 @@
<?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){

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

@ -25,7 +25,6 @@ class PacketReceiveEvent extends ServerEvent implements CancellableEvent{
private $packet; private $packet;
public function __construct(Packet $packet){ public function __construct(Packet $packet){
$this->packet = $packet; $this->packet = $packet;
} }

View file

@ -25,7 +25,6 @@ class PacketSendEvent extends ServerEvent implements CancellableEvent{
private $packet; private $packet;
public function __construct(Packet $packet){ public function __construct(Packet $packet){
$this->packet = $packet; $this->packet = $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

@ -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;
} }
@ -41,7 +41,7 @@
} }
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{
@ -97,21 +97,21 @@ LICENSE;
} }
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);
@ -121,43 +121,42 @@ LICENSE;
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);
} }
@ -166,11 +165,10 @@ LICENSE;
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",
@ -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,14 +207,14 @@ 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);
} }
@ -228,19 +226,19 @@ LICENSE;
} }
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];

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", CAKE_BLOCK => "CakeBlock",
TRAPDOOR => "TrapdoorBlock", TRAPDOOR => "TrapdoorBlock",
STONE_BRICKS => "StoneBricksBlock", STONE_BRICKS => "StoneBricksBlock",
IRON_BARS => "IronBarsBlock", IRON_BARS => "IronBarsBlock",
GLASS_PANE => "GlassPaneBlock", GLASS_PANE => "GlassPaneBlock",
MELON_BLOCK => "MelonBlock", MELON_BLOCK => "MelonBlock",
PUMPKIN_STEM => "PumpkinStemBlock", PUMPKIN_STEM => "PumpkinStemBlock",
MELON_STEM => "MelonStemBlock", MELON_STEM => "MelonStemBlock",
FENCE_GATE => "FenceGateBlock", FENCE_GATE => "FenceGateBlock",
BRICK_STAIRS => "BrickStairsBlock", BRICK_STAIRS => "BrickStairsBlock",
STONE_BRICK_STAIRS => "StoneBrickStairsBlock", STONE_BRICK_STAIRS => "StoneBrickStairsBlock",
NETHER_BRICKS => "NetherBricksBlock", NETHER_BRICKS => "NetherBricksBlock",
NETHER_BRICKS_STAIRS => "NetherBricksStairsBlock", NETHER_BRICKS_STAIRS => "NetherBricksStairsBlock",
SANDSTONE_STAIRS => "SandstoneStairsBlock", SANDSTONE_STAIRS => "SandstoneStairsBlock",
SPRUCE_WOOD_STAIRS => "SpruceWoodStairsBlock", SPRUCE_WOOD_STAIRS => "SpruceWoodStairsBlock",
BIRCH_WOOD_STAIRS => "BirchWoodStairsBlock", BIRCH_WOOD_STAIRS => "BirchWoodStairsBlock",
JUNGLE_WOOD_STAIRS => "JungleWoodStairsBlock", JUNGLE_WOOD_STAIRS => "JungleWoodStairsBlock",
STONE_WALL => "StoneWallBlock", STONE_WALL => "StoneWallBlock",
CARROT_BLOCK => "CarrotBlock", CARROT_BLOCK => "CarrotBlock",
POTATO_BLOCK => "PotatoBlock", POTATO_BLOCK => "PotatoBlock",
QUARTZ_BLOCK => "QuartzBlock", QUARTZ_BLOCK => "QuartzBlock",
QUARTZ_STAIRS => "QuartzStairsBlock", QUARTZ_STAIRS => "QuartzStairsBlock",
DOUBLE_WOOD_SLAB => "DoubleWoodSlabBlock", DOUBLE_WOOD_SLAB => "DoubleWoodSlabBlock",
WOOD_SLAB => "WoodSlabBlock", WOOD_SLAB => "WoodSlabBlock",
HAY_BALE => "HayBaleBlock", HAY_BALE => "HayBaleBlock",
CARPET => "CarpetBlock", CARPET => "CarpetBlock",
COAL_BLOCK => "CoalBlock", COAL_BLOCK => "CoalBlock",
BEETROOT_BLOCK => "BeetrootBlock", BEETROOT_BLOCK => "BeetrootBlock",
STONECUTTER => "StonecutterBlock", STONECUTTER => "StonecutterBlock",
GLOWING_OBSIDIAN => "GlowingObsidianBlock", GLOWING_OBSIDIAN => "GlowingObsidianBlock",
NETHER_REACTOR => "NetherReactorBlock", NETHER_REACTOR => "NetherReactorBlock",
INFO_UPDATE => "InfoUpdateBlock", INFO_UPDATE => "InfoUpdateBlock",
INFO_UPDATE2 => "InfoUpdate2Block", INFO_UPDATE2 => "InfoUpdate2Block",
RESERVED6 => "Reserved6Block", RESERVED6 => "Reserved6Block",
); ];
public $id; public $id;
public $meta; public $meta;
public $name; public $name;
@ -230,7 +230,6 @@ abstract class Block extends Position{
} }
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;
@ -269,11 +268,11 @@ abstract class Block extends Position{
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],
); ];
} }
} }
@ -293,7 +292,7 @@ abstract class Block extends Position{
} }
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);

View file

@ -9,7 +9,7 @@ class Item{
const DEF_DAMAGE = 1; const DEF_DAMAGE = 1;
public static $class = array( public static $class = [
//armor //armor
LEATHER_CAP => "LeatherCapItem", LEATHER_CAP => "LeatherCapItem",
@ -128,7 +128,7 @@ class Item{
CLOCK => "ClockItem", CLOCK => "ClockItem",
SHEARS => "ShearsItem", SHEARS => "ShearsItem",
); ];
public $block; public $block;
public $id; public $id;
public $meta; public $meta;
@ -263,7 +263,7 @@ class Item{
//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,
@ -294,7 +294,7 @@ class Item{
} }
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){

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

@ -121,7 +121,7 @@ class StaticBlock
} }
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
@ -135,7 +135,6 @@ class StaticBlock
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;
} }
@ -161,7 +160,7 @@ class StaticBlock
} }
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){

View file

@ -87,7 +87,6 @@ class DoorBlock extends TransparentBlock{
break; break;
} }
return [$aabb->offset($x, $y, $z)]; return [$aabb->offset($x, $y, $z)];
} }
@ -105,14 +104,13 @@ class DoorBlock extends TransparentBlock{
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){
@ -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;
@ -164,8 +157,6 @@ class DoorBlock extends TransparentBlock{
} }
/** /**
* @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
*/ */
@ -60,12 +51,12 @@ class GenericBlock extends Block{
[$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);
@ -74,7 +65,6 @@ class GenericBlock extends Block{
} }
/** /**
* @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,7 +21,7 @@ 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
}; };
} }
@ -99,7 +99,7 @@ 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;
@ -168,10 +168,10 @@ class LiquidBlock extends TransparentBlock{
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
@ -184,12 +184,11 @@ class LiquidBlock extends TransparentBlock{
} }
} }
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

@ -52,11 +52,11 @@ class StairBlock extends TransparentBlock{
$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);
@ -319,10 +319,6 @@ class StairBlock extends TransparentBlock{
} }
/** /**
* @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

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

@ -47,8 +47,8 @@ class SignPostBlock extends TransparentBlock{
} }
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

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

@ -59,21 +59,21 @@ 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)){

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{

View file

@ -89,7 +89,7 @@ class LiquidBlockDynamic extends LiquidBlock{
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;
} }
@ -195,7 +195,7 @@ 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{
@ -204,7 +204,7 @@ class LiquidBlockDynamic extends LiquidBlock{
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

@ -22,5 +22,4 @@ class LiquidBlockStatic extends LiquidBlock{
} }
} }
}
}

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{

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?

View file

@ -1,4 +1,5 @@
<?php <?php
require_once("LiquidBlockDynamic.php"); //TODO class loader? require_once("LiquidBlockDynamic.php"); //TODO class loader?
class WaterBlock extends LiquidBlockDynamic{ class WaterBlock extends LiquidBlockDynamic{

View file

@ -37,7 +37,7 @@ class BedBlock extends TransparentBlock{
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(
@ -172,9 +172,9 @@ class BedBlock extends TransparentBlock{
} }
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

@ -35,7 +35,7 @@ class FireBlock extends FlowableBlock implements LightingBlock{
} }
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;
@ -79,6 +79,5 @@ class FireBlock extends FlowableBlock implements LightingBlock{
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

@ -15,24 +15,24 @@ 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;
} }
//} //}
@ -41,12 +41,12 @@ class NetherReactorBlock extends SolidBlock{
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){
@ -59,8 +59,8 @@ class NetherReactorBlock extends SolidBlock{
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);
} }
} }
} }
@ -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;
} }
} }
@ -230,6 +230,6 @@ class NetherReactorBlock extends SolidBlock{
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

@ -13,13 +13,13 @@ class TNTBlock extends SolidBlock{
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

@ -12,7 +12,7 @@ class CakeBlock extends TransparentBlock{
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){
@ -37,7 +37,7 @@ class CakeBlock extends TransparentBlock{
} }
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){

View file

@ -4,7 +4,7 @@ class CarpetBlock extends FlowableBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(CARPET, $meta, "Carpet"); parent::__construct(CARPET, $meta, "Carpet");
$names = array( $names = [
0 => "White Carpet", 0 => "White Carpet",
1 => "Orange Carpet", 1 => "Orange Carpet",
2 => "Magenta Carpet", 2 => "Magenta Carpet",
@ -21,7 +21,7 @@ class CarpetBlock extends FlowableBlock{
13 => "Green Carpet", 13 => "Green Carpet",
14 => "Red Carpet", 14 => "Red Carpet",
15 => "Black Carpet", 15 => "Black Carpet",
); ];
$this->name = $names[$this->meta]; $this->name = $names[$this->meta];
$this->hardness = 0; $this->hardness = 0;
$this->isFullBlock = false; $this->isFullBlock = false;

View file

@ -14,12 +14,12 @@ class ChestBlock 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){
$server = ServerAPI::request(); $server = ServerAPI::request();
$faces = array( $faces = [
0 => 4, 0 => 4,
1 => 2, 1 => 2,
2 => 5, 2 => 5,
3 => 3, 3 => 3,
); ];
$chest = false; $chest = false;
$this->meta = $faces[$player->entity->getDirection()]; $this->meta = $faces[$player->entity->getDirection()];
@ -40,13 +40,13 @@ class ChestBlock extends TransparentBlock{
} }
$this->level->setBlock($block, $this, true, false, true); $this->level->setBlock($block, $this, true, false, true);
$tile = $server->api->tile->add($this->level, TILE_CHEST, $this->x, $this->y, $this->z, array( $tile = $server->api->tile->add($this->level, TILE_CHEST, $this->x, $this->y, $this->z, [
"Items" => array(), "Items" => [],
"id" => TILE_CHEST, "id" => TILE_CHEST,
"x" => $this->x, "x" => $this->x,
"y" => $this->y, "y" => $this->y,
"z" => $this->z "z" => $this->z
)); ]);
$server->api->tile->spawnToAll($tile); $server->api->tile->spawnToAll($tile);
if($chest instanceof Tile){ if($chest instanceof Tile){
@ -77,17 +77,15 @@ class ChestBlock extends TransparentBlock{
if($t !== false){ if($t !== false){
$chest = $t; $chest = $t;
}else{ }else{
$chest = $server->api->tile->add($this->level, TILE_CHEST, $this->x, $this->y, $this->z, array( $chest = $server->api->tile->add($this->level, TILE_CHEST, $this->x, $this->y, $this->z, [
"Items" => array(), "Items" => [],
"id" => TILE_CHEST, "id" => TILE_CHEST,
"x" => $this->x, "x" => $this->x,
"y" => $this->y, "y" => $this->y,
"z" => $this->z "z" => $this->z
)); ]);
} }
if(($player->gamemode & 0x01) === 0x01){ if(($player->gamemode & 0x01) === 0x01){
return true; return true;
} }
@ -97,15 +95,15 @@ class ChestBlock extends TransparentBlock{
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
$drops = array( $drops = [
array($this->id, 0, 1), [$this->id, 0, 1],
); ];
$t = ServerAPI::request()->api->tile->get($this); $t = ServerAPI::request()->api->tile->get($this);
if($t !== false and $t->class === TILE_CHEST){ if($t !== false and $t->class === TILE_CHEST){
for($s = 0; $s < CHEST_SLOTS; ++$s){ for($s = 0; $s < CHEST_SLOTS; ++$s){
$slot = $t->getSlot($s); $slot = $t->getSlot($s);
if($slot->getID() > AIR and $slot->count > 0){ if($slot->getID() > AIR and $slot->count > 0){
$drops[] = array($slot->getID(), $slot->getMetadata(), $slot->count); $drops[] = [$slot->getID(), $slot->getMetadata(), $slot->count];
} }
} }
} }

View file

@ -21,7 +21,7 @@ class CobwebBlock extends FlowableBlock{
} }
elseif ($item->isShears()){ elseif ($item->isShears()){
return [ return [
array(COBWEB, 0, 1), [COBWEB, 0, 1],
]; ];
} }
} }

View file

@ -7,9 +7,9 @@ class FarmlandBlock extends TransparentBlock{
$this->hardness = 3; $this->hardness = 3;
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return array( return [
array(DIRT, 0, 1), [DIRT, 0, 1],
); ];
} }
public function hasCrops(){ public function hasCrops(){
//TODO vanilla 0.8.1 detection method //TODO vanilla 0.8.1 detection method
@ -42,7 +42,6 @@ class FarmlandBlock extends TransparentBlock{
} }
} }
} }
public static function checkWaterStatic(Level $level, $x, $y, $z) public static function checkWaterStatic(Level $level, $x, $y, $z)

View file

@ -33,20 +33,20 @@ class FenceGateBlock extends TransparentBlock{
$this->hardness = 15; $this->hardness = 15;
} }
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 => 3, 0 => 3,
1 => 0, 1 => 0,
2 => 1, 2 => 1,
3 => 2, 3 => 2,
); ];
$this->meta = $faces[$player->entity->getDirection()] & 0x03; $this->meta = $faces[$player->entity->getDirection()] & 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 function onActivate(Item $item, Player $player){ public function onActivate(Item $item, Player $player){
@ -55,7 +55,7 @@ class FenceGateBlock extends TransparentBlock{
$meta ^= 4; $meta ^= 4;
}else{ }else{
$direction = ($player->entity->yaw * 4 / 360) + 0.5; $direction = ($player->entity->yaw * 4 / 360) + 0.5;
$blockDirection = (int)$direction; $blockDirection = (int) $direction;
if($direction < $blockDirection) --$blockDirection; if($direction < $blockDirection) --$blockDirection;
$blockDirection &= 3; $blockDirection &= 3;
if(($meta & 3) == (($blockDirection + 2) & 3)){ if(($meta & 3) == (($blockDirection + 2) & 3)){

View file

@ -22,7 +22,7 @@ class GlassPaneBlock extends TransparentBlock{
if((!$var11 || !$var12) && ($var11 || $var12 || $var9 || $var10)){ if((!$var11 || !$var12) && ($var11 || $var12 || $var9 || $var10)){
if($var11 && !$var12) $minX = 0; if($var11 && !$var12) $minX = 0;
else if(!$var11 && $var12) $maxX = 1; elseif(!$var11 && $var12) $maxX = 1;
}else{ }else{
$minX = 0; $minX = 0;
$maxX = 1; $maxX = 1;
@ -30,7 +30,7 @@ class GlassPaneBlock extends TransparentBlock{
if((!$var9 || !$var10) && ($var11 || $var12 || $var9 || $var10)){ if((!$var9 || !$var10) && ($var11 || $var12 || $var9 || $var10)){
if($var9 && !$var10) $minZ = 0; if($var9 && !$var10) $minZ = 0;
else if(!$var9 && $var10) $maxZ = 1; elseif(!$var9 && $var10) $maxZ = 1;
}else{ }else{
$minZ = 0; $minZ = 0;
$maxZ = 1; $maxZ = 1;
@ -66,8 +66,8 @@ class GlassPaneBlock extends TransparentBlock{
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return array( return [
array(GLASS_PANE, 0, 0), [GLASS_PANE, 0, 0],
); ];
} }
} }

View file

@ -23,7 +23,7 @@ class IronBarsBlock extends TransparentBlock{
if((!$var11 || !$var12) && ($var11 || $var12 || $var9 || $var10)){ if((!$var11 || !$var12) && ($var11 || $var12 || $var9 || $var10)){
if($var11 && !$var12) $minX = 0; if($var11 && !$var12) $minX = 0;
else if(!$var11 && $var12) $maxX = 1; elseif(!$var11 && $var12) $maxX = 1;
}else{ }else{
$minX = 0; $minX = 0;
$maxX = 1; $maxX = 1;
@ -31,7 +31,7 @@ class IronBarsBlock extends TransparentBlock{
if((!$var9 || !$var10) && ($var11 || $var12 || $var9 || $var10)){ if((!$var9 || !$var10) && ($var11 || $var12 || $var9 || $var10)){
if($var9 && !$var10) $minZ = 0; if($var9 && !$var10) $minZ = 0;
else if(!$var9 && $var10) $maxZ = 1; elseif(!$var9 && $var10) $maxZ = 1;
}else{ }else{
$minZ = 0; $minZ = 0;
$maxZ = 1; $maxZ = 1;

View file

@ -24,11 +24,11 @@ class IronDoorBlock extends DoorBlock{
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(IRON_DOOR, 0, 1), [IRON_DOOR, 0, 1],
); ];
}else{ }else{
return array(); return [];
} }
} }
} }

View file

@ -1,4 +1,5 @@
<?php <?php
require_once("RailBaseBlock.php"); require_once("RailBaseBlock.php");
class PoweredRailBlock extends RailBaseBlock{ class PoweredRailBlock extends RailBaseBlock{
public static $blockID; public static $blockID;

View file

@ -1,4 +1,5 @@
<?php <?php
require_once("RailBaseBlock.php"); require_once("RailBaseBlock.php");
class RailBlock extends RailBaseBlock{ class RailBlock extends RailBaseBlock{
public static $blockID; public static $blockID;

View file

@ -106,11 +106,11 @@ class SlabBlock extends TransparentBlock{
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, $this->meta & 0x07, 1), [$this->id, $this->meta & 0x07, 1],
); ];
}else{ }else{
return array(); return [];
} }
} }
} }

View file

@ -29,11 +29,11 @@ class SnowLayerBlock extends FlowableBlock{
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
if($item->isShovel() !== false){ if($item->isShovel() !== false){
return array( return [
array(SNOWBALL, 0, 1), [SNOWBALL, 0, 1],
); ];
} }
return array(); return [];
} }
} }

View file

@ -62,7 +62,7 @@ class StoneWallBlock extends TransparentBlock{
$minX = 0.3125; $minX = 0.3125;
} }
} }
}else if(!$zPos && $zNeg){ }elseif(!$zPos && $zNeg){
if($xPos){ if($xPos){
$maxY = 0.8125; $maxY = 0.8125;
$maxZ = 0.6875; $maxZ = 0.6875;

View file

@ -9,8 +9,8 @@ class WoodDoorBlock extends DoorBlock{
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return array( return [
array(WOODEN_DOOR, 0, 1), [WOODEN_DOOR, 0, 1],
); ];
} }
} }

View file

@ -1,15 +1,16 @@
<?php <?php
//TODO make it extend SlabBlock //TODO make it extend SlabBlock
class WoodSlabBlock extends TransparentBlock{ class WoodSlabBlock extends TransparentBlock{
public static $blockID; public static $blockID;
public function __construct($meta = 0){ public function __construct($meta = 0){
parent::__construct(WOOD_SLAB, $meta, "Wooden Slab"); parent::__construct(WOOD_SLAB, $meta, "Wooden Slab");
$names = array( $names = [
0 => "Oak", 0 => "Oak",
1 => "Spruce", 1 => "Spruce",
2 => "Birch", 2 => "Birch",
3 => "Jungle", 3 => "Jungle",
); ];
$this->name = (($this->meta & 0x08) === 0x08 ? "Upper ":"") . $names[$this->meta & 0x07] . " Wooden Slab"; $this->name = (($this->meta & 0x08) === 0x08 ? "Upper ":"") . $names[$this->meta & 0x07] . " Wooden Slab";
if(($this->meta & 0x08) === 0x08){ if(($this->meta & 0x08) === 0x08){
$this->isFullBlock = true; $this->isFullBlock = true;
@ -101,8 +102,8 @@ class WoodSlabBlock extends TransparentBlock{
} }
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
return array( return [
array($this->id, $this->meta & 0x07, 1), [$this->id, $this->meta & 0x07, 1],
); ];
} }
} }

View file

@ -7,8 +7,8 @@ class BirchWoodStairsBlock extends StairBlock{
} }
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

@ -7,8 +7,8 @@ class JungleWoodStairsBlock extends StairBlock{
} }
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

@ -7,8 +7,8 @@ class SpruceWoodStairsBlock extends StairBlock{
} }
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

@ -21,8 +21,8 @@ class WoodStairsBlock extends StairBlock{
} }
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

@ -23,11 +23,11 @@ class CoalOreBlock extends SolidBlock{
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(COAL, 0, 1), [COAL, 0, 1],
); ];
}else{ }else{
return array(); return [];
} }
} }

View file

@ -20,11 +20,11 @@ class DiamondOreBlock extends SolidBlock{
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
if($item->getPickaxeLevel() >= 4){ if($item->getPickaxeLevel() >= 4){
return array( return [
array(DIAMOND, 0, 1), [DIAMOND, 0, 1],
); ];
}else{ }else{
return array(); return [];
} }
} }
} }

View file

@ -28,11 +28,11 @@ class GlowingRedstoneOreBlock extends SolidBlock implements LightingBlock{
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
if($item->getPickaxeLevel() >= 4){ if($item->getPickaxeLevel() >= 4){
return array( return [
array(REDSTONE_DUST, 0, mt_rand(4, 5)), [REDSTONE_DUST, 0, mt_rand(4, 5)],
); ];
}else{ }else{
return array(); return [];
} }
} }

View file

@ -20,11 +20,11 @@ class GoldOreBlock extends SolidBlock{
public function getDrops(Item $item, Player $player){ public function getDrops(Item $item, Player $player){
if($item->getPickaxeLevel() >= 4){ if($item->getPickaxeLevel() >= 4){
return array( return [
array(GOLD_ORE, 0, 1), [GOLD_ORE, 0, 1],
); ];
}else{ }else{
return array(); return [];
} }
} }
} }

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