First step to namespaces

This commit is contained in:
Shoghi Cervantes 2014-03-05 23:43:16 +01:00
parent 23b8fc32ff
commit 5ea31b57ce
406 changed files with 3418 additions and 3597 deletions

View File

@ -19,13 +19,344 @@
* *
*/ */
namespace PocketMine;
/***REM_START***/ const VERSION = "Alpha_1.4dev";
require_once(dirname(__FILE__)."/src/config.php"); const API_VERSION = "1.0.0";
const CODENAME = "絶好(Zekkou)ケーキ(Cake)";
const MINECRAFT_VERSION = "v0.8.1 alpha";
const PHP_VERSION = "5.5";
require_once(FILE_PATH."/src/functions.php"); \spl_autoload_register(function ($load){
require_once(FILE_PATH."/src/dependencies.php"); $path = explode('\\', trim($load, '\\'));
/***REM_END***/ if(($parent = array_shift($path)) === "PocketMine"){ //part of the PocketMine-MP code
$className = array_pop($path);
if(count($path) > 0){
$path = implode(DIRECTORY_SEPARATOR, array_map("strtolower", $path)) . DIRECTORY_SEPARATOR;
}else{
$path = "";
}
$fPath = PATH . "src" . DIRECTORY_SEPARATOR . $path . $className . ".php";
if(file_exists($fPath)){
require_once($fPath);
}
}else{ //Try plugin
$className = array_pop($path);
if(count($path) > 0){
$path = implode(DIRECTORY_SEPARATOR, array_map("strtolower", $path)) . DIRECTORY_SEPARATOR;
}else{
$path = "";
}
$fPath = PATH . "plugins". DIRECTORY_SEPARATOR . $parent . DIRECTORY_SEPARATOR . "src" . DIRECTORY_SEPARATOR . $path . $className . ".php";
if(file_exists($fPath)){
require_once($fPath);
}
}
});
define("PocketMine\PATH", realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR);
//Startup code. Do not look at it, it can harm you. Most of them are hacks to fix date-related bugs, or basic functions used after this
set_time_limit(0); //Who set it to 30 seconds?!?!
if(ini_get("date.timezone") == ""){ //No Timezone set
date_default_timezone_set("GMT");
if(strpos(" ".strtoupper(php_uname("s")), " WIN") !== false){
$time = time();
$time -= $time % 60;
//TODO: Parse different time & date formats by region. ¬¬ world
//Example: USA
exec("time.exe /T", $hour);
$i = array_map("intval", explode(":", trim($hour[0])));
exec("date.exe /T", $date);
$j = array_map("intval", explode(substr($date[0], 2, 1), trim($date[0])));
$offset = round((mktime($i[0], $i[1], 0, $j[1], $j[0], $j[2]) - $time) / 60) * 60;
}else{
exec("date +%s", $t);
$offset = round((intval(trim($t[0])) - time()) / 60) * 60;
}
$daylight = (int) date("I");
$d = timezone_name_from_abbr("", $offset, $daylight);
@ini_set("date.timezone", $d);
date_default_timezone_set($d);
}else{
$d = @date_default_timezone_get();
if(strpos($d, "/") === false){
$d = timezone_name_from_abbr($d);
@ini_set("date.timezone", $d);
date_default_timezone_set($d);
}
}
gc_enable();
error_reporting(E_ALL | E_STRICT);
ini_set("allow_url_fopen", 1);
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
ini_set("default_charset", "utf-8");
ini_set("memory_limit", "128M"); //Default
define("PocketMine\START_TIME", microtime(true));
$opts = getopt("", array("enable-ansi", "disable-ansi", "data-path:", "no-wizard"));
define("PocketMine\DATA", isset($opts["data-path"]) ? realpath($opts["data-path"]) . DIRECTORY_SEPARATOR : PATH);
if((strpos(strtoupper(php_uname("s")), "WIN") or isset($opts["enable-ansi"])) and !isset($opts["disable-ansi"])){
define("PocketMine\ANSI", true);
}else{
define("PocketMine\ANSI", false);
}
function dummy(){
}
function safe_var_dump($var, $cnt = 0){
switch(true){
case is_array($var):
echo str_repeat(" ", $cnt)."array(".count($var).") {".PHP_EOL;
foreach($var as $key => $value){
echo str_repeat(" ", $cnt + 1)."[".(is_integer($key) ? $key:'"'.$key.'"')."]=>".PHP_EOL;
safe_var_dump($value, $cnt + 1);
}
echo str_repeat(" ", $cnt)."}".PHP_EOL;
break;
case is_integer($var):
echo str_repeat(" ", $cnt)."int(".$var.")".PHP_EOL;
break;
case is_float($var):
echo str_repeat(" ", $cnt)."float(".$var.")".PHP_EOL;
break;
case is_bool($var):
echo str_repeat(" ", $cnt)."bool(".($var === true ? "true":"false").")".PHP_EOL;
break;
case is_string($var):
echo str_repeat(" ", $cnt)."string(".strlen($var).") \"$var\"".PHP_EOL;
break;
case is_resource($var):
echo str_repeat(" ", $cnt)."resource() of type (".get_resource_type($var).")".PHP_EOL;
break;
case is_object($var):
echo str_repeat(" ", $cnt)."object(".get_class($var).")".PHP_EOL;
break;
case is_null($var):
echo str_repeat(" ", $cnt)."NULL".PHP_EOL;
break;
}
}
function kill($pid){
switch(Utils\Utils::getOS()){
case "win":
exec("taskkill.exe /F /PID ".((int) $pid)." > NUL");
break;
case "mac":
case "linux":
default:
exec("kill -9 ".((int) $pid)." > /dev/null 2>&1");
}
}
function hard_unset(&$var){
if(is_object($var)){
$unset = new \ReflectionClass($var);
foreach($unset->getProperties() as $prop){
$prop->setAccessible(true);
@hard_unset($prop->getValue($var));
$prop->setValue($var, null);
}
$var = null;
unset($var);
}elseif(is_array($var)){
foreach($var as $i => $v){
hard_unset($var[$i]);
}
$var = null;
unset($var);
}else{
$var = null;
unset($var);
}
}
function console($message, $EOL = true, $log = true, $level = 1){
if(!defined("DEBUG") or DEBUG >= $level){
$message .= $EOL === true ? PHP_EOL:"";
$time = (ANSI === true ? Utils\TextFormat::AQUA . date("H:i:s") . Utils\TextFormat::RESET:date("H:i:s")) . " ";
$replaced = Utils\TextFormat::clean(preg_replace('/\x1b\[[0-9;]*m/', "", $time . $message));
if($log === true and (!defined("LOG") or LOG === true)){
log(date("Y-m-d")." ".$replaced, "console", false, $level);
}
if(ANSI === true){
$add = "";
if(preg_match("/\[([a-zA-Z0-9]*)\]/", $message, $matches) > 0){
switch($matches[1]){
case "ERROR":
case "SEVERE":
$add .= Utils\TextFormat::RED;
break;
case "INTERNAL":
case "DEBUG":
$add .= Utils\TextFormat::GRAY;
break;
case "WARNING":
$add .= Utils\TextFormat::YELLOW;
break;
case "NOTICE":
$add .= Utils\TextFormat::AQUA;
break;
default:
$add = "";
break;
}
}
$message = Utils\TextFormat::toANSI($time . $add . $message . Utils\TextFormat::RESET);
}else{
$message = $replaced;
}
echo $message;
}
}
function getTrace($start = 1){
$e = new \Exception();
$trace = $e->getTrace();
$messages = array();
$j = 0;
for($i = (int) $start; isset($trace[$i]); ++$i, ++$j){
$params = "";
if(isset($trace[$i]["args"])){
foreach($trace[$i]["args"] as $name => $value){
$params .= (is_object($value) ? get_class($value)." ".(method_exists($value, "__toString") ? $value->__toString() : "object"):gettype($value)." ".@strval($value)).", ";
}
}
$messages[] = "#$j ".(isset($trace[$i]["file"]) ? $trace[$i]["file"]:"")."(".(isset($trace[$i]["line"]) ? $trace[$i]["line"]:"")."): ".(isset($trace[$i]["class"]) ? $trace[$i]["class"].$trace[$i]["type"]:"").$trace[$i]["function"]."(".substr($params, 0, -2).")";
}
return $messages;
}
function error_handler($errno, $errstr, $errfile, $errline){
if(error_reporting() === 0){ //@ error-control
return false;
}
$errorConversion = array(
E_ERROR => "E_ERROR",
E_WARNING => "E_WARNING",
E_PARSE => "E_PARSE",
E_NOTICE => "E_NOTICE",
E_CORE_ERROR => "E_CORE_ERROR",
E_CORE_WARNING => "E_CORE_WARNING",
E_COMPILE_ERROR => "E_COMPILE_ERROR",
E_COMPILE_WARNING => "E_COMPILE_WARNING",
E_USER_ERROR => "E_USER_ERROR",
E_USER_WARNING => "E_USER_WARNING",
E_USER_NOTICE => "E_USER_NOTICE",
E_STRICT => "E_STRICT",
E_RECOVERABLE_ERROR => "E_RECOVERABLE_ERROR",
E_DEPRECATED => "E_DEPRECATED",
E_USER_DEPRECATED => "E_USER_DEPRECATED",
);
$errno = isset($errorConversion[$errno]) ? $errorConversion[$errno]:$errno;
console("[ERROR] A ".$errno." error happened: \"$errstr\" in \"$errfile\" at line $errline", true, true, 0);
foreach(getTrace() as $i => $line){
console("[TRACE] $line");
}
return true;
}
function log($message, $name, $EOL = true, $level = 2, $close = false){
global $fpointers;
if((!defined("DEBUG") or DEBUG >= $level) and (!defined("LOG") or LOG === true)){
$message .= $EOL === true ? PHP_EOL:"";
if(!isset($fpointers)){
$fpointers = array();
}
if(!isset($fpointers[$name]) or $fpointers[$name] === false){
$fpointers[$name] = @fopen(DATA."/".$name.".log", "ab");
}
@fwrite($fpointers[$name], $message);
if($close === true){
fclose($fpointers[$name]);
unset($fpointers[$name]);
}
}
}
set_error_handler("\PocketMine\\error_handler", E_ALL);
$errors = 0;
if(version_compare("5.4.0", PHP_VERSION) > 0){
console("[ERROR] Use PHP >= 5.4.0", true, true, 0);
++$errors;
}
if(php_sapi_name() !== "cli"){
console("[ERROR] You must run PocketMine-MP using the CLI.", true, true, 0);
++$errors;
}
if(!extension_loaded("sockets") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "sockets." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find the Socket extension.", true, true, 0);
++$errors;
}
if(!extension_loaded("pthreads") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "pthreads." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find the pthreads extension.", true, true, 0);
++$errors;
}else{
$pthreads_version = phpversion("pthreads");
if(substr_count($pthreads_version, ".") < 2){
$pthreads_version = "0.$pthreads_version";
}
if(version_compare($pthreads_version, "0.1.0") < 0){
console("[ERROR] pthreads >= 0.1.0 is required, while you have $pthreads_version.", true, true, 0);
++$errors;
}
}
if(!extension_loaded("curl") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "curl." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find the cURL extension.", true, true, 0);
++$errors;
}
if(!extension_loaded("sqlite3") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "sqlite3." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find the SQLite3 extension.", true, true, 0);
++$errors;
}
if(!extension_loaded("yaml") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "yaml." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find the YAML extension.", true, true, 0);
++$errors;
}
if(!extension_loaded("zlib") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "zlib." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find the Zlib extension.", true, true, 0);
++$errors;
}
if($errors > 0){
console("[ERROR] Please use the installer provided on the homepage, or recompile PHP again.", true, true, 0);
exit(1); //Exit with error
}
$gitsha1 = false;
if(file_exists(PATH . ".git/refs/heads/master")){ //Found Git information!
define("PocketMine\GIT_COMMIT", strtolower(trim(file_get_contents(PATH .".git/refs/heads/master"))));
}else{ //Unknown :(
define("PocketMine\GIT_COMMIT", str_repeat("00", 20));
}
ini_set("opcache.mmap_base", bin2hex(Utils\Utils::getRandomBytes(8, false))); //Fix OPCache address errors
require_once(PATH . "src/utils/pthreads.php");
if(!file_exists(DATA . "server.properties") and !isset($opts["no-wizard"])){
$installer = new Wizard\Installer();
}
$server = new ServerAPI(); $server = new ServerAPI();
$server->start(); $server->start();

View File

@ -19,6 +19,8 @@
* *
*/ */
namespace PocketMine;
abstract class Achievement{ abstract class Achievement{
public static $list = array( public static $list = array(
/*"openInventory" => array( /*"openInventory" => array(

View File

@ -19,6 +19,8 @@
* *
*/ */
namespace PocketMine;
class BanAPI{ class BanAPI{
private $server; private $server;
/* /*
@ -38,10 +40,10 @@ class BanAPI{
} }
public function init(){ public function init(){
$this->whitelist = new Config(DATA_PATH."white-list.txt", Config::ENUM);//Open whitelist list file $this->whitelist = new Utils\Config(DATA."white-list.txt", Utils\Config::ENUM);//Open whitelist list file
$this->bannedIPs = new Config(DATA_PATH."banned-ips.txt", Config::ENUM);//Open Banned IPs list file $this->bannedIPs = new Utils\Config(DATA."banned-ips.txt", Utils\Config::ENUM);//Open Banned IPs list file
$this->banned = new Config(DATA_PATH."banned.txt", Config::ENUM);//Open Banned Usernames list file $this->banned = new Utils\Config(DATA."banned.txt", Utils\Config::ENUM);//Open Banned Usernames list file
$this->ops = new Config(DATA_PATH."ops.txt", Config::ENUM);//Open list of OPs $this->ops = new Utils\Config(DATA."ops.txt", Utils\Config::ENUM);//Open list of OPs
$this->server->api->console->register("banip", "<add|remove|list|reload> [IP|player]", array($this, "commandHandler")); $this->server->api->console->register("banip", "<add|remove|list|reload> [IP|player]", array($this, "commandHandler"));
$this->server->api->console->register("ban", "<add|remove|list|reload> [username]", array($this, "commandHandler")); $this->server->api->console->register("ban", "<add|remove|list|reload> [username]", array($this, "commandHandler"));
$this->server->api->console->register("kick", "<player> [reason ...]", array($this, "commandHandler")); $this->server->api->console->register("kick", "<player> [reason ...]", array($this, "commandHandler"));
@ -211,7 +213,7 @@ class BanAPI{
$output .= "Player \"$user\" added to white-list\n"; $output .= "Player \"$user\" added to white-list\n";
break; break;
case "reload": case "reload":
$this->whitelist = new Config(DATA_PATH."white-list.txt", Config::ENUM); $this->whitelist = new Utils\Config(DATA."white-list.txt", Utils\Config::ENUM);
break; break;
case "list": case "list":
$output .= "White-list: ".implode(", ", $this->whitelist->getAll(true))."\n"; $output .= "White-list: ".implode(", ", $this->whitelist->getAll(true))."\n";
@ -256,7 +258,7 @@ class BanAPI{
$output .= "IP \"$ip\" added to ban list\n"; $output .= "IP \"$ip\" added to ban list\n";
break; break;
case "reload": case "reload":
$this->bannedIPs = new Config(DATA_PATH."banned-ips.txt", Config::ENUM); $this->bannedIPs = new Utils\Config(DATA."banned-ips.txt", Utils\Config::ENUM);
break; break;
case "list": case "list":
$output .= "IP ban list: ".implode(", ", $this->bannedIPs->getAll(true))."\n"; $output .= "IP ban list: ".implode(", ", $this->bannedIPs->getAll(true))."\n";
@ -294,7 +296,7 @@ class BanAPI{
$output .= "Player \"$user\" added to ban list\n"; $output .= "Player \"$user\" added to ban list\n";
break; break;
case "reload": case "reload":
$this->banned = new Config(DATA_PATH."banned.txt", Config::ENUM); $this->banned = new Utils\Config(DATA."banned.txt", Utils\Config::ENUM);
break; break;
case "list": case "list":
$output .= "Ban list: ".implode(", ", $this->banned->getAll(true))."\n"; $output .= "Ban list: ".implode(", ", $this->banned->getAll(true))."\n";

View File

@ -19,6 +19,8 @@
* *
*/ */
namespace PocketMine;
class BlockAPI{ class BlockAPI{
private $server; private $server;
private $scheduledUpdates = array(); private $scheduledUpdates = array();
@ -246,14 +248,14 @@ class BlockAPI{
} }
} }
public static function get($id, $meta = 0, $v = false){ public static function get($id, $meta = 0, Level\Position $v = null){
if(isset(Block::$class[$id])){ if(isset(Block::$class[$id])){
$classname = Block::$class[$id]; $classname = Block::$class[$id];
$b = new $classname($meta); $b = new $classname($meta);
}else{ }else{
$b = new GenericBlock((int) $id, $meta); $b = new Block\GenericBlock((int) $id, $meta);
} }
if($v instanceof Position){ if($v instanceof Level\Position){
$b->position($v); $b->position($v);
} }
return $b; return $b;
@ -261,11 +263,11 @@ class BlockAPI{
public static function getItem($id, $meta = 0, $count = 1){ public static function getItem($id, $meta = 0, $count = 1){
$id = (int) $id; $id = (int) $id;
if(isset(Item::$class[$id])){ if(isset(Item\Item::$class[$id])){
$classname = Item::$class[$id]; $classname = Item\Item::$class[$id];
$i = new $classname($meta, $count); $i = new $classname($meta, $count);
}else{ }else{
$i = new Item($id, $meta, $count); $i = new Item\Item($id, $meta, $count);
} }
return $i; return $i;
} }
@ -316,8 +318,8 @@ class BlockAPI{
return $output; return $output;
} }
private function cancelAction(Block $block, Player $player, $send = true){ private function cancelAction(Block\Block $block, Player $player, $send = true){
$pk = new UpdateBlockPacket; $pk = new Network\Protocol\UpdateBlockPacket;
$pk->x = $block->x; $pk->x = $block->x;
$pk->y = $block->y; $pk->y = $block->y;
$pk->z = $block->z; $pk->z = $block->z;
@ -330,7 +332,7 @@ class BlockAPI{
return false; return false;
} }
public function playerBlockBreak(Player $player, Vector3 $vector){ public function playerBlockBreak(Player $player, Math\Math\Vector3 $vector){
$target = $player->level->getBlock($vector); $target = $player->level->getBlock($vector);
$item = $player->getSlot($player->slot); $item = $player->getSlot($player->slot);
@ -354,7 +356,7 @@ class BlockAPI{
return $this->cancelAction($target, $player, false); return $this->cancelAction($target, $player, false);
} }
if(($player->gamemode & 0x01) === 0 and $item->useOn($target) and $item->getMetadata() >= $item->getMaxDurability()){ if(($player->gamemode & 0x01) === 0 and $item->useOn($target) and $item->getMetadata() >= $item->getMaxDurability()){
$player->setSlot($player->slot, new Item(AIR, 0, 0)); $player->setSlot($player->slot, new Item\Item(AIR, 0, 0));
} }
}else{ }else{
return $this->cancelAction($target, $player, false); return $this->cancelAction($target, $player, false);
@ -370,7 +372,7 @@ class BlockAPI{
return false; return false;
} }
public function playerBlockAction(Player $player, Vector3 $vector, $face, $fx, $fy, $fz){ public function playerBlockAction(Player $player, Math\Math\Vector3 $vector, $face, $fx, $fy, $fz){
if($face < 0 or $face > 5){ if($face < 0 or $face > 5){
return false; return false;
} }
@ -424,7 +426,7 @@ class BlockAPI{
$hand = $item->getBlock(); $hand = $item->getBlock();
$hand->position($block); $hand->position($block);
}elseif($block->getID() === FIRE){ }elseif($block->getID() === FIRE){
$player->level->setBlock($block, new AirBlock(), true, false, true); $player->level->setBlock($block, new Block\AirBlock(), true, false, true);
return false; return false;
}else{ }else{
return $this->cancelAction($block, $player, false); return $this->cancelAction($block, $player, false);
@ -451,16 +453,16 @@ class BlockAPI{
return $this->cancelAction($block, $player, false); return $this->cancelAction($block, $player, false);
} }
if($hand->getID() === SIGN_POST or $hand->getID() === WALL_SIGN){ if($hand->getID() === SIGN_POST or $hand->getID() === WALL_SIGN){
new SignTile($player->level, new NBTTag_Compound(false, array( new Tile\Sign($player->level, new NBT\Tag\Compound(false, array(
"id" => new NBTTag_String("id", Tile::Sign), "id" => new NBT\Tag\String("id", Tile::Sign),
"x" => new NBTTag_Int("x", $block->x), "x" => new NBT\Tag\Int("x", $block->x),
"y" => new NBTTag_Int("y", $block->y), "y" => new NBT\Tag\Int("y", $block->y),
"z" => new NBTTag_Int("z", $block->z), "z" => new NBT\Tag\Int("z", $block->z),
"Text1" => new NBTTag_String("Text1", ""), "Text1" => new NBT\Tag\String("Text1", ""),
"Text2" => new NBTTag_String("Text2", ""), "Text2" => new NBT\Tag\String("Text2", ""),
"Text3" => new NBTTag_String("Text3", ""), "Text3" => new NBT\Tag\String("Text3", ""),
"Text4" => new NBTTag_String("Text4", ""), "Text4" => new NBT\Tag\String("Text4", ""),
"creator" => new NBTTag_String("creator", $player->getUsername()) "creator" => new NBT\Tag\String("creator", $player->getUsername())
))); )));
} }
@ -474,7 +476,7 @@ class BlockAPI{
return false; return false;
} }
public function blockUpdateAround(Position $pos, $type = BLOCK_UPDATE_NORMAL, $delay = false){ public function blockUpdateAround(Level\Position $pos, $type = BLOCK_UPDATE_NORMAL, $delay = false){
if($delay !== false){ if($delay !== false){
$this->scheduleBlockUpdate($pos->getSide(0), $delay, $type); $this->scheduleBlockUpdate($pos->getSide(0), $delay, $type);
$this->scheduleBlockUpdate($pos->getSide(1), $delay, $type); $this->scheduleBlockUpdate($pos->getSide(1), $delay, $type);
@ -492,11 +494,11 @@ class BlockAPI{
} }
} }
public function blockUpdate(Position $pos, $type = BLOCK_UPDATE_NORMAL){ public function blockUpdate(Level\Position $pos, $type = BLOCK_UPDATE_NORMAL){
if(!($pos instanceof Block)){ if(!($pos instanceof Block\Block)){
$block = $pos->level->getBlock($pos); $block = $pos->level->getBlock($pos);
}else{ }else{
$pos = new Position($pos->x, $pos->y, $pos->z, $pos->level); $pos = new Level\Position($pos->x, $pos->y, $pos->z, $pos->level);
$block = $pos->level->getBlock($pos); $block = $pos->level->getBlock($pos);
} }
if($block === false){ if($block === false){
@ -510,7 +512,7 @@ class BlockAPI{
return $level; return $level;
} }
public function scheduleBlockUpdate(Position $pos, $delay, $type = BLOCK_UPDATE_SCHEDULED){ public function scheduleBlockUpdate(Level\Position $pos, $delay, $type = BLOCK_UPDATE_SCHEDULED){
$type = (int) $type; $type = (int) $type;
if($delay < 0){ if($delay < 0){
return false; return false;
@ -530,7 +532,7 @@ class BlockAPI{
$time = microtime(true); $time = microtime(true);
if(count($this->scheduledUpdates) > 0){ if(count($this->scheduledUpdates) > 0){
$update = $this->server->query("SELECT x,y,z,level,type FROM blockUpdates WHERE delay <= ".$time.";"); $update = $this->server->query("SELECT x,y,z,level,type FROM blockUpdates WHERE delay <= ".$time.";");
if($update instanceof SQLite3Result){ if($update instanceof \SQLite3Result){
$upp = array(); $upp = array();
while(($up = $update->fetchArray(SQLITE3_ASSOC)) !== false){ while(($up = $update->fetchArray(SQLITE3_ASSOC)) !== false){
$index = $up["x"].".".$up["y"].".".$up["z"].".".$up["level"].".".$up["type"]; $index = $up["x"].".".$up["y"].".".$up["z"].".".$up["level"].".".$up["type"];

View File

@ -19,6 +19,8 @@
* *
*/ */
namespace PocketMine;
class ChatAPI{ class ChatAPI{
private $server; private $server;
function __construct(){ function __construct(){
@ -143,6 +145,7 @@ class ChatAPI{
$message["player"] = ""; $message["player"] = "";
} }
//TODO: Remove Container
$this->server->handle("server.chat", new Container($message, $whitelist, $blacklist)); $this->server->handle("server.chat", new Container($message, $whitelist, $blacklist));
} }
} }

View File

@ -19,6 +19,8 @@
* *
*/ */
namespace PocketMine;
class ConsoleAPI{ class ConsoleAPI{
private $loop, $server, $event, $help, $cmds, $alias; private $loop, $server, $event, $help, $cmds, $alias;
function __construct(){ function __construct(){
@ -130,7 +132,7 @@ class ConsoleAPI{
$max = ceil(count($cmds) / 5); $max = ceil(count($cmds) / 5);
$page = (int) (isset($params[0]) ? min($max, max(1, intval($params[0]))):1); $page = (int) (isset($params[0]) ? min($max, max(1, intval($params[0]))):1);
$output .= TextFormat::RED."-".TextFormat::RESET." Showing help page $page of $max (/help <page>) ".TextFormat::RED."-".TextFormat::RESET."\n"; $output .= Utils\TextFormat::RED."-".Utils\TextFormat::RESET." Showing help page $page of $max (/help <page>) ".Utils\TextFormat::RED."-".Utils\TextFormat::RESET."\n";
$current = 1; $current = 1;
foreach($cmds as $c => $h){ foreach($cmds as $c => $h){
$curpage = (int) ceil($current / 5); $curpage = (int) ceil($current / 5);
@ -177,9 +179,9 @@ class ConsoleAPI{
return $this->run($this->alias[$cmd] . ($params !== "" ? " " .$params:""), $issuer, $cmd); return $this->run($this->alias[$cmd] . ($params !== "" ? " " .$params:""), $issuer, $cmd);
} }
if($issuer instanceof Player){ if($issuer instanceof Player){
console("[DEBUG] ".TextFormat::AQUA.$issuer->getUsername().TextFormat::RESET." issued server command: ".ltrim("$alias ")."/$cmd ".$params, true, true, 2); console("[DEBUG] ".Utils\TextFormat::AQUA.$issuer->getUsername().Utils\TextFormat::RESET." issued server command: ".ltrim("$alias ")."/$cmd ".$params, true, true, 2);
}else{ }else{
console("[DEBUG] ".TextFormat::YELLOW."*".$issuer.TextFormat::RESET." issued server command: ".ltrim("$alias ")."/$cmd ".$params, true, true, 2); console("[DEBUG] ".Utils\TextFormat::YELLOW."*".$issuer.Utils\TextFormat::RESET." issued server command: ".ltrim("$alias ")."/$cmd ".$params, true, true, 2);
} }
if(preg_match_all('#@([@a-z]{1,})#', $params, $matches, PREG_OFFSET_CAPTURE) > 0){ if(preg_match_all('#@([@a-z]{1,})#', $params, $matches, PREG_OFFSET_CAPTURE) > 0){
@ -285,7 +287,7 @@ class ConsoleAPI{
} }
class ConsoleLoop extends Thread{ class ConsoleLoop extends \Thread{
public $line; public $line;
public $stop; public $stop;
public $base; public $base;

View File

@ -19,6 +19,9 @@
* *
*/ */
namespace PocketMine;
use PocketMine;
class Container{ class Container{
private $payload = "", $whitelist = false, $blacklist = false; private $payload = "", $whitelist = false, $blacklist = false;
public function __construct($payload = "", $whitelist = false, $blacklist = false){ public function __construct($payload = "", $whitelist = false, $blacklist = false){

View File

@ -19,6 +19,9 @@
* *
*/ */
//TODO: REMOVE
namespace PocketMine;
class Deprecation{ class Deprecation{
public static $events = array( public static $events = array(
@ -31,5 +34,4 @@ class Deprecation{
"api.player.offline.save" => "player.offline.save", "api.player.offline.save" => "player.offline.save",
); );
} }

View File

@ -19,6 +19,8 @@
* *
*/ */
__halt_compiler();
class EntityOLD extends Position{ class EntityOLD extends Position{
public $age; public $age;
public $air; public $air;
@ -346,11 +348,11 @@ class EntityOLD extends Position{
for($y = $startY; $y <= $endY; ++$y){ for($y = $startY; $y <= $endY; ++$y){
for($x = $startX; $x <= $endX; ++$x){ for($x = $startX; $x <= $endX; ++$x){
for($z = $startZ; $z <= $endZ; ++$z){ for($z = $startZ; $z <= $endZ; ++$z){
$b = $this->level->getBlock(new Vector3($x, $y, $z)); $b = $this->level->getBlock(new Math\Vector3($x, $y, $z));
switch($b->getID()){ switch($b->getID()){
case WATER: case WATER:
case STILL_WATER: //Drowing case STILL_WATER: //Drowing
if($this->fire > 0 and $this->inBlock(new Vector3($x, $y, $z))){ if($this->fire > 0 and $this->inBlock(new Math\Vector3($x, $y, $z))){
$this->fire = 0; $this->fire = 0;
$this->updateMetadata(); $this->updateMetadata();
} }
@ -366,7 +368,7 @@ class EntityOLD extends Position{
break; break;
case LAVA: //Lava damage case LAVA: //Lava damage
case STILL_LAVA: case STILL_LAVA:
if($this->inBlock(new Vector3($x, $y, $z))){ if($this->inBlock(new Math\Vector3($x, $y, $z))){
$this->harm(5, "lava"); $this->harm(5, "lava");
$this->fire = 300; $this->fire = 300;
$this->updateMetadata(); $this->updateMetadata();
@ -374,7 +376,7 @@ class EntityOLD extends Position{
} }
break; break;
case FIRE: //Fire block damage case FIRE: //Fire block damage
if($this->inBlock(new Vector3($x, $y, $z))){ if($this->inBlock(new Math\Vector3($x, $y, $z))){
$this->harm(1, "fire"); $this->harm(1, "fire");
$this->fire = 300; $this->fire = 300;
$this->updateMetadata(); $this->updateMetadata();
@ -382,13 +384,13 @@ class EntityOLD extends Position{
} }
break; break;
case CACTUS: //Cactus damage case CACTUS: //Cactus damage
if($this->touchingBlock(new Vector3($x, $y, $z))){ if($this->touchingBlock(new Math\Vector3($x, $y, $z))){
$this->harm(1, "cactus"); $this->harm(1, "cactus");
$hasUpdate = true; $hasUpdate = true;
} }
break; break;
default: default:
if($this->inBlock(new Vector3($x, $y, $z), 0.7) and $y == $endY and $b->isTransparent === false and ($this->class === ENTITY_MOB or $this->class === ENTITY_PLAYER)){ if($this->inBlock(new Math\Vector3($x, $y, $z), 0.7) and $y == $endY and $b->isTransparent === false and ($this->class === ENTITY_MOB or $this->class === ENTITY_PLAYER)){
$this->harm(1, "suffocation"); //Suffocation $this->harm(1, "suffocation"); //Suffocation
$hasUpdate = true; $hasUpdate = true;
}elseif($x == ($endX - 1) and $y == $endY and $z == ($endZ - 1)){ }elseif($x == ($endX - 1) and $y == $endY and $z == ($endZ - 1)){
@ -436,7 +438,7 @@ class EntityOLD extends Position{
$isFlying = true; $isFlying = true;
for($z = $startZ; $z <= $endZ; ++$z){ for($z = $startZ; $z <= $endZ; ++$z){
for($x = $startX; $x <= $endX; ++$x){ for($x = $startX; $x <= $endX; ++$x){
$v = new Vector3($x, $y, $z); $v = new Math\Vector3($x, $y, $z);
if($this->isSupport($v, $this->size)){ if($this->isSupport($v, $this->size)){
$b = $this->level->getBlock($v); $b = $this->level->getBlock($v);
if($b->isSolid === true){ if($b->isSolid === true){
@ -474,14 +476,14 @@ class EntityOLD extends Position{
$z = (int) ($this->z - 0.5); $z = (int) ($this->z - 0.5);
$lim = (int) floor($ny); $lim = (int) floor($ny);
for($y = (int) ceil($this->y) - 1; $y >= $lim; --$y){ for($y = (int) ceil($this->y) - 1; $y >= $lim; --$y){
if($this->level->getBlock(new Vector3($x, $y, $z))->isSolid === true){ if($this->level->getBlock(new Math\Vector3($x, $y, $z))->isSolid === true){
$ny = $y + 1; $ny = $y + 1;
$this->speedY = 0; $this->speedY = 0;
$support = true; $support = true;
if($this->class === ENTITY_FALLING){ if($this->class === ENTITY_FALLING){
$this->y = $ny; $this->y = $ny;
$fall = $this->level->getBlock(new Vector3(intval($this->x - 0.5), intval(ceil($this->y)), intval($this->z - 0.5))); $fall = $this->level->getBlock(new Math\Vector3(intval($this->x - 0.5), intval(ceil($this->y)), intval($this->z - 0.5)));
$down = $this->level->getBlock(new Vector3(intval($this->x - 0.5), intval(ceil($this->y) - 1), intval($this->z - 0.5))); $down = $this->level->getBlock(new Math\Vector3(intval($this->x - 0.5), intval(ceil($this->y) - 1), intval($this->z - 0.5)));
if($fall->isFullBlock === false or $down->isFullBlock === false){ if($fall->isFullBlock === false or $down->isFullBlock === false){
$this->server->api->entity->drop($this, BlockAPI::getItem($this->data["Tile"] & 0xFFFF, 0, 1), true); $this->server->api->entity->drop($this, BlockAPI::getItem($this->data["Tile"] & 0xFFFF, 0, 1), true);
}else{ }else{
@ -534,8 +536,8 @@ class EntityOLD extends Position{
} }
}elseif($this->fallY !== false){ //Fall damage! }elseif($this->fallY !== false){ //Fall damage!
if($y < $this->fallY){ if($y < $this->fallY){
$d = $this->level->getBlock(new Vector3($this->x, $y + 1, $this->z)); $d = $this->level->getBlock(new Math\Vector3($this->x, $y + 1, $this->z));
$d2 = $this->level->getBlock(new Vector3($this->x, $y + 2, $this->z)); $d2 = $this->level->getBlock(new Math\Vector3($this->x, $y + 2, $this->z));
$dmg = ($this->fallY - $y) - 3; $dmg = ($this->fallY - $y) - 3;
if($dmg > 0 and !($d instanceof LiquidBlock) and $d->getID() !== LADDER and $d->getID() !== COBWEB and !($d2 instanceof LiquidBlock) and $d2->getID() !== LADDER and $d2->getID() !== COBWEB){ if($dmg > 0 and !($d instanceof LiquidBlock) and $d->getID() !== LADDER and $d->getID() !== COBWEB and !($d2 instanceof LiquidBlock) and $d2->getID() !== LADDER and $d2->getID() !== COBWEB){
$this->harm($dmg, "fall"); $this->harm($dmg, "fall");
@ -547,7 +549,7 @@ class EntityOLD extends Position{
} }
$this->calculateVelocity(); $this->calculateVelocity();
if($this->speed <= 9 or ($this->speed <= 20 and ($this->player->gamemode & 0x01) === 0x01)){ if($this->speed <= 9 or ($this->speed <= 20 and ($this->player->gamemode & 0x01) === 0x01)){
$this->player->lastCorrect = new Vector3($this->last[0], $this->last[1], $this->last[2]); $this->player->lastCorrect = new Math\Vector3($this->last[0], $this->last[1], $this->last[2]);
} }
} }
} }
@ -571,9 +573,9 @@ class EntityOLD extends Position{
if($this->class === ENTITY_PLAYER or ($this->last[5] + 8) < $now){ if($this->class === ENTITY_PLAYER or ($this->last[5] + 8) < $now){
if($this->server->api->handle("entity.move", $this) === false){ if($this->server->api->handle("entity.move", $this) === false){
if($this->class === ENTITY_PLAYER and $this->player instanceof Player){ if($this->class === ENTITY_PLAYER and $this->player instanceof Player){
$this->player->teleport(new Vector3($this->last[0], $this->last[1], $this->last[2]), $this->last[3], $this->last[4]); $this->player->teleport(new Math\Vector3($this->last[0], $this->last[1], $this->last[2]), $this->last[3], $this->last[4]);
}else{ }else{
$this->setPosition(new Vector3($this->last[0], $this->last[1], $this->last[2]), $this->last[3], $this->last[4]); $this->setPosition(new Math\Vector3($this->last[0], $this->last[1], $this->last[2]), $this->last[3], $this->last[4]);
} }
}else{ }else{
$this->updateLast(); $this->updateLast();
@ -834,7 +836,7 @@ class EntityOLD extends Position{
$this->server->query("UPDATE entities SET pitch = ".$this->pitch.", yaw = ".$this->yaw." WHERE EID = ".$this->eid.";"); $this->server->query("UPDATE entities SET pitch = ".$this->pitch.", yaw = ".$this->yaw." WHERE EID = ".$this->eid.";");
} }
public function move(Vector3 $pos, $yaw = 0, $pitch = 0){ public function move(Math\Vector3 $pos, $yaw = 0, $pitch = 0){
$this->x += $pos->x; $this->x += $pos->x;
$this->y += $pos->y; $this->y += $pos->y;
$this->z += $pos->z; $this->z += $pos->z;
@ -849,7 +851,7 @@ class EntityOLD extends Position{
$this->server->query("UPDATE entities SET level = '".$this->level->getName()."', x = ".$this->x.", y = ".$this->y.", z = ".$this->z.", pitch = ".$this->pitch.", yaw = ".$this->yaw." WHERE EID = ".$this->eid.";"); $this->server->query("UPDATE entities SET level = '".$this->level->getName()."', x = ".$this->x.", y = ".$this->y.", z = ".$this->z.", pitch = ".$this->pitch.", yaw = ".$this->yaw." WHERE EID = ".$this->eid.";");
} }
public function setPosition(Vector3 $pos, $yaw = false, $pitch = false){ public function setPosition(Math\Vector3 $pos, $yaw = false, $pitch = false){
if($pos instanceof Position and $pos->level instanceof Level and $this->level !== $pos->level){ if($pos instanceof Position and $pos->level instanceof Level and $this->level !== $pos->level){
$this->level = $pos->level; $this->level = $pos->level;
$this->server->preparedSQL->entity->setLevel->reset(); $this->server->preparedSQL->entity->setLevel->reset();
@ -878,23 +880,23 @@ class EntityOLD extends Position{
$this->server->preparedSQL->entity->setPosition->execute(); $this->server->preparedSQL->entity->setPosition->execute();
} }
public function inBlock(Vector3 $block, $radius = 0.8){ public function inBlock(Math\Vector3 $block, $radius = 0.8){
$me = new Vector3($this->x - 0.5, $this->y, $this->z - 0.5); $me = new Math\Vector3($this->x - 0.5, $this->y, $this->z - 0.5);
if(($block->y == ((int) $this->y) or $block->y == (((int) $this->y) + 1)) and $block->maxPlainDistance($me) < $radius){ if(($block->y == ((int) $this->y) or $block->y == (((int) $this->y) + 1)) and $block->maxPlainDistance($me) < $radius){
return true; return true;
} }
return false; return false;
} }
public function touchingBlock(Vector3 $block, $radius = 0.9){ public function touchingBlock(Math\Vector3 $block, $radius = 0.9){
$me = new Vector3($this->x - 0.5, $this->y, $this->z - 0.5); $me = new Math\Vector3($this->x - 0.5, $this->y, $this->z - 0.5);
if(($block->y == (((int) $this->y) - 1) or $block->y == ((int) $this->y) or $block->y == (((int) $this->y) + 1)) and $block->maxPlainDistance($me) < $radius){ if(($block->y == (((int) $this->y) - 1) or $block->y == ((int) $this->y) or $block->y == (((int) $this->y) + 1)) and $block->maxPlainDistance($me) < $radius){
return true; return true;
} }
return false; return false;
} }
public function isSupport(Vector3 $pos, $radius = 1){ public function isSupport(Math\Vector3 $pos, $radius = 1){
$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){

View File

@ -2,11 +2,11 @@
/** /**
* *
* ____ _ _ __ __ _ __ __ ____ * ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by * it under the terms of the GNU Lesser General Public License as published by
@ -15,9 +15,11 @@
* *
* @author PocketMine Team * @author PocketMine Team
* @link http://www.pocketmine.net/ * @link http://www.pocketmine.net/
*
* *
*/ *
*/
namespace PocketMine;
class LevelAPI{ class LevelAPI{
private $server, $levels, $default; private $server, $levels, $default;
@ -80,7 +82,7 @@ class LevelAPI{
} }
public function generateLevel($name, $seed = false, $generator = false){ public function generateLevel($name, $seed = false, $generator = false){
if($this->levelExists($name)){ if($name == "" or $this->levelExists($name)){
return false; return false;
} }
$options = array(); $options = array();
@ -92,12 +94,12 @@ class LevelAPI{
$generator = new $generator($options); $generator = new $generator($options);
}else{ }else{
if(strtoupper($this->server->api->getProperty("level-type")) == "FLAT"){ if(strtoupper($this->server->api->getProperty("level-type")) == "FLAT"){
$generator = new SuperflatGenerator($options); $generator = new Level\Generator\Flat($options);
}else{ }else{
$generator = new NormalGenerator($options); $generator = new Level\Generator\Normal($options);
} }
} }
$gen = new WorldGenerator($generator, $name, $seed === false ? Utils::readInt(Utils::getRandomBytes(4, false)):(int) $seed); $gen = new Level\WorldGenerator($generator, $name, $seed === false ? Utils\Utils::readInt(Utils\Utils::getRandomBytes(4, false)):(int) $seed);
$gen->generate(); $gen->generate();
$gen->close(); $gen->close();
return true; return true;
@ -107,9 +109,9 @@ class LevelAPI{
if($name === ""){ if($name === ""){
return false; return false;
} }
$path = DATA_PATH."worlds/".$name."/"; $path = DATA."worlds/".$name."/";
if($this->get($name) === false and !file_exists($path."level.pmf")){ if($this->get($name) === false and !file_exists($path."level.pmf")){
$level = new LevelImport($path); $level = new Level\LevelImport($path);
if($level->import() === false){ if($level->import() === false){
return false; return false;
} }
@ -117,7 +119,7 @@ class LevelAPI{
return true; return true;
} }
public function unloadLevel(Level $level, $force = false){ public function unloadLevel(Level\Level $level, $force = false){
$name = $level->getName(); $name = $level->getName();
if($name === $this->default and $force !== true){ if($name === $this->default and $force !== true){
return false; return false;
@ -128,14 +130,6 @@ class LevelAPI{
foreach($level->getPlayers() as $player){ foreach($level->getPlayers() as $player){
$player->teleport($this->server->spawn); $player->teleport($this->server->spawn);
} }
/*foreach($this->server->api->entity->getAll($level) as $entity){
if($entity->class !== ENTITY_PLAYER){
$entity->close();
}
}*/
/*foreach($this->server->api->tile->getAll($level) as $tile){
$tile->close();
}*/
$level->close(); $level->close();
unset($this->levels[$name]); unset($this->levels[$name]);
return true; return true;
@ -148,19 +142,19 @@ class LevelAPI{
console("[NOTICE] Level \"".$name."\" not found"); console("[NOTICE] Level \"".$name."\" not found");
return false; return false;
} }
$path = DATA_PATH."worlds/".$name."/"; $path = DATA."worlds/".$name."/";
console("[INFO] Preparing level \"".$name."\""); console("[INFO] Preparing level \"".$name."\"");
$level = new PMFLevel($path."level.pmf"); $level = new PMF\Level($path."level.pmf");
if(!$level->isLoaded){ if(!$level->isLoaded){
console("[ERROR] Could not load level \"".$name."\""); console("[ERROR] Could not load level \"".$name."\"");
return false; return false;
} }
//$entities = new Config($path."entities.yml", Config::YAML); //$entities = new Utils\Config($path."entities.yml", Utils\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");
} }
$blockUpdates = new Config($path."bupdates.yml", Config::YAML); $blockUpdates = new Utils\Config($path."bupdates.yml", Utils\Config::YAML);
$this->levels[$name] = new Level($level, $name); $this->levels[$name] = new Level\Level($level, $name);
/*foreach($entities->getAll() as $entity){ /*foreach($entities->getAll() as $entity){
if(!isset($entity["id"])){ if(!isset($entity["id"])){
break; break;
@ -177,39 +171,39 @@ class LevelAPI{
)); ));
}elseif($entity["id"] === FALLING_SAND){ }elseif($entity["id"] === FALLING_SAND){
$e = $this->server->api->entity->add($this->levels[$name], ENTITY_FALLING, $entity["id"], $entity); $e = $this->server->api->entity->add($this->levels[$name], ENTITY_FALLING, $entity["id"], $entity);
$e->setPosition(new Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]); $e->setPosition(new Math\Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]);
$e->setHealth($entity["Health"]); $e->setHealth($entity["Health"]);
}elseif($entity["id"] === OBJECT_PAINTING or $entity["id"] === OBJECT_ARROW){ //Painting }elseif($entity["id"] === OBJECT_PAINTING or $entity["id"] === OBJECT_ARROW){ //Painting
$e = $this->server->api->entity->add($this->levels[$name], ENTITY_OBJECT, $entity["id"], $entity); $e = $this->server->api->entity->add($this->levels[$name], ENTITY_OBJECT, $entity["id"], $entity);
$e->setPosition(new Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]); $e->setPosition(new Math\Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]);
$e->setHealth(1); $e->setHealth(1);
}else{ }else{
$e = $this->server->api->entity->add($this->levels[$name], ENTITY_MOB, $entity["id"], $entity); $e = $this->server->api->entity->add($this->levels[$name], ENTITY_MOB, $entity["id"], $entity);
$e->setPosition(new Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]); $e->setPosition(new Math\Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]);
$e->setHealth($entity["Health"]); $e->setHealth($entity["Health"]);
} }
}*/ }*/
if(file_exists($path ."tiles.yml")){ if(file_exists($path ."tiles.yml")){
$tiles = new Config($path."tiles.yml", Config::YAML); $tiles = new Utils\Config($path."tiles.yml", Utils\Config::YAML);
foreach($tiles->getAll() as $tile){ foreach($tiles->getAll() as $tile){
if(!isset($tile["id"])){ if(!isset($tile["id"])){
continue; continue;
} }
$this->levels[$name]->loadChunk($tile["x"] >> 4, $tile["z"] >> 4); $this->levels[$name]->loadChunk($tile["x"] >> 4, $tile["z"] >> 4);
$nbt = new NBTTag_Compound(false, array()); $nbt = new NBT\Tag\Compound(false, array());
foreach($tile as $index => $data){ foreach($tile as $index => $data){
switch($index){ switch($index){
case "Items": case "Items":
$tag = new NBTTag_List("Items", array()); $tag = new NBT\Tag\Enum("Items", array());
$tag->setTagType(NBTTag::TAG_Compound); $tag->setTagType(NBT\TAG_Compound);
foreach($data as $slot => $fields){ foreach($data as $slot => $fields){
$tag[(int) $slot] = new NBTTag_Compound(false, array( $tag[(int) $slot] = new NBT\Tag\Compound(false, array(
"Count" => new NBTTag_Byte("Count", $fields["Count"]), "Count" => new NBT\Tag\Byte("Count", $fields["Count"]),
"Slot" => new NBTTag_Short("Slot", $fields["Slot"]), "Slot" => new NBT\Tag\Short("Slot", $fields["Slot"]),
"Damage" => new NBTTag_Short("Damage", $fields["Damage"]), "Damage" => new NBT\Tag\Short("Damage", $fields["Damage"]),
"id" => new NBTTag_String("id", $fields["id"]) "id" => new NBT\Tag\String("id", $fields["id"])
)); ));
} }
$nbt["Items"] = $tag; $nbt["Items"] = $tag;
@ -220,7 +214,7 @@ class LevelAPI{
case "Text2": case "Text2":
case "Text3": case "Text3":
case "Text4": case "Text4":
$nbt[$index] = new NBTTag_String($index, $data); $nbt[$index] = new NBT\Tag\String($index, $data);
break; break;
case "x": case "x":
@ -228,25 +222,25 @@ class LevelAPI{
case "z": case "z":
case "pairx": case "pairx":
case "pairz": case "pairz":
$nbt[$index] = new NBTTag_Int($index, $data); $nbt[$index] = new NBT\Tag\Int($index, $data);
break; break;
case "BurnTime": case "BurnTime":
case "CookTime": case "CookTime":
case "MaxTime": case "MaxTime":
$nbt[$index] = new NBTTag_Short($index, $data); $nbt[$index] = new NBT\Tag\Short($index, $data);
break; break;
} }
} }
switch($tile["id"]){ switch($tile["id"]){
case Tile::FURNACE: case Tile\Tile::FURNACE:
new FurnaceTile($this->levels[$name], $nbt); new Tile\Furnace($this->levels[$name], $nbt);
break; break;
case Tile::CHEST: case Tile\Tile::CHEST:
new ChestTile($this->levels[$name], $nbt); new Tile\Chest($this->levels[$name], $nbt);
break; break;
case Tile::SIGN: case Tile\Tile::SIGN:
new SignTile($this->levels[$name], $nbt); new Tile\Sign($this->levels[$name], $nbt);
break; break;
} }
} }
@ -255,7 +249,7 @@ class LevelAPI{
} }
foreach($blockUpdates->getAll() as $bupdate){ foreach($blockUpdates->getAll() as $bupdate){
$this->server->api->block->scheduleBlockUpdate(new Position((int) $bupdate["x"],(int) $bupdate["y"],(int) $bupdate["z"], $this->levels[$name]), (float) $bupdate["delay"], (int) $bupdate["type"]); $this->server->api->block->scheduleBlockUpdate(new Level\Position((int) $bupdate["x"],(int) $bupdate["y"],(int) $bupdate["z"], $this->levels[$name]), (float) $bupdate["delay"], (int) $bupdate["type"]);
} }
return true; return true;
} }

File diff suppressed because it is too large Load Diff

View File

@ -18,6 +18,8 @@
* *
* *
*/ */
namespace PocketMine;
class PlayerAPI{ class PlayerAPI{
private $server; private $server;
@ -50,7 +52,7 @@ class PlayerAPI{
$result = $this->server->preparedSQL->selectPlayersToHeal->execute(); $result = $this->server->preparedSQL->selectPlayersToHeal->execute();
if($result !== false){ if($result !== false){
while(($player = $result->fetchArray()) !== false){ while(($player = $result->fetchArray()) !== false){
if(($player = Entity::get($player["EID"])) !== false){ if(($player = Entity\Entity::get($player["EID"])) !== false){
if($player->getHealth() <= 0){ if($player->getHealth() <= 0){
continue; continue;
} }
@ -63,8 +65,8 @@ class PlayerAPI{
break; break;
case "player.death": case "player.death":
if(is_numeric($data["cause"])){ if(is_numeric($data["cause"])){
$e = Entity::get($data["cause"]); $e = Entity\Entity::get($data["cause"]);
if($e instanceof Entity){ if($e instanceof Entity\Entity){
switch($e->class){ switch($e->class){
case ENTITY_PLAYER: case ENTITY_PLAYER:
$message = " was killed by ".$e->name; $message = " was killed by ".$e->name;
@ -137,19 +139,19 @@ class PlayerAPI{
$target = $issuer; $target = $issuer;
} }
if(!($target instanceof Player) and !($target instanceof Level)){ if(!($target instanceof Player) and !($target instanceof Level\Level)){
$output .= "That player cannot be found.\n"; $output .= "That player cannot be found.\n";
break; break;
} }
if(count($params) === 3){ if(count($params) === 3){
if($target instanceof Level){ if($target instanceof Level){
$spawn = new Vector3(floatval(array_shift($params)), floatval(array_shift($params)), floatval(array_shift($params))); $spawn = new Math\Vector3(floatval(array_shift($params)), floatval(array_shift($params)), floatval(array_shift($params)));
}else{ }else{
$spawn = new Position(floatval(array_shift($params)), floatval(array_shift($params)), floatval(array_shift($params)), $issuer->level); $spawn = new Level\Position(floatval(array_shift($params)), floatval(array_shift($params)), floatval(array_shift($params)), $issuer->level);
} }
}else{ }else{
$spawn = new Position($issuer->entity->x, $issuer->entity->y, $issuer->entity->z, $issuer->entity->level); $spawn = new Level\Position($issuer->entity->x, $issuer->entity->y, $issuer->entity->z, $issuer->entity->level);
} }
$target->setSpawn($spawn); $target->setSpawn($spawn);
@ -303,7 +305,7 @@ class PlayerAPI{
} }
} }
$player = Player::get($target); $player = Player::get($target);
if(($player instanceof Player) and ($player->entity instanceof Entity)){ if($player instanceof Player and $player->spawned === true){
$target = $player->getUsername(); $target = $player->getUsername();
$origin = Player::get($name); $origin = Player::get($name);
if($origin instanceof Player){ if($origin instanceof Player){
@ -316,12 +318,12 @@ class PlayerAPI{
public function tppos(&$name, &$x, &$y, &$z){ public function tppos(&$name, &$x, &$y, &$z){
$player = Player::get($name); $player = Player::get($name);
if(($player instanceof Player) and ($player->entity instanceof Entity)){ if($player instanceof Player and $player->spawned === true){
$name = $player->getUsername(); $name = $player->getUsername();
$x = $x{0} === "~" ? $player->entity->x + floatval(substr($x, 1)):floatval($x); $x = $x{0} === "~" ? $player->entity->x + floatval(substr($x, 1)):floatval($x);
$y = $y{0} === "~" ? $player->entity->y + floatval(substr($y, 1)):floatval($y); $y = $y{0} === "~" ? $player->entity->y + floatval(substr($y, 1)):floatval($y);
$z = $z{0} === "~" ? $player->entity->z + floatval(substr($z, 1)):floatval($z); $z = $z{0} === "~" ? $player->entity->z + floatval(substr($z, 1)):floatval($z);
$player->teleport(new Vector3($x, $y, $z)); $player->teleport(new Math\Vector3($x, $y, $z));
return true; return true;
} }
return false; return false;

View File

@ -19,13 +19,15 @@
* *
*/ */
class PluginAPI extends stdClass{ namespace PocketMine;
class PluginAPI extends \stdClass{
private $server; private $server;
private $plugins = array(); private $plugins = array();
private $randomNonce; private $randomNonce;
public function __construct(){ public function __construct(){
$this->server = ServerAPI::request(); $this->server = ServerAPI::request();
$this->randomNonce = Utils::getRandomBytes(16, false); $this->randomNonce = Utils\Utils::getRandomBytes(16, false);
$this->server->api->console->register("plugins", "", array($this, "commandHandler")); $this->server->api->console->register("plugins", "", array($this, "commandHandler"));
$this->server->api->console->register("version", "", array($this, "commandHandler")); $this->server->api->console->register("version", "", array($this, "commandHandler"));
$this->server->api->ban->cmdWhitelist("version"); $this->server->api->ban->cmdWhitelist("version");
@ -42,7 +44,7 @@ class PluginAPI extends stdClass{
$output = $output === "Plugins: " ? "No plugins installed.\n" : substr($output, 0, -2)."\n"; $output = $output === "Plugins: " ? "No plugins installed.\n" : substr($output, 0, -2)."\n";
break; break;
case "version": case "version":
$output = "PocketMine-MP ".MAJOR_VERSION."".CODENAME."」 API #".CURRENT_API_VERSION." for Minecraft: PE ".CURRENT_MINECRAFT_VERSION." protocol #".ProtocolInfo::CURRENT_PROTOCOL; $output = "PocketMine-MP ".VERSION."".CODENAME."」 API #".API_VERSION." for Minecraft: PE ".MINECRAFT_VERSION." protocol #".Network\Protocol\Info::CURRENT_PROTOCOL;
if(GIT_COMMIT !== str_repeat("00", 20)){ if(GIT_COMMIT !== str_repeat("00", 20)){
$output .= " (git ".GIT_COMMIT.")"; $output .= " (git ".GIT_COMMIT.")";
} }
@ -77,7 +79,7 @@ class PluginAPI extends stdClass{
return false; return false;
} }
if(strtolower(substr($file, -3)) === "pmf"){ if(strtolower(substr($file, -3)) === "pmf"){
$pmf = new PMFPlugin($file); $pmf = new PMF\Plugin($file);
$info = $pmf->getPluginInfo(); $info = $pmf->getPluginInfo();
}else{ }else{
$content = file_get_contents($file); $content = file_get_contents($file);
@ -111,7 +113,7 @@ class PluginAPI extends stdClass{
console("[ERROR] Failed parsing of ".basename($file)); console("[ERROR] Failed parsing of ".basename($file));
return false; return false;
} }
console("[INFO] Loading plugin \"".TextFormat::GREEN.$info["name"].TextFormat::RESET."\" ".TextFormat::AQUA.$info["version"].TextFormat::RESET." by ".TextFormat::AQUA.$info["author"].TextFormat::RESET); console("[INFO] Loading plugin \"".Utils\TextFormat::GREEN.$info["name"].Utils\TextFormat::RESET."\" ".Utils\TextFormat::AQUA.$info["version"].Utils\TextFormat::RESET." by ".Utils\TextFormat::AQUA.$info["author"].Utils\TextFormat::RESET);
if($info["class"] !== "none" and class_exists($info["class"])){ if($info["class"] !== "none" and class_exists($info["class"])){
console("[ERROR] Failed loading plugin: class already exists"); console("[ERROR] Failed loading plugin: class already exists");
return false; return false;
@ -123,8 +125,8 @@ class PluginAPI extends stdClass{
$className = $info["class"]; $className = $info["class"];
$apiversion = array_map("intval", explode(",", (string) $info["apiversion"])); $apiversion = array_map("intval", explode(",", (string) $info["apiversion"]));
if(!in_array((string) CURRENT_API_VERSION, $apiversion)){ if(!in_array(API_VERSION, $apiversion)){
console("[WARNING] Plugin \"".$info["name"]."\" may not be compatible with the API (".$info["apiversion"]." != ".CURRENT_API_VERSION.")! It can crash or corrupt the server!"); console("[WARNING] Plugin \"".$info["name"]."\" may not be compatible with the API (".$info["apiversion"]." != ".API_VERSION.")! It can crash or corrupt the server!");
} }
$identifier = $this->getIdentifier($info["name"], $info["author"]); $identifier = $this->getIdentifier($info["name"], $info["author"]);
@ -167,7 +169,7 @@ class PluginAPI extends stdClass{
} }
public function pluginsPath(){ public function pluginsPath(){
$path = join(DIRECTORY_SEPARATOR, array(DATA_PATH."plugins", "")); $path = join(DIRECTORY_SEPARATOR, array(DATA."plugins", ""));
@mkdir($path); @mkdir($path);
return $path; return $path;
} }
@ -191,7 +193,7 @@ class PluginAPI extends stdClass{
return false; return false;
} }
$path = $this->configPath($plugin); $path = $this->configPath($plugin);
$cnf = new Config($path."config.yml", Config::YAML, $default); $cnf = new Utils\Config($path."config.yml", Utils\Config::YAML, $default);
$cnf->save(); $cnf->save();
return $path; return $path;
} }

View File

@ -19,7 +19,9 @@
* *
*/ */
class MainServer{ namespace PocketMine;
class Server{
public $tCnt; public $tCnt;
public $serverID, $interface, $database, $version, $invisible, $tickMeasure, $preparedSQL, $spawn, $whitelist, $seed, $stop, $gamemode, $difficulty, $name, $maxClients, $eidCnt, $custom, $description, $motd, $port, $saveEnabled; public $serverID, $interface, $database, $version, $invisible, $tickMeasure, $preparedSQL, $spawn, $whitelist, $seed, $stop, $gamemode, $difficulty, $name, $maxClients, $eidCnt, $custom, $description, $motd, $port, $saveEnabled;
private $serverip, $evCnt, $handCnt, $events, $eventsID, $handlers, $serverType, $lastTick, $doTick, $ticks, $memoryStats, $schedule, $asyncThread, $async = array(), $asyncID = 0; private $serverip, $evCnt, $handCnt, $events, $eventsID, $handlers, $serverType, $lastTick, $doTick, $ticks, $memoryStats, $schedule, $asyncThread, $async = array(), $asyncID = 0;
@ -30,14 +32,14 @@ class MainServer{
public $api; public $api;
private function load(){ private function load(){
$this->version = new VersionString(); $this->version = new Utils\VersionString();
/*if(defined("DEBUG") and DEBUG >= 0){ if(defined("DEBUG") and DEBUG >= 0){
@cli_set_process_title("PocketMine-MP ".MAJOR_VERSION); @cli_set_process_title("PocketMine-MP ".MAJOR_VERSION);
}*/ }
console("[INFO] Starting Minecraft PE server on ".($this->serverip === "0.0.0.0" ? "*":$this->serverip).":".$this->port); console("[INFO] Starting Minecraft PE server on ".($this->serverip === "0.0.0.0" ? "*":$this->serverip).":".$this->port);
define("BOOTUP_RANDOM", Utils::getRandomBytes(16)); define("BOOTUP_RANDOM", Utils\Utils::getRandomBytes(16));
$this->serverID = $this->serverID === false ? Utils::readLong(substr(Utils::getUniqueID(true, $this->serverip . $this->port), 8)):$this->serverID; $this->serverID = $this->serverID === false ? Utils\Utils::readLong(substr(Utils\Utils::getUniqueID(true, $this->serverip . $this->port), 8)):$this->serverID;
$this->seed = $this->seed === false ? Utils::readInt(Utils::getRandomBytes(4, false)):$this->seed; $this->seed = $this->seed === false ? Utils\Utils::readInt(Utils\Utils::getRandomBytes(4, false)):$this->seed;
$this->startDatabase(); $this->startDatabase();
$this->api = false; $this->api = false;
$this->tCnt = 1; $this->tCnt = 1;
@ -60,11 +62,11 @@ class MainServer{
$this->whitelist = false; $this->whitelist = false;
$this->tickMeasure = array_fill(0, 40, 0); $this->tickMeasure = array_fill(0, 40, 0);
$this->setType("normal"); $this->setType("normal");
$this->interface = new MinecraftInterface("255.255.255.255", $this->port, $this->serverip); $this->interface = new Network\Handler("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();
} }
} }
@ -91,14 +93,14 @@ class MainServer{
public function titleTick(){ public function titleTick(){
$time = microtime(true); $time = microtime(true);
if(defined("DEBUG") and DEBUG >= 0 and ENABLE_ANSI === true){ if(defined("DEBUG") and DEBUG >= 0 and ANSI === true){
echo "\x1b]0;PocketMine-MP ".MAJOR_VERSION." | Online ". count(Player::$list)."/".$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;PocketMine-MP ".VERSION." | Online ". count(Player::$list)."/".$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";
} }
$this->interface->bandwidth = array(0, 0, $time); $this->interface->bandwidth = array(0, 0, $time);
} }
public function loadEvents(){ public function loadEvents(){
if(ENABLE_ANSI === true){ if(ANSI === true){
$this->schedule(30, array($this, "titleTick"), array(), true); $this->schedule(30, array($this, "titleTick"), array(), true);
} }
$this->schedule(20 * 15, array($this, "checkTicks"), array(), true); $this->schedule(20 * 15, array($this, "checkTicks"), array(), true);
@ -123,9 +125,9 @@ class MainServer{
} }
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:", SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE); $this->database = new \SQLite3(":memory:", SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE);
$this->query("PRAGMA journal_mode = OFF;"); $this->query("PRAGMA journal_mode = OFF;");
$this->query("PRAGMA encoding = \"UTF-8\";"); $this->query("PRAGMA encoding = \"UTF-8\";");
$this->query("PRAGMA secure_delete = OFF;"); $this->query("PRAGMA secure_delete = OFF;");
@ -141,7 +143,7 @@ class MainServer{
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;
@ -152,7 +154,7 @@ class MainServer{
$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";
$info["memory_peak_usage"] = round((memory_get_peak_usage() / 1024) / 1024, 2)."MB"; $info["memory_peak_usage"] = round((memory_get_peak_usage() / 1024) / 1024, 2)."MB";
$info["entities"] = count(Entity::$list); $info["entities"] = count(Entity\Entity::$list);
$info["players"] = count(Player::$list); $info["players"] = count(Player::$list);
$info["events"] = count($this->eventsID); $info["events"] = count($this->eventsID);
$info["handlers"] = $this->query("SELECT count(ID) as count FROM handlers;", true); $info["handlers"] = $this->query("SELECT count(ID) as count FROM handlers;", true);
@ -211,25 +213,25 @@ class MainServer{
$type = (int) $type; $type = (int) $type;
switch($type){ switch($type){
case ASYNC_CURL_GET: case ASYNC_CURL_GET:
$d .= Utils::writeShort(strlen($data["url"])).$data["url"].(isset($data["timeout"]) ? Utils::writeShort($data["timeout"]) : Utils::writeShort(10)); $d .= Utils\Utils::writeShort(strlen($data["url"])).$data["url"].(isset($data["timeout"]) ? Utils\Utils::writeShort($data["timeout"]) : Utils\Utils::writeShort(10));
break; break;
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\Utils::writeShort(strlen($data["url"])).$data["url"].(isset($data["timeout"]) ? Utils\Utils::writeShort($data["timeout"]) : Utils\Utils::writeShort(10));
$d .= Utils::writeShort(count($data["data"])); $d .= Utils\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\Utils::writeShort(strlen($key)).$key . Utils\Utils::writeInt(strlen($value)).$value;
} }
break; break;
case ASYNC_FUNCTION: case ASYNC_FUNCTION:
$params = serialize($data["arguments"]); $params = serialize($data["arguments"]);
$d .= Utils::writeShort(strlen($data["function"])).$data["function"] . Utils::writeInt(strlen($params)) . $params; $d .= Utils\Utils::writeShort(strlen($data["function"])).$data["function"] . Utils\Utils::writeInt(strlen($params)) . $params;
break; break;
default: default:
return false; return false;
} }
$ID = $this->asyncID++; $ID = $this->asyncID++;
$this->async[$ID] = $callable; $this->async[$ID] = $callable;
$this->asyncThread->input .= Utils::writeInt($ID).Utils::writeShort($type).$d; $this->asyncThread->input .= Utils\Utils::writeInt($ID).Utils\Utils::writeShort($type).$d;
return $ID; return $ID;
} }
@ -239,21 +241,21 @@ class MainServer{
} }
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\Utils::readInt(substr($this->asyncThread->output, $offset, 4));
$offset += 4; $offset += 4;
$type = Utils::readShort(substr($this->asyncThread->output, $offset, 2)); $type = Utils\Utils::readShort(substr($this->asyncThread->output, $offset, 2));
$offset += 2; $offset += 2;
$data = array(); $data = array();
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\Utils::readInt(substr($this->asyncThread->output, $offset, 4));
$offset += 4; $offset += 4;
$data["result"] = substr($this->asyncThread->output, $offset, $len); $data["result"] = substr($this->asyncThread->output, $offset, $len);
$offset += $len; $offset += $len;
break; break;
case ASYNC_FUNCTION: case ASYNC_FUNCTION:
$len = Utils::readInt(substr($this->asyncThread->output, $offset, 4)); $len = Utils\Utils::readInt(substr($this->asyncThread->output, $offset, 4));
$offset += 4; $offset += 4;
$data["result"] = unserialize(substr($this->asyncThread->output, $offset, $len)); $data["result"] = unserialize(substr($this->asyncThread->output, $offset, $len));
$offset += $len; $offset += $len;
@ -307,7 +309,7 @@ class MainServer{
$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 = array(); $call = array();
while(($hn = $handlers->fetchArray(SQLITE3_ASSOC)) !== false){ while(($hn = $handlers->fetchArray(SQLITE3_ASSOC)) !== false){
$call[(int) $hn["ID"]] = true; $call[(int) $hn["ID"]] = true;
@ -424,14 +426,13 @@ class MainServer{
$dump .= "$line\r\n"; $dump .= "$line\r\n";
} }
$dump .= "\r\n\r\n"; $dump .= "\r\n\r\n";
$version = new VersionString(); $version = new Utils\VersionString();
$dump .= "PocketMine-MP version: ".$version." #".$version->getNumber()." [Protocol ".ProtocolInfo::CURRENT_PROTOCOL."; API ".CURRENT_API_VERSION."]\r\n"; $dump .= "PocketMine-MP version: ".$version." #".$version->getNumber()." [Protocol ".Network\Protocol\Info::CURRENT_PROTOCOL."; API ".API_VERSION."]\r\n";
$dump .= "Git commit: ".GIT_COMMIT."\r\n"; $dump .= "Git commit: ".GIT_COMMIT."\r\n";
$dump .= "Source SHA1 sum: ".SOURCE_SHA1SUM."\r\n";
$dump .= "uname -a: ".php_uname("a")."\r\n"; $dump .= "uname -a: ".php_uname("a")."\r\n";
$dump .= "PHP Version: " .phpversion()."\r\n"; $dump .= "PHP Version: " .phpversion()."\r\n";
$dump .= "Zend version: ".zend_version()."\r\n"; $dump .= "Zend version: ".zend_version()."\r\n";
$dump .= "OS : " .PHP_OS.", ".Utils::getOS()."\r\n"; $dump .= "OS : " .PHP_OS.", ".Utils\Utils::getOS()."\r\n";
$dump .= "Debug Info: ".var_export($this->debugInfo(false), true)."\r\n\r\n\r\n"; $dump .= "Debug Info: ".var_export($this->debugInfo(false), true)."\r\n\r\n\r\n";
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";
@ -483,17 +484,17 @@ class MainServer{
//return $ip . ":" . $port; //return $ip . ":" . $port;
} }
public function packetHandler(Packet $packet){ public function packetHandler(Network\Packet $packet){
$data =& $packet; $data =& $packet;
$CID = MainServer::clientID($packet->ip, $packet->port); $CID = Server::clientID($packet->ip, $packet->port);
if(isset(Player::$list[$CID])){ if(isset(Player::$list[$CID])){
Player::$list[$CID]->handlePacket($packet); Player::$list[$CID]->handlePacket($packet);
}else{ }else{
switch($packet->pid()){ switch($packet->pid()){
case RakNetInfo::UNCONNECTED_PING: case Network\RakNet\Info::UNCONNECTED_PING:
case RakNetInfo::UNCONNECTED_PING_OPEN_CONNECTIONS: case Network\RakNet\Info::UNCONNECTED_PING_OPEN_CONNECTIONS:
if($this->invisible === true){ if($this->invisible === true){
$pk = new RakNetPacket(RakNetInfo::UNCONNECTED_PONG); $pk = new Network\RakNet\Packet(Network\RakNet\Info::UNCONNECTED_PONG);
$pk->pingID = $packet->pingID; $pk->pingID = $packet->pingID;
$pk->serverID = $this->serverID; $pk->serverID = $this->serverID;
$pk->serverType = $this->serverType; $pk->serverType = $this->serverType;
@ -511,7 +512,7 @@ class MainServer{
} }
$txt = substr($this->description, $this->custom["times_".$CID], $ln); $txt = substr($this->description, $this->custom["times_".$CID], $ln);
$txt .= substr($this->description, 0, $ln - strlen($txt)); $txt .= substr($this->description, 0, $ln - strlen($txt));
$pk = new RakNetPacket(RakNetInfo::UNCONNECTED_PONG); $pk = new Network\RakNet\Packet(Network\RakNet\Info::UNCONNECTED_PONG);
$pk->pingID = $packet->pingID; $pk->pingID = $packet->pingID;
$pk->serverID = $this->serverID; $pk->serverID = $this->serverID;
$pk->serverType = $this->serverType . $this->name . " [".count(Player::$list)."/".$this->maxClients."] ".$txt; $pk->serverType = $this->serverType . $this->name . " [".count(Player::$list)."/".$this->maxClients."] ".$txt;
@ -520,16 +521,16 @@ class MainServer{
$this->send($pk); $this->send($pk);
$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 Network\RakNet\Info::OPEN_CONNECTION_REQUEST_1:
if($packet->structure !== RakNetInfo::STRUCTURE){ if($packet->structure !== Network\RakNet\Info::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 Network\RakNet\Packet(Network\RakNet\Info::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 Network\RakNet\Packet(Network\RakNet\Info::OPEN_CONNECTION_REPLY_1);
$pk->serverID = $this->serverID; $pk->serverID = $this->serverID;
$pk->mtuSize = strlen($packet->buffer); $pk->mtuSize = strlen($packet->buffer);
$pk->ip = $packet->ip; $pk->ip = $packet->ip;
@ -537,13 +538,13 @@ class MainServer{
$this->send($pk); $this->send($pk);
} }
break; break;
case RakNetInfo::OPEN_CONNECTION_REQUEST_2: case Network\RakNet\Info::OPEN_CONNECTION_REQUEST_2:
if($this->invisible === true){ if($this->invisible === true){
break; break;
} }
new Player($packet->clientID, $packet->ip, $packet->port, $packet->mtuSize); //New Session! new Player($packet->clientID, $packet->ip, $packet->port, $packet->mtuSize); //New Session!
$pk = new RakNetPacket(RakNetInfo::OPEN_CONNECTION_REPLY_2); $pk = new Network\RakNet\Packet(Network\RakNet\Info::OPEN_CONNECTION_REPLY_2);
$pk->serverID = $this->serverID; $pk->serverID = $this->serverID;
$pk->serverPort = $this->port; $pk->serverPort = $this->port;
$pk->mtuSize = $packet->mtuSize; $pk->mtuSize = $packet->mtuSize;
@ -555,7 +556,7 @@ class MainServer{
} }
} }
public function send(Packet $packet){ public function send(Network\Packet $packet){
return $this->interface->writePacket($packet); return $this->interface->writePacket($packet);
} }
@ -563,7 +564,7 @@ class MainServer{
$lastLoop = 0; $lastLoop = 0;
while($this->stop === false){ while($this->stop === false){
$packet = $this->interface->readPacket(); $packet = $this->interface->readPacket();
if($packet instanceof Packet){ if($packet instanceof Network\Packet){
$this->packetHandler($packet); $this->packetHandler($packet);
$lastLoop = 0; $lastLoop = 0;
} }
@ -624,7 +625,7 @@ class MainServer{
$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();

View File

@ -19,6 +19,8 @@
* *
*/ */
namespace PocketMine;
class ServerAPI{ class ServerAPI{
public $restart = false; public $restart = false;
private static $serverRequest = false; private static $serverRequest = false;
@ -74,7 +76,7 @@ class ServerAPI{
public $player; public $player;
/** /**
* @return MainServer * @return Server
*/ */
public static function request(){ public static function request(){
return self::$serverRequest; return self::$serverRequest;
@ -90,22 +92,22 @@ class ServerAPI{
} }
public function load(){ public function load(){
@mkdir(DATA_PATH."players/", 0755); @mkdir(DATA."players/", 0755);
@mkdir(DATA_PATH."worlds/", 0755); @mkdir(DATA."worlds/", 0755);
@mkdir(DATA_PATH."plugins/", 0755); @mkdir(DATA."plugins/", 0755);
//Init all the events //Init all the events
foreach(get_declared_classes() as $class){ foreach(get_declared_classes() as $class){
if(is_subclass_of($class, "BaseEvent") and property_exists($class, "handlers") and property_exists($class, "handlerPriority")){ if(is_subclass_of($class, "Event") and property_exists($class, "handlers") and property_exists($class, "handlerPriority")){
$class::unregisterAll(); $class::unregisterAll();
} }
} }
$version = new VersionString(); $version = new Utils\VersionString();
console("[INFO] Starting Minecraft PE server version ".TextFormat::AQUA.CURRENT_MINECRAFT_VERSION); console("[INFO] Starting Minecraft PE server version ".Utils\TextFormat::AQUA.MINECRAFT_VERSION);
console("[INFO] Loading properties..."); console("[INFO] Loading properties...");
$this->config = new Config(DATA_PATH . "server.properties", Config::PROPERTIES, array( $this->config = new Utils\Config(DATA . "server.properties", Utils\Config::PROPERTIES, array(
"server-name" => "Minecraft: PE Server", "server-name" => "Minecraft: PE Server",
"description" => "Server made using PocketMine-MP", "description" => "Server made using PocketMine-MP",
"motd" => "Welcome @player to this server!", "motd" => "Welcome @player to this server!",
@ -132,7 +134,7 @@ class ServerAPI{
"level-type" => "DEFAULT", "level-type" => "DEFAULT",
"enable-query" => true, "enable-query" => true,
"enable-rcon" => false, "enable-rcon" => false,
"rcon.password" => substr(base64_encode(Utils::getRandomBytes(20, false)), 3, 10), "rcon.password" => substr(base64_encode(Utils\Utils::getRandomBytes(20, false)), 3, 10),
"auto-save" => true, "auto-save" => true,
)); ));
@ -147,52 +149,52 @@ class ServerAPI{
} }
if($this->getProperty("upnp-forwarding") == true){ if($this->getProperty("upnp-forwarding") == true){
console("[INFO] [UPnP] Trying to port forward..."); console("[INFO] [UPnP] Trying to port forward...");
UPnP_PortForward($this->getProperty("server-port")); Network\UPnP\PortForward($this->getProperty("server-port"));
} }
$this->server = new MainServer($this->getProperty("server-name"), $this->getProperty("gamemode"), ($seed = $this->getProperty("level-seed")) != "" ? (int) $seed:false, $this->getProperty("server-port"), ($ip = $this->getProperty("server-ip")) != "" ? $ip:"0.0.0.0"); $this->server = new Server($this->getProperty("server-name"), $this->getProperty("gamemode"), ($seed = $this->getProperty("level-seed")) != "" ? (int) $seed:false, $this->getProperty("server-port"), ($ip = $this->getProperty("server-ip")) != "" ? $ip:"0.0.0.0");
$this->server->api = $this; $this->server->api = $this;
self::$serverRequest = $this->server; self::$serverRequest = $this->server;
console("[INFO] This server is running PocketMine-MP version ".($version->isDev() ? TextFormat::YELLOW:"").MAJOR_VERSION.TextFormat::RESET." \"".CODENAME."\" (MCPE: ".CURRENT_MINECRAFT_VERSION.") (API ".CURRENT_API_VERSION.")", true, true, 0); console("[INFO] This server is running PocketMine-MP version ".($version->isDev() ? Utils\TextFormat::YELLOW:"").VERSION.Utils\TextFormat::RESET." \"".CODENAME."\" (MCPE: ".MINECRAFT_VERSION.") (API ".API_VERSION.")", true, true, 0);
console("[INFO] PocketMine-MP is distributed under the LGPL License", true, true, 0); console("[INFO] PocketMine-MP is distributed under the LGPL License", true, true, 0);
if($this->getProperty("last-update") === false or ($this->getProperty("last-update") + 3600) < time()){ if($this->getProperty("last-update") === false or ($this->getProperty("last-update") + 3600) < time()){
console("[INFO] Checking for new server version"); console("[INFO] Checking for new server version");
console("[INFO] Last check: ".TextFormat::AQUA.date("Y-m-d H:i:s", $this->getProperty("last-update"))."\x1b[0m"); console("[INFO] Last check: ".Utils\TextFormat::AQUA.date("Y-m-d H:i:s", $this->getProperty("last-update"))."\x1b[0m");
if($this->server->version->isDev()){ if($this->server->version->isDev()){
$info = json_decode(Utils::curl_get("https://api.github.com/repos/PocketMine/PocketMine-MP/commits"), true); $info = json_decode(Utils\Utils::curl_get("https://api.github.com/repos/PocketMine/PocketMine-MP/commits"), true);
if($info === false or !isset($info[0])){ if($info === false or !isset($info[0])){
console("[ERROR] Github API error"); console("[ERROR] Github API error");
}else{ }else{
$last = new DateTime($info[0]["commit"]["committer"]["date"]); $last = new \DateTime($info[0]["commit"]["committer"]["date"]);
$last = $last->getTimestamp(); $last = $last->getTimestamp();
if($last >= $this->getProperty("last-update") and $this->getProperty("last-update") !== false and GIT_COMMIT != $info[0]["sha"]){ if($last >= $this->getProperty("last-update") and $this->getProperty("last-update") !== false and GIT_COMMIT != $info[0]["sha"]){
console("[NOTICE] ".TextFormat::YELLOW."A new DEVELOPMENT version of PocketMine-MP has been released!"); console("[NOTICE] ".Utils\TextFormat::YELLOW."A new DEVELOPMENT version of PocketMine-MP has been released!");
console("[NOTICE] ".TextFormat::YELLOW."Commit \"".$info[0]["commit"]["message"]."\" [".substr($info[0]["sha"], 0, 10)."] by ".$info[0]["commit"]["committer"]["name"]); console("[NOTICE] ".Utils\TextFormat::YELLOW."Commit \"".$info[0]["commit"]["message"]."\" [".substr($info[0]["sha"], 0, 10)."] by ".$info[0]["commit"]["committer"]["name"]);
console("[NOTICE] ".TextFormat::YELLOW."Get it at PocketMine.net or at https://github.com/PocketMine/PocketMine-MP/archive/".$info[0]["sha"].".zip"); console("[NOTICE] ".Utils\TextFormat::YELLOW."Get it at PocketMine.net or at https://github.com/PocketMine/PocketMine-MP/archive/".$info[0]["sha"].".zip");
console("[NOTICE] This message will dissapear after issuing the command \"/update-done\""); console("[NOTICE] This message will dissapear after issuing the command \"/update-done\"");
}else{ }else{
$this->setProperty("last-update", time()); $this->setProperty("last-update", time());
console("[INFO] ".TextFormat::AQUA."This is the latest DEVELOPMENT version"); console("[INFO] ".Utils\TextFormat::AQUA."This is the latest DEVELOPMENT version");
} }
} }
}else{ }else{
$info = json_decode(Utils::curl_get("https://api.github.com/repos/PocketMine/PocketMine-MP/tags"), true); $info = json_decode(Utils\Utils::curl_get("https://api.github.com/repos/PocketMine/PocketMine-MP/tags"), true);
if($info === false or !isset($info[0])){ if($info === false or !isset($info[0])){
console("[ERROR] Github API error"); console("[ERROR] Github API error");
}else{ }else{
$newest = new VersionString(MAJOR_VERSION); $newest = new Utils\VersionString(VERSION);
$newestN = $newest->getNumber(); $newestN = $newest->getNumber();
$update = new VersionString($info[0]["name"]); $update = new Utils\VersionString($info[0]["name"]);
$updateN = $update->getNumber(); $updateN = $update->getNumber();
if($updateN > $newestN){ if($updateN > $newestN){
console("[NOTICE] ".TextFormat::GREEN."A new STABLE version of PocketMine-MP has been released!"); console("[NOTICE] ".Utils\TextFormat::GREEN."A new STABLE version of PocketMine-MP has been released!");
console("[NOTICE] ".TextFormat::GREEN."Version \"".$info[0]["name"]."\" #".$updateN); console("[NOTICE] ".Utils\TextFormat::GREEN."Version \"".$info[0]["name"]."\" #".$updateN);
console("[NOTICE] Get it at PocketMine.net or at ".$info[0]["zipball_url"]); console("[NOTICE] Get it at PocketMine.net or at ".$info[0]["zipball_url"]);
console("[NOTICE] This message will dissapear as soon as you update"); console("[NOTICE] This message will dissapear as soon as you update");
}else{ }else{
$this->setProperty("last-update", time()); $this->setProperty("last-update", time());
console("[INFO] ".TextFormat::AQUA."This is the latest STABLE version"); console("[INFO] ".Utils\TextFormat::AQUA."This is the latest STABLE version");
} }
} }
} }
@ -200,14 +202,13 @@ class ServerAPI{
$this->loadProperties(); $this->loadProperties();
$this->apiList[] = $this->console = new ConsoleAPI();
$this->loadAPI("console", "ConsoleAPI"); $this->apiList[] = $this->level = new LevelAPI();
$this->loadAPI("level", "LevelAPI"); $this->apiList[] = $this->block = new BlockAPI();
$this->loadAPI("block", "BlockAPI"); $this->apiList[] = $this->chat = new ChatAPI();
$this->loadAPI("chat", "ChatAPI"); $this->apiList[] = $this->ban = new BanAPI();
$this->loadAPI("ban", "BanAPI"); $this->apiList[] = $this->player = new PlayerAPI();
$this->loadAPI("player", "PlayerAPI"); $this->apiList[] = $this->time = new TimeAPI();
$this->loadAPI("time", "TimeAPI");
foreach($this->apiList as $ob){ foreach($this->apiList as $ob){
if(is_callable(array($ob, "init"))){ if(is_callable(array($ob, "init"))){
@ -215,26 +216,25 @@ class ServerAPI{
} }
} }
$this->loadAPI("plugin", "PluginAPI"); //fix :( $this->apiList[] = $this->plugin = new PluginAPI();
$this->plugin->init();
} }
public function checkTickUpdates(){ public function checkTickUpdates(){
//Update entities that need update //Update entities that need update
if(count(Entity::$needUpdate) > 0){ if(count(Entity\Entity::$needUpdate) > 0){
foreach(Entity::$needUpdate as $id => $entity){ foreach(EntityEntity::$needUpdate as $id => $entity){
if($entity->onUpdate() === false){ if($entity->onUpdate() === false){
unset(Entity::$needUpdate[$id]); unset(Entity\Entity::$needUpdate[$id]);
} }
} }
} }
//Update tiles that need update //Update tiles that need update
if(count(Tile::$needUpdate) > 0){ if(count(Tile\Tile::$needUpdate) > 0){
foreach(Tile::$needUpdate as $id => $tile){ foreach(Tile\Tile::$needUpdate as $id => $tile){
if($tile->onUpdate() === false){ if($tile->onUpdate() === false){
unset(Tile::$needUpdate[$id]); unset(Tile\Tile::$needUpdate[$id]);
} }
} }
} }
@ -243,7 +243,7 @@ class ServerAPI{
public function async(callable $callable, $params = array(), $remove = false){ public function async(callable $callable, $params = array(), $remove = false){
$cnt = $this->asyncCnt++; $cnt = $this->asyncCnt++;
$this->asyncCalls[$cnt] = new Async($callable, $params); $this->asyncCalls[$cnt] = new \Async($callable, $params);
return $remove === true ? $this->getAsync($cnt):$cnt; return $remove === true ? $this->getAsync($cnt):$cnt;
} }
@ -272,13 +272,13 @@ class ServerAPI{
"data" => array( "data" => array(
"serverid" => $this->server->serverID, "serverid" => $this->server->serverID,
"port" => $this->server->port, "port" => $this->server->port,
"os" => Utils::getOS(), "os" => Utils\Utils::getOS(),
"memory_total" => $this->getProperty("memory-limit"), "memory_total" => $this->getProperty("memory-limit"),
"memory_usage" => memory_get_usage(true), "memory_usage" => memory_get_usage(true),
"php_version" => PHP_VERSION, "php_version" => PHP_VERSION,
"version" => MAJOR_VERSION, "version" => VERSION,
"mc_version" => CURRENT_MINECRAFT_VERSION, "mc_version" => MINECRAFT_VERSION,
"protocol" => ProtocolInfo::CURRENT_PROTOCOL, "protocol" => Network\Protocol\Info::CURRENT_PROTOCOL,
"online" => count(Player::$list), "online" => count(Player::$list),
"max" => $this->server->maxClients, "max" => $this->server->maxClients,
"plugins" => $plist, "plugins" => $plist,
@ -308,7 +308,7 @@ class ServerAPI{
$this->setProperty("memory-limit", "128M"); $this->setProperty("memory-limit", "128M");
} }
if($this->server instanceof MainServer){ if($this->server instanceof Server){
$this->server->setType($this->getProperty("server-type")); $this->server->setType($this->getProperty("server-type"));
$this->server->maxClients = $this->getProperty("max-players"); $this->server->maxClients = $this->getProperty("max-players");
$this->server->description = $this->getProperty("description"); $this->server->description = $this->getProperty("description");
@ -342,7 +342,7 @@ class ServerAPI{
break; break;
case "server-id": case "server-id":
if($v !== false){ if($v !== false){
$v = preg_match("/[^0-9\-]/", $v) > 0 ? Utils::readInt(substr(md5($v, true), 0, 4)):$v; $v = preg_match("/[^0-9\-]/", $v) > 0 ? Utils\Utils::readInt(substr(md5($v, true), 0, 4)):$v;
} }
break; break;
} }
@ -354,7 +354,7 @@ class ServerAPI{
} }
public function init(){ public function init(){
if(!(self::$serverRequest instanceof MainServer)){ if(!(self::$serverRequest instanceof Server)){
self::$serverRequest = $this->server; self::$serverRequest = $this->server;
} }
@ -366,24 +366,24 @@ class ServerAPI{
$this->server->schedule(18000, array($this, "autoSave"), array(), true); $this->server->schedule(18000, array($this, "autoSave"), array(), true);
} }
if(!defined("NO_THREADS") and $this->getProperty("enable-rcon") === true){ if(!defined("NO_THREADS") and $this->getProperty("enable-rcon") === true){
$this->rcon = new RCON($this->getProperty("rcon.password", ""), $this->getProperty("rcon.port", $this->getProperty("server-port")), ($ip = $this->getProperty("server-ip")) != "" ? $ip:"0.0.0.0", $this->getProperty("rcon.threads", 1), $this->getProperty("rcon.clients-per-thread", 50)); $this->rcon = new Network\RCON\RCON($this->getProperty("rcon.password", ""), $this->getProperty("rcon.port", $this->getProperty("server-port")), ($ip = $this->getProperty("server-ip")) != "" ? $ip:"0.0.0.0", $this->getProperty("rcon.threads", 1), $this->getProperty("rcon.clients-per-thread", 50));
} }
if($this->getProperty("enable-query") === true){ if($this->getProperty("enable-query") === true){
$this->query = new QueryHandler(); $this->query = new Network\Query\QueryHandler();
} }
CraftingRecipes::init(); Recipes\Crafting::init();
$this->schedule(2, array($this, "checkTickUpdates"), array(), true); $this->schedule(2, array($this, "checkTickUpdates"), array(), true);
$this->server->init(); $this->server->init();
unregister_tick_function(array($this->server, "tick")); unregister_tick_function(array($this->server, "tick"));
$this->console->__destruct(); $this->console->__destruct();
if($this->rcon instanceof RCON){ if($this->rcon instanceof Network\RCON\RCON){
$this->rcon->stop(); $this->rcon->stop();
} }
$this->__destruct(); $this->__destruct();
if($this->getProperty("upnp-forwarding") === true ){ if($this->getProperty("upnp-forwarding") === true ){
console("[INFO] [UPnP] Removing port forward..."); console("[INFO] [UPnP] Removing port forward...");
UPnP_RemovePortForward($this->getProperty("server-port")); Network\UPnP\RemovePortForward($this->getProperty("server-port"));
} }
return $this->restart; return $this->restart;
} }
@ -427,8 +427,11 @@ class ServerAPI{
} }
public function getProperty($name, $default = false){ public function getProperty($name, $default = false){
if(($v = arg($name)) !== false){ //Allow for command-line arguments $v = getopt("", array("$name::"));
if(isset($v[$name]) !== false){ //Allow for command-line arguments
$v = $v[$name];
switch(strtolower(trim($v))){ switch(strtolower(trim($v))){
case "":
case "on": case "on":
case "true": case "true":
case "yes": case "yes":
@ -453,14 +456,8 @@ class ServerAPI{
case "server-port": case "server-port":
case "debug": case "debug":
case "difficulty": case "difficulty":
case "time-per-second":
$v = (int) $v; $v = (int) $v;
break; break;
case "server-id":
if($v !== false){
$v = preg_match("/[^0-9\-]/", $v) > 0 ? Utils::readInt(substr(md5($v, true), 0, 4)):$v;
}
break;
} }
return $v; return $v;
} }
@ -478,28 +475,4 @@ class ServerAPI{
public function getList(){ public function getList(){
return $this->apiList; return $this->apiList;
} }
public function loadAPI($name, $class, $dir = false){
if(isset($this->$name)){
return false;
}elseif(!class_exists($class)){
$internal = false;
if($dir === false){
$internal = true;
$dir = FILE_PATH."src/API/";
}
$file = $dir.$class.".php";
if(!file_exists($file)){
console("[ERROR] API ".$name." [".$class."] in ".$dir." doesn't exist", true, true, 0);
return false;
}
require_once($file);
}else{
$internal = true;
}
$this->$name = new $class();
$this->apiList[] = $this->$name;
console("[".($internal === true ? "INTERNAL":"DEBUG")."] API \x1b[36m".$name."\x1b[0m [\x1b[30;1m".$class."\x1b[0m] loaded", true, true, ($internal === true ? 3:2));
}
} }

View File

@ -19,6 +19,8 @@
* *
*/ */
namespace PocketMine;
class TimeAPI{ class TimeAPI{
public static $phases = array( public static $phases = array(
"day" => 0, "day" => 0,

View File

@ -47,15 +47,15 @@ class BurningFurnaceBlock extends SolidBlock{
$t = $this->level->getTile($this); $t = $this->level->getTile($this);
$furnace = false; $furnace = false;
if($t instanceof FurnaceTile){ if($t instanceof Furnace){
$furnace = $t; $furnace = $t;
}else{ }else{
$furnace = new FurnaceTile($this->level, new NBTTag_Compound(false, array( $furnace = new Furnace($this->level, new NBT\Tag\Compound(false, array(
"Items" => new NBTTag_List("Items", array()), "Items" => new NBT\Tag\List("Items", array()),
"id" => new NBTTag_String("id", Tile::FURNACE), "id" => new NBT\Tag\String("id", Tile::FURNACE),
"x" => new NBTTag_Int("x", $this->x), "x" => new NBT\Tag\Int("x", $this->x),
"y" => new NBTTag_Int("y", $this->y), "y" => new NBT\Tag\Int("y", $this->y),
"z" =>new NBTTag_Int("z", $this->z) "z" =>new NBT\Tag\Int("z", $this->z)
))); )));
} }
@ -93,8 +93,8 @@ class BurningFurnaceBlock extends SolidBlock{
$drops[] = array(FURNACE, 0, 1); $drops[] = array(FURNACE, 0, 1);
} }
$t = $this->level->getTile($this); $t = $this->level->getTile($this);
if($t instanceof FurnaceTile){ if($t instanceof Furnace){
for($s = 0; $s < FurnaceTile::SLOTS; ++$s){ for($s = 0; $s < Furnace::SLOTS; ++$s){
$slot = $t->getSlot($s); $slot = $t->getSlot($s);
if($slot->getID() > AIR and $slot->getCount() > 0){ if($slot->getID() > AIR and $slot->getCount() > 0){
$drops[] = array($slot->getID(), $slot->getMetadata(), $slot->getCount()); $drops[] = array($slot->getID(), $slot->getMetadata(), $slot->getCount());

View File

@ -38,7 +38,7 @@ class CactusBlock extends TransparentBlock{
if($this->getSide(0)->getID() !== CACTUS){ if($this->getSide(0)->getID() !== CACTUS){
if($this->meta == 0x0F){ if($this->meta == 0x0F){
for($y = 1; $y < 3; ++$y){ for($y = 1; $y < 3; ++$y){
$b = $this->level->getBlock(new Vector3($this->x, $this->y + $y, $this->z)); $b = $this->level->getBlock(new Math\Vector3($this->x, $this->y + $y, $this->z));
if($b->getID() === AIR){ if($b->getID() === AIR){
$this->level->setBlock($b, new CactusBlock(), true, false, true); $this->level->setBlock($b, new CactusBlock(), true, false, true);
break; break;

View File

@ -44,7 +44,7 @@ class ChestBlock extends TransparentBlock{
} }
$c = $this->getSide($side); $c = $this->getSide($side);
if(($c instanceof ChestBlock) and $c->getMetadata() === $this->meta){ if(($c instanceof ChestBlock) and $c->getMetadata() === $this->meta){
if((($tile = $this->level->getTile($c)) instanceof ChestTile) and !$tile->isPaired()){ if((($tile = $this->level->getTile($c)) instanceof Chest) and !$tile->isPaired()){
$chest = $tile; $chest = $tile;
break; break;
} }
@ -52,15 +52,15 @@ class ChestBlock extends TransparentBlock{
} }
$this->level->setBlock($block, $this, true, false, true); $this->level->setBlock($block, $this, true, false, true);
$tile = new ChestTile($this->level, new NBTTag_Compound(false, array( $tile = new Chest($this->level, new NBT\Tag\Compound(false, array(
"Items" => new NBTTag_List("Items", array()), "Items" => new NBT\Tag\List("Items", array()),
"id" => new NBTTag_String("id", Tile::CHEST), "id" => new NBT\Tag\String("id", Tile::CHEST),
"x" => new NBTTag_Int("x", $this->x), "x" => new NBT\Tag\Int("x", $this->x),
"y" => new NBTTag_Int("y", $this->y), "y" => new NBT\Tag\Int("y", $this->y),
"z" =>new NBTTag_Int("z", $this->z) "z" =>new NBT\Tag\Int("z", $this->z)
))); )));
if($chest instanceof ChestTile){ if($chest instanceof Chest){
$chest->pairWith($tile); $chest->pairWith($tile);
$tile->pairWith($chest); $tile->pairWith($chest);
} }
@ -69,7 +69,7 @@ class ChestBlock extends TransparentBlock{
public function onBreak(Item $item, Player $player){ public function onBreak(Item $item, Player $player){
$t = $this->level->getTile($this); $t = $this->level->getTile($this);
if($t instanceof ChestTile){ if($t instanceof Chest){
$t->unpair(); $t->unpair();
} }
$this->level->setBlock($this, new AirBlock(), true, true, true); $this->level->setBlock($this, new AirBlock(), true, true, true);
@ -84,15 +84,15 @@ class ChestBlock extends TransparentBlock{
$t = $this->level->getTile($this); $t = $this->level->getTile($this);
$chest = false; $chest = false;
if($t instanceof ChestTile){ if($t instanceof Chest){
$chest = $t; $chest = $t;
}else{ }else{
$chest = new ChestTile($this->level, new NBTTag_Compound(false, array( $chest = new Chest($this->level, new NBT\Tag\Compound(false, array(
"Items" => new NBTTag_List("Items", array()), "Items" => new NBT\Tag\List("Items", array()),
"id" => new NBTTag_String("id", Tile::CHEST), "id" => new NBT\Tag\String("id", Tile::CHEST),
"x" => new NBTTag_Int("x", $this->x), "x" => new NBT\Tag\Int("x", $this->x),
"y" => new NBTTag_Int("y", $this->y), "y" => new NBT\Tag\Int("y", $this->y),
"z" =>new NBTTag_Int("z", $this->z) "z" =>new NBT\Tag\Int("z", $this->z)
))); )));
} }
@ -111,8 +111,8 @@ class ChestBlock extends TransparentBlock{
array($this->id, 0, 1), array($this->id, 0, 1),
); );
$t = $this->level->getTile($this); $t = $this->level->getTile($this);
if($t instanceof ChestTile){ if($t instanceof Chest){
for($s = 0; $s < ChestTile::SLOTS; ++$s){ for($s = 0; $s < Chest::SLOTS; ++$s){
$slot = $t->getSlot($s); $slot = $t->getSlot($s);
if($slot->getID() > AIR and $slot->getCount() > 0){ if($slot->getID() > AIR and $slot->getCount() > 0){
$drops[] = array($slot->getID(), $slot->getMetadata(), $slot->getCount()); $drops[] = array($slot->getID(), $slot->getMetadata(), $slot->getCount());

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