diff --git a/PocketMine-MP.php b/PocketMine-MP.php index f692cc1c1..78ca2a2ee 100644 --- a/PocketMine-MP.php +++ b/PocketMine-MP.php @@ -19,13 +19,344 @@ * */ +namespace PocketMine; -/***REM_START***/ -require_once(dirname(__FILE__)."/src/config.php"); +const VERSION = "Alpha_1.4dev"; +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"); -require_once(FILE_PATH."/src/dependencies.php"); -/***REM_END***/ +\spl_autoload_register(function ($load){ + $path = explode('\\', trim($load, '\\')); + 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->start(); diff --git a/src/Achievement.php b/src/Achievement.php index cf4de2d5e..a6aa912d5 100644 --- a/src/Achievement.php +++ b/src/Achievement.php @@ -19,6 +19,8 @@ * */ +namespace PocketMine; + abstract class Achievement{ public static $list = array( /*"openInventory" => array( diff --git a/src/API/BanAPI.php b/src/BanAPI.php similarity index 94% rename from src/API/BanAPI.php rename to src/BanAPI.php index c5511f608..a609543de 100644 --- a/src/API/BanAPI.php +++ b/src/BanAPI.php @@ -19,6 +19,8 @@ * */ +namespace PocketMine; + class BanAPI{ private $server; /* @@ -38,10 +40,10 @@ class BanAPI{ } public function init(){ - $this->whitelist = new Config(DATA_PATH."white-list.txt", Config::ENUM);//Open whitelist list file - $this->bannedIPs = new Config(DATA_PATH."banned-ips.txt", Config::ENUM);//Open Banned IPs list file - $this->banned = new Config(DATA_PATH."banned.txt", Config::ENUM);//Open Banned Usernames list file - $this->ops = new Config(DATA_PATH."ops.txt", Config::ENUM);//Open list of OPs + $this->whitelist = new Utils\Config(DATA."white-list.txt", Utils\Config::ENUM);//Open whitelist list file + $this->bannedIPs = new Utils\Config(DATA."banned-ips.txt", Utils\Config::ENUM);//Open Banned IPs list file + $this->banned = new Utils\Config(DATA."banned.txt", Utils\Config::ENUM);//Open Banned Usernames list file + $this->ops = new Utils\Config(DATA."ops.txt", Utils\Config::ENUM);//Open list of OPs $this->server->api->console->register("banip", " [IP|player]", array($this, "commandHandler")); $this->server->api->console->register("ban", " [username]", array($this, "commandHandler")); $this->server->api->console->register("kick", " [reason ...]", array($this, "commandHandler")); @@ -211,7 +213,7 @@ class BanAPI{ $output .= "Player \"$user\" added to white-list\n"; break; 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; case "list": $output .= "White-list: ".implode(", ", $this->whitelist->getAll(true))."\n"; @@ -256,7 +258,7 @@ class BanAPI{ $output .= "IP \"$ip\" added to ban list\n"; break; 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; case "list": $output .= "IP ban list: ".implode(", ", $this->bannedIPs->getAll(true))."\n"; @@ -294,7 +296,7 @@ class BanAPI{ $output .= "Player \"$user\" added to ban list\n"; break; case "reload": - $this->banned = new Config(DATA_PATH."banned.txt", Config::ENUM); + $this->banned = new Utils\Config(DATA."banned.txt", Utils\Config::ENUM); break; case "list": $output .= "Ban list: ".implode(", ", $this->banned->getAll(true))."\n"; diff --git a/src/API/BlockAPI.php b/src/BlockAPI.php similarity index 89% rename from src/API/BlockAPI.php rename to src/BlockAPI.php index c5f281efc..d2e0ffcbc 100644 --- a/src/API/BlockAPI.php +++ b/src/BlockAPI.php @@ -19,6 +19,8 @@ * */ +namespace PocketMine; + class BlockAPI{ private $server; 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])){ $classname = Block::$class[$id]; $b = new $classname($meta); }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); } return $b; @@ -261,11 +263,11 @@ class BlockAPI{ public static function getItem($id, $meta = 0, $count = 1){ $id = (int) $id; - if(isset(Item::$class[$id])){ - $classname = Item::$class[$id]; + if(isset(Item\Item::$class[$id])){ + $classname = Item\Item::$class[$id]; $i = new $classname($meta, $count); }else{ - $i = new Item($id, $meta, $count); + $i = new Item\Item($id, $meta, $count); } return $i; } @@ -316,8 +318,8 @@ class BlockAPI{ return $output; } - private function cancelAction(Block $block, Player $player, $send = true){ - $pk = new UpdateBlockPacket; + private function cancelAction(Block\Block $block, Player $player, $send = true){ + $pk = new Network\Protocol\UpdateBlockPacket; $pk->x = $block->x; $pk->y = $block->y; $pk->z = $block->z; @@ -330,7 +332,7 @@ class BlockAPI{ return false; } - public function playerBlockBreak(Player $player, Vector3 $vector){ + public function playerBlockBreak(Player $player, Math\Math\Vector3 $vector){ $target = $player->level->getBlock($vector); $item = $player->getSlot($player->slot); @@ -354,7 +356,7 @@ class BlockAPI{ return $this->cancelAction($target, $player, false); } if(($player->gamemode & 0x01) === 0 and $item->useOn($target) and $item->getMetadata() >= $item->getMaxDurability()){ - $player->setSlot($player->slot, new Item(AIR, 0, 0)); + $player->setSlot($player->slot, new Item\Item(AIR, 0, 0)); } }else{ return $this->cancelAction($target, $player, false); @@ -370,7 +372,7 @@ class BlockAPI{ 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){ return false; } @@ -424,7 +426,7 @@ class BlockAPI{ $hand = $item->getBlock(); $hand->position($block); }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; }else{ return $this->cancelAction($block, $player, false); @@ -451,16 +453,16 @@ class BlockAPI{ return $this->cancelAction($block, $player, false); } if($hand->getID() === SIGN_POST or $hand->getID() === WALL_SIGN){ - new SignTile($player->level, new NBTTag_Compound(false, array( - "id" => new NBTTag_String("id", Tile::Sign), - "x" => new NBTTag_Int("x", $block->x), - "y" => new NBTTag_Int("y", $block->y), - "z" => new NBTTag_Int("z", $block->z), - "Text1" => new NBTTag_String("Text1", ""), - "Text2" => new NBTTag_String("Text2", ""), - "Text3" => new NBTTag_String("Text3", ""), - "Text4" => new NBTTag_String("Text4", ""), - "creator" => new NBTTag_String("creator", $player->getUsername()) + new Tile\Sign($player->level, new NBT\Tag\Compound(false, array( + "id" => new NBT\Tag\String("id", Tile::Sign), + "x" => new NBT\Tag\Int("x", $block->x), + "y" => new NBT\Tag\Int("y", $block->y), + "z" => new NBT\Tag\Int("z", $block->z), + "Text1" => new NBT\Tag\String("Text1", ""), + "Text2" => new NBT\Tag\String("Text2", ""), + "Text3" => new NBT\Tag\String("Text3", ""), + "Text4" => new NBT\Tag\String("Text4", ""), + "creator" => new NBT\Tag\String("creator", $player->getUsername()) ))); } @@ -474,7 +476,7 @@ class BlockAPI{ 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){ $this->scheduleBlockUpdate($pos->getSide(0), $delay, $type); $this->scheduleBlockUpdate($pos->getSide(1), $delay, $type); @@ -492,11 +494,11 @@ class BlockAPI{ } } - public function blockUpdate(Position $pos, $type = BLOCK_UPDATE_NORMAL){ - if(!($pos instanceof Block)){ + public function blockUpdate(Level\Position $pos, $type = BLOCK_UPDATE_NORMAL){ + if(!($pos instanceof Block\Block)){ $block = $pos->level->getBlock($pos); }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); } if($block === false){ @@ -510,7 +512,7 @@ class BlockAPI{ 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; if($delay < 0){ return false; @@ -530,7 +532,7 @@ class BlockAPI{ $time = microtime(true); if(count($this->scheduledUpdates) > 0){ $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(); while(($up = $update->fetchArray(SQLITE3_ASSOC)) !== false){ $index = $up["x"].".".$up["y"].".".$up["z"].".".$up["level"].".".$up["type"]; diff --git a/src/API/ChatAPI.php b/src/ChatAPI.php similarity index 98% rename from src/API/ChatAPI.php rename to src/ChatAPI.php index 55dfadee1..7cf20c9b0 100644 --- a/src/API/ChatAPI.php +++ b/src/ChatAPI.php @@ -19,6 +19,8 @@ * */ +namespace PocketMine; + class ChatAPI{ private $server; function __construct(){ @@ -143,6 +145,7 @@ class ChatAPI{ $message["player"] = ""; } + //TODO: Remove Container $this->server->handle("server.chat", new Container($message, $whitelist, $blacklist)); } } \ No newline at end of file diff --git a/src/API/ConsoleAPI.php b/src/ConsoleAPI.php similarity index 94% rename from src/API/ConsoleAPI.php rename to src/ConsoleAPI.php index b5d828b71..fb9f6d4e4 100644 --- a/src/API/ConsoleAPI.php +++ b/src/ConsoleAPI.php @@ -19,6 +19,8 @@ * */ +namespace PocketMine; + class ConsoleAPI{ private $loop, $server, $event, $help, $cmds, $alias; function __construct(){ @@ -130,7 +132,7 @@ class ConsoleAPI{ $max = ceil(count($cmds) / 5); $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 ) ".TextFormat::RED."-".TextFormat::RESET."\n"; + $output .= Utils\TextFormat::RED."-".Utils\TextFormat::RESET." Showing help page $page of $max (/help ) ".Utils\TextFormat::RED."-".Utils\TextFormat::RESET."\n"; $current = 1; foreach($cmds as $c => $h){ $curpage = (int) ceil($current / 5); @@ -177,9 +179,9 @@ class ConsoleAPI{ return $this->run($this->alias[$cmd] . ($params !== "" ? " " .$params:""), $issuer, $cmd); } 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{ - 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){ @@ -285,7 +287,7 @@ class ConsoleAPI{ } -class ConsoleLoop extends Thread{ +class ConsoleLoop extends \Thread{ public $line; public $stop; public $base; diff --git a/src/utils/Container.php b/src/Container.php similarity index 97% rename from src/utils/Container.php rename to src/Container.php index 4f16421ec..c5459edf5 100644 --- a/src/utils/Container.php +++ b/src/Container.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine; +use PocketMine; + class Container{ private $payload = "", $whitelist = false, $blacklist = false; public function __construct($payload = "", $whitelist = false, $blacklist = false){ diff --git a/src/Deprecation.php b/src/Deprecation.php index 1fd6aa66d..f9fcdb31e 100644 --- a/src/Deprecation.php +++ b/src/Deprecation.php @@ -19,6 +19,9 @@ * */ +//TODO: REMOVE + +namespace PocketMine; class Deprecation{ public static $events = array( @@ -31,5 +34,4 @@ class Deprecation{ "api.player.offline.save" => "player.offline.save", ); - } \ No newline at end of file diff --git a/src/EntityOLD.php b/src/EntityOLD.php index 2e1a1585b..a5f7d3f0f 100644 --- a/src/EntityOLD.php +++ b/src/EntityOLD.php @@ -19,6 +19,8 @@ * */ +__halt_compiler(); + class EntityOLD extends Position{ public $age; public $air; @@ -346,11 +348,11 @@ class EntityOLD extends Position{ for($y = $startY; $y <= $endY; ++$y){ for($x = $startX; $x <= $endX; ++$x){ 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()){ case WATER: 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->updateMetadata(); } @@ -366,7 +368,7 @@ class EntityOLD extends Position{ break; case LAVA: //Lava damage 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->fire = 300; $this->updateMetadata(); @@ -374,7 +376,7 @@ class EntityOLD extends Position{ } break; 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->fire = 300; $this->updateMetadata(); @@ -382,13 +384,13 @@ class EntityOLD extends Position{ } break; 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"); $hasUpdate = true; } break; 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 $hasUpdate = true; }elseif($x == ($endX - 1) and $y == $endY and $z == ($endZ - 1)){ @@ -436,7 +438,7 @@ class EntityOLD extends Position{ $isFlying = true; for($z = $startZ; $z <= $endZ; ++$z){ 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)){ $b = $this->level->getBlock($v); if($b->isSolid === true){ @@ -474,14 +476,14 @@ class EntityOLD extends Position{ $z = (int) ($this->z - 0.5); $lim = (int) floor($ny); 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; $this->speedY = 0; $support = true; if($this->class === ENTITY_FALLING){ $this->y = $ny; - $fall = $this->level->getBlock(new 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))); + $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 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){ $this->server->api->entity->drop($this, BlockAPI::getItem($this->data["Tile"] & 0xFFFF, 0, 1), true); }else{ @@ -534,8 +536,8 @@ class EntityOLD extends Position{ } }elseif($this->fallY !== false){ //Fall damage! if($y < $this->fallY){ - $d = $this->level->getBlock(new Vector3($this->x, $y + 1, $this->z)); - $d2 = $this->level->getBlock(new Vector3($this->x, $y + 2, $this->z)); + $d = $this->level->getBlock(new Math\Vector3($this->x, $y + 1, $this->z)); + $d2 = $this->level->getBlock(new Math\Vector3($this->x, $y + 2, $this->z)); $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){ $this->harm($dmg, "fall"); @@ -547,7 +549,7 @@ class EntityOLD extends Position{ } $this->calculateVelocity(); 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->server->api->handle("entity.move", $this) === false){ 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{ - $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{ $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.";"); } - public function move(Vector3 $pos, $yaw = 0, $pitch = 0){ + public function move(Math\Vector3 $pos, $yaw = 0, $pitch = 0){ $this->x += $pos->x; $this->y += $pos->y; $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.";"); } - 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){ $this->level = $pos->level; $this->server->preparedSQL->entity->setLevel->reset(); @@ -878,23 +880,23 @@ class EntityOLD extends Position{ $this->server->preparedSQL->entity->setPosition->execute(); } - public function inBlock(Vector3 $block, $radius = 0.8){ - $me = new Vector3($this->x - 0.5, $this->y, $this->z - 0.5); + public function inBlock(Math\Vector3 $block, $radius = 0.8){ + $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){ return true; } return false; } - public function touchingBlock(Vector3 $block, $radius = 0.9){ - $me = new Vector3($this->x - 0.5, $this->y, $this->z - 0.5); + public function touchingBlock(Math\Vector3 $block, $radius = 0.9){ + $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){ return true; } 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); $diff = $this->y - $pos->y; if($me->distance(new Vector2($pos->x, $pos->z)) < $radius and $diff > -0.7 and $diff < 1.6){ diff --git a/src/API/LevelAPI.php b/src/LevelAPI.php similarity index 71% rename from src/API/LevelAPI.php rename to src/LevelAPI.php index e979cd6da..8990e170d 100644 --- a/src/API/LevelAPI.php +++ b/src/LevelAPI.php @@ -2,11 +2,11 @@ /** * - * ____ _ _ __ __ _ __ __ ____ - * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ + * ____ _ _ __ __ _ __ __ ____ + * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | - * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ - * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| + * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ + * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * 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 @@ -15,9 +15,11 @@ * * @author PocketMine Team * @link http://www.pocketmine.net/ - * * -*/ + * + */ + +namespace PocketMine; class LevelAPI{ private $server, $levels, $default; @@ -80,7 +82,7 @@ class LevelAPI{ } public function generateLevel($name, $seed = false, $generator = false){ - if($this->levelExists($name)){ + if($name == "" or $this->levelExists($name)){ return false; } $options = array(); @@ -92,12 +94,12 @@ class LevelAPI{ $generator = new $generator($options); }else{ if(strtoupper($this->server->api->getProperty("level-type")) == "FLAT"){ - $generator = new SuperflatGenerator($options); + $generator = new Level\Generator\Flat($options); }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->close(); return true; @@ -107,9 +109,9 @@ class LevelAPI{ if($name === ""){ return false; } - $path = DATA_PATH."worlds/".$name."/"; + $path = DATA."worlds/".$name."/"; if($this->get($name) === false and !file_exists($path."level.pmf")){ - $level = new LevelImport($path); + $level = new Level\LevelImport($path); if($level->import() === false){ return false; } @@ -117,7 +119,7 @@ class LevelAPI{ return true; } - public function unloadLevel(Level $level, $force = false){ + public function unloadLevel(Level\Level $level, $force = false){ $name = $level->getName(); if($name === $this->default and $force !== true){ return false; @@ -128,14 +130,6 @@ class LevelAPI{ foreach($level->getPlayers() as $player){ $player->teleport($this->server->spawn); } - /*foreach($this->server->api->entity->getAll($level) as $entity){ - if($entity->class !== ENTITY_PLAYER){ - $entity->close(); - } - }*/ - /*foreach($this->server->api->tile->getAll($level) as $tile){ - $tile->close(); - }*/ $level->close(); unset($this->levels[$name]); return true; @@ -148,19 +142,19 @@ class LevelAPI{ console("[NOTICE] Level \"".$name."\" not found"); return false; } - $path = DATA_PATH."worlds/".$name."/"; + $path = DATA."worlds/".$name."/"; console("[INFO] Preparing level \"".$name."\""); - $level = new PMFLevel($path."level.pmf"); + $level = new PMF\Level($path."level.pmf"); if(!$level->isLoaded){ console("[ERROR] Could not load level \"".$name."\""); 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")){ @rename($path."tileEntities.yml", $path."tiles.yml"); } - $blockUpdates = new Config($path."bupdates.yml", Config::YAML); - $this->levels[$name] = new Level($level, $name); + $blockUpdates = new Utils\Config($path."bupdates.yml", Utils\Config::YAML); + $this->levels[$name] = new Level\Level($level, $name); /*foreach($entities->getAll() as $entity){ if(!isset($entity["id"])){ break; @@ -177,39 +171,39 @@ class LevelAPI{ )); }elseif($entity["id"] === FALLING_SAND){ $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"]); }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->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); }else{ $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"]); } }*/ 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){ if(!isset($tile["id"])){ continue; } $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){ switch($index){ case "Items": - $tag = new NBTTag_List("Items", array()); - $tag->setTagType(NBTTag::TAG_Compound); + $tag = new NBT\Tag\Enum("Items", array()); + $tag->setTagType(NBT\TAG_Compound); foreach($data as $slot => $fields){ - $tag[(int) $slot] = new NBTTag_Compound(false, array( - "Count" => new NBTTag_Byte("Count", $fields["Count"]), - "Slot" => new NBTTag_Short("Slot", $fields["Slot"]), - "Damage" => new NBTTag_Short("Damage", $fields["Damage"]), - "id" => new NBTTag_String("id", $fields["id"]) + $tag[(int) $slot] = new NBT\Tag\Compound(false, array( + "Count" => new NBT\Tag\Byte("Count", $fields["Count"]), + "Slot" => new NBT\Tag\Short("Slot", $fields["Slot"]), + "Damage" => new NBT\Tag\Short("Damage", $fields["Damage"]), + "id" => new NBT\Tag\String("id", $fields["id"]) )); } $nbt["Items"] = $tag; @@ -220,7 +214,7 @@ class LevelAPI{ case "Text2": case "Text3": case "Text4": - $nbt[$index] = new NBTTag_String($index, $data); + $nbt[$index] = new NBT\Tag\String($index, $data); break; case "x": @@ -228,25 +222,25 @@ class LevelAPI{ case "z": case "pairx": case "pairz": - $nbt[$index] = new NBTTag_Int($index, $data); + $nbt[$index] = new NBT\Tag\Int($index, $data); break; case "BurnTime": case "CookTime": case "MaxTime": - $nbt[$index] = new NBTTag_Short($index, $data); + $nbt[$index] = new NBT\Tag\Short($index, $data); break; } } switch($tile["id"]){ - case Tile::FURNACE: - new FurnaceTile($this->levels[$name], $nbt); + case Tile\Tile::FURNACE: + new Tile\Furnace($this->levels[$name], $nbt); break; - case Tile::CHEST: - new ChestTile($this->levels[$name], $nbt); + case Tile\Tile::CHEST: + new Tile\Chest($this->levels[$name], $nbt); break; - case Tile::SIGN: - new SignTile($this->levels[$name], $nbt); + case Tile\Tile::SIGN: + new Tile\Sign($this->levels[$name], $nbt); break; } } @@ -255,7 +249,7 @@ class LevelAPI{ } 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; } diff --git a/src/Player.php b/src/Player.php index 154e2fc85..ad81ec5d8 100644 --- a/src/Player.php +++ b/src/Player.php @@ -19,11 +19,9 @@ * */ -/***REM_START***/ -require_once("Entity.php"); -/***REM_END***/ +namespace PocketMine; -class Player extends PlayerEntity{ +class Player extends Entity\RealHuman{ public static $list = array(); private $recoveryQueue = array(); @@ -114,45 +112,45 @@ class Player extends PlayerEntity{ public static function getOffline($name){ $server = ServerAPI::request(); $iname = strtolower($name); - if(!file_exists(DATA_PATH."players/".$iname.".dat")){ - $nbt = new NBTTag_Compound(false, array( - "Pos" => new NBTTag_List("Pos", array( - 0 => new NBTTag_Double(0, $server->spawn->x), - 1 => new NBTTag_Double(1, $server->spawn->y), - 2 => new NBTTag_Double(2, $server->spawn->z) + if(!file_exists(DATA."players/".$iname.".dat")){ + $nbt = new NBT\Tag\Compound(false, array( + "Pos" => new NBT\Tag\Enum("Pos", array( + 0 => new NBT\Tag\Double(0, $server->spawn->x), + 1 => new NBT\Tag\Double(1, $server->spawn->y), + 2 => new NBT\Tag\Double(2, $server->spawn->z) )), - "Level" => new NBTTag_String("Level", $server->spawn->level->getName()), - "SpawnLevel" => new NBTTag_String("SpawnLevel", $server->spawn->level->getName()), - "SpawnX" => new NBTTag_Int("SpawnX", (int) $server->spawn->x), - "SpawnY" => new NBTTag_Int("SpawnY", (int) $server->spawn->y), - "SpawnZ" => new NBTTag_Int("SpawnZ", (int) $server->spawn->z), - "SpawnForced" => new NBTTag_Byte("SpawnForced", 1), //TODO - "Inventory" => new NBTTag_List("Inventory", array()), - "Achievements" => new NBTTag_Compound("Achievements", array()), - "playerGameType" => new NBTTag_Int("playerGameType", $server->gamemode), - "Motion" => new NBTTag_List("Motion", array( - 0 => new NBTTag_Double(0, 0.0), - 1 => new NBTTag_Double(1, 0.0), - 2 => new NBTTag_Double(2, 0.0) + "Level" => new NBT\Tag\String("Level", $server->spawn->level->getName()), + "SpawnLevel" => new NBT\Tag\String("SpawnLevel", $server->spawn->level->getName()), + "SpawnX" => new NBT\Tag\Int("SpawnX", (int) $server->spawn->x), + "SpawnY" => new NBT\Tag\Int("SpawnY", (int) $server->spawn->y), + "SpawnZ" => new NBT\Tag\Int("SpawnZ", (int) $server->spawn->z), + "SpawnForced" => new NBT\Tag\Byte("SpawnForced", 1), //TODO + "Inventory" => new NBT\Tag\Enum("Inventory", array()), + "Achievements" => new NBT\Tag\Compound("Achievements", array()), + "playerGameType" => new NBT\Tag\Int("playerGameType", $server->gamemode), + "Motion" => new NBT\Tag\Enum("Motion", array( + 0 => new NBT\Tag\Double(0, 0.0), + 1 => new NBT\Tag\Double(1, 0.0), + 2 => new NBT\Tag\Double(2, 0.0) )), - "Rotation" => new NBTTag_List("Rotation", array( - 0 => new NBTTag_Float(0, 0.0), - 1 => new NBTTag_Float(1, 0.0) + "Rotation" => new NBT\Tag\Enum("Rotation", array( + 0 => new NBT\Tag\Float(0, 0.0), + 1 => new NBT\Tag\Float(1, 0.0) )), - "FallDistance" => new NBTTag_Float("FallDistance", 0.0), - "Fire" => new NBTTag_Short("Fire", 0), - "Air" => new NBTTag_Short("Air", 0), - "OnGround" => new NBTTag_Byte("OnGround", 1), - "Invulnerable" => new NBTTag_Byte("Invulnerable", 0), + "FallDistance" => new NBT\Tag\Float("FallDistance", 0.0), + "Fire" => new NBT\Tag\Short("Fire", 0), + "Air" => new NBT\Tag\Short("Air", 0), + "OnGround" => new NBT\Tag\Byte("OnGround", 1), + "Invulnerable" => new NBT\Tag\Byte("Invulnerable", 0), - "NameTag" => new NBTTag_String("NameTag", $name), + "NameTag" => new NBT\Tag\String("NameTag", $name), )); - $nbt->Pos->setTagType(NBTTag::TAG_Double); - $nbt->Inventory->setTagType(NBTTag::TAG_Compound); - $nbt->Motion->setTagType(NBTTag::TAG_Double); - $nbt->Rotation->setTagType(NBTTag::TAG_Float); - if(file_exists(DATA_PATH."players/".$iname.".yml")){ - $data = new Config(DATA_PATH."players/".$iname.".yml", Config::YAML, array()); + $nbt->Pos->setTagType(NBT\TAG_Double); + $nbt->Inventory->setTagType(NBT\TAG_Compound); + $nbt->Motion->setTagType(NBT\TAG_Double); + $nbt->Rotation->setTagType(NBT\TAG_Float); + if(file_exists(DATA."players/".$iname.".yml")){ + $data = new Utils\Config(DATA."players/".$iname.".yml", Utils\Config::YAML, array()); $nbt->playerGameType = (int) $data->get("gamemode"); $nbt->Level = $data->get("position")["level"]; $nbt->Pos[0] = $data->get("position")["x"]; @@ -165,49 +163,49 @@ class Player extends PlayerEntity{ console("[NOTICE] Old Player data found for \"".$iname."\", upgrading profile"); foreach($data->get("inventory") as $slot => $item){ if(count($item) === 3){ - $nbt->Inventory[$slot + 9] = new NBTTag_Compound(false, array( - "id" => new NBTTag_Short("id", $item[0]), - "Damage" => new NBTTag_Short("Damage", $item[1]), - "Count" => new NBTTag_Byte("Count", $item[2]), - "Slot" => new NBTTag_Byte("Slot", $slot + 9), - "TrueSlot" => new NBTTag_Byte("TrueSlot", $slot + 9) + $nbt->Inventory[$slot + 9] = new NBT\Tag\Compound(false, array( + "id" => new NBT\Tag\Short("id", $item[0]), + "Damage" => new NBT\Tag\Short("Damage", $item[1]), + "Count" => new NBT\Tag\Byte("Count", $item[2]), + "Slot" => new NBT\Tag\Byte("Slot", $slot + 9), + "TrueSlot" => new NBT\Tag\Byte("TrueSlot", $slot + 9) )); } } foreach($data->get("hotbar") as $slot => $itemSlot){ if(isset($nbt->Inventory[$itemSlot + 9])){ $item = $nbt->Inventory[$itemSlot + 9]; - $nbt->Inventory[$slot] = new NBTTag_Compound(false, array( - "id" => new NBTTag_Short("id", $item->id), - "Damage" => new NBTTag_Short("Damage", $item->Damage), - "Count" => new NBTTag_Byte("Count", $item->Count), - "Slot" => new NBTTag_Byte("Slot", $slot), - "TrueSlot" => new NBTTag_Byte("TrueSlot", $item->TrueSlot) + $nbt->Inventory[$slot] = new NBT\Tag\Compound(false, array( + "id" => new NBT\Tag\Short("id", $item->id), + "Damage" => new NBT\Tag\Short("Damage", $item->Damage), + "Count" => new NBT\Tag\Byte("Count", $item->Count), + "Slot" => new NBT\Tag\Byte("Slot", $slot), + "TrueSlot" => new NBT\Tag\Byte("TrueSlot", $item->TrueSlot) )); } } foreach($data->get("armor") as $slot => $item){ if(count($item) === 2){ - $nbt->Inventory[$slot + 100] = new NBTTag_Compound(false, array( - "id" => new NBTTag_Short("id", $item[0]), - "Damage" => new NBTTag_Short("Damage", $item[1]), - "Count" => new NBTTag_Byte("Count", 1), - "Slot" => new NBTTag_Byte("Slot", $slot + 100) + $nbt->Inventory[$slot + 100] = new NBT\Tag\Compound(false, array( + "id" => new NBT\Tag\Short("id", $item[0]), + "Damage" => new NBT\Tag\Short("Damage", $item[1]), + "Count" => new NBT\Tag\Byte("Count", 1), + "Slot" => new NBT\Tag\Byte("Slot", $slot + 100) )); } } foreach($data->get("achievements") as $achievement => $status){ - $nbt->Achievements[$achievement] = new NBTTag_Byte($achievement, $status == true ? 1:0); + $nbt->Achievements[$achievement] = new NBT\Tag\Byte($achievement, $status == true ? 1:0); } - unlink(DATA_PATH."players/".$iname.".yml"); + unlink(DATA."players/".$iname.".yml"); }else{ console("[NOTICE] Player data not found for \"".$iname."\", creating new profile"); Player::saveOffline($name, $nbt); } }else{ - $nbt = new NBT(NBT::BIG_ENDIAN); - $nbt->read(file_get_contents(DATA_PATH."players/".$iname.".dat")); + $nbt = new NBT(NBT\BIG_ENDIAN); + $nbt->read(file_get_contents(DATA."players/".$iname.".dat")); $nbt = $nbt->getData(); } @@ -216,14 +214,14 @@ class Player extends PlayerEntity{ return $nbt; } - public static function saveOffline($name, NBTTag_Compound $nbtTag){ + public static function saveOffline($name, NBT\Tag\Compound $nbtTag){ ServerAPI::request()->handle("player.offline.save", $nbtTag); - $nbt = new NBT(NBT::BIG_ENDIAN); + $nbt = new NBT(NBT\BIG_ENDIAN); $nbt->setData($nbtTag); - file_put_contents(DATA_PATH."players/".strtolower($name).".dat", $nbt->write()); + file_put_contents(DATA."players/".strtolower($name).".dat", $nbt->write()); } - public static function broadcastPacket(array $players, RakNetDataPacket $packet){ + public static function broadcastPacket(array $players, Network\Protocol\DataPacket $packet){ foreach($players as $player){ $player->dataPacket(clone $packet); } @@ -282,7 +280,7 @@ class Player extends PlayerEntity{ } public function isSleeping(){ - return $this->sleeping instanceof Vector3; + return $this->sleeping instanceof Math\Vector3; } public function setChunkIndex($index, $flags){ @@ -304,7 +302,7 @@ class Player extends PlayerEntity{ $this->server = ServerAPI::request(); $this->lastBreak = microtime(true); $this->clientID = $clientID; - $this->CID = MainServer::clientID($ip, $port); + $this->CID = Server::clientID($ip, $port); Player::$list[$this->CID] = $this; $this->ip = $ip; $this->port = $port; @@ -316,7 +314,7 @@ class Player extends PlayerEntity{ $this->slot = 0; $this->hotbar = array(0, -1, -1, -1, -1, -1, -1, -1, -1); $this->packetStats = array(0,0); - $this->buffer = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $this->buffer = new Network\RakNet\Packet(Network\RakNet\Info::DATA_PACKET_0); $this->buffer->data = array(); $this->server->schedule(2, array($this, "handlePacketQueues"), array(), true); $this->server->schedule(20 * 60, array($this, "clearQueue"), array(), true); @@ -329,16 +327,16 @@ class Player extends PlayerEntity{ } /** - * @param Vector3 $pos + * @param Math\Vector3 $pos */ - public function setSpawn(Vector3 $pos){ - if(!($pos instanceof Position)){ + public function setSpawn(Math\Vector3 $pos){ + if(!($pos instanceof Level\Position)){ $level = $this->level; }else{ $level = $pos->level; } - $this->spawnPosition = new Position($pos->x, $pos->y, $pos->z, $level); - $pk = new SetSpawnPositionPacket; + $this->spawnPosition = new Level\Position($pos->x, $pos->y, $pos->z, $level); + $pk = new Network\Protocol\SetSpawnPositionPacket; $pk->x = (int) $this->spawnPosition->x; $pk->y = (int) $this->spawnPosition->y; $pk->z = (int) $this->spawnPosition->z; @@ -361,7 +359,7 @@ class Player extends PlayerEntity{ for($X = $startX; $X <= $finalX; ++$X){ for($Z = $startZ; $Z <= $finalZ; ++$Z){ $distance = abs($X - $centerX) + abs($Z - $centerZ); - $index = PMFLevel::getIndex($X, $Z); + $index = PMF\Level::getIndex($X, $Z); if(!isset($this->chunksLoaded[$index]) or $this->chunksLoaded[$index] !== 0){ $newOrder[$index] = $distance; } @@ -372,7 +370,7 @@ class Player extends PlayerEntity{ $this->chunksOrder = $newOrder; $index = key($this->chunksOrder); - PMFLevel::getXZ($index, $X, $Z); + PMF\Level::getXZ($index, $X, $Z); $this->level->loadChunk($X, $Z); if(!$this->level->isChunkPopulated($X, $Z)){ $this->level->loadChunk($X - 1, $Z); @@ -389,7 +387,7 @@ class Player extends PlayerEntity{ if($Yndex !== 0xff){ $X = null; $Z = null; - PMFLevel::getXZ($index, $X, $Z); + PMF\Level::getXZ($index, $X, $Z); foreach($this->level->getChunkEntities($X, $Z) as $entity){ if($entity !== $this){ $entity->despawnFrom($this); @@ -431,7 +429,7 @@ class Player extends PlayerEntity{ } } foreach($this->level->getChunkTiles($this->lastChunk[0], $this->lastChunk[1]) as $tile){ - if($tile instanceof SpawnableTile){ + if($tile instanceof Tile\Spawnable){ $tile->spawnTo($this); } } @@ -448,7 +446,7 @@ class Player extends PlayerEntity{ } $X = null; $Z = null; - PMFLevel::getXZ($index, $X, $Z); + PMF\Level::getXZ($index, $X, $Z); if(!$this->level->isChunkPopulated($X, $Z)){ $this->orderChunks(); if($this->chunkScheduled === 0 or $force === true){ @@ -464,7 +462,7 @@ class Player extends PlayerEntity{ $Yndex = $this->chunksLoaded[$index]; $this->chunksLoaded[$index] = 0; //Load them all $this->level->useChunk($X, $Z, $this); - $pk = new ChunkDataPacket; + $pk = new Network\Protocol\ChunkDataPacket; $pk->chunkX = $X; $pk->chunkZ = $Z; $pk->data = $this->level->getOrderedChunk($X, $Z, $Yndex); @@ -495,7 +493,7 @@ class Player extends PlayerEntity{ $this->namedtag->SpawnZ = (int) $this->spawnPosition->z; foreach($this->achievements as $achievement => $status){ - $this->namedtag->Achievements[$achievement] = new NBTTag_Byte($achievement, $status === true ? 1:0); + $this->namedtag->Achievements[$achievement] = new NBT\Tag\Byte($achievement, $status === true ? 1:0); } $this->namedtag->playerGameType = $this->gamemode; @@ -519,7 +517,7 @@ class Player extends PlayerEntity{ $reason = $reason == "" ? "server stop":$reason; $this->sendChat("You have been kicked. Reason: ".$reason."\n"); $this->sendBuffer(); - $this->directDataPacket(new DisconnectPacket); + $this->directDataPacket(new Network\Protocol\DisconnectPacket); unset(Player::$list[$this->CID]); $this->connected = false; $this->level->freeAllChunks($this); @@ -530,14 +528,14 @@ class Player extends PlayerEntity{ $this->receiveQueue = array(); $this->resendQueue = array(); $this->ackQueue = array(); - if($this->username != "" and ($this->namedtag instanceof NBTTag_Compound)){ + if($this->username != "" and ($this->namedtag instanceof NBT\Tag\Compound)){ Player::saveOffline($this->username, $this->namedtag); } if($msg === true and $this->username != "" and $this->spawned !== false){ $this->server->api->chat->broadcast($this->username." left the game"); } $this->spawned = false; - console("[INFO] ".TextFormat::AQUA.$this->username.TextFormat::RESET."[/".$this->ip.":".$this->port."] logged out due to ".$reason); + console("[INFO] ".Utils\TextFormat::AQUA.$this->username.Utils\TextFormat::RESET."[/".$this->ip.":".$this->port."] logged out due to ".$reason); $this->windows = array(); $this->armor = array(); $this->inventory = array(); @@ -551,20 +549,20 @@ class Player extends PlayerEntity{ } /** - * @param Vector3 $pos + * @param Math\Vector3 $pos * * @return boolean */ - public function sleepOn(Vector3 $pos){ + public function sleepOn(Math\Vector3 $pos){ foreach($this->level->getPlayers() as $p){ - if($p->sleeping instanceof Vector3){ + if($p->sleeping instanceof Math\Vector3){ if($pos->distance($p->sleeping) <= 0.1){ return false; } } } $this->sleeping = $pos; - $this->teleport(new Position($pos->x + 0.5, $pos->y + 1, $pos->z + 0.5, $this->level)); + $this->teleport(new Level\Position($pos->x + 0.5, $pos->y + 1, $pos->z + 0.5, $this->level)); /*if($this->entity instanceof Entity){ $this->updateMetadata(); }*/ @@ -575,9 +573,9 @@ class Player extends PlayerEntity{ public function stopSleep(){ $this->sleeping = false; - if($this->entity instanceof Entity){ - $this->entity->updateMetadata(); - } + //if($this->entity instanceof Entity){ + //$this->entity->updateMetadata(); + //} } public function checkSleep(){ @@ -601,7 +599,7 @@ class Player extends PlayerEntity{ return; $s = (int) $s; if(!isset($this->inventory[$s])){ - $pk = new ContainerSetSlotPacket; + $pk = new Network\Protocol\ContainerSetSlotPacket; $pk->windowid = 0; $pk->slot = (int) $s; $pk->item = BlockAPI::getItem(AIR, 0, 0); @@ -609,7 +607,7 @@ class Player extends PlayerEntity{ } $slot = $this->inventory[$s]; - $pk = new ContainerSetSlotPacket; + $pk = new Network\Protocol\ContainerSetSlotPacket; $pk->windowid = 0; $pk->slot = (int) $s; $pk->item = $slot; @@ -625,16 +623,16 @@ class Player extends PlayerEntity{ switch($event){ case "tile.update": if($data->level === $this->level){ - if($data instanceof FurnaceTile){ + if($data instanceof Tile\Furnace){ foreach($this->windows as $id => $w){ if($w === $data){ - $pk = new ContainerSetDataPacket; + $pk = new Network\Protocol\ContainerSetDataPacket; $pk->windowid = $id; $pk->property = 0; //Smelting $pk->value = floor($data->namedtag->CookTime); $this->dataPacket($pk); - $pk = new ContainerSetDataPacket; + $pk = new Network\Protocol\ContainerSetDataPacket; $pk->windowid = $id; $pk->property = 1; //Fire icon $pk->value = $data->namedtag->BurnTicks; @@ -648,7 +646,7 @@ class Player extends PlayerEntity{ if($data["tile"]->level === $this->level){ foreach($this->windows as $id => $w){ if($w === $data["tile"]){ - $pk = new ContainerSetSlotPacket; + $pk = new Network\Protocol\ContainerSetSlotPacket; $pk->windowid = $id; $pk->slot = $data["slot"] + (isset($data["offset"]) ? $data["offset"]:0); $pk->item = $data["slotdata"]; @@ -660,7 +658,7 @@ class Player extends PlayerEntity{ case "player.pickup": if($data["eid"] === $this->id){ $data["eid"] = 0; - $pk = new TakeItemEntityPacket; + $pk = new Network\Protocol\TakeItemEntityPacket; $pk->eid = 0; $pk->target = $data["entity"]->getID(); $this->dataPacket($pk); @@ -676,7 +674,7 @@ class Player extends PlayerEntity{ break; } }elseif($data["entity"]->level === $this->level){ - $pk = new TakeItemEntityPacket; + $pk = new Network\Protocol\TakeItemEntityPacket; $pk->eid = $data["eid"]; $pk->target = $data["entity"]->getID(); $this->dataPacket($pk); @@ -686,7 +684,7 @@ class Player extends PlayerEntity{ if($data["eid"] === $this->id or $data["entity"]->level !== $this->level){ break; } - $pk = new AnimatePacket; + $pk = new Network\Protocol\AnimatePacket; $pk->eid = $data["eid"]; $pk->action = $data["action"]; //1 swing arm, $this->dataPacket($pk); @@ -698,7 +696,7 @@ class Player extends PlayerEntity{ $eid = $data->getID(); } if($data->level === $this->level){ - $pk = new SetEntityDataPacket; + $pk = new Network\Protocol\SetEntityDataPacket; $pk->eid = $eid; $pk->metadata = $data->getMetadata(); $this->dataPacket($pk); @@ -711,7 +709,7 @@ class Player extends PlayerEntity{ $eid = $data["entity"]->getID(); } if($data["entity"]->level === $this->level){ - $pk = new EntityEventPacket; + $pk = new Network\Protocol\EntityEventPacket; $pk->eid = $eid; $pk->event = $data["event"]; $this->dataPacket($pk); @@ -758,9 +756,9 @@ class Player extends PlayerEntity{ } if($m !== ""){ - $pk = new MessagePacket; + $pk = new Network\Protocol\MessagePacket; $pk->source = ($author instanceof Player) ? $author->username:$author; - $pk->message = TextFormat::clean($m); //Colors not implemented :( + $pk->message = Utils\TextFormat::clean($m); //Colors not implemented :( $this->dataPacket($pk); } } @@ -811,7 +809,7 @@ class Player extends PlayerEntity{ $flags |= 0x20; //Show Nametags } - $pk = new AdventureSettingsPacket; + $pk = new Network\Protocol\AdventureSettingsPacket; $pk->flags = $flags; $this->dataPacket($pk); } @@ -827,7 +825,7 @@ class Player extends PlayerEntity{ $craftItem = array(0, true, 0); unset($craft[-1]); foreach($craft as $slot => $item){ - if($item instanceof Item){ + if($item instanceof Item\Item){ $craftItem[0] = $item->getID(); if($item->getMetadata() !== $craftItem[1] and $craftItem[1] !== true){ $craftItem[1] = false; @@ -851,10 +849,10 @@ class Player extends PlayerEntity{ } } - $res = CraftingRecipes::canCraft($craftItem, $recipeItems, $type); + $res = Recipes\Crafting::canCraft($craftItem, $recipeItems, $type); if(!is_array($res) and $type === 1){ - $res2 = CraftingRecipes::canCraft($craftItem, $recipeItems, 0); + $res2 = Recipes\Crafting::canCraft($craftItem, $recipeItems, 0); if(is_array($res2)){ $res = $res2; } @@ -1025,7 +1023,7 @@ class Player extends PlayerEntity{ $safeCount = (int) (($this->MTU - 1) / 4); $packetCnt = (int) ($ackCnt / $safeCount + 1); for($p = 0; $p < $packetCnt; ++$p){ - $pk = new RakNetPacket(RakNetInfo::ACK); + $pk = new Network\RakNet\Packet(Network\RakNet\Info::ACK); $pk->packets = array(); for($c = 0; $c < $safeCount; ++$c){ if(($k = array_pop($this->ackQueue)) === null){ @@ -1043,7 +1041,7 @@ class Player extends PlayerEntity{ foreach($this->receiveQueue as $count => $packets){ unset($this->receiveQueue[$count]); foreach($packets as $p){ - if($p instanceof RakNetDataPacket and $p->hasSplit === false){ + if($p instanceof Network\Protocol\DataPacket and $p->hasSplit === false){ if(isset($p->messageIndex) and $p->messageIndex !== false){ if($p->messageIndex > $this->receiveCount){ $this->receiveCount = $p->messageIndex; @@ -1053,12 +1051,12 @@ class Player extends PlayerEntity{ } switch($p->pid()){ case 0x01: - case ProtocolInfo::PING_PACKET: - case ProtocolInfo::PONG_PACKET: - case ProtocolInfo::MOVE_PLAYER_PACKET: - case ProtocolInfo::REQUEST_CHUNK_PACKET: - case ProtocolInfo::ANIMATE_PACKET: - case ProtocolInfo::SET_HEALTH_PACKET: + case Network\Protocol\Info::PING_PACKET: + case Network\Protocol\Info::PONG_PACKET: + case Network\Protocol\Info::MOVE_PLAYER_PACKET: + case Network\Protocol\Info::REQUEST_CHUNK_PACKET: + case Network\Protocol\Info::ANIMATE_PACKET: + case Network\Protocol\Info::SET_HEALTH_PACKET: continue; } } @@ -1099,11 +1097,11 @@ class Player extends PlayerEntity{ } } - public function handlePacket(RakNetPacket $packet){ + public function handlePacket(Network\RakNet\Packet $packet){ if($this->connected === true){ $this->timeout = microtime(true) + 20; switch($packet->pid()){ - case RakNetInfo::NACK: + case Network\RakNet\Info::NACK: foreach($packet->packets as $count){ if(isset($this->recoveryQueue[$count])){ $this->resendQueue[$count] =& $this->recoveryQueue[$count]; @@ -1114,7 +1112,7 @@ class Player extends PlayerEntity{ } break; - case RakNetInfo::ACK: + case Network\RakNet\Info::ACK: foreach($packet->packets as $count){ if(isset($this->recoveryQueue[$count])){ $this->lag[] = microtime(true) - $this->recoveryQueue[$count]->sendtime; @@ -1125,22 +1123,22 @@ class Player extends PlayerEntity{ } break; - case RakNetInfo::DATA_PACKET_0: - case RakNetInfo::DATA_PACKET_1: - case RakNetInfo::DATA_PACKET_2: - case RakNetInfo::DATA_PACKET_3: - case RakNetInfo::DATA_PACKET_4: - case RakNetInfo::DATA_PACKET_5: - case RakNetInfo::DATA_PACKET_6: - case RakNetInfo::DATA_PACKET_7: - case RakNetInfo::DATA_PACKET_8: - case RakNetInfo::DATA_PACKET_9: - case RakNetInfo::DATA_PACKET_A: - case RakNetInfo::DATA_PACKET_B: - case RakNetInfo::DATA_PACKET_C: - case RakNetInfo::DATA_PACKET_D: - case RakNetInfo::DATA_PACKET_E: - case RakNetInfo::DATA_PACKET_F: + case Network\RakNet\Info::DATA_PACKET_0: + case Network\RakNet\Info::DATA_PACKET_1: + case Network\RakNet\Info::DATA_PACKET_2: + case Network\RakNet\Info::DATA_PACKET_3: + case Network\RakNet\Info::DATA_PACKET_4: + case Network\RakNet\Info::DATA_PACKET_5: + case Network\RakNet\Info::DATA_PACKET_6: + case Network\RakNet\Info::DATA_PACKET_7: + case Network\RakNet\Info::DATA_PACKET_8: + case Network\RakNet\Info::DATA_PACKET_9: + case Network\RakNet\Info::DATA_PACKET_A: + case Network\RakNet\Info::DATA_PACKET_B: + case Network\RakNet\Info::DATA_PACKET_C: + case Network\RakNet\Info::DATA_PACKET_D: + case Network\RakNet\Info::DATA_PACKET_E: + case Network\RakNet\Info::DATA_PACKET_F: $this->ackQueue[] = $packet->seqNumber; $this->receiveQueue[$packet->seqNumber] = array(); foreach($packet->data as $pk){ @@ -1151,45 +1149,45 @@ class Player extends PlayerEntity{ } } - public function handleDataPacket(RakNetDataPacket $packet){ + public function handleDataPacket(Network\Protocol\DataPacket $packet){ if($this->connected === false){ return; } - if(EventHandler::callEvent(new DataPacketReceiveEvent($this, $packet)) === BaseEvent::DENY){ + if(Event\EventHandler::callEvent(new Event\Server\DataPacketReceiveEvent($this, $packet)) === Event\Event::DENY){ return; } switch($packet->pid()){ case 0x01: break; - case ProtocolInfo::PONG_PACKET: + case Network\Protocol\Info::PONG_PACKET: break; - case ProtocolInfo::PING_PACKET: - $pk = new PongPacket; + case Network\Protocol\Info::PING_PACKET: + $pk = new Network\Protocol\PongPacket; $pk->ptime = $packet->time; $pk->time = abs(microtime(true) * 1000); $this->directDataPacket($pk); break; - case ProtocolInfo::DISCONNECT_PACKET: + case Network\Protocol\Info::DISCONNECT_PACKET: $this->close("client disconnect"); break; - case ProtocolInfo::CLIENT_CONNECT_PACKET: + case Network\Protocol\Info::CLIENT_CONNECT_PACKET: if($this->loggedIn === true){ break; } - $pk = new ServerHandshakePacket; + $pk = new Network\Protocol\ServerHandshakePacket; $pk->port = $this->port; $pk->session = $packet->session; - $pk->session2 = Utils::readLong("\x00\x00\x00\x00\x04\x44\x0b\xa9"); + $pk->session2 = Utils\Utils::readLong("\x00\x00\x00\x00\x04\x44\x0b\xa9"); $this->dataPacket($pk); break; - case ProtocolInfo::CLIENT_HANDSHAKE_PACKET: + case Network\Protocol\Info::CLIENT_HANDSHAKE_PACKET: if($this->loggedIn === true){ break; } break; - case ProtocolInfo::LOGIN_PACKET: + case Network\Protocol\Info::LOGIN_PACKET: if($this->loggedIn === true){ break; } @@ -1200,13 +1198,13 @@ class Player extends PlayerEntity{ $this->close("server is full!", false); return; } - if($packet->protocol1 !== ProtocolInfo::CURRENT_PROTOCOL){ - if($packet->protocol1 < ProtocolInfo::CURRENT_PROTOCOL){ - $pk = new LoginStatusPacket; + if($packet->protocol1 !== Network\Protocol\Info::CURRENT_PROTOCOL){ + if($packet->protocol1 < Network\Protocol\Info::CURRENT_PROTOCOL){ + $pk = new Network\Protocol\LoginStatusPacket; $pk->status = 1; $this->directDataPacket($pk); }else{ - $pk = new LoginStatusPacket; + $pk = new Network\Protocol\LoginStatusPacket; $pk->status = 2; $this->directDataPacket($pk); } @@ -1256,7 +1254,7 @@ class Player extends PlayerEntity{ return; } - if(!($nbt instanceof NBTTag_Compound)){ + if(!($nbt instanceof NBT\Tag\Compound)){ $this->close("no config created", false); return; } @@ -1269,7 +1267,7 @@ class Player extends PlayerEntity{ Player::saveOffline($this->username, $nbt); $this->auth = true; - $pk = new LoginStatusPacket; + $pk = new Network\Protocol\LoginStatusPacket; $pk->status = 0; $this->dataPacket($pk); @@ -1282,7 +1280,7 @@ class Player extends PlayerEntity{ $this->slot = $this->hotbar[0]; } - $pk = new StartGamePacket; + $pk = new Network\Protocol\StartGamePacket; $pk->seed = $this->level->getSeed(); $pk->x = $this->x; $pk->y = $this->y; @@ -1294,7 +1292,7 @@ class Player extends PlayerEntity{ if(($level = $this->server->api->level->get($this->namedtag->SpawnLevel)) !== false){ - $this->spawnPosition = new Position($this->namedtag->SpawnX, $this->namedtag->SpawnY, $this->namedtag->SpawnZ, $level); + $this->spawnPosition = new Level\Position($this->namedtag->SpawnX, $this->namedtag->SpawnY, $this->namedtag->SpawnZ, $level); $pk = new SetSpawnPositionPacket; $pk->x = (int) $this->spawnPosition->x; @@ -1312,9 +1310,9 @@ class Player extends PlayerEntity{ $this->evid[] = $this->server->event("tile.update", array($this, "eventHandler")); $this->lastMeasure = microtime(true); $this->server->schedule(50, array($this, "measureLag"), array(), true); - console("[INFO] ".TextFormat::AQUA.$this->username.TextFormat::RESET."[/".$this->ip.":".$this->port."] logged in with entity id ".$this->id." at (".$this->level->getName().", ".round($this->x, 4).", ".round($this->y, 4).", ".round($this->z, 4).")"); + console("[INFO] ".Utils\TextFormat::AQUA.$this->username.Utils\TextFormat::RESET."[/".$this->ip.":".$this->port."] logged in with entity id ".$this->id." at (".$this->level->getName().", ".round($this->x, 4).", ".round($this->y, 4).", ".round($this->z, 4).")"); break; - case ProtocolInfo::READY_PACKET: + case Network\Protocol\Info::READY_PACKET: if($this->loggedIn === false){ break; } @@ -1334,12 +1332,12 @@ class Player extends PlayerEntity{ $this->server->schedule(30, array($this, "orderChunks"), array(), true); $this->blocked = false; - $pk = new SetTimePacket; + $pk = new Network\Protocol\SetTimePacket; $pk->time = $this->level->getTime(); $pk->started = $this->level->stopTime == false; $this->dataPacket($pk); - $pos = new Position($this->x, $this->y, $this->z, $this->level); + $pos = new Level\Position($this->x, $this->y, $this->z, $this->level); $pos = $this->level->getSafeSpawn($pos); $this->teleport($pos); $this->sendBuffer(); @@ -1349,28 +1347,20 @@ class Player extends PlayerEntity{ break; } break; - /*case ProtocolInfo::ROTATE_HEAD_PACKET: + case Network\Protocol\Info::ROTATE_HEAD_PACKET: if($this->spawned === false){ break; } - if(($this->entity instanceof Entity)){ - if($this->blocked === true or $this->server->api->handle("player.move", $this->entity) === false){ - if($this->lastCorrect instanceof Vector3){ - $this->teleport($this->lastCorrect, $this->entity->yaw, $this->entity->pitch, false); - } - }else{ - $this->entity->setPosition($this->entity, $packet->yaw, $this->entity->pitch); - } - } - break;*/ - case ProtocolInfo::MOVE_PLAYER_PACKET: + $this->setRotation($packet->yaw, $this->pitch); + break; + case Network\Protocol\Info::MOVE_PLAYER_PACKET: if($this->spawned === false){ break; } if($packet->messageIndex > $this->lastMovement){ $this->lastMovement = $packet->messageIndex; - $newPos = new Vector3($packet->x, $packet->y, $packet->z); - if($this->forceMovement instanceof Vector3){ + $newPos = new Math\Vector3($packet->x, $packet->y, $packet->z); + if($this->forceMovement instanceof Math\Vector3){ if($this->forceMovement->distance($newPos) <= 0.7){ $this->forceMovement = false; }else{ @@ -1379,7 +1369,7 @@ class Player extends PlayerEntity{ } /*$speed = $this->entity->getSpeedMeasure(); if($this->blocked === true or ($this->server->api->getProperty("allow-flight") !== true and (($speed > 9 and ($this->gamemode & 0x01) === 0x00) or $speed > 20 or $this->entity->distance($newPos) > 7)) or $this->server->api->handle("player.move", $this->entity) === false){ - if($this->lastCorrect instanceof Vector3){ + if($this->lastCorrect instanceof Math\Vector3){ $this->teleport($this->lastCorrect, $this->entity->yaw, $this->entity->pitch, false); } if($this->blocked !== true){ @@ -1390,7 +1380,7 @@ class Player extends PlayerEntity{ //} } break; - case ProtocolInfo::PLAYER_EQUIPMENT_PACKET: + case Network\Protocol\Info::PLAYER_EQUIPMENT_PACKET: if($this->spawned === false){ break; } @@ -1414,7 +1404,7 @@ class Player extends PlayerEntity{ $item = $this->getSlot($packet->slot); } - if($packet->slot === false or EventHandler::callEvent(new PlayerEquipmentChangeEvent($this, $item, $packet->slot, 0)) === BaseEvent::DENY){ + if($packet->slot === false or EventHandler::callEvent(new PlayerEquipmentChangeEvent($this, $item, $packet->slot, 0)) === Event::DENY){ $this->sendInventorySlot($packet->slot); }else{ $this->setEquipmentSlot(0, $packet->slot); @@ -1431,16 +1421,16 @@ class Player extends PlayerEntity{ //$this->entity->updateMetadata(); } break; - case ProtocolInfo::REQUEST_CHUNK_PACKET: + case Network\Protocol\Info::REQUEST_CHUNK_PACKET: break; - case ProtocolInfo::USE_ITEM_PACKET: - $blockVector = new Vector3($packet->x, $packet->y, $packet->z); + case Network\Protocol\Info::USE_ITEM_PACKET: + $blockVector = new Math\Vector3($packet->x, $packet->y, $packet->z); if(($this->spawned === false or $this->blocked === true) and $packet->face >= 0 and $packet->face <= 5){ $target = $this->level->getBlock($blockVector); $block = $target->getSide($packet->face); - $pk = new UpdateBlockPacket; + $pk = new Network\Protocol\UpdateBlockPacket; $pk->x = $target->x; $pk->y = $target->y; $pk->z = $target->z; @@ -1448,7 +1438,7 @@ class Player extends PlayerEntity{ $pk->meta = $target->getMetadata(); $this->dataPacket($pk); - $pk = new UpdateBlockPacket; + $pk = new Network\Protocol\UpdateBlockPacket; $pk->x = $block->x; $pk->y = $block->y; $pk->z = $block->z; @@ -1496,7 +1486,7 @@ class Player extends PlayerEntity{ $target = $this->level->getBlock($blockVector); $block = $target->getSide($packet->face); - $pk = new UpdateBlockPacket; + $pk = new Network\Protocol\UpdateBlockPacket; $pk->x = $target->x; $pk->y = $target->y; $pk->z = $target->z; @@ -1504,7 +1494,7 @@ class Player extends PlayerEntity{ $pk->meta = $target->getMetadata(); $this->dataPacket($pk); - $pk = new UpdateBlockPacket; + $pk = new Network\Protocol\UpdateBlockPacket; $pk->x = $block->x; $pk->y = $block->y; $pk->z = $block->z; @@ -1518,7 +1508,7 @@ class Player extends PlayerEntity{ //$this->updateMetadata(); } break; - /*case ProtocolInfo::PLAYER_ACTION_PACKET: + /*case Network\Protocol\Info::PLAYER_ACTION_PACKET: if($this->spawned === false or $this->blocked === true){ break; } @@ -1594,12 +1584,12 @@ class Player extends PlayerEntity{ $this->stopSleep(); } break;*/ - case ProtocolInfo::REMOVE_BLOCK_PACKET: - $blockVector = new Vector3($packet->x, $packet->y, $packet->z); + case Network\Protocol\Info::REMOVE_BLOCK_PACKET: + $blockVector = new Math\Vector3($packet->x, $packet->y, $packet->z); if($this->spawned === false or $this->blocked === true or $this->distance($blockVector) > 8){ $target = $this->level->getBlock($blockVector); - $pk = new UpdateBlockPacket; + $pk = new Network\Protocol\UpdateBlockPacket; $pk->x = $target->x; $pk->y = $target->y; $pk->z = $target->z; @@ -1612,7 +1602,7 @@ class Player extends PlayerEntity{ $this->toCraft = array(); $this->server->api->block->playerBlockBreak($this, $blockVector); break; - case ProtocolInfo::PLAYER_ARMOR_EQUIPMENT_PACKET: + case Network\Protocol\Info::PLAYER_ARMOR_EQUIPMENT_PACKET: if($this->spawned === false or $this->blocked === true){ break; } @@ -1660,7 +1650,7 @@ class Player extends PlayerEntity{ //$this->entity->updateMetadata(); } break; - /*case ProtocolInfo::INTERACT_PACKET: + /*case Network\Protocol\Info::INTERACT_PACKET: if($this->spawned === false){ break; } @@ -1671,11 +1661,11 @@ class Player extends PlayerEntity{ $data["action"] = $packet->action; $this->craftingItems = array(); $this->toCraft = array(); - $target = Entity::get($packet->target); - if($target instanceof Entity and $this->entity instanceof Entity and $this->gamemode !== VIEW and $this->blocked === false and ($target instanceof Entity) and $this->entity->distance($target) <= 8){ + $target = Entity\Entity::get($packet->target); + if($target instanceof Entity\Entity and $this->gamemode !== VIEW and $this->blocked === false and ($target instanceof Entity\Entity) and $this->entity->distance($target) <= 8){ $data["targetentity"] = $target; $data["entity"] = $this->entity; - if($target instanceof PlayerEntity and ($this->server->api->getProperty("pvp") == false or $this->server->difficulty <= 0 or ($target->player->gamemode & 0x01) === 0x01)){ + if($target instanceof RealHuman and ($this->server->api->getProperty("pvp") == false or $this->server->difficulty <= 0 or ($target->player->gamemode & 0x01) === 0x01)){ break; }elseif($this->server->handle("player.interact", $data) !== false){ $slot = $this->getSlot($this->slot); @@ -1749,14 +1739,14 @@ class Player extends PlayerEntity{ } break;*/ - /*case ProtocolInfo::ANIMATE_PACKET: + /*case Network\Protocol\Info::ANIMATE_PACKET: if($this->spawned === false){ break; } $packet->eid = $this->id; $this->server->api->dhandle("entity.animate", array("eid" => $packet->eid, "entity" => $this->entity, "action" => $packet->action)); break;*/ - case ProtocolInfo::RESPAWN_PACKET: + case Network\Protocol\Info::RESPAWN_PACKET: if($this->spawned === false){ break; } @@ -1766,21 +1756,18 @@ class Player extends PlayerEntity{ $this->craftingItems = array(); $this->toCraft = array(); $this->teleport($this->spawnPosition); - if($this->entity instanceof Entity){ - $this->entity->fire = 0; - $this->entity->air = 300; - $this->entity->setHealth(20, "respawn", true); - $this->entity->updateMetadata(); - }else{ - break; - } + //$this->entity->fire = 0; + //$this->entity->air = 300; + //$this->entity->setHealth(20, "respawn", true); + //$this->entity->updateMetadata(); + $this->sendInventory(); $this->blocked = false; $this->server->handle("player.respawn", $this); break; - case ProtocolInfo::SET_HEALTH_PACKET: //Not used + case Network\Protocol\Info::SET_HEALTH_PACKET: //Not used break; - /*case ProtocolInfo::ENTITY_EVENT_PACKET: + /*case Network\Protocol\Info::ENTITY_EVENT_PACKET: if($this->spawned === false or $this->blocked === true){ break; } @@ -1817,7 +1804,7 @@ class Player extends PlayerEntity{ $slot = $this->getSlot($this->slot); if($this->entity->getHealth() < 20 and isset($items[$slot->getID()])){ - $pk = new EntityEventPacket; + $pk = new Network\Protocol\EntityEventPacket; $pk->eid = 0; $pk->event = 9; $this->dataPacket($pk); @@ -1834,7 +1821,7 @@ class Player extends PlayerEntity{ break; } break;*/ - /*case ProtocolInfo::DROP_ITEM_PACKET: + /*case Network\Protocol\Info::DROP_ITEM_PACKET: if($this->spawned === false or $this->blocked === true){ break; } @@ -1856,13 +1843,13 @@ class Player extends PlayerEntity{ $this->entity->updateMetadata(); } break;*/ - case ProtocolInfo::MESSAGE_PACKET: + case Network\Protocol\Info::MESSAGE_PACKET: if($this->spawned === false){ break; } $this->craftingItems = array(); $this->toCraft = array(); - $packet->message = TextFormat::clean($packet->message); + $packet->message = Utils\TextFormat::clean($packet->message); if(trim($packet->message) != "" and strlen($packet->message) <= 255){ $message = $packet->message; if($message{0} === "/"){ //Command @@ -1879,7 +1866,7 @@ class Player extends PlayerEntity{ } } break; - case ProtocolInfo::CONTAINER_CLOSE_PACKET: + case Network\Protocol\Info::CONTAINER_CLOSE_PACKET: if($this->spawned === false){ break; } @@ -1888,7 +1875,7 @@ class Player extends PlayerEntity{ if(isset($this->windows[$packet->windowid])){ if(is_array($this->windows[$packet->windowid])){ foreach($this->windows[$packet->windowid] as $ob){ - $pk = new TileEventPacket; + $pk = new Network\Protocol\TileEventPacket; $pk->x = $ob->x; $pk->y = $ob->y; $pk->z = $ob->z; @@ -1896,8 +1883,8 @@ class Player extends PlayerEntity{ $pk->case2 = 0; Player::broadcastPacket($this->level->players, $pk); } - }elseif($this->windows[$packet->windowid] instanceof ChestTile){ - $pk = new TileEventPacket; + }elseif($this->windows[$packet->windowid] instanceof Chest){ + $pk = new Network\Protocol\TileEventPacket; $pk->x = $this->windows[$packet->windowid]->x; $pk->y = $this->windows[$packet->windowid]->y; $pk->z = $this->windows[$packet->windowid]->z; @@ -1908,11 +1895,11 @@ class Player extends PlayerEntity{ } unset($this->windows[$packet->windowid]); - $pk = new ContainerClosePacket; + $pk = new Network\Protocol\ContainerClosePacket; $pk->windowid = $packet->windowid; $this->dataPacket($pk); break; - case ProtocolInfo::CONTAINER_SET_SLOT_PACKET: + case Network\Protocol\Info::CONTAINER_SET_SLOT_PACKET: if($this->spawned === false or $this->blocked === true){ break; } @@ -1974,14 +1961,14 @@ class Player extends PlayerEntity{ if(is_array($this->windows[$packet->windowid])){ $tiles = $this->windows[$packet->windowid]; - if($packet->slot >= 0 and $packet->slot < ChestTile::SLOTS){ + if($packet->slot >= 0 and $packet->slot < Tile\Chest::SLOTS){ $tile = $tiles[0]; $slotn = $packet->slot; $offset = 0; - }elseif($packet->slot >= ChestTile::SLOTS and $packet->slot <= (ChestTile::SLOTS << 1)){ + }elseif($packet->slot >= Tile\Chest::SLOTS and $packet->slot <= (Tile\Chest::SLOTS << 1)){ $tile = $tiles[1]; - $slotn = $packet->slot - ChestTile::SLOTS; - $offset = ChestTile::SLOTS; + $slotn = $packet->slot - Tile\Chest::SLOTS; + $offset = Tile\Chest::SLOTS; }else{ break; } @@ -1997,7 +1984,7 @@ class Player extends PlayerEntity{ "itemdata" => $item, "player" => $this, )) === false){ - $pk = new ContainerSetSlotPacket; + $pk = new Network\Protocol\ContainerSetSlotPacket; $pk->windowid = $packet->windowid; $pk->slot = $packet->slot; $pk->item = $slot; @@ -2028,13 +2015,13 @@ class Player extends PlayerEntity{ }else{ $tile = $this->windows[$packet->windowid]; if( - !($tile instanceof ChestTile or $tile instanceof FurnaceTile) + !($tile instanceof Tile\Chest or $tile instanceof Tile\Furnace) or $packet->slot < 0 or ( - $tile instanceof ChestTile - and $packet->slot >= ChestTile::SLOTS + $tile instanceof Tile\Chest + and $packet->slot >= Tile\Chest::SLOTS ) or ( - $tile instanceof FurnaceTile and $packet->slot >= FurnaceTile::SLOTS + $tile instanceof Tile\Furnace and $packet->slot >= Tile\Furnace::SLOTS ) ){ break; @@ -2049,7 +2036,7 @@ class Player extends PlayerEntity{ "itemdata" => $item, "player" => $this, )) === false){ - $pk = new ContainerSetSlotPacket; + $pk = new Network\Protocol\ContainerSetSlotPacket; $pk->windowid = $packet->windowid; $pk->slot = $packet->slot; $pk->item = $slot; @@ -2057,7 +2044,7 @@ class Player extends PlayerEntity{ break; } - if($tile instanceof FurnaceTile and $packet->slot == 2){ + if($tile instanceof Tile\Furnace and $packet->slot == 2){ switch($slot->getID()){ case IRON_INGOT: $this->grantAchievement("acquireIron"); @@ -2088,25 +2075,25 @@ class Player extends PlayerEntity{ $tile->setSlot($packet->slot, $item); } break; - case ProtocolInfo::SEND_INVENTORY_PACKET: //TODO, Mojang, enable this ´^_^` + case Network\Protocol\Info::SEND_INVENTORY_PACKET: //TODO, Mojang, enable this ´^_^` if($this->spawned === false){ break; } break; - case ProtocolInfo::ENTITY_DATA_PACKET: + case Network\Protocol\Info::ENTITY_DATA_PACKET: if($this->spawned === false or $this->blocked === true){ break; } $this->craftingItems = array(); $this->toCraft = array(); - $t = $this->level->getTile(new Vector3($packet->x, $packet->y, $packet->z)); - if($t instanceof SignTile){ + $t = $this->level->getTile(new Math\Vector3($packet->x, $packet->y, $packet->z)); + if($t instanceof Tile\Sign){ if($t->namedtag->creator !== $this->username){ $t->spawnTo($this); }else{ - $nbt = new NBT(); + $nbt = new NBT\NBT(NBT\LITTLE_ENDIAN); $nbt->read($packet->namedtag); - if($nbt->id !== Tile::SIGN){ + if($nbt->id !== Tile\Tile::SIGN){ $t->spawnTo($this); }else{ $t->setText($nbt->Text1, $nbt->Text2, $nbt->Text3, $nbt->Text4); @@ -2129,14 +2116,14 @@ class Player extends PlayerEntity{ $hotbar[] = $slot <= -1 ? -1 : $slot + 9; } - $pk = new ContainerSetContentPacket; + $pk = new Network\Protocol\ContainerSetContentPacket; $pk->windowid = 0; $pk->slots = $this->inventory; $pk->hotbar = $hotbar; $this->dataPacket($pk); } - public function send(RakNetPacket $packet){ + public function send(Network\RakNet\Packet $packet){ if($this->connected === true){ $packet->ip = $this->ip; $packet->port = $this->port; @@ -2146,18 +2133,18 @@ class Player extends PlayerEntity{ public function sendBuffer(){ if($this->connected === true){ - if($this->bufferLen > 0 and $this->buffer instanceof RakNetPacket){ + if($this->bufferLen > 0 and $this->buffer instanceof Network\RakNet\Packet){ $this->buffer->seqNumber = $this->counter[0]++; $this->send($this->buffer); } $this->bufferLen = 0; - $this->buffer = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $this->buffer = new Network\RakNet\Packet(Network\RakNet\Info::DATA_PACKET_0); $this->buffer->data = array(); $this->nextBuffer = microtime(true) + 0.1; } } - private function directBigRawPacket(RakNetDataPacket $packet){ + private function directBigRawPacket(DataPacket $packet){ if($this->connected === false){ return false; } @@ -2173,7 +2160,7 @@ class Player extends PlayerEntity{ foreach($buffer as $i => $buf){ $cnts[] = $count = $this->counter[0]++; - $pk = new UnknownPacket; + $pk = new Network\Protocol\UnknownPacket; $pk->packetID = $packet->pid(); $pk->reliability = 2; $pk->hasSplit = true; @@ -2183,7 +2170,7 @@ class Player extends PlayerEntity{ $pk->buffer = $buf; $pk->messageIndex = $this->counter[3]++; - $rk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $rk = new Network\RakNet\Packet(Network\RakNet\Info::DATA_PACKET_0); $rk->data[] = $pk; $rk->seqNumber = $count; $rk->sendtime = $sendtime; @@ -2193,16 +2180,16 @@ class Player extends PlayerEntity{ return $cnts; } - public function directDataPacket(RakNetDataPacket $packet, $recover = true){ + public function directDataPacket(DataPacket $packet, $recover = true){ if($this->connected === false){ return false; } - if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY){ + if(Event\EventHandler::callEvent(new Event\Server\DataPacketSendEvent($this, $packet)) === Event\Event::DENY){ return array(); } $packet->encode(); - $pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $pk = new Network\RakNet\Packet(Network\RakNet\Info::DATA_PACKET_0); $pk->data[] = $packet; $pk->seqNumber = $this->counter[0]++; $pk->sendtime = microtime(true); @@ -2220,12 +2207,12 @@ class Player extends PlayerEntity{ * * @return array|bool */ - public function dataPacket(RakNetDataPacket $packet){ + public function dataPacket(DataPacket $packet){ if($this->connected === false){ return false; } - if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY){ + if(Event\EventHandler::callEvent(new Event\Server\DataPacketSendEvent($this, $packet)) === Event\Event::DENY){ return; } diff --git a/src/API/PlayerAPI.php b/src/PlayerAPI.php similarity index 92% rename from src/API/PlayerAPI.php rename to src/PlayerAPI.php index ce1d8bf59..f322824d4 100644 --- a/src/API/PlayerAPI.php +++ b/src/PlayerAPI.php @@ -18,6 +18,8 @@ * * */ + +namespace PocketMine; class PlayerAPI{ private $server; @@ -50,7 +52,7 @@ class PlayerAPI{ $result = $this->server->preparedSQL->selectPlayersToHeal->execute(); if($result !== 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){ continue; } @@ -63,8 +65,8 @@ class PlayerAPI{ break; case "player.death": if(is_numeric($data["cause"])){ - $e = Entity::get($data["cause"]); - if($e instanceof Entity){ + $e = Entity\Entity::get($data["cause"]); + if($e instanceof Entity\Entity){ switch($e->class){ case ENTITY_PLAYER: $message = " was killed by ".$e->name; @@ -137,19 +139,19 @@ class PlayerAPI{ $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"; break; } if(count($params) === 3){ 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{ - $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{ - $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); @@ -303,7 +305,7 @@ class PlayerAPI{ } } $player = Player::get($target); - if(($player instanceof Player) and ($player->entity instanceof Entity)){ + if($player instanceof Player and $player->spawned === true){ $target = $player->getUsername(); $origin = Player::get($name); if($origin instanceof Player){ @@ -316,12 +318,12 @@ class PlayerAPI{ public function tppos(&$name, &$x, &$y, &$z){ $player = Player::get($name); - if(($player instanceof Player) and ($player->entity instanceof Entity)){ + if($player instanceof Player and $player->spawned === true){ $name = $player->getUsername(); $x = $x{0} === "~" ? $player->entity->x + floatval(substr($x, 1)):floatval($x); $y = $y{0} === "~" ? $player->entity->y + floatval(substr($y, 1)):floatval($y); $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 false; diff --git a/src/API/PluginAPI.php b/src/PluginAPI.php similarity index 88% rename from src/API/PluginAPI.php rename to src/PluginAPI.php index 68791458f..7e4b2cc8e 100644 --- a/src/API/PluginAPI.php +++ b/src/PluginAPI.php @@ -19,13 +19,15 @@ * */ -class PluginAPI extends stdClass{ +namespace PocketMine; + +class PluginAPI extends \stdClass{ private $server; private $plugins = array(); private $randomNonce; public function __construct(){ $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("version", "", array($this, "commandHandler")); $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"; break; 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)){ $output .= " (git ".GIT_COMMIT.")"; } @@ -77,7 +79,7 @@ class PluginAPI extends stdClass{ return false; } if(strtolower(substr($file, -3)) === "pmf"){ - $pmf = new PMFPlugin($file); + $pmf = new PMF\Plugin($file); $info = $pmf->getPluginInfo(); }else{ $content = file_get_contents($file); @@ -111,7 +113,7 @@ class PluginAPI extends stdClass{ console("[ERROR] Failed parsing of ".basename($file)); 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"])){ console("[ERROR] Failed loading plugin: class already exists"); return false; @@ -123,8 +125,8 @@ class PluginAPI extends stdClass{ $className = $info["class"]; $apiversion = array_map("intval", explode(",", (string) $info["apiversion"])); - if(!in_array((string) CURRENT_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!"); + if(!in_array(API_VERSION, $apiversion)){ + 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"]); @@ -167,7 +169,7 @@ class PluginAPI extends stdClass{ } public function pluginsPath(){ - $path = join(DIRECTORY_SEPARATOR, array(DATA_PATH."plugins", "")); + $path = join(DIRECTORY_SEPARATOR, array(DATA."plugins", "")); @mkdir($path); return $path; } @@ -191,7 +193,7 @@ class PluginAPI extends stdClass{ return false; } $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(); return $path; } diff --git a/src/MainServer.php b/src/Server.php similarity index 85% rename from src/MainServer.php rename to src/Server.php index 103473d6b..22ec3f67b 100644 --- a/src/MainServer.php +++ b/src/Server.php @@ -19,7 +19,9 @@ * */ -class MainServer{ +namespace PocketMine; + +class Server{ public $tCnt; 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; @@ -30,14 +32,14 @@ class MainServer{ public $api; private function load(){ - $this->version = new VersionString(); - /*if(defined("DEBUG") and DEBUG >= 0){ + $this->version = new Utils\VersionString(); + if(defined("DEBUG") and DEBUG >= 0){ @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); - define("BOOTUP_RANDOM", Utils::getRandomBytes(16)); - $this->serverID = $this->serverID === false ? Utils::readLong(substr(Utils::getUniqueID(true, $this->serverip . $this->port), 8)):$this->serverID; - $this->seed = $this->seed === false ? Utils::readInt(Utils::getRandomBytes(4, false)):$this->seed; + define("BOOTUP_RANDOM", Utils\Utils::getRandomBytes(16)); + $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\Utils::readInt(Utils\Utils::getRandomBytes(4, false)):$this->seed; $this->startDatabase(); $this->api = false; $this->tCnt = 1; @@ -60,11 +62,11 @@ class MainServer{ $this->whitelist = false; $this->tickMeasure = array_fill(0, 40, 0); $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->ticks = 0; if(!defined("NO_THREADS")){ - $this->asyncThread = new AsyncMultipleQueue(); + $this->asyncThread = new \AsyncMultipleQueue(); } } @@ -91,14 +93,14 @@ class MainServer{ public function titleTick(){ $time = microtime(true); - if(defined("DEBUG") and DEBUG >= 0 and ENABLE_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"; + if(defined("DEBUG") and DEBUG >= 0 and ANSI === true){ + 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); } public function loadEvents(){ - if(ENABLE_ANSI === true){ + if(ANSI === true){ $this->schedule(30, array($this, "titleTick"), array(), true); } $this->schedule(20 * 15, array($this, "checkTicks"), array(), true); @@ -123,9 +125,9 @@ class MainServer{ } public function startDatabase(){ - $this->preparedSQL = new stdClass(); - $this->preparedSQL->entity = new stdClass(); - $this->database = new SQLite3(":memory:", SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE); + $this->preparedSQL = new \stdClass(); + $this->preparedSQL->entity = new \stdClass(); + $this->database = new \SQLite3(":memory:", SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE); $this->query("PRAGMA journal_mode = OFF;"); $this->query("PRAGMA encoding = \"UTF-8\";"); $this->query("PRAGMA secure_delete = OFF;"); @@ -141,7 +143,7 @@ class MainServer{ public function query($sql, $fetch = false){ $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); } return $result; @@ -152,7 +154,7 @@ class MainServer{ $info["tps"] = $this->getTPS(); $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["entities"] = count(Entity::$list); + $info["entities"] = count(Entity\Entity::$list); $info["players"] = count(Player::$list); $info["events"] = count($this->eventsID); $info["handlers"] = $this->query("SELECT count(ID) as count FROM handlers;", true); @@ -211,25 +213,25 @@ class MainServer{ $type = (int) $type; switch($type){ 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; case ASYNC_CURL_POST: - $d .= Utils::writeShort(strlen($data["url"])).$data["url"].(isset($data["timeout"]) ? Utils::writeShort($data["timeout"]) : Utils::writeShort(10)); - $d .= Utils::writeShort(count($data["data"])); + $d .= Utils\Utils::writeShort(strlen($data["url"])).$data["url"].(isset($data["timeout"]) ? Utils\Utils::writeShort($data["timeout"]) : Utils\Utils::writeShort(10)); + $d .= Utils\Utils::writeShort(count($data["data"])); 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; case ASYNC_FUNCTION: $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; default: return false; } $ID = $this->asyncID++; $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; } @@ -239,21 +241,21 @@ class MainServer{ } if(isset($this->asyncThread->output{5})){ $offset = 0; - $ID = Utils::readInt(substr($this->asyncThread->output, $offset, 4)); + $ID = Utils\Utils::readInt(substr($this->asyncThread->output, $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; $data = array(); switch($type){ case ASYNC_CURL_GET: 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; $data["result"] = substr($this->asyncThread->output, $offset, $len); $offset += $len; break; case ASYNC_FUNCTION: - $len = Utils::readInt(substr($this->asyncThread->output, $offset, 4)); + $len = Utils\Utils::readInt(substr($this->asyncThread->output, $offset, 4)); $offset += 4; $data["result"] = unserialize(substr($this->asyncThread->output, $offset, $len)); $offset += $len; @@ -307,7 +309,7 @@ class MainServer{ $this->preparedSQL->selectHandlers->bindValue(":name", $event, SQLITE3_TEXT); $handlers = $this->preparedSQL->selectHandlers->execute(); $result = null; - if($handlers instanceof SQLite3Result){ + if($handlers instanceof \SQLite3Result){ $call = array(); while(($hn = $handlers->fetchArray(SQLITE3_ASSOC)) !== false){ $call[(int) $hn["ID"]] = true; @@ -424,14 +426,13 @@ class MainServer{ $dump .= "$line\r\n"; } $dump .= "\r\n\r\n"; - $version = new VersionString(); - $dump .= "PocketMine-MP version: ".$version." #".$version->getNumber()." [Protocol ".ProtocolInfo::CURRENT_PROTOCOL."; API ".CURRENT_API_VERSION."]\r\n"; + $version = new Utils\VersionString(); + $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 .= "Source SHA1 sum: ".SOURCE_SHA1SUM."\r\n"; $dump .= "uname -a: ".php_uname("a")."\r\n"; $dump .= "PHP Version: " .phpversion()."\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"; global $arguments; $dump .= "Parameters: ".var_export($arguments, true)."\r\n\r\n\r\n"; @@ -483,17 +484,17 @@ class MainServer{ //return $ip . ":" . $port; } - public function packetHandler(Packet $packet){ + public function packetHandler(Network\Packet $packet){ $data =& $packet; - $CID = MainServer::clientID($packet->ip, $packet->port); + $CID = Server::clientID($packet->ip, $packet->port); if(isset(Player::$list[$CID])){ Player::$list[$CID]->handlePacket($packet); }else{ switch($packet->pid()){ - case RakNetInfo::UNCONNECTED_PING: - case RakNetInfo::UNCONNECTED_PING_OPEN_CONNECTIONS: + case Network\RakNet\Info::UNCONNECTED_PING: + case Network\RakNet\Info::UNCONNECTED_PING_OPEN_CONNECTIONS: 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->serverID = $this->serverID; $pk->serverType = $this->serverType; @@ -511,7 +512,7 @@ class MainServer{ } $txt = substr($this->description, $this->custom["times_".$CID], $ln); $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->serverID = $this->serverID; $pk->serverType = $this->serverType . $this->name . " [".count(Player::$list)."/".$this->maxClients."] ".$txt; @@ -520,16 +521,16 @@ class MainServer{ $this->send($pk); $this->custom["times_".$CID] = ($this->custom["times_".$CID] + 1) % strlen($this->description); break; - case RakNetInfo::OPEN_CONNECTION_REQUEST_1: - if($packet->structure !== RakNetInfo::STRUCTURE){ + case Network\RakNet\Info::OPEN_CONNECTION_REQUEST_1: + if($packet->structure !== Network\RakNet\Info::STRUCTURE){ 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->ip = $packet->ip; $pk->port = $packet->port; $this->send($pk); }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->mtuSize = strlen($packet->buffer); $pk->ip = $packet->ip; @@ -537,13 +538,13 @@ class MainServer{ $this->send($pk); } break; - case RakNetInfo::OPEN_CONNECTION_REQUEST_2: + case Network\RakNet\Info::OPEN_CONNECTION_REQUEST_2: if($this->invisible === true){ break; } 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->serverPort = $this->port; $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); } @@ -563,7 +564,7 @@ class MainServer{ $lastLoop = 0; while($this->stop === false){ $packet = $this->interface->readPacket(); - if($packet instanceof Packet){ + if($packet instanceof Network\Packet){ $this->packetHandler($packet); $lastLoop = 0; } @@ -624,7 +625,7 @@ class MainServer{ $actions = $this->preparedSQL->selectActions->execute(); $actionCount = 0; - if($actions instanceof SQLite3Result){ + if($actions instanceof \SQLite3Result){ while(($action = $actions->fetchArray(SQLITE3_ASSOC)) !== false){ $cid = $action["ID"]; $this->preparedSQL->updateAction->reset(); diff --git a/src/API/ServerAPI.php b/src/ServerAPI.php similarity index 68% rename from src/API/ServerAPI.php rename to src/ServerAPI.php index 9d0e25108..ea4ee7458 100644 --- a/src/API/ServerAPI.php +++ b/src/ServerAPI.php @@ -19,6 +19,8 @@ * */ +namespace PocketMine; + class ServerAPI{ public $restart = false; private static $serverRequest = false; @@ -74,7 +76,7 @@ class ServerAPI{ public $player; /** - * @return MainServer + * @return Server */ public static function request(){ return self::$serverRequest; @@ -90,22 +92,22 @@ class ServerAPI{ } public function load(){ - @mkdir(DATA_PATH."players/", 0755); - @mkdir(DATA_PATH."worlds/", 0755); - @mkdir(DATA_PATH."plugins/", 0755); + @mkdir(DATA."players/", 0755); + @mkdir(DATA."worlds/", 0755); + @mkdir(DATA."plugins/", 0755); //Init all the events 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(); } } - $version = new VersionString(); - console("[INFO] Starting Minecraft PE server version ".TextFormat::AQUA.CURRENT_MINECRAFT_VERSION); + $version = new Utils\VersionString(); + console("[INFO] Starting Minecraft PE server version ".Utils\TextFormat::AQUA.MINECRAFT_VERSION); 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", "description" => "Server made using PocketMine-MP", "motd" => "Welcome @player to this server!", @@ -132,7 +134,7 @@ class ServerAPI{ "level-type" => "DEFAULT", "enable-query" => true, "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, )); @@ -147,52 +149,52 @@ class ServerAPI{ } if($this->getProperty("upnp-forwarding") == true){ 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; 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); if($this->getProperty("last-update") === false or ($this->getProperty("last-update") + 3600) < time()){ 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()){ - $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])){ console("[ERROR] Github API error"); }else{ - $last = new DateTime($info[0]["commit"]["committer"]["date"]); + $last = new \DateTime($info[0]["commit"]["committer"]["date"]); $last = $last->getTimestamp(); 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] ".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."A new DEVELOPMENT version of PocketMine-MP has been released!"); + console("[NOTICE] ".Utils\TextFormat::YELLOW."Commit \"".$info[0]["commit"]["message"]."\" [".substr($info[0]["sha"], 0, 10)."] by ".$info[0]["commit"]["committer"]["name"]); + 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\""); }else{ $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{ - $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])){ console("[ERROR] Github API error"); }else{ - $newest = new VersionString(MAJOR_VERSION); + $newest = new Utils\VersionString(VERSION); $newestN = $newest->getNumber(); - $update = new VersionString($info[0]["name"]); + $update = new Utils\VersionString($info[0]["name"]); $updateN = $update->getNumber(); if($updateN > $newestN){ - console("[NOTICE] ".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."A new STABLE version of PocketMine-MP has been released!"); + 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] This message will dissapear as soon as you update"); }else{ $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->loadAPI("console", "ConsoleAPI"); - $this->loadAPI("level", "LevelAPI"); - $this->loadAPI("block", "BlockAPI"); - $this->loadAPI("chat", "ChatAPI"); - $this->loadAPI("ban", "BanAPI"); - $this->loadAPI("player", "PlayerAPI"); - $this->loadAPI("time", "TimeAPI"); + $this->apiList[] = $this->console = new ConsoleAPI(); + $this->apiList[] = $this->level = new LevelAPI(); + $this->apiList[] = $this->block = new BlockAPI(); + $this->apiList[] = $this->chat = new ChatAPI(); + $this->apiList[] = $this->ban = new BanAPI(); + $this->apiList[] = $this->player = new PlayerAPI(); + $this->apiList[] = $this->time = new TimeAPI(); foreach($this->apiList as $ob){ if(is_callable(array($ob, "init"))){ @@ -215,26 +216,25 @@ class ServerAPI{ } } - $this->loadAPI("plugin", "PluginAPI"); //fix :( - $this->plugin->init(); + $this->apiList[] = $this->plugin = new PluginAPI(); } public function checkTickUpdates(){ //Update entities that need update - if(count(Entity::$needUpdate) > 0){ - foreach(Entity::$needUpdate as $id => $entity){ + if(count(Entity\Entity::$needUpdate) > 0){ + foreach(EntityEntity::$needUpdate as $id => $entity){ if($entity->onUpdate() === false){ - unset(Entity::$needUpdate[$id]); + unset(Entity\Entity::$needUpdate[$id]); } } } //Update tiles that need update - if(count(Tile::$needUpdate) > 0){ - foreach(Tile::$needUpdate as $id => $tile){ + if(count(Tile\Tile::$needUpdate) > 0){ + foreach(Tile\Tile::$needUpdate as $id => $tile){ 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){ $cnt = $this->asyncCnt++; - $this->asyncCalls[$cnt] = new Async($callable, $params); + $this->asyncCalls[$cnt] = new \Async($callable, $params); return $remove === true ? $this->getAsync($cnt):$cnt; } @@ -272,13 +272,13 @@ class ServerAPI{ "data" => array( "serverid" => $this->server->serverID, "port" => $this->server->port, - "os" => Utils::getOS(), + "os" => Utils\Utils::getOS(), "memory_total" => $this->getProperty("memory-limit"), "memory_usage" => memory_get_usage(true), "php_version" => PHP_VERSION, - "version" => MAJOR_VERSION, - "mc_version" => CURRENT_MINECRAFT_VERSION, - "protocol" => ProtocolInfo::CURRENT_PROTOCOL, + "version" => VERSION, + "mc_version" => MINECRAFT_VERSION, + "protocol" => Network\Protocol\Info::CURRENT_PROTOCOL, "online" => count(Player::$list), "max" => $this->server->maxClients, "plugins" => $plist, @@ -308,7 +308,7 @@ class ServerAPI{ $this->setProperty("memory-limit", "128M"); } - if($this->server instanceof MainServer){ + if($this->server instanceof Server){ $this->server->setType($this->getProperty("server-type")); $this->server->maxClients = $this->getProperty("max-players"); $this->server->description = $this->getProperty("description"); @@ -342,7 +342,7 @@ class ServerAPI{ break; case "server-id": 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; } @@ -354,7 +354,7 @@ class ServerAPI{ } public function init(){ - if(!(self::$serverRequest instanceof MainServer)){ + if(!(self::$serverRequest instanceof Server)){ self::$serverRequest = $this->server; } @@ -366,24 +366,24 @@ class ServerAPI{ $this->server->schedule(18000, array($this, "autoSave"), array(), 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){ - $this->query = new QueryHandler(); + $this->query = new Network\Query\QueryHandler(); } - CraftingRecipes::init(); + Recipes\Crafting::init(); $this->schedule(2, array($this, "checkTickUpdates"), array(), true); $this->server->init(); unregister_tick_function(array($this->server, "tick")); $this->console->__destruct(); - if($this->rcon instanceof RCON){ + if($this->rcon instanceof Network\RCON\RCON){ $this->rcon->stop(); } $this->__destruct(); if($this->getProperty("upnp-forwarding") === true ){ console("[INFO] [UPnP] Removing port forward..."); - UPnP_RemovePortForward($this->getProperty("server-port")); + Network\UPnP\RemovePortForward($this->getProperty("server-port")); } return $this->restart; } @@ -427,8 +427,11 @@ class ServerAPI{ } 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))){ + case "": case "on": case "true": case "yes": @@ -453,14 +456,8 @@ class ServerAPI{ case "server-port": case "debug": case "difficulty": - case "time-per-second": $v = (int) $v; 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; } @@ -478,28 +475,4 @@ class ServerAPI{ public function getList(){ 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)); - } - } diff --git a/src/API/TimeAPI.php b/src/TimeAPI.php similarity index 99% rename from src/API/TimeAPI.php rename to src/TimeAPI.php index f0f9dac2f..378f23d03 100644 --- a/src/API/TimeAPI.php +++ b/src/TimeAPI.php @@ -19,6 +19,8 @@ * */ +namespace PocketMine; + class TimeAPI{ public static $phases = array( "day" => 0, diff --git a/src/material/block/misc/Air.php b/src/block/Air.php similarity index 100% rename from src/material/block/misc/Air.php rename to src/block/Air.php diff --git a/src/material/block/misc/Bed.php b/src/block/Bed.php similarity index 100% rename from src/material/block/misc/Bed.php rename to src/block/Bed.php diff --git a/src/material/block/solid/Bedrock.php b/src/block/Bedrock.php similarity index 100% rename from src/material/block/solid/Bedrock.php rename to src/block/Bedrock.php diff --git a/src/material/block/plant/Beetroot.php b/src/block/Beetroot.php similarity index 100% rename from src/material/block/plant/Beetroot.php rename to src/block/Beetroot.php diff --git a/src/material/block/nonfull/stairs/BirchWoodStairs.php b/src/block/BirchWoodStairs.php similarity index 100% rename from src/material/block/nonfull/stairs/BirchWoodStairs.php rename to src/block/BirchWoodStairs.php diff --git a/src/material/Block.php b/src/block/Block.php similarity index 100% rename from src/material/Block.php rename to src/block/Block.php diff --git a/src/material/block/solid/Bookshelf.php b/src/block/Bookshelf.php similarity index 100% rename from src/material/block/solid/Bookshelf.php rename to src/block/Bookshelf.php diff --git a/src/material/block/nonfull/stairs/BrickStairs.php b/src/block/BrickStairs.php similarity index 100% rename from src/material/block/nonfull/stairs/BrickStairs.php rename to src/block/BrickStairs.php diff --git a/src/material/block/solid/Bricks.php b/src/block/Bricks.php similarity index 100% rename from src/material/block/solid/Bricks.php rename to src/block/Bricks.php diff --git a/src/material/block/plant/BrownMushroom.php b/src/block/BrownMushroom.php similarity index 100% rename from src/material/block/plant/BrownMushroom.php rename to src/block/BrownMushroom.php diff --git a/src/material/block/solid/BurningFurnace.php b/src/block/BurningFurnace.php similarity index 84% rename from src/material/block/solid/BurningFurnace.php rename to src/block/BurningFurnace.php index 50fd89432..77ab1d9d2 100644 --- a/src/material/block/solid/BurningFurnace.php +++ b/src/block/BurningFurnace.php @@ -47,15 +47,15 @@ class BurningFurnaceBlock extends SolidBlock{ $t = $this->level->getTile($this); $furnace = false; - if($t instanceof FurnaceTile){ + if($t instanceof Furnace){ $furnace = $t; }else{ - $furnace = new FurnaceTile($this->level, new NBTTag_Compound(false, array( - "Items" => new NBTTag_List("Items", array()), - "id" => new NBTTag_String("id", Tile::FURNACE), - "x" => new NBTTag_Int("x", $this->x), - "y" => new NBTTag_Int("y", $this->y), - "z" =>new NBTTag_Int("z", $this->z) + $furnace = new Furnace($this->level, new NBT\Tag\Compound(false, array( + "Items" => new NBT\Tag\List("Items", array()), + "id" => new NBT\Tag\String("id", Tile::FURNACE), + "x" => new NBT\Tag\Int("x", $this->x), + "y" => new NBT\Tag\Int("y", $this->y), + "z" =>new NBT\Tag\Int("z", $this->z) ))); } @@ -93,8 +93,8 @@ class BurningFurnaceBlock extends SolidBlock{ $drops[] = array(FURNACE, 0, 1); } $t = $this->level->getTile($this); - if($t instanceof FurnaceTile){ - for($s = 0; $s < FurnaceTile::SLOTS; ++$s){ + if($t instanceof Furnace){ + for($s = 0; $s < Furnace::SLOTS; ++$s){ $slot = $t->getSlot($s); if($slot->getID() > AIR and $slot->getCount() > 0){ $drops[] = array($slot->getID(), $slot->getMetadata(), $slot->getCount()); diff --git a/src/material/block/plant/Cactus.php b/src/block/Cactus.php similarity index 96% rename from src/material/block/plant/Cactus.php rename to src/block/Cactus.php index eb4193c3e..48dd5a719 100644 --- a/src/material/block/plant/Cactus.php +++ b/src/block/Cactus.php @@ -38,7 +38,7 @@ class CactusBlock extends TransparentBlock{ if($this->getSide(0)->getID() !== CACTUS){ if($this->meta == 0x0F){ 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){ $this->level->setBlock($b, new CactusBlock(), true, false, true); break; diff --git a/src/material/block/nonfull/Cake.php b/src/block/Cake.php similarity index 100% rename from src/material/block/nonfull/Cake.php rename to src/block/Cake.php diff --git a/src/material/block/nonfull/Carpet.php b/src/block/Carpet.php similarity index 100% rename from src/material/block/nonfull/Carpet.php rename to src/block/Carpet.php diff --git a/src/material/block/plant/Carrot.php b/src/block/Carrot.php similarity index 100% rename from src/material/block/plant/Carrot.php rename to src/block/Carrot.php diff --git a/src/material/block/solid/Chest.php b/src/block/Chest.php similarity index 75% rename from src/material/block/solid/Chest.php rename to src/block/Chest.php index 0dbfae8da..abc41be4d 100644 --- a/src/material/block/solid/Chest.php +++ b/src/block/Chest.php @@ -44,7 +44,7 @@ class ChestBlock extends TransparentBlock{ } $c = $this->getSide($side); 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; break; } @@ -52,15 +52,15 @@ class ChestBlock extends TransparentBlock{ } $this->level->setBlock($block, $this, true, false, true); - $tile = new ChestTile($this->level, new NBTTag_Compound(false, array( - "Items" => new NBTTag_List("Items", array()), - "id" => new NBTTag_String("id", Tile::CHEST), - "x" => new NBTTag_Int("x", $this->x), - "y" => new NBTTag_Int("y", $this->y), - "z" =>new NBTTag_Int("z", $this->z) + $tile = new Chest($this->level, new NBT\Tag\Compound(false, array( + "Items" => new NBT\Tag\List("Items", array()), + "id" => new NBT\Tag\String("id", Tile::CHEST), + "x" => new NBT\Tag\Int("x", $this->x), + "y" => new NBT\Tag\Int("y", $this->y), + "z" =>new NBT\Tag\Int("z", $this->z) ))); - if($chest instanceof ChestTile){ + if($chest instanceof Chest){ $chest->pairWith($tile); $tile->pairWith($chest); } @@ -69,7 +69,7 @@ class ChestBlock extends TransparentBlock{ public function onBreak(Item $item, Player $player){ $t = $this->level->getTile($this); - if($t instanceof ChestTile){ + if($t instanceof Chest){ $t->unpair(); } $this->level->setBlock($this, new AirBlock(), true, true, true); @@ -84,15 +84,15 @@ class ChestBlock extends TransparentBlock{ $t = $this->level->getTile($this); $chest = false; - if($t instanceof ChestTile){ + if($t instanceof Chest){ $chest = $t; }else{ - $chest = new ChestTile($this->level, new NBTTag_Compound(false, array( - "Items" => new NBTTag_List("Items", array()), - "id" => new NBTTag_String("id", Tile::CHEST), - "x" => new NBTTag_Int("x", $this->x), - "y" => new NBTTag_Int("y", $this->y), - "z" =>new NBTTag_Int("z", $this->z) + $chest = new Chest($this->level, new NBT\Tag\Compound(false, array( + "Items" => new NBT\Tag\List("Items", array()), + "id" => new NBT\Tag\String("id", Tile::CHEST), + "x" => new NBT\Tag\Int("x", $this->x), + "y" => new NBT\Tag\Int("y", $this->y), + "z" =>new NBT\Tag\Int("z", $this->z) ))); } @@ -111,8 +111,8 @@ class ChestBlock extends TransparentBlock{ array($this->id, 0, 1), ); $t = $this->level->getTile($this); - if($t instanceof ChestTile){ - for($s = 0; $s < ChestTile::SLOTS; ++$s){ + if($t instanceof Chest){ + for($s = 0; $s < Chest::SLOTS; ++$s){ $slot = $t->getSlot($s); if($slot->getID() > AIR and $slot->getCount() > 0){ $drops[] = array($slot->getID(), $slot->getMetadata(), $slot->getCount()); diff --git a/src/material/block/solid/Clay.php b/src/block/Clay.php similarity index 100% rename from src/material/block/solid/Clay.php rename to src/block/Clay.php diff --git a/src/material/block/solid/Coal.php b/src/block/Coal.php similarity index 100% rename from src/material/block/solid/Coal.php rename to src/block/Coal.php diff --git a/src/material/block/ore/CoalOre.php b/src/block/CoalOre.php similarity index 100% rename from src/material/block/ore/CoalOre.php rename to src/block/CoalOre.php diff --git a/src/material/block/solid/Cobblestone.php b/src/block/Cobblestone.php similarity index 100% rename from src/material/block/solid/Cobblestone.php rename to src/block/Cobblestone.php diff --git a/src/material/block/nonfull/stairs/CobblestoneStairs.php b/src/block/CobblestoneStairs.php similarity index 100% rename from src/material/block/nonfull/stairs/CobblestoneStairs.php rename to src/block/CobblestoneStairs.php diff --git a/src/material/block/nonfull/Cobweb.php b/src/block/Cobweb.php similarity index 100% rename from src/material/block/nonfull/Cobweb.php rename to src/block/Cobweb.php diff --git a/src/material/block/plant/CyanFlower.php b/src/block/CyanFlower.php similarity index 100% rename from src/material/block/plant/CyanFlower.php rename to src/block/CyanFlower.php diff --git a/src/material/block/plant/Dandelion.php b/src/block/Dandelion.php similarity index 100% rename from src/material/block/plant/Dandelion.php rename to src/block/Dandelion.php diff --git a/src/material/block/plant/DeadBush.php b/src/block/DeadBush.php similarity index 100% rename from src/material/block/plant/DeadBush.php rename to src/block/DeadBush.php diff --git a/src/material/block/solid/Diamond.php b/src/block/Diamond.php similarity index 100% rename from src/material/block/solid/Diamond.php rename to src/block/Diamond.php diff --git a/src/material/block/ore/DiamondOre.php b/src/block/DiamondOre.php similarity index 100% rename from src/material/block/ore/DiamondOre.php rename to src/block/DiamondOre.php diff --git a/src/material/block/solid/Dirt.php b/src/block/Dirt.php similarity index 100% rename from src/material/block/solid/Dirt.php rename to src/block/Dirt.php diff --git a/src/material/block/DoorBlock.php b/src/block/DoorBlock.php similarity index 100% rename from src/material/block/DoorBlock.php rename to src/block/DoorBlock.php diff --git a/src/material/block/solid/DoubleSlab.php b/src/block/DoubleSlab.php similarity index 100% rename from src/material/block/solid/DoubleSlab.php rename to src/block/DoubleSlab.php diff --git a/src/material/block/solid/DoubleWoodSlab.php b/src/block/DoubleWoodSlab.php similarity index 100% rename from src/material/block/solid/DoubleWoodSlab.php rename to src/block/DoubleWoodSlab.php diff --git a/src/material/block/FallableBlock.php b/src/block/FallableBlock.php similarity index 100% rename from src/material/block/FallableBlock.php rename to src/block/FallableBlock.php diff --git a/src/material/block/solid/Farmland.php b/src/block/Farmland.php similarity index 100% rename from src/material/block/solid/Farmland.php rename to src/block/Farmland.php diff --git a/src/material/block/nonfull/Fence.php b/src/block/Fence.php similarity index 100% rename from src/material/block/nonfull/Fence.php rename to src/block/Fence.php diff --git a/src/material/block/nonfull/FenceGate.php b/src/block/FenceGate.php similarity index 100% rename from src/material/block/nonfull/FenceGate.php rename to src/block/FenceGate.php diff --git a/src/material/block/misc/Fire.php b/src/block/Fire.php similarity index 100% rename from src/material/block/misc/Fire.php rename to src/block/Fire.php diff --git a/src/material/block/FlowableBlock.php b/src/block/FlowableBlock.php similarity index 100% rename from src/material/block/FlowableBlock.php rename to src/block/FlowableBlock.php diff --git a/src/material/block/solid/Furnace.php b/src/block/Furnace.php similarity index 100% rename from src/material/block/solid/Furnace.php rename to src/block/Furnace.php diff --git a/src/material/block/GenericBlock.php b/src/block/GenericBlock.php similarity index 100% rename from src/material/block/GenericBlock.php rename to src/block/GenericBlock.php diff --git a/src/material/block/solid/Glass.php b/src/block/Glass.php similarity index 100% rename from src/material/block/solid/Glass.php rename to src/block/Glass.php diff --git a/src/material/block/nonfull/GlassPane.php b/src/block/GlassPane.php similarity index 100% rename from src/material/block/nonfull/GlassPane.php rename to src/block/GlassPane.php diff --git a/src/material/block/solid/GlowingObsidian.php b/src/block/GlowingObsidian.php similarity index 100% rename from src/material/block/solid/GlowingObsidian.php rename to src/block/GlowingObsidian.php diff --git a/src/material/block/ore/GlowingRedstoneOre.php b/src/block/GlowingRedstoneOre.php similarity index 100% rename from src/material/block/ore/GlowingRedstoneOre.php rename to src/block/GlowingRedstoneOre.php diff --git a/src/material/block/solid/Glowstone.php b/src/block/Glowstone.php similarity index 100% rename from src/material/block/solid/Glowstone.php rename to src/block/Glowstone.php diff --git a/src/material/block/solid/Gold.php b/src/block/Gold.php similarity index 100% rename from src/material/block/solid/Gold.php rename to src/block/Gold.php diff --git a/src/material/block/ore/GoldOre.php b/src/block/GoldOre.php similarity index 100% rename from src/material/block/ore/GoldOre.php rename to src/block/GoldOre.php diff --git a/src/material/block/solid/Grass.php b/src/block/Grass.php similarity index 100% rename from src/material/block/solid/Grass.php rename to src/block/Grass.php diff --git a/src/material/block/solid/Gravel.php b/src/block/Gravel.php similarity index 100% rename from src/material/block/solid/Gravel.php rename to src/block/Gravel.php diff --git a/src/material/block/solid/HayBale.php b/src/block/HayBale.php similarity index 100% rename from src/material/block/solid/HayBale.php rename to src/block/HayBale.php diff --git a/src/material/block/solid/Ice.php b/src/block/Ice.php similarity index 100% rename from src/material/block/solid/Ice.php rename to src/block/Ice.php diff --git a/src/material/block/solid/Iron.php b/src/block/Iron.php similarity index 100% rename from src/material/block/solid/Iron.php rename to src/block/Iron.php diff --git a/src/material/block/nonfull/IronBars.php b/src/block/IronBars.php similarity index 100% rename from src/material/block/nonfull/IronBars.php rename to src/block/IronBars.php diff --git a/src/material/block/nonfull/IronDoor.php b/src/block/IronDoor.php similarity index 100% rename from src/material/block/nonfull/IronDoor.php rename to src/block/IronDoor.php diff --git a/src/material/block/ore/IronOre.php b/src/block/IronOre.php similarity index 100% rename from src/material/block/ore/IronOre.php rename to src/block/IronOre.php diff --git a/src/material/block/nonfull/stairs/JungleWoodStairs.php b/src/block/JungleWoodStairs.php similarity index 100% rename from src/material/block/nonfull/stairs/JungleWoodStairs.php rename to src/block/JungleWoodStairs.php diff --git a/src/material/block/attachable/Ladder.php b/src/block/Ladder.php similarity index 100% rename from src/material/block/attachable/Ladder.php rename to src/block/Ladder.php diff --git a/src/material/block/solid/Lapis.php b/src/block/Lapis.php similarity index 100% rename from src/material/block/solid/Lapis.php rename to src/block/Lapis.php diff --git a/src/material/block/ore/LapisOre.php b/src/block/LapisOre.php similarity index 100% rename from src/material/block/ore/LapisOre.php rename to src/block/LapisOre.php diff --git a/src/material/block/liquid/Lava.php b/src/block/Lava.php similarity index 100% rename from src/material/block/liquid/Lava.php rename to src/block/Lava.php diff --git a/src/material/block/solid/Leaves.php b/src/block/Leaves.php similarity index 100% rename from src/material/block/solid/Leaves.php rename to src/block/Leaves.php diff --git a/src/material/block/LiquidBlock.php b/src/block/LiquidBlock.php similarity index 100% rename from src/material/block/LiquidBlock.php rename to src/block/LiquidBlock.php diff --git a/src/material/block/solid/LitPumpkin.php b/src/block/LitPumpkin.php similarity index 100% rename from src/material/block/solid/LitPumpkin.php rename to src/block/LitPumpkin.php diff --git a/src/material/block/solid/Melon.php b/src/block/Melon.php similarity index 100% rename from src/material/block/solid/Melon.php rename to src/block/Melon.php diff --git a/src/material/block/plant/MelonStem.php b/src/block/MelonStem.php similarity index 100% rename from src/material/block/plant/MelonStem.php rename to src/block/MelonStem.php diff --git a/src/material/block/solid/MossStone.php b/src/block/MossStone.php similarity index 100% rename from src/material/block/solid/MossStone.php rename to src/block/MossStone.php diff --git a/src/material/block/solid/NetherBrick.php b/src/block/NetherBrick.php similarity index 100% rename from src/material/block/solid/NetherBrick.php rename to src/block/NetherBrick.php diff --git a/src/material/block/nonfull/stairs/NetherBricksStairs.php b/src/block/NetherBricksStairs.php similarity index 100% rename from src/material/block/nonfull/stairs/NetherBricksStairs.php rename to src/block/NetherBricksStairs.php diff --git a/src/material/block/misc/NetherReactor.php b/src/block/NetherReactor.php similarity index 100% rename from src/material/block/misc/NetherReactor.php rename to src/block/NetherReactor.php diff --git a/src/material/block/solid/Netherrack.php b/src/block/Netherrack.php similarity index 100% rename from src/material/block/solid/Netherrack.php rename to src/block/Netherrack.php diff --git a/src/material/block/solid/Obsidian.php b/src/block/Obsidian.php similarity index 100% rename from src/material/block/solid/Obsidian.php rename to src/block/Obsidian.php diff --git a/src/material/block/solid/Planks.php b/src/block/Planks.php similarity index 100% rename from src/material/block/solid/Planks.php rename to src/block/Planks.php diff --git a/src/material/block/plant/PotatoBlock.php b/src/block/PotatoBlock.php similarity index 100% rename from src/material/block/plant/PotatoBlock.php rename to src/block/PotatoBlock.php diff --git a/src/material/block/solid/Pumpkin.php b/src/block/Pumpkin.php similarity index 100% rename from src/material/block/solid/Pumpkin.php rename to src/block/Pumpkin.php diff --git a/src/material/block/plant/PumpkinStem.php b/src/block/PumpkinStem.php similarity index 100% rename from src/material/block/plant/PumpkinStem.php rename to src/block/PumpkinStem.php diff --git a/src/material/block/solid/Quartz.php b/src/block/Quartz.php similarity index 100% rename from src/material/block/solid/Quartz.php rename to src/block/Quartz.php diff --git a/src/material/block/nonfull/stairs/QuartzStairs.php b/src/block/QuartzStairs.php similarity index 100% rename from src/material/block/nonfull/stairs/QuartzStairs.php rename to src/block/QuartzStairs.php diff --git a/src/material/block/plant/RedMushroom.php b/src/block/RedMushroom.php similarity index 100% rename from src/material/block/plant/RedMushroom.php rename to src/block/RedMushroom.php diff --git a/src/material/block/ore/RedstoneOre.php b/src/block/RedstoneOre.php similarity index 100% rename from src/material/block/ore/RedstoneOre.php rename to src/block/RedstoneOre.php diff --git a/src/material/block/solid/Sand.php b/src/block/Sand.php similarity index 100% rename from src/material/block/solid/Sand.php rename to src/block/Sand.php diff --git a/src/material/block/solid/Sandstone.php b/src/block/Sandstone.php similarity index 100% rename from src/material/block/solid/Sandstone.php rename to src/block/Sandstone.php diff --git a/src/material/block/nonfull/stairs/SandstoneStairs.php b/src/block/SandstoneStairs.php similarity index 100% rename from src/material/block/nonfull/stairs/SandstoneStairs.php rename to src/block/SandstoneStairs.php diff --git a/src/material/block/plant/Sapling.php b/src/block/Sapling.php similarity index 100% rename from src/material/block/plant/Sapling.php rename to src/block/Sapling.php diff --git a/src/material/block/attachable/SignPost.php b/src/block/SignPost.php similarity index 100% rename from src/material/block/attachable/SignPost.php rename to src/block/SignPost.php diff --git a/src/material/block/nonfull/Slab.php b/src/block/Slab.php similarity index 100% rename from src/material/block/nonfull/Slab.php rename to src/block/Slab.php diff --git a/src/material/block/solid/Snow.php b/src/block/Snow.php similarity index 100% rename from src/material/block/solid/Snow.php rename to src/block/Snow.php diff --git a/src/material/block/nonfull/SnowLayer.php b/src/block/SnowLayer.php similarity index 100% rename from src/material/block/nonfull/SnowLayer.php rename to src/block/SnowLayer.php diff --git a/src/material/block/SolidBlock.php b/src/block/SolidBlock.php similarity index 100% rename from src/material/block/SolidBlock.php rename to src/block/SolidBlock.php diff --git a/src/material/block/solid/SoulSand.php b/src/block/SoulSand.php similarity index 100% rename from src/material/block/solid/SoulSand.php rename to src/block/SoulSand.php diff --git a/src/material/block/solid/Sponge.php b/src/block/Sponge.php similarity index 100% rename from src/material/block/solid/Sponge.php rename to src/block/Sponge.php diff --git a/src/material/block/nonfull/stairs/SpruceWoodStairs.php b/src/block/SpruceWoodStairs.php similarity index 100% rename from src/material/block/nonfull/stairs/SpruceWoodStairs.php rename to src/block/SpruceWoodStairs.php diff --git a/src/material/block/StairBlock.php b/src/block/StairBlock.php similarity index 100% rename from src/material/block/StairBlock.php rename to src/block/StairBlock.php diff --git a/src/material/block/liquid/StillLava.php b/src/block/StillLava.php similarity index 100% rename from src/material/block/liquid/StillLava.php rename to src/block/StillLava.php diff --git a/src/material/block/liquid/StillWater.php b/src/block/StillWater.php similarity index 100% rename from src/material/block/liquid/StillWater.php rename to src/block/StillWater.php diff --git a/src/material/block/solid/Stone.php b/src/block/Stone.php similarity index 100% rename from src/material/block/solid/Stone.php rename to src/block/Stone.php diff --git a/src/material/block/nonfull/stairs/StoneBrickStairs.php b/src/block/StoneBrickStairs.php similarity index 100% rename from src/material/block/nonfull/stairs/StoneBrickStairs.php rename to src/block/StoneBrickStairs.php diff --git a/src/material/block/solid/StoneBricks.php b/src/block/StoneBricks.php similarity index 100% rename from src/material/block/solid/StoneBricks.php rename to src/block/StoneBricks.php diff --git a/src/material/block/nonfull/StoneWall.php b/src/block/StoneWall.php similarity index 100% rename from src/material/block/nonfull/StoneWall.php rename to src/block/StoneWall.php diff --git a/src/material/block/solid/Stonecutter.php b/src/block/Stonecutter.php similarity index 100% rename from src/material/block/solid/Stonecutter.php rename to src/block/Stonecutter.php diff --git a/src/material/block/plant/Sugarcane.php b/src/block/Sugarcane.php similarity index 95% rename from src/material/block/plant/Sugarcane.php rename to src/block/Sugarcane.php index 01f909ac5..baeb330be 100644 --- a/src/material/block/plant/Sugarcane.php +++ b/src/block/Sugarcane.php @@ -35,7 +35,7 @@ class SugarcaneBlock extends FlowableBlock{ if($item->getID() === DYE and $item->getMetadata() === 0x0F){ //Bonemeal if($this->getSide(0)->getID() !== SUGARCANE_BLOCK){ 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){ $this->level->setBlock($b, new SugarcaneBlock(), true, false, true); break; @@ -65,7 +65,7 @@ class SugarcaneBlock extends FlowableBlock{ if($this->getSide(0)->getID() !== SUGARCANE_BLOCK){ if($this->meta === 0x0F){ 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){ $this->level->setBlock($b, new SugarcaneBlock(), true, false, true); break; diff --git a/src/material/block/misc/TNT.php b/src/block/TNT.php similarity index 100% rename from src/material/block/misc/TNT.php rename to src/block/TNT.php diff --git a/src/material/block/plant/TallGrass.php b/src/block/TallGrass.php similarity index 100% rename from src/material/block/plant/TallGrass.php rename to src/block/TallGrass.php diff --git a/src/material/block/attachable/Torch.php b/src/block/Torch.php similarity index 100% rename from src/material/block/attachable/Torch.php rename to src/block/Torch.php diff --git a/src/material/block/TransparentBlock.php b/src/block/TransparentBlock.php similarity index 100% rename from src/material/block/TransparentBlock.php rename to src/block/TransparentBlock.php diff --git a/src/material/block/attachable/Trapdoor.php b/src/block/Trapdoor.php similarity index 100% rename from src/material/block/attachable/Trapdoor.php rename to src/block/Trapdoor.php diff --git a/src/material/block/attachable/WallSign.php b/src/block/WallSign.php similarity index 100% rename from src/material/block/attachable/WallSign.php rename to src/block/WallSign.php diff --git a/src/material/block/liquid/Water.php b/src/block/Water.php similarity index 100% rename from src/material/block/liquid/Water.php rename to src/block/Water.php diff --git a/src/material/block/plant/Wheat.php b/src/block/Wheat.php similarity index 100% rename from src/material/block/plant/Wheat.php rename to src/block/Wheat.php diff --git a/src/material/block/solid/Wood.php b/src/block/Wood.php similarity index 100% rename from src/material/block/solid/Wood.php rename to src/block/Wood.php diff --git a/src/material/block/nonfull/WoodDoor.php b/src/block/WoodDoor.php similarity index 100% rename from src/material/block/nonfull/WoodDoor.php rename to src/block/WoodDoor.php diff --git a/src/material/block/nonfull/WoodSlab.php b/src/block/WoodSlab.php similarity index 100% rename from src/material/block/nonfull/WoodSlab.php rename to src/block/WoodSlab.php diff --git a/src/material/block/nonfull/stairs/WoodStairs.php b/src/block/WoodStairs.php similarity index 100% rename from src/material/block/nonfull/stairs/WoodStairs.php rename to src/block/WoodStairs.php diff --git a/src/material/block/solid/Wool.php b/src/block/Wool.php similarity index 100% rename from src/material/block/solid/Wool.php rename to src/block/Wool.php diff --git a/src/material/block/solid/Workbench.php b/src/block/Workbench.php similarity index 100% rename from src/material/block/solid/Workbench.php rename to src/block/Workbench.php diff --git a/src/config.php b/src/config.php deleted file mode 100644 index 5ac68d303..000000000 --- a/src/config.php +++ /dev/null @@ -1,80 +0,0 @@ - 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 -} - -$sha1sum = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; -/***REM_START***/ -require_once(FILE_PATH."/src/math/Vector3.php"); -require_once(FILE_PATH."/src/math/Position.php"); -require_once(FILE_PATH."/src/pmf/PMF.php"); - -require_all(FILE_PATH . "src/", array_flip(array("notimplemented"))); //REMOVE LATER! - -$inc = get_included_files(); -$inc[] = array_shift($inc); -$srcdir = realpath(FILE_PATH."src/"); -foreach($inc as $s){ - if(strpos(realpath(dirname($s)), $srcdir) === false and strtolower(basename($s)) !== "pocketmine-mp.php"){ - continue; - } - $sha1sum ^= sha1_file($s, true); -} -/***REM_END***/ -ini_set("opcache.mmap_base", bin2hex(Utils::getRandomBytes(8, false))); //Fix OPCache address errors -define("SOURCE_SHA1SUM", bin2hex($sha1sum)); - -/***REM_START***/ -if(!file_exists(DATA_PATH."server.properties") and arg("no-wizard", false) != true){ - $installer = new Installer(); -} -/***REM_END***/ \ No newline at end of file diff --git a/src/entity/notimplemented/TNTPrimedEntity.php b/src/entity/Ageable.php similarity index 91% rename from src/entity/notimplemented/TNTPrimedEntity.php rename to src/entity/Ageable.php index f8f3651c4..432d6a6da 100644 --- a/src/entity/notimplemented/TNTPrimedEntity.php +++ b/src/entity/Ageable.php @@ -19,6 +19,9 @@ * */ -class TNTPrimedEntity extends Entity implements ExplosiveEntity{ +namespace PocketMine\Entity +use PocketMine; + +interface Ageable{ } \ No newline at end of file diff --git a/src/entity/Animal.php b/src/entity/Animal.php new file mode 100644 index 000000000..f93029669 --- /dev/null +++ b/src/entity/Animal.php @@ -0,0 +1,27 @@ +id = Entity::$entityCount++; $this->justCreated = true; $this->closed = false; $this->namedtag = $nbt; $this->level = $level; - $this->boundingBox = new AxisAlignedBB(0, 0, 0, 0, 0, 0); - $this->setPositionAndRotation(new Vector3($this->namedtag->Pos[0], $this->namedtag->Pos[1], $this->namedtag->Pos[2]), $this->namedtag->Rotation[0], $this->namedtag->Rotation[1]); - $this->setMotion(new Vector3($this->namedtag->Motion[0], $this->namedtag->Motion[1], $this->namedtag->Motion[2])); + $this->boundingBox = new Math\AxisAlignedBB(0, 0, 0, 0, 0, 0); + $this->setPositionAndRotation(new Math\Vector3($this->namedtag->Pos[0], $this->namedtag->Pos[1], $this->namedtag->Pos[2]), $this->namedtag->Rotation[0], $this->namedtag->Rotation[1]); + $this->setMotion(new Math\Vector3($this->namedtag->Motion[0], $this->namedtag->Motion[1], $this->namedtag->Motion[2])); $this->fallDistance = $this->namedtag->FallDistance; $this->fireTicks = $this->namedtag->Fire; @@ -98,7 +101,7 @@ abstract class Entity extends Position{ $this->onGround = $this->namedtag->OnGround > 0 ? true:false; $this->invulnerable = $this->namedtag->Invulnerable > 0 ? true:false; - $index = PMFLevel::getIndex($this->x >> 4, $this->z >> 4); + $index = PMF\Level::getIndex($this->x >> 4, $this->z >> 4); $this->chunkIndex = $index; Entity::$list[$this->id] = $this; $this->level->entities[$this->id] = $this; @@ -137,7 +140,7 @@ abstract class Entity extends Position{ public function despawnFrom(Player $player){ if(isset($this->hasSpawned[$player->getID()])){ - $pk = new RemoveEntityPacket; + $pk = new Network\Protocol\RemoveEntityPacket; $pk->eid = $this->id; $player->dataPacket($pk); unset($this->hasSpawned[$player->getID()]); @@ -196,8 +199,8 @@ abstract class Entity extends Position{ $this->lastYaw = $this->yaw; $this->lastPitch = $this->pitch; - if($this instanceof HumanEntity){ - $pk = new MovePlayerPacket; + if($this instanceof Human){ + $pk = new Network\Protocol\MovePlayerPacket; $pk->eid = $this->id; $pk->x = $this->x; $pk->y = $this->y; @@ -206,7 +209,7 @@ abstract class Entity extends Position{ $pk->pitch = $this->pitch; $pk->bodyYaw = $this->yaw; }else{ - $pk = new MoveEntityPacket_PosRot; + $pk = new Network\Protocol\MoveEntityPacket_PosRot; $pk->eid = $this->id; $pk->x = $this->x; $pk->y = $this->y; @@ -220,7 +223,7 @@ abstract class Entity extends Position{ if($this->motionChanged === true){ $this->motionChanged = false; - $pk = new SetEntityMotionPacket; + $pk = new Network\Protocol\SetEntityMotionPacket; $pk->eid = $this->id; $pk->speedX = $this->motionX; $pk->speedY = $this->motionY; @@ -292,13 +295,13 @@ abstract class Entity extends Position{ } - public function onCollideWithPlayer(EntityPlayer $entityPlayer){ + public function onCollideWithPlayer(Human $entityPlayer){ } - protected function switchLevel(Level $targetLevel){ - if($this->level instanceof Level){ - if(EventHandler::callEvent(new EntityLevelChangeEvent($this, $this->level, $targetLevel)) === BaseEvent::DENY){ + protected function switchLevel(Level\Level $targetLevel){ + if($this->level instanceof Level\Level){ + if(Event\EventHandler::callEvent(new Event\Entity\EntityLevelChangeEvent($this, $this->level, $targetLevel)) === Event\Event::DENY){ return false; } unset($this->level->entities[$this->id]); @@ -309,7 +312,7 @@ abstract class Entity extends Position{ if($Yndex !== 0xff){ $X = null; $Z = null; - PMFLevel::getXZ($index, $X, $Z); + PMF\Level::getXZ($index, $X, $Z); foreach($this->level->getChunkEntities($X, $Z) as $entity){ $entity->despawnFrom($this); } @@ -332,10 +335,10 @@ abstract class Entity extends Position{ } public function getPosition(){ - return new Position($this->x, $this->y, $this->z, $this->level); + return new Level\Position($this->x, $this->y, $this->z, $this->level); } - public function move(Vector3 $displacement){ + public function move(Math\Vector3 $displacement){ if($displacement->x == 0 and $displacement->y == 0 and $displacement->z == 0){ return; } @@ -346,7 +349,7 @@ abstract class Entity extends Position{ $this->scheduleUpdate(); } - public function setPositionAndRotation(Vector3 $pos, $yaw, $pitch){ + public function setPositionAndRotation(Math\Vector3 $pos, $yaw, $pitch){ if($this->setPosition($pos) === true){ $this->setRotation($yaw, $pitch); return true; @@ -360,13 +363,13 @@ abstract class Entity extends Position{ $this->scheduleUpdate(); } - public function setPosition(Vector3 $pos){ - if($pos instanceof Position and $pos->level instanceof Level and $pos->level !== $this->level){ + public function setPosition(Math\Vector3 $pos){ + if($pos instanceof Level\Position and $pos->level instanceof Level\Level and $pos->level !== $this->level){ if($this->switchLevel($pos->level) === false){ return false; } } - if(EventHandler::callEvent(new EntityMoveEvent($this, $pos)) === BaseEvent::DENY){ + if(Event\EventHandler::callEvent(new Event\Entity\EntityMoveEvent($this, $pos)) === Event\Event::DENY){ return false; } $this->x = $pos->x; @@ -374,7 +377,7 @@ abstract class Entity extends Position{ $this->z = $pos->z; $radius = $this->width / 2; - if(($index = PMFLevel::getIndex($this->x >> 4, $this->z >> 4)) !== $this->chunkIndex){ + if(($index = PMF\Level::getIndex($this->x >> 4, $this->z >> 4)) !== $this->chunkIndex){ if($this->chunkIndex !== false){ unset($this->level->chunkEntities[$this->chunkIndex][$this->id]); } @@ -402,11 +405,11 @@ abstract class Entity extends Position{ } public function getMotion(){ - return new Vector3($this->motionX, $this->motionY, $this->motionZ); + return new Math\Vector3($this->motionX, $this->motionY, $this->motionZ); } - public function setMotion(Vector3 $motion){ - if(EventHandler::callEvent(new EntityMotionEvent($this, $motion)) === BaseEvent::DENY){ + public function setMotion(Math\Vector3 $motion){ + if(Event\EventHandler::callEvent(new Event\Entity\EntityMotionEvent($this, $motion)) === Event\Event::DENY){ return false; } $this->motionX = $motion->x; @@ -427,8 +430,8 @@ abstract class Entity extends Position{ return $this->level; } - public function teleport(Position $pos, $yaw = false, $pitch = false){ - $this->setMotion(new Vector3(0, 0, 0)); + public function teleport(Level\Position $pos, $yaw = false, $pitch = false){ + $this->setMotion(new Math\Vector3(0, 0, 0)); if($this->setPositionAndRotation($pos, $yaw === false ? $this->yaw : $yaw, $pitch === false ? $this->pitch : $pitch) !== false){ if($this instanceof Player){ $this->airTicks = 300; @@ -437,7 +440,7 @@ abstract class Entity extends Position{ $this->getNextChunk(true); $this->forceMovement = $pos; - $pk = new MovePlayerPacket; + $pk = new Network\Protocol\MovePlayerPacket; $pk->eid = 0; $pk->x = $this->x; $pk->y = $this->y; @@ -486,28 +489,4 @@ abstract class Entity extends Position{ $this->close(); } -} - -/***REM_START***/ -require_once("entity/DamageableEntity.php"); -require_once("entity/ProjectileSourceEntity.php"); -require_once("entity/InventorySourceEntity.php"); -require_once("entity/RideableEntity.php"); -require_once("entity/TameableEntity.php"); -require_once("entity/AttachableEntity.php"); -require_once("entity/AgeableEntity.php"); -require_once("entity/ExplosiveEntity.php"); -require_once("entity/ColorableEntity.php"); - -require_once("entity/LivingEntity.php"); -require_once("entity/CreatureEntity.php"); -require_once("entity/MonsterEntity.php"); -require_once("entity/AnimalEntity.php"); -require_once("entity/HumanEntity.php"); -require_once("entity/ProjectileEntity.php"); -require_once("entity/VehicleEntity.php"); -require_once("entity/HangingEntity.php"); - -require_once("entity/HumanEntity.php"); -require_once("entity/PlayerEntity.php"); -/***REM_END***/ \ No newline at end of file +} \ No newline at end of file diff --git a/src/entity/ColorableEntity.php b/src/entity/Explosive.php similarity index 91% rename from src/entity/ColorableEntity.php rename to src/entity/Explosive.php index fb4a6271a..f245b34d3 100644 --- a/src/entity/ColorableEntity.php +++ b/src/entity/Explosive.php @@ -19,6 +19,9 @@ * */ -interface ColorableEntity{ +namespace PocketMine\Entity; +use PocketMine; + +interface Explosive{ } \ No newline at end of file diff --git a/src/entity/ExplosiveEntity.php b/src/entity/ExplosiveEntity.php deleted file mode 100644 index 492b63ff2..000000000 --- a/src/entity/ExplosiveEntity.php +++ /dev/null @@ -1,24 +0,0 @@ -hotbar[$slot]) and $this->hotbar[$slot] !== -1){ $item = $this->getSlot($this->hotbar[$slot]); if($item->getID() !== AIR and $item->getCount() > 0){ - $this->namedtag->Inventory[$slot] = new NBTTag_Compound(false, array( - "Count" => new NBTTag_Byte("Count", $item->getCount()), - "Damage" => new NBTTag_Short("Damage", $item->getMetadata()), - "Slot" => new NBTTag_Byte("Slot", $slot), - "TrueSlot" => new NBTTag_Byte("TrueSlot", $this->hotbar[$slot]), - "id" => new NBTTag_Short("id", $item->getID()), + $this->namedtag->Inventory[$slot] = new NBT\Tag\Compound(false, array( + "Count" => new NBT\Tag\Byte("Count", $item->getCount()), + "Damage" => new NBT\Tag\Short("Damage", $item->getMetadata()), + "Slot" => new NBT\Tag\Byte("Slot", $slot), + "TrueSlot" => new NBT\Tag\Byte("TrueSlot", $this->hotbar[$slot]), + "id" => new NBT\Tag\Short("id", $item->getID()), )); continue; } } - $this->namedtag->Inventory[$slot] = new NBTTag_Compound(false, array( - "Count" => new NBTTag_Byte("Count", 0), - "Damage" => new NBTTag_Short("Damage", 0), - "Slot" => new NBTTag_Byte("Slot", $slot), - "TrueSlot" => new NBTTag_Byte("Slot", -1), - "id" => new NBTTag_Short("id", 0), + $this->namedtag->Inventory[$slot] = new NBT\Tag\Compound(false, array( + "Count" => new NBT\Tag\Byte("Count", 0), + "Damage" => new NBT\Tag\Short("Damage", 0), + "Slot" => new NBT\Tag\Byte("Slot", $slot), + "TrueSlot" => new NBT\Tag\Byte("Slot", -1), + "id" => new NBT\Tag\Short("id", 0), )); } @@ -83,11 +87,11 @@ class HumanEntity extends CreatureEntity implements ProjectileSourceEntity, Inve $slotCount = (($this->gamemode & 0x01) === 0 ? PLAYER_SURVIVAL_SLOTS:PLAYER_CREATIVE_SLOTS) + 9; for($slot = 9; $slot < $slotCount; ++$slot){ $item = $this->getSlot($slot); - $this->namedtag->Inventory[$slot] = new NBTTag_Compound(false, array( - "Count" => new NBTTag_Byte("Count", $item->getCount()), - "Damage" => new NBTTag_Short("Damage", $item->getMetadata()), - "Slot" => new NBTTag_Byte("Slot", $slot), - "id" => new NBTTag_Short("id", $item->getID()), + $this->namedtag->Inventory[$slot] = new NBT\Tag\Compound(false, array( + "Count" => new NBT\Tag\Byte("Count", $item->getCount()), + "Damage" => new NBT\Tag\Short("Damage", $item->getMetadata()), + "Slot" => new NBT\Tag\Byte("Slot", $slot), + "id" => new NBT\Tag\Short("id", $item->getID()), )); } @@ -95,11 +99,11 @@ class HumanEntity extends CreatureEntity implements ProjectileSourceEntity, Inve for($slot = 100; $slot < 104; ++$slot){ $item = $this->armor[$slot - 100]; if($item instanceof Item){ - $this->namedtag->Inventory[$slot] = new NBTTag_Compound(false, array( - "Count" => new NBTTag_Byte("Count", $item->getCount()), - "Damage" => new NBTTag_Short("Damage", $item->getMetadata()), - "Slot" => new NBTTag_Byte("Slot", $slot), - "id" => new NBTTag_Short("id", $item->getID()), + $this->namedtag->Inventory[$slot] = new NBT\Tag\Compound(false, array( + "Count" => new NBT\Tag\Byte("Count", $item->getCount()), + "Damage" => new NBT\Tag\Short("Damage", $item->getMetadata()), + "Slot" => new NBT\Tag\Byte("Slot", $slot), + "id" => new NBT\Tag\Short("id", $item->getID()), )); } } @@ -109,7 +113,7 @@ class HumanEntity extends CreatureEntity implements ProjectileSourceEntity, Inve if($player !== $this and !isset($this->hasSpawned[$player->getID()])){ $this->hasSpawned[$player->getID()] = $player; - $pk = new AddPlayerPacket; + $pk = new Network\Protocol\AddPlayerPacket; $pk->clientID = 0; $pk->username = $this->nameTag; $pk->eid = $this->id; @@ -123,7 +127,7 @@ class HumanEntity extends CreatureEntity implements ProjectileSourceEntity, Inve $pk->metadata = $this->getMetadata(); $player->dataPacket($pk); - $pk = new SetEntityMotionPacket; + $pk = new Network\Protocol\SetEntityMotionPacket; $pk->eid = $this->id; $pk->speedX = $this->motionX; $pk->speedY = $this->motionY; @@ -138,7 +142,7 @@ class HumanEntity extends CreatureEntity implements ProjectileSourceEntity, Inve public function despawnFrom(Player $player){ if(isset($this->hasSpawned[$player->getID()])){ - $pk = new RemovePlayerPacket; + $pk = new Network\Protocol\RemovePlayerPacket; $pk->eid = $this->id; $pk->clientID = 0; $player->dataPacket($pk); @@ -165,7 +169,7 @@ class HumanEntity extends CreatureEntity implements ProjectileSourceEntity, Inve } public function sendCurrentEquipmentSlot(Player $player){ - $pk = new PlayerEquipmentPacket; + $pk = new Network\Protocol\PlayerEquipmentPacket; $pk->eid = $this->id; $pk->item = $this->getSlot($this->slot)->getID(); $pk->meta = $this->getSlot($this->slot)->getMetadata(); @@ -174,7 +178,7 @@ class HumanEntity extends CreatureEntity implements ProjectileSourceEntity, Inve } public function setArmorSlot($slot, Item $item){ - if(EventHandler::callEvent($ev = new EntityArmorChangeEvent($this, $this->getArmorSlot($slot), $item, $slot)) === BaseEvent::DENY){ + if(Event\EventHandler::callEvent($ev = new Event\Entity\EntityArmorChangeEvent($this, $this->getArmorSlot($slot), $item, $slot)) === Event\Event::DENY){ return false; } $this->armor[(int) $slot] = $ev->getNewItem(); @@ -206,12 +210,12 @@ class HumanEntity extends CreatureEntity implements ProjectileSourceEntity, Inve } } if($player instanceof Player){ - $pk = new PlayerArmorEquipmentPacket; + $pk = new Netowrk\Protocol\PlayerArmorEquipmentPacket; $pk->eid = $this->id; $pk->slots = $slots; $player->dataPacket($pk); }elseif($this instanceof Player){ - $pk = new ContainerSetContentPacket; + $pk = new Network\Protocol\ContainerSetContentPacket; $pk->windowid = 0x78; //Armor window id $pk->slots = $this->armor; $this->dataPacket($pk); @@ -348,7 +352,7 @@ class HumanEntity extends CreatureEntity implements ProjectileSourceEntity, Inve } public function setSlot($slot, Item $item){ - if(EventHandler::callEvent($ev = new EntityInventoryChangeEvent($this, $this->getSlot($slot), $item, $slot)) === BaseEvent::DENY){ + if(Event\EventHandler::callEvent($ev = new Event\Entity\EntityInventoryChangeEvent($this, $this->getSlot($slot), $item, $slot)) === Event\Event::DENY){ return false; } $this->inventory[(int) $slot] = $ev->getNewItem(); diff --git a/src/entity/InventorySourceEntity.php b/src/entity/InventorySource.php similarity index 91% rename from src/entity/InventorySourceEntity.php rename to src/entity/InventorySource.php index c06e42aec..907e6aa13 100644 --- a/src/entity/InventorySourceEntity.php +++ b/src/entity/InventorySource.php @@ -19,7 +19,11 @@ * */ -interface InventorySourceEntity{ +namespace PocketMine\Entity; +use PocketMine; +use PocketMine\Item\Item as Item; + +interface InventorySource{ public function hasItem(Item $item, $checkDamage = true); @@ -45,5 +49,5 @@ interface InventorySourceEntity{ public function setSlot($slot, Item $item); - + } \ No newline at end of file diff --git a/src/entity/Living.php b/src/entity/Living.php new file mode 100644 index 000000000..10d891ecf --- /dev/null +++ b/src/entity/Living.php @@ -0,0 +1,27 @@ +level->players[$this->CID] = $this; diff --git a/src/entity/notimplemented/WolfEntity.php b/src/entity/Rideable.php similarity index 91% rename from src/entity/notimplemented/WolfEntity.php rename to src/entity/Rideable.php index 54b36bfe5..17b0dc70d 100644 --- a/src/entity/notimplemented/WolfEntity.php +++ b/src/entity/Rideable.php @@ -19,6 +19,9 @@ * */ -class WolfEntity extends AnimalEntity implements TameableEntity{ +namespace PocketMine\Entity; +use PocketMine; + +interface Rideable{ } \ No newline at end of file diff --git a/src/entity/RideableEntity.php b/src/entity/RideableEntity.php deleted file mode 100644 index 4cc393585..000000000 --- a/src/entity/RideableEntity.php +++ /dev/null @@ -1,24 +0,0 @@ - EventPriority::LOWEST){ return false; } - $identifier = Utils::getCallableIdentifier($handler); + $identifier = Utils\Utils::getCallableIdentifier($handler); if(isset(static::$handlers[$identifier])){ //Already registered return false; }else{ @@ -66,7 +69,7 @@ abstract class BaseEvent{ } public static function unregister(callable $handler, $priority = EventPriority::NORMAL){ - $identifier = Utils::getCallableIdentifier($handler); + $identifier = Utils\Utils::getCallableIdentifier($handler); if(isset(static::$handlers[$identifier])){ if(isset(static::$handlerPriority[(int) $priority][$identifier])){ unset(static::$handlerPriority[(int) $priority][$identifier]); @@ -89,7 +92,7 @@ abstract class BaseEvent{ protected $eventName = null; - private $status = BaseEvent::NORMAL; + private $status = Event::NORMAL; private $prioritySlot; final public function getEventName(){ @@ -106,34 +109,34 @@ abstract class BaseEvent{ public function isAllowed(){ - return ($this->status & 0x7FFFFFFF) === BaseEvent::ALLOW; + return ($this->status & 0x7FFFFFFF) === Event::ALLOW; } public function setAllowed($forceAllow = false){ - $this->status = BaseEvent::ALLOW | ($forceAllow === true ? BaseEvent::FORCE : 0); + $this->status = Event::ALLOW | ($forceAllow === true ? Event::FORCE : 0); } public function isCancelled(){ - return ($this->status & 0x7FFFFFFF) === BaseEvent::DENY; + return ($this->status & 0x7FFFFFFF) === Event::DENY; } public function setCancelled($forceCancel = false){ if($this instanceof CancellableEvent){ - $this->status = BaseEvent::DENY | ($forceCancel === true ? BaseEvent::FORCE : 0); + $this->status = Event::DENY | ($forceCancel === true ? Event::FORCE : 0); } return false; } public function isNormal(){ - return $this->status === BaseEvent::NORMAL; + return $this->status === Event::NORMAL; } public function setNormal(){ - $this->status = BaseEvent::NORMAL; + $this->status = Event::NORMAL; } public function isForced(){ - return ($this->status & BaseEvent::FORCE) > 0; + return ($this->status & Event::FORCE) > 0; } } \ No newline at end of file diff --git a/src/event/EventHandler.php b/src/event/EventHandler.php index 30dbead41..6c57d2a2e 100644 --- a/src/event/EventHandler.php +++ b/src/event/EventHandler.php @@ -19,11 +19,14 @@ * */ +namespace PocketMine\Event; +use PocketMine; + abstract class EventHandler{ - public static function callEvent(BaseEvent $event){ + public static function callEvent(Event $event){ if(count($event::$handlerPriority) === 0){ - return BaseEvent::NORMAL; + return Event::NORMAL; } foreach($event::$handlerPriority as $priority => $handlerList){ if(count($handlerList) > 0){ @@ -33,20 +36,20 @@ abstract class EventHandler{ } if($event->isForced()){ if($event instanceof CancellableEvent and $event->isCancelled()){ - return BaseEvent::DENY; + return Event::DENY; }else{ - return BaseEvent::ALLOW; + return Event::ALLOW; } } } } if($event instanceof CancellableEvent and $event->isCancelled()){ - return BaseEvent::DENY; + return Event::DENY; }elseif($event->isAllowed()){ - return BaseEvent::ALLOW; + return Event::ALLOW; }else{ - return BaseEvent::NORMAL; + return Event::NORMAL; } } diff --git a/src/event/EventPriority.php b/src/event/EventPriority.php index f42e8d732..777ea39e0 100644 --- a/src/event/EventPriority.php +++ b/src/event/EventPriority.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine\Event; +use PocketMine; + abstract class EventPriority{ /** * Event call is of very low importance and should be ran first, to allow diff --git a/src/event/entity/EntityArmorChangeEvent.php b/src/event/entity/EntityArmorChangeEvent.php index 9fb750cf8..7cb442dc0 100644 --- a/src/event/entity/EntityArmorChangeEvent.php +++ b/src/event/entity/EntityArmorChangeEvent.php @@ -19,6 +19,10 @@ * */ +namespace PocketMine\Event\Entity; +use PocketMine\Event; +use PocketMine; + class EntityArmorChangeEvent extends EntityEvent implements CancellableEvent{ public static $handlers; public static $handlerPriority; @@ -27,7 +31,7 @@ class EntityArmorChangeEvent extends EntityEvent implements CancellableEvent{ private $newItem; private $slot; - public function __construct(Entity $entity, Item $oldItem, Item $newItem, $slot){ + public function __construct(Entity\Entity $entity, Item\Item $oldItem, Item\Item $newItem, $slot){ $this->entity = $entity; $this->oldItem = $oldItem; $this->newItem = $newItem; @@ -42,7 +46,7 @@ class EntityArmorChangeEvent extends EntityEvent implements CancellableEvent{ return $this->newItem; } - public function setNewItem(Item $item){ + public function setNewItem(Item\Item $item){ $this->newItem = $item; } diff --git a/src/event/EntityEvent.php b/src/event/entity/EntityEvent.php similarity index 86% rename from src/event/EntityEvent.php rename to src/event/entity/EntityEvent.php index 98552fa75..585d437e2 100644 --- a/src/event/EntityEvent.php +++ b/src/event/entity/EntityEvent.php @@ -19,7 +19,11 @@ * */ -abstract class EntityEvent extends BaseEvent{ +namespace PocketMine\Event\Entity; +use PocketMine\Event; +use PocketMine; + +abstract class EntityEvent extends Event{ protected $entity; public function getEntity(){ diff --git a/src/event/entity/EntityInventoryChangeEvent.php b/src/event/entity/EntityInventoryChangeEvent.php index ea92753d5..550867d9b 100644 --- a/src/event/entity/EntityInventoryChangeEvent.php +++ b/src/event/entity/EntityInventoryChangeEvent.php @@ -19,6 +19,10 @@ * */ +namespace PocketMine\Event\Entity; +use PocketMine\Event; +use PocketMine; + class EntityInventoryChangeEvent extends EntityEvent implements CancellableEvent{ public static $handlers; public static $handlerPriority; @@ -27,7 +31,7 @@ class EntityInventoryChangeEvent extends EntityEvent implements CancellableEvent private $newItem; private $slot; - public function __construct(Entity $entity, Item $oldItem, Item $newItem, $slot){ + public function __construct(Entity\Entity $entity, Item\Item $oldItem, Item\Item $newItem, $slot){ $this->entity = $entity; $this->oldItem = $oldItem; $this->newItem = $newItem; @@ -42,7 +46,7 @@ class EntityInventoryChangeEvent extends EntityEvent implements CancellableEvent return $this->newItem; } - public function setNewItem(Item $item){ + public function setNewItem(Item\Item $item){ $this->newItem = $item; } diff --git a/src/event/entity/EntityLevelChangeEvent.php b/src/event/entity/EntityLevelChangeEvent.php index 7ac26f15e..fd06bf236 100644 --- a/src/event/entity/EntityLevelChangeEvent.php +++ b/src/event/entity/EntityLevelChangeEvent.php @@ -19,6 +19,10 @@ * */ +namespace PocketMine\Event\Entity; +use PocketMine\Event; +use PocketMine; + class EntityLevelChangeEvent extends EntityEvent implements CancellableEvent{ public static $handlers; public static $handlerPriority; @@ -26,7 +30,7 @@ class EntityLevelChangeEvent extends EntityEvent implements CancellableEvent{ private $originLevel; private $targetLevel; - public function __construct(Entity $entity, Level $originLevel, Level $targetLevel){ + public function __construct(Entity\Entity $entity, Level\Level $originLevel, Level\Level $targetLevel){ $this->entity = $entity; $this->originLevel = $originLevel; $this->targetLevel = $targetLevel; diff --git a/src/event/entity/EntityMotionEvent.php b/src/event/entity/EntityMotionEvent.php index 72ad7aab0..c2e22357e 100644 --- a/src/event/entity/EntityMotionEvent.php +++ b/src/event/entity/EntityMotionEvent.php @@ -19,13 +19,17 @@ * */ +namespace PocketMine\Event\Entity; +use PocketMine\Event; +use PocketMine; + class EntityMotionEvent extends EntityEvent implements CancellableEvent{ public static $handlers; public static $handlerPriority; private $mot; - public function __construct(Entity $entity, Vector3 $mot){ + public function __construct(Entity\Entity $entity, Math\Vector3 $mot){ $this->entity = $entity; $this->mot = $mot; } diff --git a/src/event/entity/EntityMoveEvent.php b/src/event/entity/EntityMoveEvent.php index e2a57e857..0c0ec6e33 100644 --- a/src/event/entity/EntityMoveEvent.php +++ b/src/event/entity/EntityMoveEvent.php @@ -19,13 +19,17 @@ * */ +namespace PocketMine\Event\Entity; +use PocketMine\Event; +use PocketMine; + class EntityMoveEvent extends EntityEvent implements CancellableEvent{ public static $handlers; public static $handlerPriority; private $pos; - public function __construct(Entity $entity, Vector3 $pos){ + public function __construct(Entity\Entity $entity, Math\Vector3 $pos){ $this->entity = $entity; $this->pos = $pos; } diff --git a/src/event/player/PlayerEquipmentChangeEvent.php b/src/event/player/PlayerEquipmentChangeEvent.php index c6546ac93..c07adbf8c 100644 --- a/src/event/player/PlayerEquipmentChangeEvent.php +++ b/src/event/player/PlayerEquipmentChangeEvent.php @@ -19,6 +19,10 @@ * */ +namespace PocketMine\Event\Player; +use PocketMine\Event; +use PocketMine; + class PlayerEquipmentChangeEvent extends PlayerEvent implements CancellableEvent{ public static $handlers; public static $handlerPriority; @@ -27,7 +31,7 @@ class PlayerEquipmentChangeEvent extends PlayerEvent implements CancellableEvent private $slot; private $inventorySlot; - public function __construct(Player $player, Item $item, $inventorySlot, $slot){ + public function __construct(Player $player, Item\Item $item, $inventorySlot, $slot){ $this->player = $player; $this->item = $item; $this->inventorySlot = (int) $inventorySlot; diff --git a/src/event/PlayerEvent.php b/src/event/player/PlayerEvent.php similarity index 86% rename from src/event/PlayerEvent.php rename to src/event/player/PlayerEvent.php index 8adfe17c4..daacc362c 100644 --- a/src/event/PlayerEvent.php +++ b/src/event/player/PlayerEvent.php @@ -19,7 +19,11 @@ * */ -abstract class PlayerEvent extends BaseEvent{ +namespace PocketMine\Event\Player; +use PocketMine\Event; +use PocketMine; + +abstract class PlayerEvent extends Event{ protected $player; public function getPlayer(){ diff --git a/src/event/PluginEvent.php b/src/event/plugin/PluginEvent.php similarity index 81% rename from src/event/PluginEvent.php rename to src/event/plugin/PluginEvent.php index 6546774b3..75c8a61ca 100644 --- a/src/event/PluginEvent.php +++ b/src/event/plugin/PluginEvent.php @@ -19,11 +19,15 @@ * */ +namespace PocketMine\Event\Plugin; +use PocketMine\Event; +use PocketMine; -abstract class PluginEvent extends BaseEvent{ + +abstract class PluginEvent extends Event{ private $plugin; - public function __construct(Plugin $plugin){ + public function __construct(Plugin $plugin){ //TODO: NEW PLUGIN CLASS! $this->plugin = $plugin; } diff --git a/src/event/server/DataPacketReceiveEvent.php b/src/event/server/DataPacketReceiveEvent.php index ee0faf394..876ee8589 100644 --- a/src/event/server/DataPacketReceiveEvent.php +++ b/src/event/server/DataPacketReceiveEvent.php @@ -19,6 +19,10 @@ * */ +namespace PocketMine\Event\Server; +use PocketMine\Event; +use PocketMine; + class DataPacketReceiveEvent extends ServerEvent implements CancellableEvent{ public static $handlers; public static $handlerPriority; @@ -26,7 +30,7 @@ class DataPacketReceiveEvent extends ServerEvent implements CancellableEvent{ private $packet; private $player; - public function __construct(Player $player, RakNetDataPacket $packet){ + public function __construct(Player $player, Network\Protocol\DataPacket $packet){ $this->packet = $packet; $this->player = $player; } diff --git a/src/event/server/DataPacketSendEvent.php b/src/event/server/DataPacketSendEvent.php index 5e55a29b9..003e251f1 100644 --- a/src/event/server/DataPacketSendEvent.php +++ b/src/event/server/DataPacketSendEvent.php @@ -19,6 +19,10 @@ * */ +namespace PocketMine\Event\Server; +use PocketMine\Event; +use PocketMine; + class DataPacketSendEvent extends ServerEvent implements CancellableEvent{ public static $handlers; public static $handlerPriority; @@ -26,7 +30,7 @@ class DataPacketSendEvent extends ServerEvent implements CancellableEvent{ private $packet; private $player; - public function __construct(Player $player, RakNetDataPacket $packet){ + public function __construct(Player $player, Network\Protocol\DataPacket $packet){ $this->packet = $packet; $this->player = $player; } diff --git a/src/event/server/PacketReceiveEvent.php b/src/event/server/PacketReceiveEvent.php index cb26cbf05..ca9de31fd 100644 --- a/src/event/server/PacketReceiveEvent.php +++ b/src/event/server/PacketReceiveEvent.php @@ -19,6 +19,10 @@ * */ +namespace PocketMine\Event\Server; +use PocketMine\Event; +use PocketMine; + class PacketReceiveEvent extends ServerEvent implements CancellableEvent{ public static $handlers; public static $handlerPriority; @@ -26,7 +30,7 @@ class PacketReceiveEvent extends ServerEvent implements CancellableEvent{ private $packet; - public function __construct(Packet $packet){ + public function __construct(Network\Packet $packet){ $this->packet = $packet; } diff --git a/src/event/server/PacketSendEvent.php b/src/event/server/PacketSendEvent.php index becb15e48..3ec3de94f 100644 --- a/src/event/server/PacketSendEvent.php +++ b/src/event/server/PacketSendEvent.php @@ -19,6 +19,10 @@ * */ +namespace PocketMine\Event\Server; +use PocketMine\Event; +use PocketMine; + class PacketSendEvent extends ServerEvent implements CancellableEvent{ public static $handlers; public static $handlerPriority; @@ -26,7 +30,7 @@ class PacketSendEvent extends ServerEvent implements CancellableEvent{ private $packet; - public function __construct(Packet $packet){ + public function __construct(Network\Packet $packet){ $this->packet = $packet; } diff --git a/src/event/ServerEvent.php b/src/event/server/ServerEvent.php similarity index 85% rename from src/event/ServerEvent.php rename to src/event/server/ServerEvent.php index f99355828..53ff5d23f 100644 --- a/src/event/ServerEvent.php +++ b/src/event/server/ServerEvent.php @@ -19,6 +19,10 @@ * */ -abstract class ServerEvent extends BaseEvent{ +namespace PocketMine\Event\Server; +use PocketMine\Event; +use PocketMine; + +abstract class ServerEvent extends Event{ } \ No newline at end of file diff --git a/src/event/TileEvent.php b/src/event/tile/TileEvent.php similarity index 87% rename from src/event/TileEvent.php rename to src/event/tile/TileEvent.php index 2f2582c37..9ae8be2ab 100644 --- a/src/event/TileEvent.php +++ b/src/event/tile/TileEvent.php @@ -19,7 +19,11 @@ * */ -abstract class TileEvent extends BaseEvent{ +namespace PocketMine\Event\Tile; +use PocketMine\Event; +use PocketMine; + +abstract class TileEvent extends Event{ protected $tile; public function getTile(){ diff --git a/src/event/tile/TileInventoryChange.php b/src/event/tile/TileInventoryChangeEvent.php similarity index 85% rename from src/event/tile/TileInventoryChange.php rename to src/event/tile/TileInventoryChangeEvent.php index d30ef0fa2..cf1083943 100644 --- a/src/event/tile/TileInventoryChange.php +++ b/src/event/tile/TileInventoryChangeEvent.php @@ -19,6 +19,10 @@ * */ +namespace PocketMine\Event\Tile; +use PocketMine\Event; +use PocketMine; + class TileInventoryChangeEvent extends TileEvent implements CancellableEvent{ public static $handlers; public static $handlerPriority; @@ -27,7 +31,7 @@ class TileInventoryChangeEvent extends TileEvent implements CancellableEvent{ private $newItem; private $slot; - public function __construct(Tile $tile, Item $oldItem, Item $newItem, $slot){ + public function __construct(Tile\Tile $tile, Item\Item $oldItem, Item\Item $newItem, $slot){ $this->tile = $tile; $this->oldItem = $oldItem; $this->newItem = $newItem; @@ -42,7 +46,7 @@ class TileInventoryChangeEvent extends TileEvent implements CancellableEvent{ return $this->newItem; } - public function setNewItem(Item $item){ + public function setNewItem(Item\Item $item){ $this->newItem = $item; } diff --git a/src/functions.php b/src/functions.php deleted file mode 100644 index fcac66d08..000000000 --- a/src/functions.php +++ /dev/null @@ -1,282 +0,0 @@ - $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::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 require_all($path, array $ignore = array(), &$count = 0){ - $dir = dir($path."/"); - $dirs = array(); - while(false !== ($file = $dir->read())){ - if($file !== "." and $file !== ".." and !isset($ignore[$file])){ - if(!is_dir($path.$file) and strtolower(substr($file, -3)) === "php"){ - require_once($path.$file); - ++$count; - }elseif(is_dir($path.$file)){ - $dirs[] = $path.$file."/"; - } - } - } - foreach($dirs as $dir){ - require_all($dir, $ignore, $count); - } - -} - -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 arg($name, $default = false){ - global $arguments, $argv; - if(!isset($arguments)){ - $arguments = arguments($argv); - } - - if(isset($arguments["commands"][$name])){ - return $arguments["commands"][$name]; - }else{ - return $default; - } -} - -function arguments($args){ - if(!is_array($args)){ - $args = array(); - } - array_shift( $args ); - $args = implode(' ', $args); - - preg_match_all('/ (--[\w\-]+ (?:[= ] [^-\s]+ )? ) | (-\w+) | (\w+) /x', $args, $match ); - $args = array_shift( $match ); - - $ret = array( - 'input' => array(), - 'commands' => array(), - 'flags' => array() - ); - - foreach ( $args as $arg ) { - - // Is it a command? (prefixed with --) - if ( substr( $arg, 0, 2 ) === '--' ) { - - $value = preg_split( '/[= ]/', $arg, 2 ); - $com = substr( array_shift($value), 2 ); - $value = implode($value); - - $ret['commands'][$com] = !empty($value) ? $value : true; - continue; - - } - - // Is it a flag? (prefixed with -) - if ( substr( $arg, 0, 1 ) === '-' ) { - $ret['flags'][] = substr( $arg, 1 ); - continue; - } - - $ret['input'][] = $arg; - continue; - - } - - return $ret; -} - -function console($message, $EOL = true, $log = true, $level = 1){ - if(!defined("DEBUG") or DEBUG >= $level){ - $message .= $EOL === true ? PHP_EOL:""; - $time = (ENABLE_ANSI === true ? TextFormat::AQUA . date("H:i:s") . TextFormat::RESET:date("H:i:s")) . " "; - $replaced = TextFormat::clean(preg_replace('/\x1b\[[0-9;]*m/', "", $time . $message)); - if($log === true and (!defined("LOG") or LOG === true)){ - logg(date("Y-m-d")." ".$replaced, "console", false, $level); - } - if(ENABLE_ANSI === true){ - $add = ""; - if(preg_match("/\[([a-zA-Z0-9]*)\]/", $message, $matches) > 0){ - switch($matches[1]){ - case "ERROR": - case "SEVERE": - $add .= TextFormat::RED; - break; - case "INTERNAL": - case "DEBUG": - $add .= TextFormat::GRAY; - break; - case "WARNING": - $add .= TextFormat::YELLOW; - break; - case "NOTICE": - $add .= TextFormat::AQUA; - break; - default: - $add = ""; - break; - } - } - $message = TextFormat::toANSI($time . $add . $message . 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 logg($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_PATH."/".$name.".log", "ab"); - } - @fwrite($fpointers[$name], $message); - if($close === true){ - fclose($fpointers[$name]); - unset($fpointers[$name]); - } - } -} \ No newline at end of file diff --git a/src/inventory/Window.php b/src/inventory/Window.php deleted file mode 100644 index 7fe4954e3..000000000 --- a/src/inventory/Window.php +++ /dev/null @@ -1,32 +0,0 @@ -server = ServerAPI::request(); - } -} \ No newline at end of file diff --git a/src/material/item/generic/Apple.php b/src/item/Apple.php similarity index 100% rename from src/material/item/generic/Apple.php rename to src/item/Apple.php diff --git a/src/material/item/generic/Bed.php b/src/item/Bed.php similarity index 100% rename from src/material/item/generic/Bed.php rename to src/item/Bed.php diff --git a/src/material/item/generic/BeetrootSeeds.php b/src/item/BeetrootSeeds.php similarity index 100% rename from src/material/item/generic/BeetrootSeeds.php rename to src/item/BeetrootSeeds.php diff --git a/src/material/item/generic/BeetrootSoup.php b/src/item/BeetrootSoup.php similarity index 100% rename from src/material/item/generic/BeetrootSoup.php rename to src/item/BeetrootSoup.php diff --git a/src/material/item/generic/Bowl.php b/src/item/Bowl.php similarity index 100% rename from src/material/item/generic/Bowl.php rename to src/item/Bowl.php diff --git a/src/material/item/generic/Brick.php b/src/item/Brick.php similarity index 100% rename from src/material/item/generic/Brick.php rename to src/item/Brick.php diff --git a/src/material/item/generic/Bucket.php b/src/item/Bucket.php similarity index 100% rename from src/material/item/generic/Bucket.php rename to src/item/Bucket.php diff --git a/src/material/item/generic/Cake.php b/src/item/Cake.php similarity index 100% rename from src/material/item/generic/Cake.php rename to src/item/Cake.php diff --git a/src/material/item/generic/Carrot.php b/src/item/Carrot.php similarity index 100% rename from src/material/item/generic/Carrot.php rename to src/item/Carrot.php diff --git a/src/material/item/generic/Coal.php b/src/item/Coal.php similarity index 100% rename from src/material/item/generic/Coal.php rename to src/item/Coal.php diff --git a/src/material/item/generic/Diamond.php b/src/item/Diamond.php similarity index 100% rename from src/material/item/generic/Diamond.php rename to src/item/Diamond.php diff --git a/src/material/item/generic/Feather.php b/src/item/Feather.php similarity index 100% rename from src/material/item/generic/Feather.php rename to src/item/Feather.php diff --git a/src/material/item/tool/FlintSteel.php b/src/item/FlintSteel.php similarity index 100% rename from src/material/item/tool/FlintSteel.php rename to src/item/FlintSteel.php diff --git a/src/material/item/generic/GoldIngot.php b/src/item/GoldIngot.php similarity index 100% rename from src/material/item/generic/GoldIngot.php rename to src/item/GoldIngot.php diff --git a/src/material/item/tool/IronAxe.php b/src/item/IronAxe.php similarity index 100% rename from src/material/item/tool/IronAxe.php rename to src/item/IronAxe.php diff --git a/src/material/item/generic/IronDoor.php b/src/item/IronDoor.php similarity index 100% rename from src/material/item/generic/IronDoor.php rename to src/item/IronDoor.php diff --git a/src/material/item/tool/IronHoe.php b/src/item/IronHoe.php similarity index 100% rename from src/material/item/tool/IronHoe.php rename to src/item/IronHoe.php diff --git a/src/material/item/generic/IronIngot.php b/src/item/IronIngot.php similarity index 100% rename from src/material/item/generic/IronIngot.php rename to src/item/IronIngot.php diff --git a/src/material/item/tool/IronPickaxe.php b/src/item/IronPickaxe.php similarity index 100% rename from src/material/item/tool/IronPickaxe.php rename to src/item/IronPickaxe.php diff --git a/src/material/item/tool/IronShovel.php b/src/item/IronShovel.php similarity index 100% rename from src/material/item/tool/IronShovel.php rename to src/item/IronShovel.php diff --git a/src/material/Item.php b/src/item/Item.php similarity index 92% rename from src/material/Item.php rename to src/item/Item.php index b7f49bfef..976b8a879 100644 --- a/src/material/Item.php +++ b/src/item/Item.php @@ -117,29 +117,29 @@ class Item{ } final public function getFuelTime(){ - if(!isset(FuelData::$duration[$this->id])){ + if(!isset(Recipes\Fuel::$duration[$this->id])){ return false; } if($this->id !== BUCKET or $this->meta === 10){ - return FuelData::$duration[$this->id]; + return Recipes\Fuel::$duration[$this->id]; } return false; } final public function getSmeltItem(){ - if(!isset(SmeltingData::$product[$this->id])){ + if(!isset(Recipes\Smelt::$product[$this->id])){ return false; } - if(isset(SmeltingData::$product[$this->id][0]) and !is_array(SmeltingData::$product[$this->id][0])){ - return BlockAPI::getItem(SmeltingData::$product[$this->id][0], SmeltingData::$product[$this->id][1]); + if(isset(Recipes\Smelt::$product[$this->id][0]) and !is_array(Recipes\Smelt::$product[$this->id][0])){ + return BlockAPI::getItem(Recipes\Smelt::$product[$this->id][0], Recipes\Smelt::$product[$this->id][1]); } - if(!isset(SmeltingData::$product[$this->id][$this->meta])){ + if(!isset(Recipes\Smelt::$product[$this->id][$this->meta])){ return false; } - return BlockAPI::getItem(SmeltingData::$product[$this->id][$this->meta][0], SmeltingData::$product[$this->id][$this->meta][1]); + return BlockAPI::getItem(Recipes\Smelt::$product[$this->id][$this->meta][0], Recipes\Smelt::$product[$this->id][$this->meta][1]); } diff --git a/src/material/item/generic/MelonSeeds.php b/src/item/MelonSeeds.php similarity index 100% rename from src/material/item/generic/MelonSeeds.php rename to src/item/MelonSeeds.php diff --git a/src/material/item/generic/MushroomStew.php b/src/item/MushroomStew.php similarity index 100% rename from src/material/item/generic/MushroomStew.php rename to src/item/MushroomStew.php diff --git a/src/material/item/generic/Painting.php b/src/item/Painting.php similarity index 100% rename from src/material/item/generic/Painting.php rename to src/item/Painting.php diff --git a/src/material/item/generic/Potato.php b/src/item/Potato.php similarity index 100% rename from src/material/item/generic/Potato.php rename to src/item/Potato.php diff --git a/src/material/item/generic/PumpkinSeeds.php b/src/item/PumpkinSeeds.php similarity index 100% rename from src/material/item/generic/PumpkinSeeds.php rename to src/item/PumpkinSeeds.php diff --git a/src/material/item/generic/SignItem.php b/src/item/SignItem.php similarity index 100% rename from src/material/item/generic/SignItem.php rename to src/item/SignItem.php diff --git a/src/material/item/generic/SpawnEgg.php b/src/item/SpawnEgg.php similarity index 100% rename from src/material/item/generic/SpawnEgg.php rename to src/item/SpawnEgg.php diff --git a/src/material/item/generic/Stick.php b/src/item/Stick.php similarity index 100% rename from src/material/item/generic/Stick.php rename to src/item/Stick.php diff --git a/src/material/item/generic/Sugarcane.php b/src/item/Sugarcane.php similarity index 100% rename from src/material/item/generic/Sugarcane.php rename to src/item/Sugarcane.php diff --git a/src/material/item/generic/WheatSeeds.php b/src/item/WheatSeeds.php similarity index 100% rename from src/material/item/generic/WheatSeeds.php rename to src/item/WheatSeeds.php diff --git a/src/material/item/tool/WoodenAxe.php b/src/item/WoodenAxe.php similarity index 100% rename from src/material/item/tool/WoodenAxe.php rename to src/item/WoodenAxe.php diff --git a/src/material/item/generic/WoodenDoor.php b/src/item/WoodenDoor.php similarity index 100% rename from src/material/item/generic/WoodenDoor.php rename to src/item/WoodenDoor.php diff --git a/src/material/item/tool/WoodenPickaxe.php b/src/item/WoodenPickaxe.php similarity index 100% rename from src/material/item/tool/WoodenPickaxe.php rename to src/item/WoodenPickaxe.php diff --git a/src/material/item/tool/WoodenShovel.php b/src/item/WoodenShovel.php similarity index 100% rename from src/material/item/tool/WoodenShovel.php rename to src/item/WoodenShovel.php diff --git a/src/material/item/tool/WoodenSword.php b/src/item/WoodenSword.php similarity index 100% rename from src/material/item/tool/WoodenSword.php rename to src/item/WoodenSword.php diff --git a/src/world/Explosion.php b/src/level/Explosion.php similarity index 78% rename from src/world/Explosion.php rename to src/level/Explosion.php index 83677b21e..3b1e07b99 100644 --- a/src/world/Explosion.php +++ b/src/level/Explosion.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine\Level; +use PocketMine; + class Explosion{ public static $specialDrops = array( GRASS => DIRT, @@ -34,7 +37,7 @@ class Explosion{ public $affectedBlocks = array(); public $stepLen = 0.3; - public function __construct(Position $center, $size){ + public function __construct(Level\Position $center, $size){ $this->level = $center->level; $this->source = $center; $this->size = max($size, 0); @@ -55,7 +58,7 @@ class Explosion{ for($j = 0; $j < $this->rays; ++$j){ for($k = 0; $k < $this->rays; ++$k){ if($i == 0 or $i == $mRays or $j == 0 or $j == $mRays or $k == 0 or $k == $mRays){ - $vector = new Vector3($i / $mRays * 2 - 1, $j / $mRays * 2 - 1, $k / $mRays * 2 - 1); //($i / $mRays) * 2 - 1 + $vector = new Math\Vector3($i / $mRays * 2 - 1, $j / $mRays * 2 - 1, $k / $mRays * 2 - 1); //($i / $mRays) * 2 - 1 $vector = $vector->normalize()->multiply($this->stepLen); $pointer = clone $this->source; @@ -95,7 +98,7 @@ class Explosion{ foreach($this->affectedBlocks as $block){ - if($block instanceof TNTBlock){ + if($block instanceof Block\TNT){ $data = array( "x" => $block->x + 0.5, "y" => $block->y + 0.5, @@ -104,27 +107,27 @@ class Explosion{ "fuse" => mt_rand(10, 30), //0.5 to 1.5 seconds ); //TODO - $e = $server->api->entity->add($this->level, ENTITY_OBJECT, OBJECT_PRIMEDTNT, $data); - $e->spawnToAll(); + //$e = $server->api->entity->add($this->level, ENTITY_OBJECT, OBJECT_PRIMEDTNT, $data); + //$e->spawnToAll(); }elseif(mt_rand(0, 10000) < ((1/$this->size) * 10000)){ if(isset(self::$specialDrops[$block->getID()])){ //TODO - $server->api->entity->drop(new Position($block->x + 0.5, $block->y, $block->z + 0.5, $this->level), BlockAPI::getItem(self::$specialDrops[$block->getID()], 0)); + //$server->api->entity->drop(new Position($block->x + 0.5, $block->y, $block->z + 0.5, $this->level), BlockAPI::getItem(self::$specialDrops[$block->getID()], 0)); }else{ //TODO - $server->api->entity->drop(new Position($block->x + 0.5, $block->y, $block->z + 0.5, $this->level), BlockAPI::getItem($block->getID(), $this->level->level->getBlockDamage($block->x, $block->y, $block->z))); + //$server->api->entity->drop(new Position($block->x + 0.5, $block->y, $block->z + 0.5, $this->level), BlockAPI::getItem($block->getID(), $this->level->level->getBlockDamage($block->x, $block->y, $block->z))); } } $this->level->level->setBlockID($block->x, $block->y, $block->z, 0); - $send[] = new Vector3($block->x - $source->x, $block->y - $source->y, $block->z - $source->z); + $send[] = new Math\Vector3($block->x - $source->x, $block->y - $source->y, $block->z - $source->z); } - $pk = new ExplodePacket; + $pk = new Network\Protocol\ExplodePacket; $pk->x = $this->source->x; $pk->y = $this->source->y; $pk->z = $this->source->z; $pk->radius = $this->size; $pk->records = $send; - $server->api->player->broadcastPacket($this->level->players, $pk); + Player::broadcastPacket($this->level->getPlayers(), $pk); } } diff --git a/src/world/Level.php b/src/level/Level.php similarity index 80% rename from src/world/Level.php rename to src/level/Level.php index 598bc7413..c57c59ca2 100644 --- a/src/world/Level.php +++ b/src/level/Level.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine\Level; +use PocketMine; + class Level{ public $players = array(); @@ -32,7 +35,7 @@ class Level{ public $stopTime; private $time, $startCheck, $startTime, $server, $name, $usedChunks, $changedBlocks, $changedCount, $generator; - public function __construct(PMFLevel $level, $name){ + public function __construct(PMF\Level $level, $name){ $this->server = ServerAPI::request(); $this->level = $level; $this->level->level = $this; @@ -46,17 +49,9 @@ class Level{ $this->usedChunks = array(); $this->changedBlocks = array(); $this->changedCount = array(); - if(class_exists($this->level->levelData["generator"])){ - $gen = $this->level->levelData["generator"]; - $this->generator = new $gen((array) $this->level->levelData["generatorSettings"]); - }else{ - if(strtoupper($this->server->api->getProperty("level-type")) == "FLAT"){ - $this->generator = new SuperflatGenerator(); - }else{ - $this->generator = new NormalGenerator(); - } - } - $this->generator->init($this, new Random($this->level->levelData["seed"])); + $gen = Generator\Generator::getGenerator($this->level->levelData["generator"]); + $this->generator = new $gen((array) $this->level->levelData["generatorSettings"]); + $this->generator->init($this, new Utils\Random($this->level->levelData["seed"])); } public function close(){ @@ -64,12 +59,12 @@ class Level{ } public function getUsingChunk($X, $Z){ - $index = PMFLevel::getIndex($X, $Z); + $index = PMF\Level::getIndex($X, $Z); return isset($this->usedChunks[$index]) ? $this->usedChunks[$index]:array(); } public function useChunk($X, $Z, Player $player){ - $index = PMFLevel::getIndex($X, $Z); + $index = PMF\Level::getIndex($X, $Z); $this->loadChunk($X, $Z); $this->usedChunks[$index][$player->CID] = $player; } @@ -81,7 +76,7 @@ class Level{ } public function freeChunk($X, $Z, Player $player){ - unset($this->usedChunks[PMFLevel::getIndex($X, $Z)][$player->CID]); + unset($this->usedChunks[PMF\Level::getIndex($X, $Z)][$player->CID]); } public function isChunkPopulated($X, $Z){ @@ -101,7 +96,7 @@ class Level{ if($this->server->api->dhandle("time.change", array("level" => $this, "time" => $time)) !== false){ $this->time = $time; - $pk = new SetTimePacket; + $pk = new Network\Protocol\SetTimePacket; $pk->time = (int) $this->time; $pk->started = $this->stopTime == false; Player::broadcastPacket($this->players, $pk); @@ -135,7 +130,7 @@ class Level{ foreach($this->changedBlocks as $index => $mini){ foreach($mini as $blocks){ foreach($blocks as $b){ - $pk = new UpdateBlockPacket; + $pk = new Network\Protocol\UpdateBlockPacket; $pk->x = $b->x; $pk->y = $b->y; $pk->z = $b->z; @@ -153,11 +148,11 @@ class Level{ //Do chunk updates foreach($this->usedChunks as $index => $p){ - PMFLevel::getXZ($index, $X, $Z); + PMF\Level::getXZ($index, $X, $Z); for($Y = 0; $Y < 8; ++$Y){ if(!$this->level->isMiniChunkEmpty($X, $Z, $Y)){ for($i = 0; $i < 3; ++$i){ - $block = $this->getBlockRaw(new Vector3(($X << 4) + mt_rand(0, 15), ($Y << 4) + mt_rand(0, 15), ($Z << 4) + mt_rand(0, 15))); + $block = $this->getBlockRaw(new Math\Vector3(($X << 4) + mt_rand(0, 15), ($Y << 4) + mt_rand(0, 15), ($Z << 4) + mt_rand(0, 15))); if($block instanceof Block){ if($block->onUpdate(BLOCK_UPDATE_RANDOM) === BLOCK_UPDATE_NORMAL){ $this->server->api->block->blockUpdateAround($block, $this); @@ -175,7 +170,7 @@ class Level{ foreach($this->usedChunks as $i => $c){ if(count($c) === 0){ unset($this->usedChunks[$i]); - PMFLevel::getXZ($i, $X, $Z); + PMF\Level::getXZ($i, $X, $Z); if(!$this->isSpawnChunk($X, $Z)){ $this->level->unloadChunk($X, $Z, $this->server->saveEnabled); } @@ -226,14 +221,14 @@ class Level{ protected function doSaveRoundExtra(){ foreach($this->usedChunks as $index => $d){ - PMFLevel::getXZ($index, $X, $Z); - $nbt = new NBT(NBT::BIG_ENDIAN); - $nbt->setData(new NBTTag_Compound("", array( - "Entities" => new NBTTag_List("Entities", array()), - "TileEntities" => new NBTTag_List("TileEntities", array()), + PMF\Level::getXZ($index, $X, $Z); + $nbt = new NBT(NBT\BIG_ENDIAN); + $nbt->setData(new NBT\Tag\Compound("", array( + "Entities" => new NBT\Tag\Enum("Entities", array()), + "TileEntities" => new NBT\Tag\Enum("TileEntities", array()), ))); - $nbt->Entities->setTagType(NBTTag::TAG_Compound); - $nbt->TileEntities->setTagType(NBTTag::TAG_Compound); + $nbt->Entities->setTagType(NBT\TAG_Compound); + $nbt->TileEntities->setTagType(NBT\TAG_Compound); $i = 0; foreach($this->chunkEntities[$index] as $entity){ @@ -256,23 +251,23 @@ class Level{ } } - public function getBlockRaw(Vector3 $pos){ + public function getBlockRaw(Math\Vector3 $pos){ $b = $this->level->getBlock($pos->x, $pos->y, $pos->z); return BlockAPI::get($b[0], $b[1], new Position($pos->x, $pos->y, $pos->z, $this)); } - public function getBlock(Vector3 $pos){ - if(!isset($this->level) or ($pos instanceof Position) and $pos->level !== $this){ + public function getBlock(Math\Vector3 $pos){ + if($pos instanceof Position and $pos->level !== $this){ return false; } $b = $this->level->getBlock($pos->x, $pos->y, $pos->z); return BlockAPI::get($b[0], $b[1], new Position($pos->x, $pos->y, $pos->z, $this)); } - public function setBlockRaw(Vector3 $pos, Block $block, $direct = true, $send = true){ + public function setBlockRaw(Math\Vector3 $pos, Block\Block $block, $direct = true, $send = true){ if(($ret = $this->level->setBlock($pos->x, $pos->y, $pos->z, $block->getID(), $block->getMetadata())) === true and $send !== false){ if($direct === true){ - $pk = new UpdateBlockPacket; + $pk = new Network\Protocol\UpdateBlockPacket; $pk->x = $pos->x; $pk->y = $pos->y; $pk->z = $pos->z; @@ -284,9 +279,9 @@ class Level{ $pos = new Position($pos->x, $pos->y, $pos->z, $this); } $block->position($pos); - $index = PMFLevel::getIndex($pos->x >> 4, $pos->z >> 4); + $index = PMF\Level::getIndex($pos->x >> 4, $pos->z >> 4); if(ADVANCED_CACHE == true){ - Cache::remove("world:{$this->name}:{$index}"); + Utils\Cache::remove("world:{$this->name}:{$index}"); } if(!isset($this->changedBlocks[$index])){ $this->changedBlocks[$index] = array(); @@ -303,8 +298,8 @@ class Level{ return $ret; } - public function setBlock(Vector3 $pos, Block $block, $update = true, $tiles = false, $direct = false){ - if(!isset($this->level) or (($pos instanceof Position) and $pos->level !== $this) or $pos->x < 0 or $pos->y < 0 or $pos->z < 0){ + public function setBlock(Math\Vector3 $pos, Block\Block $block, $update = true, $tiles = false, $direct = false){ + if((($pos instanceof Position) and $pos->level !== $this) or $pos->x < 0 or $pos->y < 0 or $pos->z < 0){ return false; } @@ -316,7 +311,7 @@ class Level{ $block->position($pos); if($direct === true){ - $pk = new UpdateBlockPacket; + $pk = new Network\Protocol\UpdateBlockPacket; $pk->x = $pos->x; $pk->y = $pos->y; $pk->z = $pos->z; @@ -324,9 +319,9 @@ class Level{ $pk->meta = $block->getMetadata(); Player::broadcastPacket($this->players, $pk); }else{ - $index = PMFLevel::getIndex($pos->x >> 4, $pos->z >> 4); + $index = PMF\Level::getIndex($pos->x >> 4, $pos->z >> 4); if(ADVANCED_CACHE == true){ - Cache::remove("world:{$this->name}:{$index}"); + Utils\Cache::remove("world:{$this->name}:{$index}"); } if(!isset($this->changedBlocks[$index])){ $this->changedBlocks[$index] = array(); @@ -344,7 +339,7 @@ class Level{ $this->server->api->block->blockUpdateAround($pos, BLOCK_UPDATE_NORMAL, 1); } if($tiles === true){ - if(($t = $this->getTile($pos)) !== false){ + if($t = $this->getTile($pos) instanceof Tile\Tile){ $t->close(); } } @@ -372,7 +367,7 @@ class Level{ return $this->players; } - public function getTile(Vector3 $pos){ + public function getTile(Math\Vector3 $pos){ if($pos instanceof Position and $pos->level !== $this){ return false; } @@ -388,25 +383,19 @@ class Level{ } public function getMiniChunk($X, $Z, $Y){ - if(!isset($this->level)){ - return false; - } return $this->level->getMiniChunk($X, $Z, $Y); } public function setMiniChunk($X, $Z, $Y, $data){ - if(!isset($this->level)){ - return false; - } $this->changedCount[$X.":".$Y.":".$Z] = 4096; if(ADVANCED_CACHE == true){ - Cache::remove("world:{$this->name}:$X:$Z"); + Utils\Cache::remove("world:{$this->name}:$X:$Z"); } return $this->level->setMiniChunk($X, $Z, $Y, $data); } public function getChunkEntities($X, $Z){ - $index = PMFLevel::getIndex($X, $Z); + $index = PMF\Level::getIndex($X, $Z); if(isset($this->usedChunks[$index]) or $this->loadChunk($X, $Z) === true){ return $this->chunkEntities[$index]; } @@ -414,7 +403,7 @@ class Level{ } public function getChunkTiles($X, $Z){ - $index = PMFLevel::getIndex($X, $Z); + $index = PMF\Level::getIndex($X, $Z); if(isset($this->usedChunks[$index]) or $this->loadChunk($X, $Z) === true){ return $this->chunkTiles[$index]; } @@ -424,7 +413,7 @@ class Level{ public function loadChunk($X, $Z){ - $index = PMFLevel::getIndex($X, $Z); + $index = PMF\Level::getIndex($X, $Z); if(isset($this->usedChunks[$index])){ return true; }elseif($this->level->loadChunk($X, $Z) !== false){ @@ -438,14 +427,14 @@ class Level{ } foreach($this->level->getChunkNBT($X, $Z)->TileEntities as $nbt){ switch($nbt->id){ - case Tile::CHEST: - new ChestTile($this, $nbt); + case Tile\Tile::CHEST: + new Tile\Chest($this, $nbt); break; - case Tile::FURNACE: - new FurnaceTile($this, $nbt); + case Tile\Tile::FURNACE: + new Tile\Furnace($this, $nbt); break; - case Tile::SIGN: - new SignTile($this, $nbt); + case Tile\Tile::SIGN: + new Tile\Sign($this, $nbt); break; } } @@ -465,7 +454,7 @@ class Level{ unset($this->usedChunks[$index]); unset($this->chunkEntities[$index]); unset($this->chunkTiles[$index]); - Cache::remove("world:{$this->name}:$X:$Z"); + Utils\Cache::remove("world:{$this->name}:$X:$Z"); return $this->level->unloadChunk($X, $Z, $this->server->saveEnabled); } @@ -480,8 +469,8 @@ class Level{ return false; } if(ADVANCED_CACHE == true and $Yndex === 0xff){ - $identifier = "world:{$this->name}:".PMFLevel::getIndex($X, $Z); - if(($cache = Cache::get($identifier)) !== false){ + $identifier = "world:{$this->name}:".PMF\Level::getIndex($X, $Z); + if(($cache = Utils\Cache::get($identifier)) !== false){ return $cache; } } @@ -503,7 +492,7 @@ class Level{ } } if(ADVANCED_CACHE == true and $Yndex == 0xff){ - Cache::add($identifier, $ordered, 60); + Utils\Cache::add($identifier, $ordered, 60); } return $ordered; } @@ -522,9 +511,6 @@ class Level{ } public function getSpawn(){ - if(!isset($this->level)){ - return false; - } return new Position($this->level->getData("spawnX"), $this->level->getData("spawnY"), $this->level->getData("spawnZ"), $this); } @@ -532,23 +518,23 @@ class Level{ if($spawn === false){ $spawn = $this->getSpawn(); } - if($spawn instanceof Vector3){ + if($spawn instanceof Math\Vector3){ $x = (int) round($spawn->x); $y = (int) round($spawn->y); $z = (int) round($spawn->z); for(; $y > 0; --$y){ - $v = new Vector3($x, $y, $z); + $v = new Math\Vector3($x, $y, $z); $b = $this->getBlock($v->getSide(0)); if($b === false){ return $spawn; - }elseif(!($b instanceof AirBlock)){ + }elseif(!($b instanceof Block\Air)){ break; } } for(; $y < 128; ++$y){ - $v = new Vector3($x, $y, $z); - if($this->getBlock($v->getSide(1)) instanceof AirBlock){ - if($this->getBlock($v) instanceof AirBlock){ + $v = new Math\Vector3($x, $y, $z); + if($this->getBlock($v->getSide(1)) instanceof Block\Air){ + if($this->getBlock($v) instanceof Block\Air){ return new Position($x, $y, $z, $this); } }else{ @@ -560,10 +546,7 @@ class Level{ return false; } - public function setSpawn(Vector3 $pos){ - if(!isset($this->level)){ - return false; - } + public function setSpawn(Math\Vector3 $pos){ $this->level->setData("spawnX", $pos->x); $this->level->setData("spawnY", $pos->y); $this->level->setData("spawnZ", $pos->z); @@ -596,9 +579,6 @@ class Level{ } public function getSeed(){ - if(!isset($this->level)){ - return false; - } return (int) $this->level->getData("seed"); } @@ -610,9 +590,6 @@ class Level{ } public function scheduleBlockUpdate(Position $pos, $delay, $type = BLOCK_UPDATE_SCHEDULED){ - if(!isset($this->level)){ - return false; - } return $this->server->api->block->scheduleBlockUpdate($pos, $delay, $type); } } diff --git a/src/world/LevelImport.php b/src/level/LevelImport.php similarity index 85% rename from src/world/LevelImport.php rename to src/level/LevelImport.php index d112b0626..f67f6df48 100644 --- a/src/world/LevelImport.php +++ b/src/level/LevelImport.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine\Level; +use PocketMine; + class LevelImport{ private $path; public function __construct($path){ @@ -29,12 +32,12 @@ class LevelImport{ if(file_exists($this->path."tileEntities.dat")){ //OldPM $level = unserialize(file_get_contents($this->path."level.dat")); console("[INFO] Importing OldPM level \"".$level["LevelName"]."\" to PMF format"); - $entities = new Config($this->path."entities.yml", Config::YAML, unserialize(file_get_contents($this->path."entities.dat"))); + $entities = new Utils\Config($this->path."entities.yml", Utils\Config::YAML, unserialize(file_get_contents($this->path."entities.dat"))); $entities->save(); - $tiles = new Config($this->path."tiles.yml", Config::YAML, unserialize(file_get_contents($this->path."tileEntities.dat"))); + $tiles = new Utils\Config($this->path."tiles.yml", Utils\Config::YAML, unserialize(file_get_contents($this->path."tileEntities.dat"))); $tiles->save(); }elseif(file_exists($this->path."chunks.dat") and file_exists($this->path."level.dat")){ //Pocket - $nbt = new NBT(NBT::LITTLE_ENDIAN); + $nbt = new NBT(NBT\LITTLE_ENDIAN); $nbt->read(substr(file_get_contents($this->path."level.dat"), 8)); $level = $nbt->getData(); if($level->LevelName == ""){ @@ -49,15 +52,15 @@ class LevelImport{ } $tiles = $entities->TileEntities; $entities = $entities->Entities; - $entities = new Config($this->path."entities.yml", Config::YAML, $entities); + $entities = new Utils\Config($this->path."entities.yml", Utils\Config::YAML, $entities); $entities->save(); - $tiles = new Config($this->path."tiles.yml", Config::YAML, $tiles); + $tiles = new Utils\Config($this->path."tiles.yml", Utils\Config::YAML, $tiles); $tiles->save(); }else{ return false; } - $pmf = new PMFLevel($this->path."level.pmf", array( + $pmf = new PMF\Level($this->path."level.pmf", array( "name" => $level["LevelName"], "seed" => $level["RandomSeed"], "time" => $level["Time"], diff --git a/src/world/PocketChunkParser.php b/src/level/PocketChunkParser.php similarity index 96% rename from src/world/PocketChunkParser.php rename to src/level/PocketChunkParser.php index b694a0fd6..d1976245d 100644 --- a/src/world/PocketChunkParser.php +++ b/src/level/PocketChunkParser.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine\Level; +use PocketMine; + /** * WARNING: This code is old, and only supports the file format partially (reverse engineering) * It can break, lock, or hit you in the face in any moment. @@ -38,7 +41,7 @@ class PocketChunkParser{ $this->location = array(); console("[DEBUG] Loading Chunk Location table...", true, true, 2); for($offset = 0; $offset < 0x1000; $offset += 4){ - $data = Utils::readLInt(substr($this->raw, $offset, 4)); + $data = Utils\Utils::readLInt(substr($this->raw, $offset, 4)); $sectors = $data & 0xff; if($sectors === 0){ continue; @@ -96,14 +99,14 @@ class PocketChunkParser{ $chunk .= $data[$i]; } } - return Utils::writeLInt(strlen($chunk)).$chunk; + return Utils\Utils::writeLInt(strlen($chunk)).$chunk; } public function parseChunk($X, $Z){ $X = (int) $X; $Z = (int) $Z; $offset = $this->getOffset($X, $Z); - $len = Utils::readLInt(substr($this->raw, $offset, 4)); + $len = Utils\Utils::readLInt(substr($this->raw, $offset, 4)); $offset += 4; $chunk = array( 0 => array(), //Block diff --git a/src/math/Position.php b/src/level/Position.php similarity index 91% rename from src/math/Position.php rename to src/level/Position.php index 8ccef5e6b..9799eb4b0 100644 --- a/src/math/Position.php +++ b/src/level/Position.php @@ -19,11 +19,14 @@ * */ -class Position extends Vector3{ +namespace PocketMine\Level; +use PocketMine; + +class Position extends Math\Vector3{ public $level; public function __construct($x = 0, $y = 0, $z = 0, Level $level){ - if(($x instanceof Vector3) === true){ + if(($x instanceof Math\Vector3) === true){ $this->__construct($x->x, $x->y, $x->z, $level); }else{ $this->x = $x; diff --git a/src/world/generator/WorldGenerator.php b/src/level/WorldGenerator.php similarity index 73% rename from src/world/generator/WorldGenerator.php rename to src/level/WorldGenerator.php index bc61efb11..f4fcb5baa 100644 --- a/src/world/generator/WorldGenerator.php +++ b/src/level/WorldGenerator.php @@ -19,15 +19,18 @@ * */ +namespace PocketMine\Level; +use PocketMine; + class WorldGenerator{ private $seed, $level, $path, $random, $generator, $height; - public function __construct(LevelGenerator $generator, $name, $seed = false, $height = 8){ - $this->seed = $seed !== false ? (int) $seed:Utils::readInt(Utils::getRandomBytes(4, false)); - $this->random = new Random($this->seed); + public function __construct(Generator\Generator $generator, $name, $seed = false, $height = 8){ + $this->seed = $seed !== false ? (int) $seed:Utils\Utils::readInt(Utils\Utils::getRandomBytes(4, false)); + $this->random = new Utils\Random($this->seed); $this->height = (int) $height; - $this->path = DATA_PATH."worlds/".$name."/"; + $this->path = DATA."worlds/".$name."/"; $this->generator = $generator; - $level = new PMFLevel($this->path."level.pmf", array( + $level = new PMF\Level($this->path."level.pmf", array( "name" => $name, "seed" => $this->seed, "time" => 0, @@ -35,11 +38,11 @@ class WorldGenerator{ "spawnY" => 128, "spawnZ" => 128, "height" => $this->height, - "generator" => get_class($this->generator), + "generator" => $this->generator->getName(), "generatorSettings" => $this->generator->getSettings(), "extra" => "" )); - $blockUpdates = new Config($this->path."bupdates.yml", Config::YAML); + $blockUpdates = new Utils\Config($this->path."bupdates.yml", Utils\Config::YAML); $this->level = new Level($level, $name); } diff --git a/src/world/generator/SuperflatGenerator.php b/src/level/generator/Flat.php similarity index 57% rename from src/world/generator/SuperflatGenerator.php rename to src/level/generator/Flat.php index 0b455d32a..91aec7a97 100644 --- a/src/world/generator/SuperflatGenerator.php +++ b/src/level/generator/Flat.php @@ -19,17 +19,21 @@ * */ -/***REM_START***/ -require_once("LevelGenerator.php"); -/***REM_END***/ +namespace PocketMine\Level\Generator; +use PocketMine\Level; +use PocketMine; -class SuperflatGenerator implements LevelGenerator{ +class Flat extends Generator{ private $level, $random, $structure, $chunks, $options, $floorLevel, $preset, $populators = array(); public function getSettings(){ return $this->options; } + public function getName(){ + return "flat"; + } + public function __construct(array $options = array()){ $this->preset = "2;7,59x1,3x3,2;1;spawn(radius=10 block=89),decoration(treecount=80 grasscount=45)"; $this->options = $options; @@ -39,16 +43,16 @@ class SuperflatGenerator implements LevelGenerator{ $this->parsePreset($this->preset); } if(isset($this->options["decoration"])){ - $ores = new OrePopulator(); + $ores = new Populator\Ore(); $ores->setOreTypes(array( - new OreType(new CoalOreBlock(), 20, 16, 0, 128), - new OreType(New IronOreBlock(), 20, 8, 0, 64), - new OreType(new RedstoneOreBlock(), 8, 7, 0, 16), - new OreType(new LapisOreBlock(), 1, 6, 0, 32), - new OreType(new GoldOreBlock(), 2, 8, 0, 32), - new OreType(new DiamondOreBlock(), 1, 7, 0, 16), - new OreType(new DirtBlock(), 20, 32, 0, 128), - new OreType(new GravelBlock(), 10, 16, 0, 128), + new Object\Ore\Type(new Block\CoalOre(), 20, 16, 0, 128), + new Object\Ore\Type(New Block\IronOre(), 20, 8, 0, 64), + new Object\Ore\Type(new Block\RedstoneOre(), 8, 7, 0, 16), + new Object\Ore\Type(new Block\LapisOre(), 1, 6, 0, 32), + new Object\Ore\Type(new Block\GoldOre(), 2, 8, 0, 32), + new Object\Ore\Type(new Block\DiamondOre(), 1, 7, 0, 16), + new Object\Ore\Type(new Block\Dirt(), 20, 32, 0, 128), + new Object\Ore\Type(new Block\Gravel(), 10, 16, 0, 128), )); $this->populators[] = $ores; } @@ -80,7 +84,7 @@ class SuperflatGenerator implements LevelGenerator{ $this->floorLevel = $y; for(;$y < 0xFF; ++$y){ - $this->structure[$y] = new AirBlock(); + $this->structure[$y] = new Block\Special\Air(); } @@ -136,60 +140,9 @@ class SuperflatGenerator implements LevelGenerator{ } } - public function populateLevel(){ - $this->random->setSeed($this->level->getSeed()); - if(isset($this->options["spawn"])){ - $spawn = array(10, new SandstoneBlock()); - if(isset($this->options["spawn"]["radius"])){ - $spawn[0] = intval($this->options["spawn"]["radius"]); - } - if(isset($this->options["spawn"]["block"])){ - $spawn[1] = BlockAPI::fromString($this->options["spawn"]["block"])->getBlock(); - if(!($spawn[1] instanceof Block)){ - $spawn[1] = new SandstoneBlock(); - } - } - - $start = 128 - $spawn[0]; - $end = 128 + $spawn[0]; - for($x = $start; $x <= $end; ++$x){ - for($z = $start; $z <= $end; ++$z){ - if(floor(sqrt(pow($x - 128, 2) + pow($z - 128, 2))) <= $spawn[0]){ - $this->level->setBlockRaw(new Vector3($x, $this->floorLevel - 1, $z), $spawn[1], null); - } - } - } - } - - if(isset($this->options["decoration"])){ - $treecount = 80; - $grasscount = 120; - if(isset($this->options["spawn"]["treecount"])){ - $treecount = intval($this->options["spawn"]["treecount"]); - } - if(isset($this->options["spawn"]["grasscount"])){ - $grasscount = intval($this->options["spawn"]["grasscount"]); - } - for($t = 0; $t < $treecount; ++$t){ - $centerX = $this->random->nextRange(0, 255); - $centerZ = $this->random->nextRange(0, 255); - $down = $this->level->level->getBlockID($centerX, $this->floorLevel - 1, $centerZ); - if($down === DIRT or $down === GRASS or $down === FARMLAND){ - TreeObject::growTree($this->level, new Vector3($centerX, $this->floorLevel, $centerZ), $this->random, $this->random->nextRange(0,3)); - } - } - for($t = 0; $t < $grasscount; ++$t){ - $centerX = $this->random->nextRange(0, 255); - $centerZ = $this->random->nextRange(0, 255); - $down = $this->level->level->getBlockID($centerX, $this->floorLevel - 1, $centerZ); - if($down === GRASS){ - TallGrassObject::growGrass($this->level, new Vector3($centerX, $this->floorLevel - 1, $centerZ), $this->random, $this->random->nextRange(8, 40)); - } - } - } - } - public function getSpawn(){ - return new Vector3(128, $this->floorLevel, 128); + return new Math\Vector3(128, $this->floorLevel, 128); } -} \ No newline at end of file +} + +Generator::addGenerator(__NAMESPACE__ . "\\Flat", "flat"); diff --git a/src/level/generator/Generator.php b/src/level/generator/Generator.php new file mode 100644 index 000000000..40dcd9946 --- /dev/null +++ b/src/level/generator/Generator.php @@ -0,0 +1,57 @@ +level = $level; $this->random = $random; $this->random->setSeed($this->level->getSeed()); - $this->noiseHills = new NoiseGeneratorSimplex($this->random, 3); - $this->noisePatches = new NoiseGeneratorSimplex($this->random, 2); - $this->noisePatchesSmall = new NoiseGeneratorSimplex($this->random, 2); - $this->noiseBase = new NoiseGeneratorSimplex($this->random, 16); + $this->noiseHills = new Noise\Simplex($this->random, 3); + $this->noisePatches = new Noise\Simplex($this->random, 2); + $this->noisePatchesSmall = new Noise\Simplex($this->random, 2); + $this->noiseBase = new Noise\Simplex($this->random, 16); $ores = new OrePopulator(); $ores->setOreTypes(array( - new OreType(new CoalOreBlock(), 20, 16, 0, 128), - new OreType(New IronOreBlock(), 20, 8, 0, 64), - new OreType(new RedstoneOreBlock(), 8, 7, 0, 16), - new OreType(new LapisOreBlock(), 1, 6, 0, 32), - new OreType(new GoldOreBlock(), 2, 8, 0, 32), - new OreType(new DiamondOreBlock(), 1, 7, 0, 16), - new OreType(new DirtBlock(), 20, 32, 0, 128), - new OreType(new GravelBlock(), 10, 16, 0, 128), + new Object\Ore\Type(new Block\CoalOre(), 20, 16, 0, 128), + new Object\Ore\Type(New Block\IronOre(), 20, 8, 0, 64), + new Object\Ore\Type(new Block\RedstoneOre(), 8, 7, 0, 16), + new Object\Ore\Type(new Block\LapisOre(), 1, 6, 0, 32), + new Object\Ore\Type(new Block\GoldOre(), 2, 8, 0, 32), + new Object\Ore\Type(new Block\DiamondOre(), 1, 7, 0, 16), + new Object\Ore\Type(new Block\Dirt(), 20, 32, 0, 128), + new Object\Ore\Type(new Block\Gravel(), 10, 16, 0, 128), )); $this->populators[] = $ores; - $trees = new TreePopulator(); + $trees = new Populator\Tree(); $trees->setBaseAmount(3); $trees->setRandomAmount(0); $this->populators[] = $trees; - $tallGrass = new TallGrassPopulator(); + $tallGrass = new Populator\TallGrass(); $tallGrass->setBaseAmount(5); $tallGrass->setRandomAmount(0); $this->populators[] = $tallGrass; @@ -164,7 +168,10 @@ class NormalGenerator implements LevelGenerator{ } public function getSpawn(){ - return $this->level->getSafeSpawn(new Vector3(127.5, 128, 127.5)); + return $this->level->getSafeSpawn(new Math\Vector3(127.5, 128, 127.5)); } -} \ No newline at end of file +} + +Generator::addGenerator(__NAMESPACE__ . "\\Normal", "normal"); +Generator::addGenerator(__NAMESPACE__ . "\\Normal", "default"); \ No newline at end of file diff --git a/src/world/generator/noise/NoiseGenerator.php b/src/level/generator/noise/Generator.php similarity index 96% rename from src/world/generator/noise/NoiseGenerator.php rename to src/level/generator/noise/Generator.php index 067e5d517..4c892b502 100644 --- a/src/world/generator/noise/NoiseGenerator.php +++ b/src/level/generator/noise/Generator.php @@ -19,8 +19,11 @@ * */ +namespace PocketMine\Level\Generator\Noise; +use PocketMine; -abstract class NoiseGenerator{ + +abstract class Generator{ protected $perm = array(); protected $offsetX = 0; protected $offsetY = 0; diff --git a/src/world/generator/noise/NoiseGeneratorPerlin.php b/src/level/generator/noise/Perlin.php similarity index 95% rename from src/world/generator/noise/NoiseGeneratorPerlin.php rename to src/level/generator/noise/Perlin.php index c1b78cc6c..e10c2641c 100644 --- a/src/world/generator/noise/NoiseGeneratorPerlin.php +++ b/src/level/generator/noise/Perlin.php @@ -19,11 +19,10 @@ * */ -/***REM_START***/ -require_once("NoiseGenerator.php"); -/***REM_END***/ +namespace PocketMine\Level\Generator; +use PocketMine; -class NoiseGeneratorPerlin extends NoiseGenerator{ +class Perlin extends Generator{ public static $grad3 = [ [1, 1, 0], [-1, 1, 0], [1, -1, 0], [-1, -1, 0], [1, 0, 1], [-1, 0, 1], [1, 0, -1], [-1, 0, -1], diff --git a/src/world/generator/noise/NoiseGeneratorSimplex.php b/src/level/generator/noise/Simplex.php similarity index 94% rename from src/world/generator/noise/NoiseGeneratorSimplex.php rename to src/level/generator/noise/Simplex.php index 3498acbc3..c333b862a 100644 --- a/src/world/generator/noise/NoiseGeneratorSimplex.php +++ b/src/level/generator/noise/Simplex.php @@ -1,9 +1,27 @@ * http://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf */ -class NoiseGeneratorSimplex extends NoiseGeneratorPerlin{ +class Simplex extends Perlin{ protected static $SQRT_3; protected static $SQRT_5; protected static $F2; diff --git a/src/world/generator/object/PondObject.php b/src/level/generator/object/Pond.php similarity index 74% rename from src/world/generator/object/PondObject.php rename to src/level/generator/object/Pond.php index cb76dbb17..4eb8feb44 100644 --- a/src/world/generator/object/PondObject.php +++ b/src/level/generator/object/Pond.php @@ -19,19 +19,22 @@ * */ -class PondObject{ +namespace PocketMine\Level\Generator\Object; +use PocketMine; + +class Pond{ private $random; public $type; - public function __construct(Random $random, Block $type){ + public function __construct(Utils\Random $random, Block\Block $type){ $this->type = $type; $this->random = $random; } - public function canPlaceObject(Level $level, Vector3 $pos){ + public function canPlaceObject(Level\Level $level, Math\Vector3 $pos){ } - public function placeObject(Level $level, Vector3 $pos){ + public function placeObject(Level\Level $level, Math\Vector3 $pos){ } } \ No newline at end of file diff --git a/src/world/generator/object/grass/TallGrassObject.php b/src/level/generator/object/TallGrass.php similarity index 82% rename from src/world/generator/object/grass/TallGrassObject.php rename to src/level/generator/object/TallGrass.php index ad803dc76..6a9dd45d3 100644 --- a/src/world/generator/object/grass/TallGrassObject.php +++ b/src/level/generator/object/TallGrass.php @@ -19,9 +19,12 @@ * */ +namespace PocketMine\Level\Generator\Object; +use PocketMine\Level; +use PocketMine; -class TallGrassObject{ - public static function growGrass(Level $level, Vector3 $pos, Random $random, $count = 15, $radius = 10){ +class TallGrass{ + public static function growGrass(Level $level, Math\Vector3 $pos, Random $random, $count = 15, $radius = 10){ $arr = array( BlockAPI::get(DANDELION, 0), BlockAPI::get(CYAN_FLOWER, 0), @@ -36,7 +39,7 @@ class TallGrassObject{ $z = $random->nextRange($pos->z - $radius, $pos->z + $radius); if($level->level->getBlockID($x, $pos->y + 1, $z) === AIR and $level->level->getBlockID($x, $pos->y, $z) === GRASS){ $t = $arr[$random->nextRange(0, $arrC)]; - $level->setBlockRaw(new Vector3($x, $pos->y + 1, $z), $t); + $level->setBlockRaw(new Math\Vector3($x, $pos->y + 1, $z), $t); } } } diff --git a/src/world/generator/object/OreObject.php b/src/level/generator/object/ore/OreObject.php similarity index 94% rename from src/world/generator/object/OreObject.php rename to src/level/generator/object/ore/OreObject.php index 8700618e4..dc2958a9f 100644 --- a/src/world/generator/object/OreObject.php +++ b/src/level/generator/object/ore/OreObject.php @@ -36,7 +36,7 @@ class OreObject{ return ($level->level->getBlockID($x, $y, $z) != AIR); } - public function placeObject(Level $level, Vector3 $pos){ + public function placeObject(Level $level, Math\Vector3 $pos){ $clusterSize = (int) $this->type->clusterSize; $angle = $this->random->nextFloat() * M_PI; $offset = VectorMath::getDirection2D($angle)->multiply($clusterSize)->divide(8); @@ -74,7 +74,7 @@ class OreObject{ $sizeZ *= $sizeZ; if(($sizeX + $sizeY + $sizeZ) < 1 and $level->level->getBlockID($x, $y, $z) === STONE){ - $level->setBlockRaw(new Vector3($x, $y, $z), $this->type->material); + $level->setBlockRaw(new Math\Vector3($x, $y, $z), $this->type->material); } } } diff --git a/src/world/generator/object/OreType.php b/src/level/generator/object/ore/OreType.php similarity index 100% rename from src/world/generator/object/OreType.php rename to src/level/generator/object/ore/OreType.php diff --git a/src/world/generator/object/tree/BigTreeObject.php b/src/level/generator/object/tree/BigTree.php similarity index 90% rename from src/world/generator/object/tree/BigTreeObject.php rename to src/level/generator/object/tree/BigTree.php index 8c5d5f266..c05d755a3 100644 --- a/src/world/generator/object/tree/BigTreeObject.php +++ b/src/level/generator/object/tree/BigTree.php @@ -19,11 +19,10 @@ * */ -/***REM_START***/ -require_once("src/world/generator/object/tree/TreeObject.php"); -/***REM_END***/ +namespace PocketMine\Level\Generator\Object; +use PocketMine; -class BigTreeObject extends TreeObject{ +class BigTree extends Tree{ private $trunkHeightMultiplier = 0.618; private $trunkHeight; private $leafAmount = 1; @@ -38,11 +37,11 @@ class BigTreeObject extends TreeObject{ private $addLogVines = false; private $addCocoaPlants = false; - public function canPlaceObject(Level $level, Vector3 $pos){ + public function canPlaceObject(Level\Level $level, Math\Vector3 $pos){ return false; } - public function placeObject(Level $level, Vector3 $pos, $type){ + public function placeObject(Level\Level $level, Math\Vector3 $pos, $type){ $this->trunkHeight = (int) ($this->totalHeight * $this->trunkHeightMultiplier); $leaves = $this->getLeafGroupPoints($level, $pos); diff --git a/src/world/generator/object/tree/PineTreeObject.php b/src/level/generator/object/tree/PineTree.php similarity index 79% rename from src/world/generator/object/tree/PineTreeObject.php rename to src/level/generator/object/tree/PineTree.php index 7c31df1fc..59bc0c999 100644 --- a/src/world/generator/object/tree/PineTreeObject.php +++ b/src/level/generator/object/tree/PineTree.php @@ -19,17 +19,16 @@ * */ -/***REM_START***/ -require_once("src/world/generator/object/tree/TreeObject.php"); -/***REM_END***/ +namespace PocketMine\Level\Generator\Object; +use PocketMine; -class PineTreeObject extends TreeObject{ +class PineTree extends Tree{ var $type = 1; private $totalHeight = 8; private $leavesSizeY = -1; private $leavesAbsoluteMaxRadius = -1; - public function canPlaceObject(Level $level, Vector3 $pos, Random $random){ + public function canPlaceObject(Level\Level $level, Math\Vector3 $pos, Random $random){ $this->findRandomLeavesSize($random); $checkRadius = 0; for($yy = 0; $yy < $this->totalHeight; ++$yy) { @@ -47,17 +46,17 @@ class PineTreeObject extends TreeObject{ return true; } - private function findRandomLeavesSize(Random $random){ + private function findRandomLeavesSize(Utils\Random $random){ $this->totalHeight += $random->nextRange(-1, 2); $this->leavesSizeY = 1 + $random->nextRange(0, 2); $this->leavesAbsoluteMaxRadius = 2 + $random->nextRange(0, 1); } - public function placeObject(Level $level, Vector3 $pos, Random $random){ + public function placeObject(Level\Level $level, Math\Vector3 $pos, Utils\Random $random){ if($this->leavesSizeY === -1 or $this->leavesAbsoluteMaxRadius === -1) { $this->findRandomLeavesSize($random); } - $level->setBlockRaw(new Vector3($pos->x, $pos->y - 1, $pos->z), new DirtBlock()); + $level->setBlockRaw(new Math\Vector3($pos->x, $pos->y - 1, $pos->z), new Block\Dirt()); $leavesRadius = 0; $leavesMaxRadius = 1; $leavesBottomY = $this->totalHeight - $this->leavesSizeY; @@ -67,7 +66,7 @@ class PineTreeObject extends TreeObject{ for($xx = -$leavesRadius; $xx <= $leavesRadius; ++$xx) { for($zz = -$leavesRadius; $zz <= $leavesRadius; ++$zz) { if(abs($xx) != $leavesRadius or abs($zz) != $leavesRadius or $leavesRadius <= 0) { - $level->setBlockRaw(new Vector3($pos->x + $xx, $pos->y + $yy, $pos->z + $zz), new LeavesBlock($this->type)); + $level->setBlockRaw(new Math\Vector3($pos->x + $xx, $pos->y + $yy, $pos->z + $zz), new Block\Leaves($this->type)); } } } @@ -83,7 +82,7 @@ class PineTreeObject extends TreeObject{ } $trunkHeightReducer = $random->nextRange(0, 3); for($yy = 0; $yy < ($this->totalHeight - $trunkHeightReducer); ++$yy){ - $level->setBlockRaw(new Vector3($pos->x, $pos->y + $yy, $pos->z), new WoodBlock($this->type)); + $level->setBlockRaw(new Math\Vector3($pos->x, $pos->y + $yy, $pos->z), new Block\Wood($this->type)); } } diff --git a/src/world/generator/object/tree/SmallTreeObject.php b/src/level/generator/object/tree/SmallTree.php similarity index 79% rename from src/world/generator/object/tree/SmallTreeObject.php rename to src/level/generator/object/tree/SmallTree.php index 7bb7e6003..e3509a174 100644 --- a/src/world/generator/object/tree/SmallTreeObject.php +++ b/src/level/generator/object/tree/SmallTree.php @@ -19,11 +19,10 @@ * */ -/***REM_START***/ -require_once("TreeObject.php"); -/***REM_END***/ +namespace PocketMine\Level\Generator\Object; +use PocketMine; -class SmallTreeObject extends TreeObject{ +class SmallTree extends Tree{ public $type = 0; private $trunkHeight = 5; private static $leavesHeight = 4; // All trees appear to be 4 tall @@ -33,7 +32,7 @@ class SmallTreeObject extends TreeObject{ private $addLogVines = false; private $addCocoaPlants = false; - public function canPlaceObject(Level $level, Vector3 $pos, Random $random){ + public function canPlaceObject(Level\Level $level, Math\Vector3 $pos, Utils\Random $random){ $radiusToCheck = 0; for ($yy = 0; $yy < $this->trunkHeight + 3; ++$yy) { if($yy == 1 or $yy === $this->trunkHeight) { @@ -50,10 +49,10 @@ class SmallTreeObject extends TreeObject{ return true; } - public function placeObject(Level $level, Vector3 $pos, Random $random){ + public function placeObject(Level\Level $level, Math\Vector3 $pos, Utils\Random $random){ // The base dirt block - $dirtpos = new Vector3( $pos->x, $pos->y - 1, $pos->z ); - $level->setBlockRaw( $dirtpos, new DirtBlock() ); + $dirtpos = new Math\Vector3( $pos->x, $pos->y - 1, $pos->z ); + $level->setBlockRaw( $dirtpos, new Block\Dirt() ); // Adjust the tree trunk's height randomly // plot [-14:11] int( x / 8 ) + 5 @@ -72,8 +71,7 @@ class SmallTreeObject extends TreeObject{ $leaflevel = 0; for( $yy = ($this->trunkHeight + 1); $yy >= 0; --$yy ) { - if( $leaflevel < self::$leavesHeight ) - { + if( $leaflevel < self::$leavesHeight ){ // The size is a slight variation on the trunkheight $radius = self::$leafRadii[ $leaflevel ] + $leafPre; $bRadius = 3; @@ -83,10 +81,10 @@ class SmallTreeObject extends TreeObject{ { if( sqrt(($xx * $xx) + ($zz * $zz)) <= $radius ) { - $leafpos = new Vector3( $pos->x + $xx, + $leafpos = new Math\Vector3( $pos->x + $xx, $pos->y + $yy, $pos->z + $zz ); - $level->setBlockRaw($leafpos, new LeavesBlock( $this->type ) ); + $level->setBlockRaw($leafpos, new Block\Leaves($this->type) ); } } } @@ -96,8 +94,8 @@ class SmallTreeObject extends TreeObject{ // Place the trunk last if($leaflevel > 1) { - $trunkpos = new Vector3( $pos->x, $pos->y + $yy, $pos->z ); - $level->setBlockRaw($trunkpos, new WoodBlock( $this->type ) ); + $trunkpos = new Math\Vector3( $pos->x, $pos->y + $yy, $pos->z ); + $level->setBlockRaw($trunkpos, new Block\Wood($this->type)); } } } diff --git a/src/world/generator/object/tree/SpruceTreeObject.php b/src/level/generator/object/tree/SpruceTree.php similarity index 76% rename from src/world/generator/object/tree/SpruceTreeObject.php rename to src/level/generator/object/tree/SpruceTree.php index 40c8b361a..4c8afcb4a 100644 --- a/src/world/generator/object/tree/SpruceTreeObject.php +++ b/src/level/generator/object/tree/SpruceTree.php @@ -19,17 +19,16 @@ * */ -/***REM_START***/ -require_once("src/world/generator/object/tree/TreeObject.php"); -/***REM_END***/ +namespace PocketMine\Level\Generator\Object; +use PocketMine; -class SpruceTreeObject extends TreeObject{ +class SpruceTree extends Tree{ var $type = 1; private $totalHeight = 8; private $leavesBottomY = -1; private $leavesMaxRadius = -1; - public function canPlaceObject(Level $level, Vector3 $pos, Random $random){ + public function canPlaceObject(Level\Level $level, Math\Vector3 $pos, Utils\Random $random){ $this->findRandomLeavesSize($random); $checkRadius = 0; for($yy = 0; $yy < $this->totalHeight + 2; ++$yy) { @@ -47,23 +46,23 @@ class SpruceTreeObject extends TreeObject{ return true; } - private function findRandomLeavesSize(Random $random){ + private function findRandomLeavesSize(Utils\Random $random){ $this->totalHeight += $random->nextRange(-1, 2); $this->leavesBottomY = (int) ($this->totalHeight - $random->nextRange(1, 2) - 3); $this->leavesMaxRadius = 1 + $random->nextRange(0, 1); } - public function placeObject(Level $level, Vector3 $pos, Random $random){ + public function placeObject(Level\Level $level, Math\Vector3 $pos, Utils\Random $random){ if($this->leavesBottomY === -1 or $this->leavesMaxRadius === -1) { $this->findRandomLeavesSize($random); } - $level->setBlockRaw(new Vector3($pos->x, $pos->y - 1, $pos->z), new DirtBlock()); + $level->setBlockRaw(new Math\Vector3($pos->x, $pos->y - 1, $pos->z), new Block\Dirt()); $leavesRadius = 0; for($yy = $this->totalHeight; $yy >= $this->leavesBottomY; --$yy){ for($xx = -$leavesRadius; $xx <= $leavesRadius; ++$xx) { for($zz = -$leavesRadius; $zz <= $leavesRadius; ++$zz) { if(abs($xx) != $leavesRadius or abs($zz) != $leavesRadius or $leavesRadius <= 0) { - $level->setBlockRaw(new Vector3($pos->x + $xx, $pos->y + $yy, $pos->z + $zz), new LeavesBlock($this->type)); + $level->setBlockRaw(new Math\Vector3($pos->x + $xx, $pos->y + $yy, $pos->z + $zz), new Block\Leaves($this->type)); } } } @@ -74,7 +73,7 @@ class SpruceTreeObject extends TreeObject{ } } for($yy = 0; $yy < ($this->totalHeight - 1); ++$yy){ - $level->setBlockRaw(new Vector3($pos->x, $pos->y + $yy, $pos->z), new WoodBlock($this->type)); + $level->setBlockRaw(new Math\Vector3($pos->x, $pos->y + $yy, $pos->z), new Block\Wood($this->type)); } } diff --git a/src/world/generator/object/tree/TreeObject.php b/src/level/generator/object/tree/Tree.php similarity index 74% rename from src/world/generator/object/tree/TreeObject.php rename to src/level/generator/object/tree/Tree.php index 02a87fb1a..e6110876f 100644 --- a/src/world/generator/object/tree/TreeObject.php +++ b/src/level/generator/object/tree/Tree.php @@ -19,8 +19,10 @@ * */ +namespace PocketMine\Level\Generator\Object; +use PocketMine; -class TreeObject{ +class Tree{ public $overridable = array( 0 => true, 2 => true, @@ -30,29 +32,29 @@ class TreeObject{ 18 => true, ); - public static function growTree(Level $level, Vector3 $pos, Random $random, $type = 0){ + public static function growTree(Level\Level $level, Math\Vector3 $pos, Level\Random $random, $type = 0){ switch($type & 0x03){ case SaplingBlock::SPRUCE: if($random->nextRange(0, 1) === 1){ - $tree = new SpruceTreeObject(); + $tree = new SpruceTree(); }else{ - $tree = new PineTreeObject(); + $tree = new PineTree(); } break; case SaplingBlock::BIRCH: - $tree = new SmallTreeObject(); - $tree->type = SaplingBlock::BIRCH; + $tree = new SmallTree(); + $tree->type = Block\Sapling::BIRCH; break; case SaplingBlock::JUNGLE: - $tree = new SmallTreeObject(); - $tree->type = SaplingBlock::JUNGLE; + $tree = new SmallTree(); + $tree->type = Block\Sapling::JUNGLE; break; case SaplingBlock::OAK: default: /*if($random->nextRange(0, 9) === 0){ - $tree = new BigTreeObject(); + $tree = new BigTree(); }else{*/ - $tree = new SmallTreeObject(); + $tree = new SmallTree(); //} break; } diff --git a/src/world/generator/populator/MineshaftPopulator.php b/src/level/generator/populator/Mineshaft.php similarity index 79% rename from src/world/generator/populator/MineshaftPopulator.php rename to src/level/generator/populator/Mineshaft.php index 5bbe5b86a..9f582f526 100644 --- a/src/world/generator/populator/MineshaftPopulator.php +++ b/src/level/generator/populator/Mineshaft.php @@ -19,15 +19,18 @@ * */ -class MineshaftPopulator extends Populator{ +namespace PocketMine\Level\Generator\Populator; +use PocketMine; + +class Mineshaft extends Populator{ private static $DISTANCE = 256; private static $VARIATION = 16; private static $ODD = 3; private static $BASE_Y = 35; private static $RAND_Y = 11; - public function populate(Level $level, $chunkX, $chunkZ, Random $random){ - if($random->nextRange(0, MineshaftPopulator::$ODD) === 0){ + public function populate(Level\Level $level, $chunkX, $chunkZ, Utils\Random $random){ + if($random->nextRange(0, self::$ODD) === 0){ //$mineshaft = new Mineshaft($random); } } diff --git a/src/world/generator/populator/OrePopulator.php b/src/level/generator/populator/Ore.php similarity index 79% rename from src/world/generator/populator/OrePopulator.php rename to src/level/generator/populator/Ore.php index 8e5269fdb..d96783166 100644 --- a/src/world/generator/populator/OrePopulator.php +++ b/src/level/generator/populator/Ore.php @@ -19,17 +19,20 @@ * */ -class OrePopulator extends Populator{ +namespace PocketMine\Level\Generator\Populator; +use PocketMine; + +class Ore extends Populator{ private $oreTypes = array(); - public function populate(Level $level, $chunkX, $chunkZ, Random $random){ + public function populate(Level\Level $level, $chunkX, $chunkZ, Utils\Random $random){ foreach($this->oreTypes as $type){ - $ore = new OreObject($random, $type); + $ore = new Level\Generator\Object\Ore($random, $type); for($i = 0; $i < $ore->type->clusterCount; ++$i){ $x = $random->nextRange($chunkX << 4, ($chunkX << 4) + 15); $y = $random->nextRange($ore->type->minHeight, $ore->type->maxHeight); $z = $random->nextRange($chunkZ << 4, ($chunkZ << 4) + 15); if($ore->canPlaceObject($level, $x, $y, $z)){ - $ore->placeObject($level, new Vector3($x, $y, $z)); + $ore->placeObject($level, new Math\Vector3($x, $y, $z)); } } } diff --git a/src/world/generator/populator/PondPopulator.php b/src/level/generator/populator/Pond.php similarity index 82% rename from src/world/generator/populator/PondPopulator.php rename to src/level/generator/populator/Pond.php index 3dd6b2116..1ab9c9aee 100644 --- a/src/world/generator/populator/PondPopulator.php +++ b/src/level/generator/populator/Pond.php @@ -19,18 +19,21 @@ * */ -class PondPopulator extends Populator{ +namespace PocketMine\Level\Generator\Populator; +use PocketMine; + +class Pond extends Populator{ private $waterOdd = 4; private $lavaOdd = 4; private $lavaSurfaceOdd = 4; - public function populate(Level $level, $chunkX, $chunkZ, Random $random){ + public function populate(Level\Level $level, $chunkX, $chunkZ, Utils\Random $random){ if($random->nextRange(0, $this->waterOdd) === 0){ - $v = new Vector3( + $v = new Math\Vector3( $random->nextRange($chunkX << 4, ($chunkX << 4) + 16), $random->nextRange(0, 128), $random->nextRange($chunkZ << 4, ($chunkZ << 4) + 16) ); - $pond = new PondObject($random, new WaterBlock()); + $pond = new Level\Genenerator\Object\Pond($random, new Block\Water()); if($pond->canPlaceObject($level, $v)){ $pond->placeObject($level, $v); } diff --git a/src/world/generator/Populator.php b/src/level/generator/populator/Populator.php similarity index 82% rename from src/world/generator/Populator.php rename to src/level/generator/populator/Populator.php index b07a21395..6a84e3edd 100644 --- a/src/world/generator/Populator.php +++ b/src/level/generator/populator/Populator.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine\Level\Generator\Populator; +use PocketMine; + abstract class Populator{ - public abstract function populate(Level $level, $chunkX, $chunkZ, Random $random); + public abstract function populate(Level\Level $level, $chunkX, $chunkZ, Utils\Random $random); } \ No newline at end of file diff --git a/src/world/generator/populator/TallGrassPopulator.php b/src/level/generator/populator/TallGrass.php similarity index 87% rename from src/world/generator/populator/TallGrassPopulator.php rename to src/level/generator/populator/TallGrass.php index 34b7e5a20..30d1707ae 100644 --- a/src/world/generator/populator/TallGrassPopulator.php +++ b/src/level/generator/populator/TallGrass.php @@ -19,7 +19,10 @@ * */ -class TallGrassPopulator extends Populator{ +namespace PocketMine\Level\Generator\Populator; +use PocketMine; + +class TallGrass extends Populator{ private $level; private $randomAmount; private $baseAmount; @@ -42,9 +45,9 @@ class TallGrassPopulator extends Populator{ $xx = $x - 7 + $random->nextRange(0, 15); $zz = $z - 7 + $random->nextRange(0, 15); $yy = $this->getHighestWorkableBlock($xx, $zz); - $vector = new Vector3($xx, $yy, $zz); + $vector = new Math\Vector3($xx, $yy, $zz); if($yy !== -1 and $this->canTallGrassStay($this->level->getBlockRaw($vector))){ - $this->level->setBlockRaw($vector, new TallGrassBlock(1)); + $this->level->setBlockRaw($vector, new Block\TallGrass(1)); } } } @@ -56,7 +59,7 @@ class TallGrassPopulator extends Populator{ private function getHighestWorkableBlock($x, $z){ for($y = 128; $y > 0; --$y){ - $b = $this->level->getBlockRaw(new Vector3($x, $y, $z)); + $b = $this->level->getBlockRaw(new Math\Vector3($x, $y, $z)); if($b->getID() === AIR or $b->getID() === LEAVES){ if(--$y <= 0){ return -1; diff --git a/src/world/generator/populator/TreePopulator.php b/src/level/generator/populator/Tree.php similarity index 83% rename from src/world/generator/populator/TreePopulator.php rename to src/level/generator/populator/Tree.php index 010cab6e4..f707cb7d7 100644 --- a/src/world/generator/populator/TreePopulator.php +++ b/src/level/generator/populator/Tree.php @@ -19,7 +19,10 @@ * */ -class TreePopulator extends Populator{ +namespace PocketMine\Level\Generator\Populator; +use PocketMine; + +class Tree extends Populator{ private $level; private $randomAmount; private $baseAmount; @@ -32,7 +35,7 @@ class TreePopulator extends Populator{ $this->baseAmount = $amount; } - public function populate(Level $level, $chunkX, $chunkZ, Random $random){ + public function populate(Level\Level $level, $chunkX, $chunkZ, Utils\Random $random){ $this->level = $level; $amount = $random->nextRange(0, $this->randomAmount + 1) + $this->baseAmount; for($i = 0; $i < $amount; ++$i){ @@ -47,13 +50,13 @@ class TreePopulator extends Populator{ }else{ $meta = SaplingBlock::OAK; } - TreeObject::growTree($this->level, new Vector3($x, $y, $z), $random, $meta); + TreeObject::growTree($this->level, new Math\Vector3($x, $y, $z), $random, $meta); } } private function getHighestWorkableBlock($x, $z){ for($y = 128; $y > 0; --$y){ - $b = $this->level->getBlockRaw(new Vector3($x, $y, $z)); + $b = $this->level->getBlockRaw(new Math\Vector3($x, $y, $z)); if($b->getID() !== DIRT and $b->getID() !== GRASS){ if(--$y <= 0){ return -1; diff --git a/src/math/AxisAlignedBB.php b/src/math/AxisAlignedBB.php index 3d2906a03..ccc18fa14 100644 --- a/src/math/AxisAlignedBB.php +++ b/src/math/AxisAlignedBB.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine\Math; +use PocketMine; + class AxisAlignedBB{ public $minX; public $minY; @@ -192,7 +195,7 @@ class AxisAlignedBB{ return $bb->maxZ > $this->minZ and $bb->minZ < $this->maxZ; } - public function isVectorInside(Vector3 $vector){ + public function isVectorInside(Math\Vector3 $vector){ if($vector->x <= $this->minX or $vector->x >= $this->maxX){ return false; } @@ -206,15 +209,15 @@ class AxisAlignedBB{ return ($this->maxX - $this->minX + $this->maxY - $this->minY + $this->maxZ - $this->minZ) / 3; } - public function isVectorInYZ(Vector3 $vector){ + public function isVectorInYZ(Math\Vector3 $vector){ return $vector->y >= $this->minY and $vector->y <= $this->maxY and $vector->z >= $this->minZ and $vector->z <= $this->maxZ; } - public function isVectorInXZ(Vector3 $vector){ + public function isVectorInXZ(Math\Vector3 $vector){ return $vector->x >= $this->minX and $vector->x <= $this->maxX and $vector->z >= $this->minZ and $vector->z <= $this->maxZ; } - public function isVectorInXY(Vector3 $vector){ + public function isVectorInXY(Math\Vector3 $vector){ return $vector->x >= $this->minX and $vector->x <= $this->maxX and $vector->y >= $this->minY and $vector->y <= $this->maxY; } diff --git a/src/math/Matrix.php b/src/math/Matrix.php index e3932b038..7d8ba3a7c 100644 --- a/src/math/Matrix.php +++ b/src/math/Matrix.php @@ -19,7 +19,10 @@ * */ -class Matrix implements ArrayAccess{ +namespace PocketMine\Math; +use PocketMine; + +class Matrix implements \ArrayAccess{ private $matrix = array(); private $rows = 0; private $columns = 0; diff --git a/src/math/Vector2.php b/src/math/Vector2.php index 5d9bd4ca2..5e92685bf 100644 --- a/src/math/Vector2.php +++ b/src/math/Vector2.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine\Math; +use PocketMine; + class Vector2{ public $x, $y; @@ -49,7 +52,7 @@ class Vector2{ }else{ $this->x += $x; $this->y += $y; - return new Vector3($this->x + $x, $this->y + $y); + return new Math\Vector3($this->x + $x, $this->y + $y); } } diff --git a/src/math/Vector3.php b/src/math/Vector3.php index 224470e34..726a97926 100644 --- a/src/math/Vector3.php +++ b/src/math/Vector3.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine\Math; +use PocketMine; + class Vector3{ public $x, $y, $z; @@ -73,15 +76,15 @@ class Vector3{ } public function add($x = 0, $y = 0, $z = 0){ - if(($x instanceof Vector3) === true){ + if(($x instanceof Math\Vector3) === true){ return $this->add($x->x, $x->y, $x->z); }else{ - return new Vector3($this->x + $x, $this->y + $y, $this->z + $z); + return new Math\Vector3($this->x + $x, $this->y + $y, $this->z + $z); } } public function subtract($x = 0, $y = 0, $z = 0){ - if(($x instanceof Vector3) === true){ + if(($x instanceof Math\Vector3) === true){ return $this->add(-$x->x, -$x->y, -$x->z); }else{ return $this->add(-$x, -$y, -$z); @@ -89,50 +92,50 @@ class Vector3{ } public function multiply($number){ - return new Vector3($this->x * $number, $this->y * $number, $this->z * $number); + return new Math\Vector3($this->x * $number, $this->y * $number, $this->z * $number); } public function divide($number){ - return new Vector3($this->x / $number, $this->y / $number, $this->z / $number); + return new Math\Vector3($this->x / $number, $this->y / $number, $this->z / $number); } public function ceil(){ - return new Vector3((int) ($this->x + 1), (int) ($this->y + 1), (int) ($this->z + 1)); + return new Math\Vector3((int) ($this->x + 1), (int) ($this->y + 1), (int) ($this->z + 1)); } public function floor(){ - return new Vector3((int) $this->x, (int) $this->y, (int) $this->z); + return new Math\Vector3((int) $this->x, (int) $this->y, (int) $this->z); } public function round(){ - return new Vector3(round($this->x), round($this->y), round($this->z)); + return new Math\Vector3(round($this->x), round($this->y), round($this->z)); } public function abs(){ - return new Vector3(abs($this->x), abs($this->y), abs($this->z)); + return new Math\Vector3(abs($this->x), abs($this->y), abs($this->z)); } public function getSide($side){ switch((int) $side){ case 0: - return new Vector3($this->x, $this->y - 1, $this->z); + return new Math\Vector3($this->x, $this->y - 1, $this->z); case 1: - return new Vector3($this->x, $this->y + 1, $this->z); + return new Math\Vector3($this->x, $this->y + 1, $this->z); case 2: - return new Vector3($this->x, $this->y, $this->z - 1); + return new Math\Vector3($this->x, $this->y, $this->z - 1); case 3: - return new Vector3($this->x, $this->y, $this->z + 1); + return new Math\Vector3($this->x, $this->y, $this->z + 1); case 4: - return new Vector3($this->x - 1, $this->y, $this->z); + return new Math\Vector3($this->x - 1, $this->y, $this->z); case 5: - return new Vector3($this->x + 1, $this->y, $this->z); + return new Math\Vector3($this->x + 1, $this->y, $this->z); default: return $this; } } public function distance($x = 0, $y = 0, $z = 0){ - if(($x instanceof Vector3) === true){ + if(($x instanceof Math\Vector3) === true){ return sqrt($this->distanceSquared($x->x, $x->y, $x->z)); }else{ return sqrt($this->distanceSquared($x, $y, $z)); @@ -140,7 +143,7 @@ class Vector3{ } public function distanceSquared($x = 0, $y = 0, $z = 0){ - if(($x instanceof Vector3) === true){ + if(($x instanceof Math\Vector3) === true){ return $this->distanceSquared($x->x, $x->y, $x->z); }else{ return pow($this->x - $x, 2) + pow($this->y - $y, 2) + pow($this->z - $z, 2); @@ -148,7 +151,7 @@ class Vector3{ } public function maxPlainDistance($x = 0, $z = 0){ - if(($x instanceof Vector3) === true){ + if(($x instanceof Math\Vector3) === true){ return $this->maxPlainDistance($x->x, $x->z); }else{ return max(abs($this->x - $x), abs($this->z - $z)); @@ -168,15 +171,15 @@ class Vector3{ if($len != 0){ return $this->divide($len); } - return new Vector3(0, 0, 0); + return new Math\Vector3(0, 0, 0); } - public function dot(Vector3 $v){ + public function dot(Math\Vector3 $v){ return $this->x * $v->x + $this->y * $v->y + $this->z * $v->z; } - public function cross(Vector3 $v){ - return new Vector3( + public function cross(Math\Vector3 $v){ + return new Math\Vector3( $this->y * $v->z - $this->z * $v->y, $this->z * $v->x - $this->x * $v->z, $this->x * $v->y - $this->y * $v->x diff --git a/src/math/VectorMath.php b/src/math/VectorMath.php index 653567a66..b5be48a09 100644 --- a/src/math/VectorMath.php +++ b/src/math/VectorMath.php @@ -19,7 +19,10 @@ * */ -class VectorMath{ +namespace PocketMine\Math; +use PocketMine; + +abstract class VectorMath{ public static function getDirection2D($azimuth){ return new Vector2(cos($azimuth), sin($azimuth)); diff --git a/src/nbt/NBT.php b/src/nbt/NBT.php index 20e3d7a92..ed5fb12ab 100644 --- a/src/nbt/NBT.php +++ b/src/nbt/NBT.php @@ -19,10 +19,12 @@ * */ -class NBT implements ArrayAccess{ - const LITTLE_ENDIAN = 0; - const BIG_ENDIAN = 1; +namespace PocketMine\NBT; +const LITTLE_ENDIAN = 0; +const BIG_ENDIAN = 1; +use PocketMine; +class NBT implements \ArrayAccess{ private $buffer; private $offset; private $endianness; @@ -51,7 +53,7 @@ class NBT implements ArrayAccess{ return !isset($this->buffer{$this->offset}); } - public function __construct($endianness = NBT::LITTLE_ENDIAN){ + public function __construct($endianness = NBT\LITTLE_ENDIAN){ $this->offset = 0; $this->endianness = $endianness & 0x01; } @@ -65,7 +67,7 @@ class NBT implements ArrayAccess{ public function write(){ $this->offset = 0; - if($this->data instanceof NBTTag_Compound){ + if($this->data instanceof NBT\Tag\Compound){ $this->writeTag($this->data); return $this->buffer; }else{ @@ -75,58 +77,58 @@ class NBT implements ArrayAccess{ public function readTag(){ switch($this->getByte()){ - case NBTTag::TAG_Byte: - $tag = new NBTTag_Byte($this->getString()); + case NBT\TAG_Byte: + $tag = new NBT\Tag\Byte($this->getString()); $tag->read($this); break; - case NBTTag::TAG_Byte: - $tag = new NBTTag_Byte($this->getString()); + case NBT\TAG_Byte: + $tag = new NBT\Tag\Byte($this->getString()); $tag->read($this); break; - case NBTTag::TAG_Short: - $tag = new NBTTag_Short($this->getString()); + case NBT\TAG_Short: + $tag = new NBT\Tag\Short($this->getString()); $tag->read($this); break; - case NBTTag::TAG_Int: - $tag = new NBTTag_Int($this->getString()); + case NBT\TAG_Int: + $tag = new NBT\Tag\Int($this->getString()); $tag->read($this); break; - case NBTTag::TAG_Long: - $tag = new NBTTag_Long($this->getString()); + case NBT\TAG_Long: + $tag = new NBT\Tag\Long($this->getString()); $tag->read($this); break; - case NBTTag::TAG_Float: - $tag = new NBTTag_Float($this->getString()); + case NBT\TAG_Float: + $tag = new NBT\Tag\Float($this->getString()); $tag->read($this); break; - case NBTTag::TAG_Double: - $tag = new NBTTag_Double($this->getString()); + case NBT\TAG_Double: + $tag = new NBT\Tag\Double($this->getString()); $tag->read($this); break; - case NBTTag::TAG_Byte_Array: - $tag = new NBTTag_Byte_Array($this->getString()); + case NBT\TAG_Byte_Array: + $tag = new NBT\Tag\Byte_Array($this->getString()); $tag->read($this); break; - case NBTTag::TAG_String: - $tag = new NBTTag_String($this->getString()); + case NBT\TAG_String: + $tag = new NBT\Tag\String($this->getString()); $tag->read($this); break; - case NBTTag::TAG_List: - $tag = new NBTTag_List($this->getString()); + case NBT\TAG_Enum: + $tag = new NBT\Tag\Enum($this->getString()); $tag->read($this); break; - case NBTTag::TAG_Compound: - $tag = new NBTTag_Compound($this->getString()); + case NBT\TAG_Compound: + $tag = new NBT\Tag\Compound($this->getString()); $tag->read($this); break; - case NBTTag::TAG_Int_Array: - $tag = new NBTTag_Int_Array($this->getString()); + case NBT\TAG_Int_Array: + $tag = new NBT\Tag\Int_Array($this->getString()); $tag->read($this); break; - case NBTTag::TAG_End: //No named tag + case NBT\TAG_End: //No named tag default: - $tag = new NBTTag_End; + $tag = new NBT\Tag\End; break; } return $tag; @@ -149,43 +151,43 @@ class NBT implements ArrayAccess{ } public function getShort(){ - return $this->endianness === self::BIG_ENDIAN ? Utils::readShort($this->get(2)) : Utils::readLShort($this->get(2)); + return $this->endianness === self::BIG_ENDIAN ? Utils\Utils::readShort($this->get(2)) : Utils\Utils::readLShort($this->get(2)); } public function putShort($v){ - $this->buffer .= $this->endianness === self::BIG_ENDIAN ? Utils::writeShort($v) : Utils::writeLShort($v); + $this->buffer .= $this->endianness === self::BIG_ENDIAN ? Utils\Utils::writeShort($v) : Utils\Utils::writeLShort($v); } public function getInt(){ - return $this->endianness === self::BIG_ENDIAN ? Utils::readInt($this->get(4)) : Utils::readLInt($this->get(4)); + return $this->endianness === self::BIG_ENDIAN ? Utils\Utils::readInt($this->get(4)) : Utils\Utils::readLInt($this->get(4)); } public function putInt($v){ - $this->buffer .= $this->endianness === self::BIG_ENDIAN ? Utils::writeInt($v) : Utils::writeLInt($v); + $this->buffer .= $this->endianness === self::BIG_ENDIAN ? Utils\Utils::writeInt($v) : Utils\Utils::writeLInt($v); } public function getLong(){ - return $this->endianness === self::BIG_ENDIAN ? Utils::readLong($this->get(8)) : Utils::readLLong($this->get(8)); + return $this->endianness === self::BIG_ENDIAN ? Utils\Utils::readLong($this->get(8)) : Utils\Utils::readLLong($this->get(8)); } public function putLong($v){ - $this->buffer .= $this->endianness === self::BIG_ENDIAN ? Utils::writeLong($v) : Utils::writeLLong($v); + $this->buffer .= $this->endianness === self::BIG_ENDIAN ? Utils\Utils::writeLong($v) : Utils\Utils::writeLLong($v); } public function getFloat(){ - return $this->endianness === self::BIG_ENDIAN ? Utils::readFloat($this->get(4)) : Utils::readLFloat($this->get(4)); + return $this->endianness === self::BIG_ENDIAN ? Utils\Utils::readFloat($this->get(4)) : Utils\Utils::readLFloat($this->get(4)); } public function putFloat($v){ - $this->buffer .= $this->endianness === self::BIG_ENDIAN ? Utils::writeFloat($v) : Utils::writeLFloat($v); + $this->buffer .= $this->endianness === self::BIG_ENDIAN ? Utils\Utils::writeFloat($v) : Utils\Utils::writeLFloat($v); } public function getDouble(){ - return $this->endianness === self::BIG_ENDIAN ? Utils::readDouble($this->get(8)) : Utils::readLDouble($this->get(8)); + return $this->endianness === self::BIG_ENDIAN ? Utils\Utils::readDouble($this->get(8)) : Utils\Utils::readLDouble($this->get(8)); } public function putDouble($v){ - $this->buffer .= $this->endianness === self::BIG_ENDIAN ? Utils::writeDouble($v) : Utils::writeLDouble($v); + $this->buffer .= $this->endianness === self::BIG_ENDIAN ? Utils\Utils::writeDouble($v) : Utils\Utils::writeLDouble($v); } public function getString(){ @@ -198,22 +200,22 @@ class NBT implements ArrayAccess{ } public function &__get($name){ - $ret = $this->data instanceof NBTTag_Compound ? $this->data[$name] : false; + $ret = $this->data instanceof NBT\Tag\Compound ? $this->data[$name] : false; return $ret; } public function __set($name, $value){ - if($this->data instanceof NBTTag_Compound){ + if($this->data instanceof NBT\Tag\Compound){ $this->data[$name] = $value; } } public function __isset($name){ - return $this->data instanceof NBTTag_Compound ? isset($this->data[$name]) : false; + return $this->data instanceof NBT\Tag\Compound ? isset($this->data[$name]) : false; } public function __unset($name){ - if($this->data instanceof NBTTag_Compound){ + if($this->data instanceof NBT\Tag\Compound){ unset($this->data[$name]); } } @@ -238,7 +240,7 @@ class NBT implements ArrayAccess{ return $this->data; } - public function setData(NBTTag_Compound $data){ + public function setData(NBT\Tag\Compound $data){ $this->data = $data; } diff --git a/src/nbt/NBTTag.php b/src/nbt/NBTTag.php index b75ccc77f..91ee9ebc4 100644 --- a/src/nbt/NBTTag.php +++ b/src/nbt/NBTTag.php @@ -19,19 +19,22 @@ * */ +namespace PocketMine\NBT; +const TAG_End = 0; +const TAG_Byte = 1; +const TAG_Short = 2; +const TAG_Int = 3; +const TAG_Long = 4; +const TAG_Float = 5; +const TAG_Double = 6; +const TAG_Byte_Array = 7; +const TAG_String = 8; +const TAG_Enum = 9; +const TAG_Compound = 10; +const TAG_Int_Array = 11; +use PocketMine; + abstract class NBTTag{ - const TAG_End = 0; - const TAG_Byte = 1; - const TAG_Short = 2; - const TAG_Int = 3; - const TAG_Long = 4; - const TAG_Float = 5; - const TAG_Double = 6; - const TAG_Byte_Array = 7; - const TAG_String = 8; - const TAG_List = 9; - const TAG_Compound = 10; - const TAG_Int_Array = 11; protected $value; diff --git a/src/nbt/NamedNBTTag.php b/src/nbt/NamedNBTTag.php index afdcb3416..6985c632e 100644 --- a/src/nbt/NamedNBTTag.php +++ b/src/nbt/NamedNBTTag.php @@ -19,9 +19,8 @@ * */ -/***REM_START***/ -require_once("NBTTag.php"); -/***REM_END***/ +namespace PocketMine\NBT; +use PocketMine; abstract class NamedNBTTag extends NBTTag{ diff --git a/src/nbt/tags/TAG_Byte.php b/src/nbt/tag/Byte.php similarity index 87% rename from src/nbt/tags/TAG_Byte.php rename to src/nbt/tag/Byte.php index 836e08e9c..812f45ce7 100644 --- a/src/nbt/tags/TAG_Byte.php +++ b/src/nbt/tag/Byte.php @@ -19,10 +19,14 @@ * */ -class NBTTag_Byte extends NamedNBTTag{ +namespace PocketMine\NBT\Tag; +use PocketMine\NBT; +use PocketMine; + +class Byte extends NamedNBTTag{ public function getType(){ - return NBTTag::TAG_Byte; + return NBT\TAG_Byte; } public function read(NBT $nbt){ diff --git a/src/nbt/tags/TAG_Byte_Array.php b/src/nbt/tag/Byte_Array.php similarity index 87% rename from src/nbt/tags/TAG_Byte_Array.php rename to src/nbt/tag/Byte_Array.php index 79c0099c6..677674d02 100644 --- a/src/nbt/tags/TAG_Byte_Array.php +++ b/src/nbt/tag/Byte_Array.php @@ -19,10 +19,14 @@ * */ -class NBTTag_Byte_Array extends NamedNBTTag{ +namespace PocketMine\NBT\Tag; +use PocketMine\NBT; +use PocketMine; + +class Byte_Array extends NamedNBTTag{ public function getType(){ - return NBTTag::TAG_Byte_Array; + return NBT\TAG_Byte_Array; } public function read(NBT $nbt){ diff --git a/src/nbt/tags/TAG_Compound.php b/src/nbt/tag/Compound.php similarity index 87% rename from src/nbt/tags/TAG_Compound.php rename to src/nbt/tag/Compound.php index 67ffc9baa..fb34dc74b 100644 --- a/src/nbt/tags/TAG_Compound.php +++ b/src/nbt/tag/Compound.php @@ -19,10 +19,14 @@ * */ -class NBTTag_Compound extends NamedNBTTag implements ArrayAccess, Iterator{ +namespace PocketMine\NBT\Tag; +use PocketMine\NBT; +use PocketMine; + +class Compound extends NamedNBTTag implements \ArrayAccess, \Iterator{ public function getType(){ - return NBTTag::TAG_Compound; + return NBT\TAG_Compound; } public function rewind(){ @@ -97,18 +101,18 @@ class NBTTag_Compound extends NamedNBTTag implements ArrayAccess, Iterator{ $tag = $nbt->readTag(); if($tag instanceof NamedNBTTag and $tag->getName() !== ""){ $this->value[$tag->getName()] = $tag; - }elseif(!($tag instanceof NBTTag_End)){ + }elseif(!($tag instanceof NBT\Tag\End)){ $this->value[] = $tag; } - }while(!($tag instanceof NBTTag_End) and !$nbt->feof()); + }while(!($tag instanceof NBT\Tag\End) and !$nbt->feof()); } public function write(NBT $nbt){ foreach($this->value as $tag){ - if(!($tag instanceof NBTTag_End)){ + if(!($tag instanceof NBT\Tag\End)){ $nbt->writeTag($tag); } } - $nbt->writeTag(new NBTTag_End); + $nbt->writeTag(new NBT\Tag\End); } } \ No newline at end of file diff --git a/src/nbt/tags/TAG_Double.php b/src/nbt/tag/Double.php similarity index 87% rename from src/nbt/tags/TAG_Double.php rename to src/nbt/tag/Double.php index 34e83a14f..eeb056669 100644 --- a/src/nbt/tags/TAG_Double.php +++ b/src/nbt/tag/Double.php @@ -19,10 +19,14 @@ * */ -class NBTTag_Double extends NamedNBTTag{ +namespace PocketMine\NBT\Tag; +use PocketMine\NBT; +use PocketMine; + +class Double extends NamedNBTTag{ public function getType(){ - return NBTTag::TAG_Double; + return NBT\TAG_Double; } public function read(NBT $nbt){ diff --git a/src/nbt/tags/TAG_End.php b/src/nbt/tag/End.php similarity index 87% rename from src/nbt/tags/TAG_End.php rename to src/nbt/tag/End.php index dc76f186a..be55d1a5a 100644 --- a/src/nbt/tags/TAG_End.php +++ b/src/nbt/tag/End.php @@ -19,10 +19,14 @@ * */ -class NBTTag_End extends NBTTag{ +namespace PocketMine\NBT\Tag; +use PocketMine\NBT; +use PocketMine; + +class End extends NBTTag{ public function getType(){ - return NBTTag::TAG_End; + return NBT\TAG_End; } public function read(NBT $nbt){ diff --git a/src/nbt/tags/TAG_List.php b/src/nbt/tag/Enum.php similarity index 79% rename from src/nbt/tags/TAG_List.php rename to src/nbt/tag/Enum.php index 0872f49f0..8c52bb667 100644 --- a/src/nbt/tags/TAG_List.php +++ b/src/nbt/tag/Enum.php @@ -19,12 +19,16 @@ * */ -class NBTTag_List extends NamedNBTTag implements ArrayAccess, Iterator{ +namespace PocketMine\NBT\Tag; +use PocketMine\NBT; +use PocketMine; + +class Enum extends NamedNBTTag implements \ArrayAccess, \Iterator{ private $tagType; public function getType(){ - return NBTTag::TAG_List; + return NBT\TAG_Enum; } public function setTagType($type){ @@ -103,63 +107,63 @@ class NBTTag_List extends NamedNBTTag implements ArrayAccess, Iterator{ $size = $nbt->getInt(); for($i = 0; $i < $size and !$nbt->feof(); ++$i){ switch($this->tagType){ - case NBTTag::TAG_Byte: - $tag = new NBTTag_Byte(false); + case NBT\TAG_Byte: + $tag = new NBT\Tag\Byte(false); $tag->read($nbt); $this->value[] = $tag; break; - case NBTTag::TAG_Byte: - $tag = new NBTTag_Byte(false); + case NBT\TAG_Byte: + $tag = new NBT\Tag\Byte(false); $tag->read($nbt); $this->value[] = $tag; break; - case NBTTag::TAG_Short: - $tag = new NBTTag_Short(false); + case NBT\TAG_Short: + $tag = new NBT\Tag\Short(false); $tag->read($nbt); $this->value[] = $tag; break; - case NBTTag::TAG_Int: - $tag = new NBTTag_Int(false); + case NBT\TAG_Int: + $tag = new NBT\Tag\Int(false); $tag->read($nbt); $this->value[] = $tag; break; - case NBTTag::TAG_Long: - $tag = new NBTTag_Long(false); + case NBT\TAG_Long: + $tag = new NBT\Tag\Long(false); $tag->read($nbt); $this->value[] = $tag; break; - case NBTTag::TAG_Float: - $tag = new NBTTag_Float(false); + case NBT\TAG_Float: + $tag = new NBT\Tag\Float(false); $tag->read($nbt); $this->value[] = $tag; break; - case NBTTag::TAG_Double: - $tag = new NBTTag_Double(false); + case NBT\TAG_Double: + $tag = new NBT\Tag\Double(false); $tag->read($nbt); $this->value[] = $tag; break; - case NBTTag::TAG_Byte_Array: - $tag = new NBTTag_Byte_Array(false); + case NBT\TAG_Byte_Array: + $tag = new NBT\Tag\Byte_Array(false); $tag->read($nbt); $this->value[] = $tag; break; - case NBTTag::TAG_String: - $tag = new NBTTag_String(false); + case NBT\TAG_String: + $tag = new NBT\Tag\String(false); $tag->read($nbt); $this->value[] = $tag; break; - case NBTTag::TAG_List: - $tag = new NBTTag_List(false); + case NBT\TAG_Enum: + $tag = new NBT\Tag\Enum(false); $tag->read($nbt); $this->value[] = $tag; break; - case NBTTag::TAG_Compound: - $tag = new NBTTag_Compound(false); + case NBT\TAG_Compound: + $tag = new NBT\Tag\Compound(false); $tag->read($nbt); $this->value[] = $tag; break; - case NBTTag::TAG_Int_Array: - $tag = new NBTTag_Int_Array(false); + case NBT\TAG_Int_Array: + $tag = new NBT\Tag\Int_Array(false); $tag->read($nbt); $this->value[] = $tag; break; diff --git a/src/nbt/tags/TAG_Float.php b/src/nbt/tag/Float.php similarity index 87% rename from src/nbt/tags/TAG_Float.php rename to src/nbt/tag/Float.php index dd4cad33e..3de791a2b 100644 --- a/src/nbt/tags/TAG_Float.php +++ b/src/nbt/tag/Float.php @@ -19,10 +19,14 @@ * */ -class NBTTag_Float extends NamedNBTTag{ +namespace PocketMine\NBT\Tag; +use PocketMine\NBT; +use PocketMine; + +class Float extends NamedNBTTag{ public function getType(){ - return NBTTag::TAG_Float; + return NBT\TAG_Float; } public function read(NBT $nbt){ diff --git a/src/nbt/tags/TAG_Int.php b/src/nbt/tag/Int.php similarity index 88% rename from src/nbt/tags/TAG_Int.php rename to src/nbt/tag/Int.php index e9022ddf9..d0e712f37 100644 --- a/src/nbt/tags/TAG_Int.php +++ b/src/nbt/tag/Int.php @@ -19,10 +19,14 @@ * */ -class NBTTag_Int extends NamedNBTTag{ +namespace PocketMine\NBT\Tag; +use PocketMine\NBT; +use PocketMine; + +class Int extends NamedNBTTag{ public function getType(){ - return NBTTag::TAG_Int; + return NBT\TAG_Int; } public function read(NBT $nbt){ diff --git a/src/nbt/tags/TAG_Int_Array.php b/src/nbt/tag/Int_Array.php similarity index 88% rename from src/nbt/tags/TAG_Int_Array.php rename to src/nbt/tag/Int_Array.php index 1cc52a331..73e8cf7c5 100644 --- a/src/nbt/tags/TAG_Int_Array.php +++ b/src/nbt/tag/Int_Array.php @@ -19,10 +19,14 @@ * */ -class NBTTag_Int_Array extends NamedNBTTag{ +namespace PocketMine\NBT\Tag; +use PocketMine\NBT; +use PocketMine; + +class Int_Array extends NamedNBTTag{ public function getType(){ - return NBTTag::TAG_Int_Array; + return NBT\TAG_Int_Array; } public function read(NBT $nbt){ diff --git a/src/nbt/tags/TAG_Long.php b/src/nbt/tag/Long.php similarity index 87% rename from src/nbt/tags/TAG_Long.php rename to src/nbt/tag/Long.php index 864ea2004..90e04bb5c 100644 --- a/src/nbt/tags/TAG_Long.php +++ b/src/nbt/tag/Long.php @@ -19,10 +19,14 @@ * */ -class NBTTag_Long extends NamedNBTTag{ +namespace PocketMine\NBT\Tag; +use PocketMine\NBT; +use PocketMine; + +class Long extends NamedNBTTag{ public function getType(){ - return NBTTag::TAG_Long; + return NBT\TAG_Long; } public function read(NBT $nbt){ diff --git a/src/nbt/tags/TAG_Short.php b/src/nbt/tag/Short.php similarity index 87% rename from src/nbt/tags/TAG_Short.php rename to src/nbt/tag/Short.php index a421a1794..a5c18d056 100644 --- a/src/nbt/tags/TAG_Short.php +++ b/src/nbt/tag/Short.php @@ -19,10 +19,14 @@ * */ -class NBTTag_Short extends NamedNBTTag{ +namespace PocketMine\NBT\Tag; +use PocketMine\NBT; +use PocketMine; + +class Short extends NamedNBTTag{ public function getType(){ - return NBTTag::TAG_Short; + return NBT\TAG_Short; } public function read(NBT $nbt){ diff --git a/src/nbt/tags/TAG_String.php b/src/nbt/tag/String.php similarity index 88% rename from src/nbt/tags/TAG_String.php rename to src/nbt/tag/String.php index 8efb40b89..2663ec150 100644 --- a/src/nbt/tags/TAG_String.php +++ b/src/nbt/tag/String.php @@ -19,10 +19,14 @@ * */ -class NBTTag_String extends NamedNBTTag{ +namespace PocketMine\NBT\Tag; +use PocketMine\NBT; +use PocketMine; + +class String extends NamedNBTTag{ public function getType(){ - return NBTTag::TAG_String; + return NBT\TAG_String; } public function read(NBT $nbt){ diff --git a/src/network/MinecraftInterface.php b/src/network/Handler.php similarity index 93% rename from src/network/MinecraftInterface.php rename to src/network/Handler.php index 6f62bfa27..c94f16347 100644 --- a/src/network/MinecraftInterface.php +++ b/src/network/Handler.php @@ -19,7 +19,10 @@ * */ -class MinecraftInterface{ +namespace PocketMine\Network; +use PocketMine; + +class Handler{ public $bandwidth; private $socket; private $packets; @@ -55,7 +58,7 @@ class MinecraftInterface{ $packet->ip = $source; $packet->port = $port; $packet->decode(); - if(EventHandler::callEvent(new PacketReceiveEvent($packet)) === BaseEvent::DENY){ + if(EventHandler::callEvent(new PacketReceiveEvent($packet)) === Event::DENY){ return false; } return $packet; @@ -64,7 +67,7 @@ class MinecraftInterface{ $packet->ip = $source; $packet->port = $port; $packet->buffer =& $buffer; - if(EventHandler::callEvent(new PacketReceiveEvent($packet)) === BaseEvent::DENY){ + if(EventHandler::callEvent(new PacketReceiveEvent($packet)) === Event::DENY){ return false; } ServerAPI::request()->api->query->handle($packet); @@ -79,7 +82,7 @@ class MinecraftInterface{ } public function writePacket(Packet $packet){ - if(EventHandler::callEvent(new PacketSendEvent($packet)) === BaseEvent::DENY){ + if(EventHandler::callEvent(new PacketSendEvent($packet)) === Event::DENY){ return 0; }elseif($packet instanceof RakNetPacket){ $packet->encode(); diff --git a/src/network/Packet.php b/src/network/Packet.php index df3d26625..a54fc4c8c 100644 --- a/src/network/Packet.php +++ b/src/network/Packet.php @@ -19,7 +19,10 @@ * */ -class Packet extends stdClass{ +namespace PocketMine\Network; +use PocketMine; + +class Packet extends \stdClass{ public $ip; public $port; public $buffer; diff --git a/src/network/UDPSocket.php b/src/network/UDPSocket.php index 4ed3de19f..c5559f10a 100644 --- a/src/network/UDPSocket.php +++ b/src/network/UDPSocket.php @@ -19,7 +19,8 @@ * */ - +namespace PocketMine\Network; +use PocketMine; class UDPSocket{ public $connected, $sock, $server, $port; diff --git a/src/network/raknet/RakNetDataPacket.php b/src/network/protocol/DataPacket.php similarity index 82% rename from src/network/raknet/RakNetDataPacket.php rename to src/network/protocol/DataPacket.php index cb942b366..9851dc953 100644 --- a/src/network/raknet/RakNetDataPacket.php +++ b/src/network/protocol/DataPacket.php @@ -19,7 +19,10 @@ * */ -abstract class RakNetDataPacket extends stdClass{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +abstract class DataPacket{ private $offset = 0; public $buffer = b""; @@ -72,52 +75,52 @@ abstract class RakNetDataPacket extends stdClass{ } protected function getLong($unsigned = false){ - return Utils::readLong($this->get(8), $unsigned); + return Utils\Utils::readLong($this->get(8), $unsigned); } protected function putLong($v){ - $this->buffer .= Utils::writeLong($v); + $this->buffer .= Utils\Utils::writeLong($v); } protected function getInt(){ - return Utils::readInt($this->get(4)); + return Utils\Utils::readInt($this->get(4)); } protected function putInt($v){ - $this->buffer .= Utils::writeInt($v); + $this->buffer .= Utils\Utils::writeInt($v); } protected function getShort($unsigned = false){ - return Utils::readShort($this->get(2), $unsigned); + return Utils\Utils::readShort($this->get(2), $unsigned); } protected function putShort($v){ - $this->buffer .= Utils::writeShort($v); + $this->buffer .= Utils\Utils::writeShort($v); } protected function getFloat(){ - return Utils::readFloat($this->get(4)); + return Utils\Utils::readFloat($this->get(4)); } protected function putFloat($v){ - $this->buffer .= Utils::writeFloat($v); + $this->buffer .= Utils\Utils::writeFloat($v); } protected function getTriad(){ - return Utils::readTriad($this->get(3)); + return Utils\Utils::readTriad($this->get(3)); } protected function putTriad($v){ - $this->buffer .= Utils::writeTriad($v); + $this->buffer .= Utils\Utils::writeTriad($v); } protected function getLTriad(){ - return Utils::readTriad(strrev($this->get(3))); + return Utils\Utils::readTriad(strrev($this->get(3))); } protected function putLTriad($v){ - $this->buffer .= strrev(Utils::writeTriad($v)); + $this->buffer .= strrev(Utils\Utils::writeTriad($v)); } protected function getByte(){ diff --git a/src/network/protocol/ProtocolInfo.php b/src/network/protocol/Info.php similarity index 95% rename from src/network/protocol/ProtocolInfo.php rename to src/network/protocol/Info.php index 92a9c9c8b..156b5a8f2 100644 --- a/src/network/protocol/ProtocolInfo.php +++ b/src/network/protocol/Info.php @@ -19,8 +19,11 @@ * */ +namespace PocketMine\Network\Protocol; +use PocketMine; -abstract class ProtocolInfo{ + +abstract class Info{ const CURRENT_PROTOCOL = 14; @@ -96,8 +99,4 @@ abstract class ProtocolInfo{ const ENTITY_DATA_PACKET = 0xb8; //const PLAYER_INPUT_PACKET = 0xb9; -} - -/***REM_START***/ -require_once(FILE_PATH . "src/network/raknet/RakNetDataPacket.php"); -/***REM_END***/ \ No newline at end of file +} \ No newline at end of file diff --git a/src/network/protocol/packet/AddEntityPacket.php b/src/network/protocol/packet/AddEntityPacket.php index c51cd6036..d893b71dc 100644 --- a/src/network/protocol/packet/AddEntityPacket.php +++ b/src/network/protocol/packet/AddEntityPacket.php @@ -19,7 +19,10 @@ * */ -class AddEntityPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class AddEntityPacket extends DataPacket{ public $eid; public $type; public $x; @@ -31,7 +34,7 @@ class AddEntityPacket extends RakNetDataPacket{ public $speedZ; public function pid(){ - return ProtocolInfo::ADD_ENTITY_PACKET; + return Info::ADD_ENTITY_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/AddItemEntityPacket.php b/src/network/protocol/packet/AddItemEntityPacket.php index 031615b75..5fe765508 100644 --- a/src/network/protocol/packet/AddItemEntityPacket.php +++ b/src/network/protocol/packet/AddItemEntityPacket.php @@ -19,7 +19,10 @@ * */ -class AddItemEntityPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class AddItemEntityPacket extends DataPacket{ public $eid; public $item; public $x; @@ -30,7 +33,7 @@ class AddItemEntityPacket extends RakNetDataPacket{ public $roll; public function pid(){ - return ProtocolInfo::ADD_ITEM_ENTITY_PACKET; + return Info::ADD_ITEM_ENTITY_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/AddMobPacket.php b/src/network/protocol/packet/AddMobPacket.php index 9e8dca14b..e5056ee5d 100644 --- a/src/network/protocol/packet/AddMobPacket.php +++ b/src/network/protocol/packet/AddMobPacket.php @@ -19,7 +19,10 @@ * */ -class AddMobPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class AddMobPacket extends DataPacket{ public $eid; public $type; public $x; @@ -30,7 +33,7 @@ class AddMobPacket extends RakNetDataPacket{ public $metadata; public function pid(){ - return ProtocolInfo::ADD_MOB_PACKET; + return Info::ADD_MOB_PACKET; } public function decode(){ @@ -46,7 +49,7 @@ class AddMobPacket extends RakNetDataPacket{ $this->putFloat($this->z); $this->putByte($this->yaw); $this->putByte($this->pitch); - $this->put(Utils::writeMetadata($this->metadata)); + $this->put(Utils\Utils::writeMetadata($this->metadata)); } } \ No newline at end of file diff --git a/src/network/protocol/packet/AddPaintingPacket.php b/src/network/protocol/packet/AddPaintingPacket.php index cca7211ae..250eef130 100644 --- a/src/network/protocol/packet/AddPaintingPacket.php +++ b/src/network/protocol/packet/AddPaintingPacket.php @@ -19,7 +19,10 @@ * */ -class AddPaintingPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class AddPaintingPacket extends DataPacket{ public $eid; public $x; public $y; @@ -28,7 +31,7 @@ class AddPaintingPacket extends RakNetDataPacket{ public $title; public function pid(){ - return ProtocolInfo::ADD_PAINTING_PACKET; + return Info::ADD_PAINTING_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/AddPlayerPacket.php b/src/network/protocol/packet/AddPlayerPacket.php index 5ed45416f..4b049ef26 100644 --- a/src/network/protocol/packet/AddPlayerPacket.php +++ b/src/network/protocol/packet/AddPlayerPacket.php @@ -19,7 +19,10 @@ * */ -class AddPlayerPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class AddPlayerPacket extends DataPacket{ public $clientID; public $username; public $eid; @@ -33,7 +36,7 @@ class AddPlayerPacket extends RakNetDataPacket{ public $metadata; public function pid(){ - return ProtocolInfo::ADD_PLAYER_PACKET; + return Info::ADD_PLAYER_PACKET; } public function decode(){ @@ -52,7 +55,7 @@ class AddPlayerPacket extends RakNetDataPacket{ $this->putByte($this->pitch); $this->putShort($this->unknown1); $this->putShort($this->unknown2); - $this->put(Utils::writeMetadata($this->metadata)); + $this->put(Utils\Utils::writeMetadata($this->metadata)); } } \ No newline at end of file diff --git a/src/network/protocol/packet/AdventureSettingsPacket.php b/src/network/protocol/packet/AdventureSettingsPacket.php index da016aba9..cb182d954 100644 --- a/src/network/protocol/packet/AdventureSettingsPacket.php +++ b/src/network/protocol/packet/AdventureSettingsPacket.php @@ -19,11 +19,14 @@ * */ -class AdventureSettingsPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class AdventureSettingsPacket extends DataPacket{ public $flags; public function pid(){ - return ProtocolInfo::ADVENTURE_SETTINGS_PACKET; + return Info::ADVENTURE_SETTINGS_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/AnimatePacket.php b/src/network/protocol/packet/AnimatePacket.php index eeccfc691..e4f32b652 100644 --- a/src/network/protocol/packet/AnimatePacket.php +++ b/src/network/protocol/packet/AnimatePacket.php @@ -19,12 +19,15 @@ * */ -class AnimatePacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class AnimatePacket extends DataPacket{ public $action; public $eid; public function pid(){ - return ProtocolInfo::ANIMATE_PACKET; + return Info::ANIMATE_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/ChatPacket.php b/src/network/protocol/packet/ChatPacket.php index 18b23e97f..ac3b90836 100644 --- a/src/network/protocol/packet/ChatPacket.php +++ b/src/network/protocol/packet/ChatPacket.php @@ -19,11 +19,14 @@ * */ -class ChatPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class ChatPacket extends DataPacket{ public $message; public function pid(){ - return ProtocolInfo::CHAT_PACKET; + return Info::CHAT_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/ChunkDataPacket.php b/src/network/protocol/packet/ChunkDataPacket.php index cc320ff1e..395ead10c 100644 --- a/src/network/protocol/packet/ChunkDataPacket.php +++ b/src/network/protocol/packet/ChunkDataPacket.php @@ -19,13 +19,16 @@ * */ -class ChunkDataPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class ChunkDataPacket extends DataPacket{ public $chunkX; public $chunkZ; public $data; public function pid(){ - return ProtocolInfo::CHUNK_DATA_PACKET; + return Info::CHUNK_DATA_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/ClientConnectPacket.php b/src/network/protocol/packet/ClientConnectPacket.php index 580b92a1f..6dab6efcd 100644 --- a/src/network/protocol/packet/ClientConnectPacket.php +++ b/src/network/protocol/packet/ClientConnectPacket.php @@ -19,13 +19,16 @@ * */ -class ClientConnectPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class ClientConnectPacket extends DataPacket{ public $clientID; public $session; public $unknown1; public function pid(){ - return ProtocolInfo::CLIENT_CONNECT_PACKET; + return Info::CLIENT_CONNECT_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/ClientHandshakePacket.php b/src/network/protocol/packet/ClientHandshakePacket.php index 6ad22beba..7df3531c5 100644 --- a/src/network/protocol/packet/ClientHandshakePacket.php +++ b/src/network/protocol/packet/ClientHandshakePacket.php @@ -19,7 +19,10 @@ * */ -class ClientHandshakePacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class ClientHandshakePacket extends DataPacket{ public $cookie; public $security; public $port; @@ -30,7 +33,7 @@ class ClientHandshakePacket extends RakNetDataPacket{ public $session; public function pid(){ - return ProtocolInfo::CLIENT_HANDSHAKE_PACKET; + return Info::CLIENT_HANDSHAKE_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/ContainerClosePacket.php b/src/network/protocol/packet/ContainerClosePacket.php index 1730193b2..c028204b6 100644 --- a/src/network/protocol/packet/ContainerClosePacket.php +++ b/src/network/protocol/packet/ContainerClosePacket.php @@ -19,11 +19,14 @@ * */ -class ContainerClosePacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class ContainerClosePacket extends DataPacket{ public $windowid; public function pid(){ - return ProtocolInfo::CONTAINER_CLOSE_PACKET; + return Info::CONTAINER_CLOSE_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/ContainerOpenPacket.php b/src/network/protocol/packet/ContainerOpenPacket.php index cb6a1ff03..4257b857c 100644 --- a/src/network/protocol/packet/ContainerOpenPacket.php +++ b/src/network/protocol/packet/ContainerOpenPacket.php @@ -19,7 +19,10 @@ * */ -class ContainerOpenPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class ContainerOpenPacket extends DataPacket{ public $windowid; public $type; public $slots; @@ -28,7 +31,7 @@ class ContainerOpenPacket extends RakNetDataPacket{ public $z; public function pid(){ - return ProtocolInfo::CONTAINER_OPEN_PACKET; + return Info::CONTAINER_OPEN_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/ContainerSetContentPacket.php b/src/network/protocol/packet/ContainerSetContentPacket.php index 5195bfe62..32d5d59c0 100644 --- a/src/network/protocol/packet/ContainerSetContentPacket.php +++ b/src/network/protocol/packet/ContainerSetContentPacket.php @@ -19,13 +19,16 @@ * */ -class ContainerSetContentPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class ContainerSetContentPacket extends DataPacket{ public $windowid; public $slots = array(); public $hotbar = array(); public function pid(){ - return ProtocolInfo::CONTAINER_SET_CONTENT_PACKET; + return Info::CONTAINER_SET_CONTENT_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/ContainerSetDataPacket.php b/src/network/protocol/packet/ContainerSetDataPacket.php index f1c4cc650..89db6c787 100644 --- a/src/network/protocol/packet/ContainerSetDataPacket.php +++ b/src/network/protocol/packet/ContainerSetDataPacket.php @@ -19,13 +19,16 @@ * */ -class ContainerSetDataPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class ContainerSetDataPacket extends DataPacket{ public $windowid; public $property; public $value; public function pid(){ - return ProtocolInfo::CONTAINER_SET_DATA_PACKET; + return Info::CONTAINER_SET_DATA_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/ContainerSetSlotPacket.php b/src/network/protocol/packet/ContainerSetSlotPacket.php index 1add0874c..be88a50af 100644 --- a/src/network/protocol/packet/ContainerSetSlotPacket.php +++ b/src/network/protocol/packet/ContainerSetSlotPacket.php @@ -19,13 +19,16 @@ * */ -class ContainerSetSlotPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class ContainerSetSlotPacket extends DataPacket{ public $windowid; public $slot; public $item; public function pid(){ - return ProtocolInfo::CONTAINER_SET_SLOT_PACKET; + return Info::CONTAINER_SET_SLOT_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/DisconnectPacket.php b/src/network/protocol/packet/DisconnectPacket.php index 6efcffa1c..68afafc85 100644 --- a/src/network/protocol/packet/DisconnectPacket.php +++ b/src/network/protocol/packet/DisconnectPacket.php @@ -19,9 +19,12 @@ * */ -class DisconnectPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class DisconnectPacket extends DataPacket{ public function pid(){ - return ProtocolInfo::DISCONNECT_PACKET; + return Info::DISCONNECT_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/DropItemPacket.php b/src/network/protocol/packet/DropItemPacket.php index 6a1117aff..3338327f2 100644 --- a/src/network/protocol/packet/DropItemPacket.php +++ b/src/network/protocol/packet/DropItemPacket.php @@ -19,13 +19,16 @@ * */ -class DropItemPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class DropItemPacket extends DataPacket{ public $eid; public $unknown; public $item; public function pid(){ - return ProtocolInfo::DROP_ITEM_PACKET; + return Info::DROP_ITEM_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/EntityDataPacket.php b/src/network/protocol/packet/EntityDataPacket.php index 05ef96fb7..7ad892e38 100644 --- a/src/network/protocol/packet/EntityDataPacket.php +++ b/src/network/protocol/packet/EntityDataPacket.php @@ -19,14 +19,17 @@ * */ -class EntityDataPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class EntityDataPacket extends DataPacket{ public $x; public $y; public $z; public $namedtag; public function pid(){ - return ProtocolInfo::ENTITY_DATA_PACKET; + return Info::ENTITY_DATA_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/EntityEventPacket.php b/src/network/protocol/packet/EntityEventPacket.php index a1f0f16bf..d666633e0 100644 --- a/src/network/protocol/packet/EntityEventPacket.php +++ b/src/network/protocol/packet/EntityEventPacket.php @@ -19,12 +19,15 @@ * */ -class EntityEventPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class EntityEventPacket extends DataPacket{ public $eid; public $event; public function pid(){ - return ProtocolInfo::ENTITY_EVENT_PACKET; + return Info::ENTITY_EVENT_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/ExplodePacket.php b/src/network/protocol/packet/ExplodePacket.php index 4c8a232ad..f4823c621 100644 --- a/src/network/protocol/packet/ExplodePacket.php +++ b/src/network/protocol/packet/ExplodePacket.php @@ -19,7 +19,10 @@ * */ -class ExplodePacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class ExplodePacket extends DataPacket{ public $x; public $y; public $z; @@ -27,7 +30,7 @@ class ExplodePacket extends RakNetDataPacket{ public $records; public function pid(){ - return ProtocolInfo::EXPLODE_PACKET; + return Info::EXPLODE_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/HurtArmorPacket.php b/src/network/protocol/packet/HurtArmorPacket.php index e69edd9f7..62c2be85a 100644 --- a/src/network/protocol/packet/HurtArmorPacket.php +++ b/src/network/protocol/packet/HurtArmorPacket.php @@ -19,11 +19,14 @@ * */ -class HurtArmorPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class HurtArmorPacket extends DataPacket{ public $health; public function pid(){ - return ProtocolInfo::HURT_ARMOR_PACKET; + return Info::HURT_ARMOR_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/InteractPacket.php b/src/network/protocol/packet/InteractPacket.php index 5f17ed279..7a3fe0c8b 100644 --- a/src/network/protocol/packet/InteractPacket.php +++ b/src/network/protocol/packet/InteractPacket.php @@ -19,13 +19,16 @@ * */ -class InteractPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class InteractPacket extends DataPacket{ public $action; public $eid; public $target; public function pid(){ - return ProtocolInfo::INTERACT_PACKET; + return Info::INTERACT_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/LevelEventPacket.php b/src/network/protocol/packet/LevelEventPacket.php index 521e9d62d..f682612fa 100644 --- a/src/network/protocol/packet/LevelEventPacket.php +++ b/src/network/protocol/packet/LevelEventPacket.php @@ -19,7 +19,10 @@ * */ -class LevelEventPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class LevelEventPacket extends DataPacket{ public $evid; public $x; public $y; @@ -27,7 +30,7 @@ class LevelEventPacket extends RakNetDataPacket{ public $data; public function pid(){ - return ProtocolInfo::LEVEL_EVENT_PACKET; + return Info::LEVEL_EVENT_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/LoginPacket.php b/src/network/protocol/packet/LoginPacket.php index c9283ffd5..bf1e48d34 100644 --- a/src/network/protocol/packet/LoginPacket.php +++ b/src/network/protocol/packet/LoginPacket.php @@ -19,7 +19,10 @@ * */ -class LoginPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class LoginPacket extends DataPacket{ public $username; public $protocol1; public $protocol2; @@ -27,7 +30,7 @@ class LoginPacket extends RakNetDataPacket{ public $loginData; public function pid(){ - return ProtocolInfo::LOGIN_PACKET; + return Info::LOGIN_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/LoginStatusPacket.php b/src/network/protocol/packet/LoginStatusPacket.php index 54fd0bc50..4450f27c8 100644 --- a/src/network/protocol/packet/LoginStatusPacket.php +++ b/src/network/protocol/packet/LoginStatusPacket.php @@ -19,11 +19,14 @@ * */ -class LoginStatusPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class LoginStatusPacket extends DataPacket{ public $status; public function pid(){ - return ProtocolInfo::LOGIN_STATUS_PACKET; + return Info::LOGIN_STATUS_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/MessagePacket.php b/src/network/protocol/packet/MessagePacket.php index 3d48f5e14..e1ba9688e 100644 --- a/src/network/protocol/packet/MessagePacket.php +++ b/src/network/protocol/packet/MessagePacket.php @@ -19,12 +19,15 @@ * */ -class MessagePacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class MessagePacket extends DataPacket{ public $source; public $message; public function pid(){ - return ProtocolInfo::MESSAGE_PACKET; + return Info::MESSAGE_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/MoveEntityPacket.php b/src/network/protocol/packet/MoveEntityPacket.php index 05f2da50b..65b76e9ce 100644 --- a/src/network/protocol/packet/MoveEntityPacket.php +++ b/src/network/protocol/packet/MoveEntityPacket.php @@ -19,10 +19,13 @@ * */ -class MoveEntityPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class MoveEntityPacket extends DataPacket{ public function pid(){ - return ProtocolInfo::MOVE_ENTITY_PACKET; + return Info::MOVE_ENTITY_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/MoveEntityPacket_PosRot.php b/src/network/protocol/packet/MoveEntityPacket_PosRot.php index a1a456c08..2d36e8f2f 100644 --- a/src/network/protocol/packet/MoveEntityPacket_PosRot.php +++ b/src/network/protocol/packet/MoveEntityPacket_PosRot.php @@ -19,7 +19,10 @@ * */ -class MoveEntityPacket_PosRot extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class MoveEntityPacket_PosRot extends DataPacket{ public $eid; public $x; public $y; @@ -28,7 +31,7 @@ class MoveEntityPacket_PosRot extends RakNetDataPacket{ public $pitch; public function pid(){ - return ProtocolInfo::MOVE_ENTITY_PACKET_POSROT; + return Info::MOVE_ENTITY_PACKET_POSROT; } public function decode(){ diff --git a/src/network/protocol/packet/MovePlayerPacket.php b/src/network/protocol/packet/MovePlayerPacket.php index 01e086436..dff525ae0 100644 --- a/src/network/protocol/packet/MovePlayerPacket.php +++ b/src/network/protocol/packet/MovePlayerPacket.php @@ -19,7 +19,10 @@ * */ -class MovePlayerPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class MovePlayerPacket extends DataPacket{ public $eid; public $x; public $y; @@ -29,7 +32,7 @@ class MovePlayerPacket extends RakNetDataPacket{ public $bodyYaw; public function pid(){ - return ProtocolInfo::MOVE_PLAYER_PACKET; + return Info::MOVE_PLAYER_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/PingPacket.php b/src/network/protocol/packet/PingPacket.php index f3b6a8349..30752f435 100644 --- a/src/network/protocol/packet/PingPacket.php +++ b/src/network/protocol/packet/PingPacket.php @@ -19,11 +19,14 @@ * */ -class PingPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class PingPacket extends DataPacket{ public $time = 0; public function pid(){ - return ProtocolInfo::PING_PACKET; + return Info::PING_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/PlayerActionPacket.php b/src/network/protocol/packet/PlayerActionPacket.php index 383d5f5ea..85792bb99 100644 --- a/src/network/protocol/packet/PlayerActionPacket.php +++ b/src/network/protocol/packet/PlayerActionPacket.php @@ -19,7 +19,10 @@ * */ -class PlayerActionPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class PlayerActionPacket extends DataPacket{ public $action; public $x; public $y; @@ -28,7 +31,7 @@ class PlayerActionPacket extends RakNetDataPacket{ public $eid; public function pid(){ - return ProtocolInfo::PLAYER_ACTION_PACKET; + return Info::PLAYER_ACTION_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/PlayerArmorEquipmentPacket.php b/src/network/protocol/packet/PlayerArmorEquipmentPacket.php index 6ced5d222..0ae0d9136 100644 --- a/src/network/protocol/packet/PlayerArmorEquipmentPacket.php +++ b/src/network/protocol/packet/PlayerArmorEquipmentPacket.php @@ -19,12 +19,15 @@ * */ -class PlayerArmorEquipmentPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class PlayerArmorEquipmentPacket extends DataPacket{ public $eid; public $slots = array(); public function pid(){ - return ProtocolInfo::PLAYER_ARMOR_EQUIPMENT_PACKET; + return Info::PLAYER_ARMOR_EQUIPMENT_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/PlayerEquipmentPacket.php b/src/network/protocol/packet/PlayerEquipmentPacket.php index 2a6670824..488b2e406 100644 --- a/src/network/protocol/packet/PlayerEquipmentPacket.php +++ b/src/network/protocol/packet/PlayerEquipmentPacket.php @@ -19,14 +19,17 @@ * */ -class PlayerEquipmentPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class PlayerEquipmentPacket extends DataPacket{ public $eid; public $item; public $meta; public $slot; public function pid(){ - return ProtocolInfo::PLAYER_EQUIPMENT_PACKET; + return Info::PLAYER_EQUIPMENT_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/PongPacket.php b/src/network/protocol/packet/PongPacket.php index 5eed84a43..ec5928425 100644 --- a/src/network/protocol/packet/PongPacket.php +++ b/src/network/protocol/packet/PongPacket.php @@ -19,12 +19,15 @@ * */ -class PongPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class PongPacket extends DataPacket{ public $time = 0; public $ptime = 0; public function pid(){ - return ProtocolInfo::PONG_PACKET; + return Info::PONG_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/ReadyPacket.php b/src/network/protocol/packet/ReadyPacket.php index 3026875f0..71422bb4e 100644 --- a/src/network/protocol/packet/ReadyPacket.php +++ b/src/network/protocol/packet/ReadyPacket.php @@ -19,11 +19,14 @@ * */ -class ReadyPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class ReadyPacket extends DataPacket{ public $status; public function pid(){ - return ProtocolInfo::READY_PACKET; + return Info::READY_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/RemoveBlockPacket.php b/src/network/protocol/packet/RemoveBlockPacket.php index 4e3b74032..2e6c6e51d 100644 --- a/src/network/protocol/packet/RemoveBlockPacket.php +++ b/src/network/protocol/packet/RemoveBlockPacket.php @@ -19,14 +19,17 @@ * */ -class RemoveBlockPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class RemoveBlockPacket extends DataPacket{ public $eid; public $x; public $y; public $z; public function pid(){ - return ProtocolInfo::REMOVE_BLOCK_PACKET; + return Info::REMOVE_BLOCK_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/RemoveEntityPacket.php b/src/network/protocol/packet/RemoveEntityPacket.php index b5b754147..37c570268 100644 --- a/src/network/protocol/packet/RemoveEntityPacket.php +++ b/src/network/protocol/packet/RemoveEntityPacket.php @@ -19,11 +19,14 @@ * */ -class RemoveEntityPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class RemoveEntityPacket extends DataPacket{ public $eid; public function pid(){ - return ProtocolInfo::REMOVE_ENTITY_PACKET; + return Info::REMOVE_ENTITY_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/RemovePlayerPacket.php b/src/network/protocol/packet/RemovePlayerPacket.php index 27d161152..70356f8d9 100644 --- a/src/network/protocol/packet/RemovePlayerPacket.php +++ b/src/network/protocol/packet/RemovePlayerPacket.php @@ -19,12 +19,15 @@ * */ -class RemovePlayerPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class RemovePlayerPacket extends DataPacket{ public $eid; public $clientID; public function pid(){ - return ProtocolInfo::REMOVE_PLAYER_PACKET; + return Info::REMOVE_PLAYER_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/RequestChunkPacket.php b/src/network/protocol/packet/RequestChunkPacket.php index 708346866..83b8e0138 100644 --- a/src/network/protocol/packet/RequestChunkPacket.php +++ b/src/network/protocol/packet/RequestChunkPacket.php @@ -19,12 +19,15 @@ * */ -class RequestChunkPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class RequestChunkPacket extends DataPacket{ public $chunkX; public $chunkZ; public function pid(){ - return ProtocolInfo::REQUEST_CHUNK_PACKET; + return Info::REQUEST_CHUNK_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/RespawnPacket.php b/src/network/protocol/packet/RespawnPacket.php index 65d183e05..b73637dc0 100644 --- a/src/network/protocol/packet/RespawnPacket.php +++ b/src/network/protocol/packet/RespawnPacket.php @@ -19,14 +19,17 @@ * */ -class RespawnPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class RespawnPacket extends DataPacket{ public $eid; public $x; public $y; public $z; public function pid(){ - return ProtocolInfo::RESPAWN_PACKET; + return Info::RESPAWN_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/RotateHeadPacket.php b/src/network/protocol/packet/RotateHeadPacket.php index 485133548..4227c7b33 100644 --- a/src/network/protocol/packet/RotateHeadPacket.php +++ b/src/network/protocol/packet/RotateHeadPacket.php @@ -19,12 +19,15 @@ * */ -class RotateHeadPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class RotateHeadPacket extends DataPacket{ public $eid; public $yaw; public function pid(){ - return ProtocolInfo::ROTATE_HEAD_PACKET; + return Info::ROTATE_HEAD_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/SendInventoryPacket.php b/src/network/protocol/packet/SendInventoryPacket.php index 6d32826b0..0ec0f6513 100644 --- a/src/network/protocol/packet/SendInventoryPacket.php +++ b/src/network/protocol/packet/SendInventoryPacket.php @@ -19,14 +19,17 @@ * */ -class SendInventoryPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class SendInventoryPacket extends DataPacket{ public $eid; public $windowid; public $slots = array(); public $armor = array(); public function pid(){ - return ProtocolInfo::SEND_INVENTORY_PACKET; + return Info::SEND_INVENTORY_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/ServerHandshakePacket.php b/src/network/protocol/packet/ServerHandshakePacket.php index aa79ba803..10f7172bd 100644 --- a/src/network/protocol/packet/ServerHandshakePacket.php +++ b/src/network/protocol/packet/ServerHandshakePacket.php @@ -19,13 +19,16 @@ * */ -class ServerHandshakePacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class ServerHandshakePacket extends DataPacket{ public $port; public $session; public $session2; public function pid(){ - return ProtocolInfo::SERVER_HANDSHAKE_PACKET; + return Info::SERVER_HANDSHAKE_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/SetEntityDataPacket.php b/src/network/protocol/packet/SetEntityDataPacket.php index 923cd7502..b72e160b4 100644 --- a/src/network/protocol/packet/SetEntityDataPacket.php +++ b/src/network/protocol/packet/SetEntityDataPacket.php @@ -19,12 +19,15 @@ * */ -class SetEntityDataPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class SetEntityDataPacket extends DataPacket{ public $eid; public $metadata; public function pid(){ - return ProtocolInfo::SET_ENTITY_DATA_PACKET; + return Info::SET_ENTITY_DATA_PACKET; } public function decode(){ @@ -34,7 +37,7 @@ class SetEntityDataPacket extends RakNetDataPacket{ public function encode(){ $this->reset(); $this->putInt($this->eid); - $this->put(Utils::writeMetadata($this->metadata)); + $this->put(Utils\Utils::writeMetadata($this->metadata)); } } \ No newline at end of file diff --git a/src/network/protocol/packet/SetEntityMotionPacket.php b/src/network/protocol/packet/SetEntityMotionPacket.php index 5844ac1ac..85b69bb61 100644 --- a/src/network/protocol/packet/SetEntityMotionPacket.php +++ b/src/network/protocol/packet/SetEntityMotionPacket.php @@ -19,14 +19,17 @@ * */ -class SetEntityMotionPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class SetEntityMotionPacket extends DataPacket{ public $eid; public $speedX; public $speedY; public $speedZ; public function pid(){ - return ProtocolInfo::SET_ENTITY_MOTION_PACKET; + return Info::SET_ENTITY_MOTION_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/SetHealthPacket.php b/src/network/protocol/packet/SetHealthPacket.php index 7e1e2a0fa..13cec73dd 100644 --- a/src/network/protocol/packet/SetHealthPacket.php +++ b/src/network/protocol/packet/SetHealthPacket.php @@ -19,11 +19,14 @@ * */ -class SetHealthPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class SetHealthPacket extends DataPacket{ public $health; public function pid(){ - return ProtocolInfo::SET_HEALTH_PACKET; + return Info::SET_HEALTH_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/SetSpawnPositionPacket.php b/src/network/protocol/packet/SetSpawnPositionPacket.php index 8509c3d8e..454f2ffdc 100644 --- a/src/network/protocol/packet/SetSpawnPositionPacket.php +++ b/src/network/protocol/packet/SetSpawnPositionPacket.php @@ -19,13 +19,16 @@ * */ -class SetSpawnPositionPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class SetSpawnPositionPacket extends DataPacket{ public $x; public $z; public $y; public function pid(){ - return ProtocolInfo::SET_SPAWN_POSITION_PACKET; + return Info::SET_SPAWN_POSITION_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/SetTimePacket.php b/src/network/protocol/packet/SetTimePacket.php index 91b26dceb..7304c3bfd 100644 --- a/src/network/protocol/packet/SetTimePacket.php +++ b/src/network/protocol/packet/SetTimePacket.php @@ -19,12 +19,15 @@ * */ -class SetTimePacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class SetTimePacket extends DataPacket{ public $time; public $started = true; public function pid(){ - return ProtocolInfo::SET_TIME_PACKET; + return Info::SET_TIME_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/StartGamePacket.php b/src/network/protocol/packet/StartGamePacket.php index 0f090fcaa..e35b238ed 100644 --- a/src/network/protocol/packet/StartGamePacket.php +++ b/src/network/protocol/packet/StartGamePacket.php @@ -19,7 +19,10 @@ * */ -class StartGamePacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class StartGamePacket extends DataPacket{ public $seed; public $generator; public $gamemode; @@ -29,7 +32,7 @@ class StartGamePacket extends RakNetDataPacket{ public $z; public function pid(){ - return ProtocolInfo::START_GAME_PACKET; + return Info::START_GAME_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/TakeItemEntityPacket.php b/src/network/protocol/packet/TakeItemEntityPacket.php index 61d171e54..68543da6f 100644 --- a/src/network/protocol/packet/TakeItemEntityPacket.php +++ b/src/network/protocol/packet/TakeItemEntityPacket.php @@ -19,12 +19,15 @@ * */ -class TakeItemEntityPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class TakeItemEntityPacket extends DataPacket{ public $target; public $eid; public function pid(){ - return ProtocolInfo::TAKE_ITEM_ENTITY_PACKET; + return Info::TAKE_ITEM_ENTITY_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/TileEventPacket.php b/src/network/protocol/packet/TileEventPacket.php index 0c14c576f..e275d05d1 100644 --- a/src/network/protocol/packet/TileEventPacket.php +++ b/src/network/protocol/packet/TileEventPacket.php @@ -19,7 +19,10 @@ * */ -class TileEventPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class TileEventPacket extends DataPacket{ public $x; public $y; public $z; @@ -27,7 +30,7 @@ class TileEventPacket extends RakNetDataPacket{ public $case2; public function pid(){ - return ProtocolInfo::TILE_EVENT_PACKET; + return Info::TILE_EVENT_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/UnknownPacket.php b/src/network/protocol/packet/UnknownPacket.php index d6194f317..71358a2b1 100644 --- a/src/network/protocol/packet/UnknownPacket.php +++ b/src/network/protocol/packet/UnknownPacket.php @@ -19,7 +19,10 @@ * */ -class UnknownPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class UnknownPacket extends DataPacket{ public $packetID = -1; public function pid(){ diff --git a/src/network/protocol/packet/UpdateBlockPacket.php b/src/network/protocol/packet/UpdateBlockPacket.php index ed724c767..69e0e6ec1 100644 --- a/src/network/protocol/packet/UpdateBlockPacket.php +++ b/src/network/protocol/packet/UpdateBlockPacket.php @@ -19,7 +19,10 @@ * */ -class UpdateBlockPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class UpdateBlockPacket extends DataPacket{ public $x; public $z; public $y; @@ -27,7 +30,7 @@ class UpdateBlockPacket extends RakNetDataPacket{ public $meta; public function pid(){ - return ProtocolInfo::UPDATE_BLOCK_PACKET; + return Info::UPDATE_BLOCK_PACKET; } public function decode(){ diff --git a/src/network/protocol/packet/UseItemPacket.php b/src/network/protocol/packet/UseItemPacket.php index 0762ab48d..fc8f56496 100644 --- a/src/network/protocol/packet/UseItemPacket.php +++ b/src/network/protocol/packet/UseItemPacket.php @@ -19,7 +19,10 @@ * */ -class UseItemPacket extends RakNetDataPacket{ +namespace PocketMine\Network\Protocol; +use PocketMine; + +class UseItemPacket extends DataPacket{ public $x; public $y; public $z; @@ -35,7 +38,7 @@ class UseItemPacket extends RakNetDataPacket{ public $posZ; public function pid(){ - return ProtocolInfo::USE_ITEM_PACKET; + return Info::USE_ITEM_PACKET; } public function decode(){ diff --git a/src/network/query/QueryHandler.php b/src/network/query/QueryHandler.php index bad428b59..247b5aa2f 100644 --- a/src/network/query/QueryHandler.php +++ b/src/network/query/QueryHandler.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine\Network\Query; +use PocketMine; + /* Implementation of the UT3 Query Protocol (GameSpot) Source: http://wiki.unrealadmin.org/UT3_query_protocol @@ -51,7 +54,7 @@ class QueryHandler{ public function regenerateInfo(){ $str = ""; - $plist = "PocketMine-MP ".MAJOR_VERSION; + $plist = "PocketMine-MP ".VERSION; $pl = $this->server->api->plugin->getList(); if(count($pl) > 0){ $plist .= ":"; @@ -65,8 +68,8 @@ class QueryHandler{ "hostname" => $this->server->name, "gametype" => ($this->server->gamemode & 0x01) === 0 ? "SMP":"CMP", "game_id" => "MINECRAFTPE", - "version" => CURRENT_MINECRAFT_VERSION, - "server_engine" => "PocketMine-MP ".MAJOR_VERSION, + "version" => MINECRAFT_VERSION, + "server_engine" => "PocketMine-MP ".VERSION, "plugins" => $plist, "map" => $this->server->api->level->getDefault()->getName(), "numplayers" => count(Player::$list), @@ -91,11 +94,11 @@ class QueryHandler{ public function regenerateToken(){ $this->lastToken = $this->token; - $this->token = Utils::getRandomBytes(16, false); + $this->token = Utils\Utils::getRandomBytes(16, false); } public static function getTokenString($token, $salt){ - return Utils::readInt(substr(hash("sha512", $salt . ":". $token, true), 7, 4)); + return Utils\Utils::readInt(substr(hash("sha512", $salt . ":". $token, true), 7, 4)); } public function handle(QueryPacket $packet){ @@ -112,7 +115,7 @@ class QueryHandler{ $this->server->send($pk); break; case QueryPacket::STATISTICS: //Stat - $token = Utils::readInt(substr($packet->payload, 0, 4)); + $token = Utils\Utils::readInt(substr($packet->payload, 0, 4)); if($token !== self::getTokenString($this->token, $packet->ip) and $token !== self::getTokenString($this->lastToken, $packet->ip)){ break; } @@ -127,7 +130,7 @@ class QueryHandler{ } $pk->payload = $this->longData; }else{ - $pk->payload = $this->server->name."\x00".(($this->server->gamemode & 0x01) === 0 ? "SMP":"CMP")."\x00".$this->server->api->level->getDefault()->getName()."\x00".count(Player::$list)."\x00".$this->server->maxClients."\x00".Utils::writeLShort($this->server->api->getProperty("server-port")).$this->server->api->getProperty("server-ip", "0.0.0.0")."\x00"; + $pk->payload = $this->server->name."\x00".(($this->server->gamemode & 0x01) === 0 ? "SMP":"CMP")."\x00".$this->server->api->level->getDefault()->getName()."\x00".count(Player::$list)."\x00".$this->server->maxClients."\x00".Utils\Utils::writeLShort($this->server->api->getProperty("server-port")).$this->server->api->getProperty("server-ip", "0.0.0.0")."\x00"; } $pk->encode(); $this->server->send($pk); diff --git a/src/network/query/QueryPacket.php b/src/network/query/QueryPacket.php index f24caeec7..5bdb6438a 100644 --- a/src/network/query/QueryPacket.php +++ b/src/network/query/QueryPacket.php @@ -19,7 +19,10 @@ * */ -class QueryPacket extends Packet{ +namespace PocketMine\Network\Query; +use PocketMine; + +class QueryPacket extends Network\Packet{ const HANDSHAKE = 9; const STATISTICS = 0; @@ -29,13 +32,13 @@ class QueryPacket extends Packet{ public function decode(){ $this->packetType = ord($this->buffer{2}); - $this->sessionID = Utils::readInt(substr($this->buffer, 3, 4)); + $this->sessionID = Utils\Utils::readInt(substr($this->buffer, 3, 4)); $this->payload = substr($this->buffer, 7); } public function encode(){ $this->buffer .= chr($this->packetType); - $this->buffer .= Utils::writeInt($this->sessionID); + $this->buffer .= Utils\Utils::writeInt($this->sessionID); $this->buffer .= $this->payload; } } \ No newline at end of file diff --git a/src/network/raknet/RakNetInfo.php b/src/network/raknet/Info.php similarity index 63% rename from src/network/raknet/RakNetInfo.php rename to src/network/raknet/Info.php index fb3460638..f9ce0dabd 100644 --- a/src/network/raknet/RakNetInfo.php +++ b/src/network/raknet/Info.php @@ -19,7 +19,10 @@ * */ -abstract class RakNetInfo{ +namespace PocketMine\Network\RakNet; +use PocketMine; + +abstract class Info{ const STRUCTURE = 5; const MAGIC = "\x00\xff\xff\x00\xfe\xfe\xfe\xfe\xfd\xfd\xfd\xfd\x12\x34\x56\x78"; const UNCONNECTED_PING = 0x01; @@ -59,33 +62,33 @@ abstract class RakNetInfo{ public static function isValid($pid){ switch((int) $pid){ - case RakNetInfo::UNCONNECTED_PING: - case RakNetInfo::UNCONNECTED_PING_OPEN_CONNECTIONS: - case RakNetInfo::OPEN_CONNECTION_REQUEST_1: - case RakNetInfo::OPEN_CONNECTION_REPLY_1: - case RakNetInfo::OPEN_CONNECTION_REQUEST_2: - case RakNetInfo::OPEN_CONNECTION_REPLY_2: - case RakNetInfo::INCOMPATIBLE_PROTOCOL_VERSION: - case RakNetInfo::UNCONNECTED_PONG: - case RakNetInfo::ADVERTISE_SYSTEM: - case RakNetInfo::DATA_PACKET_0: - case RakNetInfo::DATA_PACKET_1: - case RakNetInfo::DATA_PACKET_2: - case RakNetInfo::DATA_PACKET_3: - case RakNetInfo::DATA_PACKET_4: - case RakNetInfo::DATA_PACKET_5: - case RakNetInfo::DATA_PACKET_6: - case RakNetInfo::DATA_PACKET_7: - case RakNetInfo::DATA_PACKET_8: - case RakNetInfo::DATA_PACKET_9: - case RakNetInfo::DATA_PACKET_A: - case RakNetInfo::DATA_PACKET_B: - case RakNetInfo::DATA_PACKET_C: - case RakNetInfo::DATA_PACKET_D: - case RakNetInfo::DATA_PACKET_E: - case RakNetInfo::DATA_PACKET_F: - case RakNetInfo::NACK: - case RakNetInfo::ACK: + case self::UNCONNECTED_PING: + case self::UNCONNECTED_PING_OPEN_CONNECTIONS: + case self::OPEN_CONNECTION_REQUEST_1: + case self::OPEN_CONNECTION_REPLY_1: + case self::OPEN_CONNECTION_REQUEST_2: + case self::OPEN_CONNECTION_REPLY_2: + case self::INCOMPATIBLE_PROTOCOL_VERSION: + case self::UNCONNECTED_PONG: + case self::ADVERTISE_SYSTEM: + case self::DATA_PACKET_0: + case self::DATA_PACKET_1: + case self::DATA_PACKET_2: + case self::DATA_PACKET_3: + case self::DATA_PACKET_4: + case self::DATA_PACKET_5: + case self::DATA_PACKET_6: + case self::DATA_PACKET_7: + case self::DATA_PACKET_8: + case self::DATA_PACKET_9: + case self::DATA_PACKET_A: + case self::DATA_PACKET_B: + case self::DATA_PACKET_C: + case self::DATA_PACKET_D: + case self::DATA_PACKET_E: + case self::DATA_PACKET_F: + case self::NACK: + case self::ACK: return true; default: return false; diff --git a/src/network/raknet/RakNetPacket.php b/src/network/raknet/Packet.php similarity index 64% rename from src/network/raknet/RakNetPacket.php rename to src/network/raknet/Packet.php index 90c43f645..a4b87fe9d 100644 --- a/src/network/raknet/RakNetPacket.php +++ b/src/network/raknet/Packet.php @@ -19,7 +19,10 @@ * */ -class RakNetPacket extends Packet{ +namespace PocketMine\Network\RakNet; +use PocketMine; + +class Packet extends Network\Packet{ private $packetID; private $offset = 1; public $data = array(); @@ -48,19 +51,19 @@ class RakNetPacket extends Packet{ } private function getLong($unsigned = false){ - return Utils::readLong($this->get(8), $unsigned); + return Utils\Utils::readLong($this->get(8), $unsigned); } private function getInt(){ - return Utils::readInt($this->get(4)); + return Utils\Utils::readInt($this->get(4)); } private function getShort($unsigned = false){ - return Utils::readShort($this->get(2), $unsigned); + return Utils\Utils::readShort($this->get(2), $unsigned); } private function getLTriad(){ - return Utils::readTriad(strrev($this->get(3))); + return Utils\Utils::readTriad(strrev($this->get(3))); } private function getByte(){ @@ -74,47 +77,47 @@ class RakNetPacket extends Packet{ public function decode(){ $this->offset = 1; switch($this->packetID){ - case RakNetInfo::UNCONNECTED_PING: - case RakNetInfo::UNCONNECTED_PING_OPEN_CONNECTIONS: + case Info::UNCONNECTED_PING: + case Info::UNCONNECTED_PING_OPEN_CONNECTIONS: $this->pingID = $this->getLong(); $this->offset += 16; //Magic break; - case RakNetInfo::OPEN_CONNECTION_REQUEST_1: + case Info::OPEN_CONNECTION_REQUEST_1: $this->offset += 16; //Magic $this->structure = $this->getByte(); $this->mtuSize = strlen($this->get(true)); break; - case RakNetInfo::OPEN_CONNECTION_REQUEST_2: + case Info::OPEN_CONNECTION_REQUEST_2: $this->offset += 16; //Magic $this->security = $this->get(5); $this->clientPort = $this->getShort(false); $this->mtuSize = $this->getShort(false); $this->clientID = $this->getLong(); break; - case RakNetInfo::DATA_PACKET_0: - case RakNetInfo::DATA_PACKET_1: - case RakNetInfo::DATA_PACKET_2: - case RakNetInfo::DATA_PACKET_3: - case RakNetInfo::DATA_PACKET_4: - case RakNetInfo::DATA_PACKET_5: - case RakNetInfo::DATA_PACKET_6: - case RakNetInfo::DATA_PACKET_7: - case RakNetInfo::DATA_PACKET_8: - case RakNetInfo::DATA_PACKET_9: - case RakNetInfo::DATA_PACKET_A: - case RakNetInfo::DATA_PACKET_B: - case RakNetInfo::DATA_PACKET_C: - case RakNetInfo::DATA_PACKET_D: - case RakNetInfo::DATA_PACKET_E: - case RakNetInfo::DATA_PACKET_F: + case Info::DATA_PACKET_0: + case Info::DATA_PACKET_1: + case Info::DATA_PACKET_2: + case Info::DATA_PACKET_3: + case Info::DATA_PACKET_4: + case Info::DATA_PACKET_5: + case Info::DATA_PACKET_6: + case Info::DATA_PACKET_7: + case Info::DATA_PACKET_8: + case Info::DATA_PACKET_9: + case Info::DATA_PACKET_A: + case Info::DATA_PACKET_B: + case Info::DATA_PACKET_C: + case Info::DATA_PACKET_D: + case Info::DATA_PACKET_E: + case Info::DATA_PACKET_F: $this->seqNumber = $this->getLTriad(); $this->data = array(); while(!$this->feof() and $this->parseDataPacket() !== false){ } break; - case RakNetInfo::NACK: - case RakNetInfo::ACK: + case Info::NACK: + case Info::ACK: $count = $this->getShort(); $this->packets = array(); for($i = 0; $i < $count and !$this->feof(); ++$i){ @@ -184,163 +187,163 @@ class RakNetPacket extends Packet{ return false; } switch($pid){ - case ProtocolInfo::PING_PACKET: + case Network\Protocol\Info::PING_PACKET: $data = new PingPacket; break; - case ProtocolInfo::PONG_PACKET: + case Network\Protocol\Info::PONG_PACKET: $data = new PongPacket; break; - case ProtocolInfo::CLIENT_CONNECT_PACKET: + case Network\Protocol\Info::CLIENT_CONNECT_PACKET: $data = new ClientConnectPacket; break; - case ProtocolInfo::SERVER_HANDSHAKE_PACKET: + case Network\Protocol\Info::SERVER_HANDSHAKE_PACKET: $data = new ServerHandshakePacket; break; - case ProtocolInfo::DISCONNECT_PACKET: + case Network\Protocol\Info::DISCONNECT_PACKET: $data = new DisconnectPacket; break; - case ProtocolInfo::LOGIN_PACKET: + case Network\Protocol\Info::LOGIN_PACKET: $data = new LoginPacket; break; - case ProtocolInfo::LOGIN_STATUS_PACKET: + case Network\Protocol\Info::LOGIN_STATUS_PACKET: $data = new LoginStatusPacket; break; - case ProtocolInfo::READY_PACKET: + case Network\Protocol\Info::READY_PACKET: $data = new ReadyPacket; break; - case ProtocolInfo::MESSAGE_PACKET: + case Network\Protocol\Info::MESSAGE_PACKET: $data = new MessagePacket; break; - case ProtocolInfo::SET_TIME_PACKET: + case Network\Protocol\Info::SET_TIME_PACKET: $data = new SetTimePacket; break; - case ProtocolInfo::START_GAME_PACKET: + case Network\Protocol\Info::START_GAME_PACKET: $data = new StartGamePacket; break; - case ProtocolInfo::ADD_MOB_PACKET: + case Network\Protocol\Info::ADD_MOB_PACKET: $data = new AddMobPacket; break; - case ProtocolInfo::ADD_PLAYER_PACKET: + case Network\Protocol\Info::ADD_PLAYER_PACKET: $data = new AddPlayerPacket; break; - case ProtocolInfo::REMOVE_PLAYER_PACKET: + case Network\Protocol\Info::REMOVE_PLAYER_PACKET: $data = new RemovePlayerPacket; break; - case ProtocolInfo::ADD_ENTITY_PACKET: + case Network\Protocol\Info::ADD_ENTITY_PACKET: $data = new AddEntityPacket; break; - case ProtocolInfo::REMOVE_ENTITY_PACKET: + case Network\Protocol\Info::REMOVE_ENTITY_PACKET: $data = new RemoveEntityPacket; break; - case ProtocolInfo::ADD_ITEM_ENTITY_PACKET: + case Network\Protocol\Info::ADD_ITEM_ENTITY_PACKET: $data = new AddItemEntityPacket; break; - case ProtocolInfo::TAKE_ITEM_ENTITY_PACKET: + case Network\Protocol\Info::TAKE_ITEM_ENTITY_PACKET: $data = new TakeItemEntityPacket; break; - case ProtocolInfo::MOVE_ENTITY_PACKET: + case Network\Protocol\Info::MOVE_ENTITY_PACKET: $data = new MoveEntityPacket; break; - case ProtocolInfo::MOVE_ENTITY_PACKET_POSROT: + case Network\Protocol\Info::MOVE_ENTITY_PACKET_POSROT: $data = new MoveEntityPacket_PosRot; break; - case ProtocolInfo::ROTATE_HEAD_PACKET: + case Network\Protocol\Info::ROTATE_HEAD_PACKET: $data = new RotateHeadPacket; break; - case ProtocolInfo::MOVE_PLAYER_PACKET: + case Network\Protocol\Info::MOVE_PLAYER_PACKET: $data = new MovePlayerPacket; break; - case ProtocolInfo::REMOVE_BLOCK_PACKET: + case Network\Protocol\Info::REMOVE_BLOCK_PACKET: $data = new RemoveBlockPacket; break; - case ProtocolInfo::UPDATE_BLOCK_PACKET: + case Network\Protocol\Info::UPDATE_BLOCK_PACKET: $data = new UpdateBlockPacket; break; - case ProtocolInfo::ADD_PAINTING_PACKET: + case Network\Protocol\Info::ADD_PAINTING_PACKET: $data = new AddPaintingPacket; break; - case ProtocolInfo::EXPLODE_PACKET: + case Network\Protocol\Info::EXPLODE_PACKET: $data = new ExplodePacket; break; - case ProtocolInfo::LEVEL_EVENT_PACKET: + case Network\Protocol\Info::LEVEL_EVENT_PACKET: $data = new LevelEventPacket; break; - case ProtocolInfo::TILE_EVENT_PACKET: + case Network\Protocol\Info::TILE_EVENT_PACKET: $data = new TileEventPacket; break; - case ProtocolInfo::ENTITY_EVENT_PACKET: + case Network\Protocol\Info::ENTITY_EVENT_PACKET: $data = new EntityEventPacket; break; - case ProtocolInfo::REQUEST_CHUNK_PACKET: + case Network\Protocol\Info::REQUEST_CHUNK_PACKET: $data = new RequestChunkPacket; break; - case ProtocolInfo::CHUNK_DATA_PACKET: + case Network\Protocol\Info::CHUNK_DATA_PACKET: $data = new ChunkDataPacket; break; - case ProtocolInfo::PLAYER_EQUIPMENT_PACKET: + case Network\Protocol\Info::PLAYER_EQUIPMENT_PACKET: $data = new PlayerEquipmentPacket; break; - case ProtocolInfo::PLAYER_ARMOR_EQUIPMENT_PACKET: + case Network\Protocol\Info::PLAYER_ARMOR_EQUIPMENT_PACKET: $data = new PlayerArmorEquipmentPacket; break; - case ProtocolInfo::INTERACT_PACKET: + case Network\Protocol\Info::INTERACT_PACKET: $data = new InteractPacket; break; - case ProtocolInfo::USE_ITEM_PACKET: + case Network\Protocol\Info::USE_ITEM_PACKET: $data = new UseItemPacket; break; - case ProtocolInfo::PLAYER_ACTION_PACKET: + case Network\Protocol\Info::PLAYER_ACTION_PACKET: $data = new PlayerActionPacket; break; - case ProtocolInfo::HURT_ARMOR_PACKET: + case Network\Protocol\Info::HURT_ARMOR_PACKET: $data = new HurtArmorPacket; break; - case ProtocolInfo::SET_ENTITY_DATA_PACKET: + case Network\Protocol\Info::SET_ENTITY_DATA_PACKET: $data = new SetEntityDataPacket; break; - case ProtocolInfo::SET_ENTITY_MOTION_PACKET: + case Network\Protocol\Info::SET_ENTITY_MOTION_PACKET: $data = new SetEntityMotionPacket; break; - case ProtocolInfo::SET_HEALTH_PACKET: + case Network\Protocol\Info::SET_HEALTH_PACKET: $data = new SetHealthPacket; break; - case ProtocolInfo::SET_SPAWN_POSITION_PACKET: + case Network\Protocol\Info::SET_SPAWN_POSITION_PACKET: $data = new SetSpawnPositionPacket; break; - case ProtocolInfo::ANIMATE_PACKET: + case Network\Protocol\Info::ANIMATE_PACKET: $data = new AnimatePacket; break; - case ProtocolInfo::RESPAWN_PACKET: + case Network\Protocol\Info::RESPAWN_PACKET: $data = new RespawnPacket; break; - case ProtocolInfo::SEND_INVENTORY_PACKET: + case Network\Protocol\Info::SEND_INVENTORY_PACKET: $data = new SendInventoryPacket; break; - case ProtocolInfo::DROP_ITEM_PACKET: + case Network\Protocol\Info::DROP_ITEM_PACKET: $data = new DropItemPacket; break; - case ProtocolInfo::CONTAINER_OPEN_PACKET: + case Network\Protocol\Info::CONTAINER_OPEN_PACKET: $data = new ContainerOpenPacket; break; - case ProtocolInfo::CONTAINER_CLOSE_PACKET: + case Network\Protocol\Info::CONTAINER_CLOSE_PACKET: $data = new ContainerClosePacket; break; - case ProtocolInfo::CONTAINER_SET_SLOT_PACKET: + case Network\Protocol\Info::CONTAINER_SET_SLOT_PACKET: $data = new ContainerSetSlotPacket; break; - case ProtocolInfo::CONTAINER_SET_DATA_PACKET: + case Network\Protocol\Info::CONTAINER_SET_DATA_PACKET: $data = new ContainerSetDataPacket; break; - case ProtocolInfo::CONTAINER_SET_CONTENT_PACKET: + case Network\Protocol\Info::CONTAINER_SET_CONTENT_PACKET: $data = new ContainerSetContentPacket; break; - case ProtocolInfo::CHAT_PACKET: + case Network\Protocol\Info::CHAT_PACKET: $data = new ChatPacket; break; - case ProtocolInfo::ADVENTURE_SETTINGS_PACKET: + case Network\Protocol\Info::ADVENTURE_SETTINGS_PACKET: $data = new AdventureSettingsPacket; break; - case ProtocolInfo::ENTITY_DATA_PACKET: + case Network\Protocol\Info::ENTITY_DATA_PACKET: $data = new EntityDataPacket; break; default: @@ -369,54 +372,54 @@ class RakNetPacket extends Packet{ $this->buffer = chr($this->packetID); switch($this->packetID){ - case RakNetInfo::OPEN_CONNECTION_REPLY_1: - $this->buffer .= RakNetInfo::MAGIC; + case Info::OPEN_CONNECTION_REPLY_1: + $this->buffer .= Info::MAGIC; $this->putLong($this->serverID); $this->putByte(0); //server security $this->putShort($this->mtuSize); break; - case RakNetInfo::OPEN_CONNECTION_REPLY_2: - $this->buffer .= RakNetInfo::MAGIC; + case Info::OPEN_CONNECTION_REPLY_2: + $this->buffer .= Info::MAGIC; $this->putLong($this->serverID); $this->putShort($this->serverPort); $this->putShort($this->mtuSize); $this->putByte(0); //Server security break; - case RakNetInfo::INCOMPATIBLE_PROTOCOL_VERSION: - $this->putByte(RakNetInfo::STRUCTURE); - $this->buffer .= RakNetInfo::MAGIC; + case Info::INCOMPATIBLE_PROTOCOL_VERSION: + $this->putByte(Info::STRUCTURE); + $this->buffer .= Info::MAGIC; $this->putLong($this->serverID); break; - case RakNetInfo::UNCONNECTED_PONG: - case RakNetInfo::ADVERTISE_SYSTEM: + case Info::UNCONNECTED_PONG: + case Info::ADVERTISE_SYSTEM: $this->putLong($this->pingID); $this->putLong($this->serverID); - $this->buffer .= RakNetInfo::MAGIC; + $this->buffer .= Info::MAGIC; $this->putString($this->serverType); break; - case RakNetInfo::DATA_PACKET_0: - case RakNetInfo::DATA_PACKET_1: - case RakNetInfo::DATA_PACKET_2: - case RakNetInfo::DATA_PACKET_3: - case RakNetInfo::DATA_PACKET_4: - case RakNetInfo::DATA_PACKET_5: - case RakNetInfo::DATA_PACKET_6: - case RakNetInfo::DATA_PACKET_7: - case RakNetInfo::DATA_PACKET_8: - case RakNetInfo::DATA_PACKET_9: - case RakNetInfo::DATA_PACKET_A: - case RakNetInfo::DATA_PACKET_B: - case RakNetInfo::DATA_PACKET_C: - case RakNetInfo::DATA_PACKET_D: - case RakNetInfo::DATA_PACKET_E: - case RakNetInfo::DATA_PACKET_F: + case Info::DATA_PACKET_0: + case Info::DATA_PACKET_1: + case Info::DATA_PACKET_2: + case Info::DATA_PACKET_3: + case Info::DATA_PACKET_4: + case Info::DATA_PACKET_5: + case Info::DATA_PACKET_6: + case Info::DATA_PACKET_7: + case Info::DATA_PACKET_8: + case Info::DATA_PACKET_9: + case Info::DATA_PACKET_A: + case Info::DATA_PACKET_B: + case Info::DATA_PACKET_C: + case Info::DATA_PACKET_D: + case Info::DATA_PACKET_E: + case Info::DATA_PACKET_F: $this->putLTriad($this->seqNumber); foreach($this->data as $pk){ $this->encodeDataPacket($pk); } break; - case RakNetInfo::NACK: - case RakNetInfo::ACK: + case Info::NACK: + case Info::ACK: $payload = b""; $records = 0; $pointer = 0; @@ -439,11 +442,11 @@ class RakNetPacket extends Packet{ ++$pointer; if($type === false){ $payload .= "\x00"; - $payload .= strrev(Utils::writeTriad($start)); - $payload .= strrev(Utils::writeTriad($end)); + $payload .= strrev(Utils\Utils::writeTriad($start)); + $payload .= strrev(Utils\Utils::writeTriad($end)); }else{ - $payload .= Utils::writeBool(true); - $payload .= strrev(Utils::writeTriad($start)); + $payload .= Utils\Utils::writeBool(true); + $payload .= strrev(Utils\Utils::writeTriad($start)); } ++$records; } @@ -456,7 +459,7 @@ class RakNetPacket extends Packet{ } - private function encodeDataPacket(RakNetDataPacket $pk){ + private function encodeDataPacket(DataPacket $pk){ $this->putByte(($pk->reliability << 5) | ($pk->hasSplit > 0 ? 0b00010000:0)); $this->putShort(strlen($pk->buffer) << 3); if($pk->reliability === 2 @@ -489,23 +492,23 @@ class RakNetPacket extends Packet{ } protected function putLong($v){ - $this->buffer .= Utils::writeLong($v); + $this->buffer .= Utils\Utils::writeLong($v); } protected function putInt($v){ - $this->buffer .= Utils::writeInt($v); + $this->buffer .= Utils\Utils::writeInt($v); } protected function putShort($v){ - $this->buffer .= Utils::writeShort($v); + $this->buffer .= Utils\Utils::writeShort($v); } protected function putTriad($v){ - $this->buffer .= Utils::writeTriad($v); + $this->buffer .= Utils\Utils::writeTriad($v); } protected function putLTriad($v){ - $this->buffer .= strrev(Utils::writeTriad($v)); + $this->buffer .= strrev(Utils\Utils::writeTriad($v)); } protected function putByte($v){ diff --git a/src/network/rcon/RCON.php b/src/network/rcon/RCON.php new file mode 100644 index 000000000..377e4f7b1 --- /dev/null +++ b/src/network/rcon/RCON.php @@ -0,0 +1,84 @@ +workers = array(); + $this->password = (string) $password; + console("[INFO] Starting remote control listener"); + if($this->password === ""){ + console("[ERROR] RCON can't be started: Empty password"); + return; + } + $this->threads = (int) max(1, $threads); + $this->clientsPerThread = (int) max(1, $clientsPerThread); + $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); + if($this->socket === false or !socket_bind($this->socket, $interface, (int) $port) or !socket_listen($this->socket)){ + console("[ERROR] RCON can't be started: ".socket_strerror(socket_last_error())); + return; + } + @socket_set_block($this->socket); + for($n = 0; $n < $this->threads; ++$n){ + $this->workers[$n] = new RCONInstance($this->socket, $this->password, $this->clientsPerThread); + } + @socket_getsockname($this->socket, $addr, $port); + console("[INFO] RCON running on $addr:$port"); + ServerAPI::request()->schedule(2, array($this, "check"), array(), true); + } + + public function stop(){ + for($n = 0; $n < $this->threads; ++$n){ + $this->workers[$n]->close(); + $this->workers[$n]->join(); + usleep(50000); + $this->workers[$n]->kill(); + } + @socket_close($this->socket); + $this->threads = 0; + } + + public function check(){ + for($n = 0; $n < $this->threads; ++$n){ + if($this->workers[$n]->isTerminated() === true){ + $this->workers[$n] = new RCONInstance($this->socket, $this->password, $this->clientsPerThread); + }elseif($this->workers[$n]->isWaiting()){ + if($this->workers[$n]->response !== ""){ + console($this->workers[$n]->response); + $this->workers[$n]->notify(); + }else{ + $this->workers[$n]->response = ServerAPI::request()->api->console->run($this->workers[$n]->cmd, "rcon"); + $this->workers[$n]->notify(); + } + } + } + } + +} diff --git a/src/network/RCON.php b/src/network/rcon/RCONInstance.php similarity index 65% rename from src/network/RCON.php rename to src/network/rcon/RCONInstance.php index 4abe44644..567c05498 100644 --- a/src/network/RCON.php +++ b/src/network/rcon/RCONInstance.php @@ -19,68 +19,10 @@ * */ -/* -Implementation of the Source RCON Protocol to allow remote console commands -Source: https://developer.valvesoftware.com/wiki/Source_RCON_Protocol -*/ +namespace PocketMine\Network\RCON; +use PocketMine; -class RCON{ - private $socket, $password, $workers, $threads, $clientsPerThread; - - public function __construct($password, $port = 19132, $interface = "0.0.0.0", $threads = 1, $clientsPerThread = 50){ - $this->workers = array(); - $this->password = (string) $password; - console("[INFO] Starting remote control listener"); - if($this->password === ""){ - console("[ERROR] RCON can't be started: Empty password"); - return; - } - $this->threads = (int) max(1, $threads); - $this->clientsPerThread = (int) max(1, $clientsPerThread); - $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); - if($this->socket === false or !socket_bind($this->socket, $interface, (int) $port) or !socket_listen($this->socket)){ - console("[ERROR] RCON can't be started: ".socket_strerror(socket_last_error())); - return; - } - @socket_set_block($this->socket); - for($n = 0; $n < $this->threads; ++$n){ - $this->workers[$n] = new RCONInstance($this->socket, $this->password, $this->clientsPerThread); - } - @socket_getsockname($this->socket, $addr, $port); - console("[INFO] RCON running on $addr:$port"); - ServerAPI::request()->schedule(2, array($this, "check"), array(), true); - } - - public function stop(){ - for($n = 0; $n < $this->threads; ++$n){ - $this->workers[$n]->close(); - $this->workers[$n]->join(); - usleep(50000); - $this->workers[$n]->kill(); - } - @socket_close($this->socket); - $this->threads = 0; - } - - public function check(){ - for($n = 0; $n < $this->threads; ++$n){ - if($this->workers[$n]->isTerminated() === true){ - $this->workers[$n] = new RCONInstance($this->socket, $this->password, $this->clientsPerThread); - }elseif($this->workers[$n]->isWaiting()){ - if($this->workers[$n]->response !== ""){ - console($this->workers[$n]->response); - $this->workers[$n]->notify(); - }else{ - $this->workers[$n]->response = ServerAPI::request()->api->console->run($this->workers[$n]->cmd, "rcon"); - $this->workers[$n]->notify(); - } - } - } - } - -} - -class RCONInstance extends Thread{ +class RCONInstance extends \Thread{ public $stop; public $cmd; public $response; @@ -104,11 +46,11 @@ class RCONInstance extends Thread{ } private function writePacket($client, $requestID, $packetType, $payload){ - $pk = Utils::writeLInt((int) $requestID) - . Utils::writeLInt((int) $packetType) + $pk = Utils\Utils::writeLInt((int) $requestID) + . Utils\Utils::writeLInt((int) $packetType) . $payload . "\x00\x00"; //Terminate payload and packet - return socket_write($client, Utils::writeLInt(strlen($pk)).$pk); + return socket_write($client, Utils\Utils::writeLInt(strlen($pk)).$pk); } private function readPacket($client, &$size, &$requestID, &$packetType, &$payload){ @@ -122,12 +64,12 @@ class RCONInstance extends Thread{ return false; } @socket_set_block($client); - $size = Utils::readLInt($d); + $size = Utils\Utils::readLInt($d); if($size < 0 or $size > 65535){ return false; } - $requestID = Utils::readLInt(socket_read($client, 4)); - $packetType = Utils::readLInt(socket_read($client, 4)); + $requestID = Utils\Utils::readLInt(socket_read($client, 4)); + $packetType = Utils\Utils::readLInt(socket_read($client, 4)); $payload = rtrim(socket_read($client, $size + 2)); //Strip two null bytes return true; } diff --git a/src/utils/UPnP.php b/src/network/upnp/PortForward.php similarity index 82% rename from src/utils/UPnP.php rename to src/network/upnp/PortForward.php index 12ec6068e..73a8e59cd 100644 --- a/src/utils/UPnP.php +++ b/src/network/upnp/PortForward.php @@ -19,11 +19,14 @@ * */ -function UPnP_PortForward($port){ - if(Utils::$online === false){ +namespace PocketMine\Network\UPnP; +use PocketMine; + +function PortForward($port){ + if(Utils\Utils::$online === false){ return false; } - if(Utils::getOS() != "win" or !class_exists("COM")){ + if(Utils\Utils::getOS() != "win" or !class_exists("COM")){ return false; } $port = (int) $port; @@ -40,11 +43,11 @@ function UPnP_PortForward($port){ return true; } -function UPnP_RemovePortForward($port){ - if(Utils::$online === false){ +function RemovePortForward($port){ + if(Utils\Utils::$online === false){ return false; } - if(Utils::getOS() != "win" or !class_exists("COM")){ + if(Utils\Utils::getOS() != "win" or !class_exists("COM")){ return false; } $port = (int) $port; diff --git a/src/network/upnp/RemovePortForward.php b/src/network/upnp/RemovePortForward.php new file mode 100644 index 000000000..9c5df4ebf --- /dev/null +++ b/src/network/upnp/RemovePortForward.php @@ -0,0 +1,43 @@ +StaticPortMappingCollection)){ + return false; + } + $com->StaticPortMappingCollection->Remove($port, "UDP"); + }catch(Exception $e){ + return false; + } + return true; +} \ No newline at end of file diff --git a/src/pmf/PMFLevel.php b/src/pmf/Level.php similarity index 85% rename from src/pmf/PMFLevel.php rename to src/pmf/Level.php index 5cf95164b..035b7c0b1 100644 --- a/src/pmf/PMFLevel.php +++ b/src/pmf/Level.php @@ -19,7 +19,10 @@ * */ -class PMFLevel extends PMF{ +namespace PocketMine\PMF +use PocketMine; + +class Level extends PMF{ const VERSION = 2; const ZLIB_LEVEL = 6; const ZLIB_ENCODING = 15; //15 = zlib, -15 = raw deflate, 31 = gzip @@ -77,22 +80,22 @@ class PMFLevel extends PMF{ } public function saveData(){ - $this->levelData["version"] = PMFLevel::VERSION; + $this->levelData["version"] = self::VERSION; @ftruncate($this->fp, 5); $this->seek(5); $this->write(chr($this->levelData["version"])); - $this->write(Utils::writeShort(strlen($this->levelData["name"])).$this->levelData["name"]); - $this->write(Utils::writeInt($this->levelData["seed"])); - $this->write(Utils::writeInt($this->levelData["time"])); - $this->write(Utils::writeFloat($this->levelData["spawnX"])); - $this->write(Utils::writeFloat($this->levelData["spawnY"])); - $this->write(Utils::writeFloat($this->levelData["spawnZ"])); + $this->write(Utils\Utils::writeShort(strlen($this->levelData["name"])).$this->levelData["name"]); + $this->write(Utils\Utils::writeInt($this->levelData["seed"])); + $this->write(Utils\Utils::writeInt($this->levelData["time"])); + $this->write(Utils\Utils::writeFloat($this->levelData["spawnX"])); + $this->write(Utils\Utils::writeFloat($this->levelData["spawnY"])); + $this->write(Utils\Utils::writeFloat($this->levelData["spawnZ"])); $this->write(chr($this->levelData["height"])); - $this->write(Utils::writeShort(strlen($this->levelData["generator"])).$this->levelData["generator"]); + $this->write(Utils\Utils::writeShort(strlen($this->levelData["generator"])).$this->levelData["generator"]); $settings = serialize($this->levelData["generatorSettings"]); - $this->write(Utils::writeShort(strlen($settings)).$settings); - $extra = zlib_encode($this->levelData["extra"], PMFLevel::ZLIB_ENCODING, PMFLevel::ZLIB_LEVEL); - $this->write(Utils::writeShort(strlen($extra)).$extra); + $this->write(Utils\Utils::writeShort(strlen($settings)).$settings); + $extra = zlib_encode($this->levelData["extra"], self::ZLIB_ENCODING, self::ZLIB_LEVEL); + $this->write(Utils\Utils::writeShort(strlen($extra)).$extra); } private function createBlank(){ @@ -106,16 +109,16 @@ class PMFLevel extends PMF{ } $this->seek(5); $this->levelData["version"] = ord($this->read(1)); - if($this->levelData["version"] > PMFLevel::VERSION){ - console("[ERROR] New unsupported PMF Level format version #".$this->levelData["version"].", current version is #".PMFLevel::VERSION); + if($this->levelData["version"] > self::VERSION){ + console("[ERROR] New unsupported PMF Level format version #".$this->levelData["version"].", current version is #".self::VERSION); return false; } - $this->levelData["name"] = $this->read(Utils::readShort($this->read(2), false)); - $this->levelData["seed"] = Utils::readInt($this->read(4)); - $this->levelData["time"] = Utils::readInt($this->read(4)); - $this->levelData["spawnX"] = Utils::readFloat($this->read(4)); - $this->levelData["spawnY"] = Utils::readFloat($this->read(4)); - $this->levelData["spawnZ"] = Utils::readFloat($this->read(4)); + $this->levelData["name"] = $this->read(Utils\Utils::readShort($this->read(2), false)); + $this->levelData["seed"] = Utils\Utils::readInt($this->read(4)); + $this->levelData["time"] = Utils\Utils::readInt($this->read(4)); + $this->levelData["spawnX"] = Utils\Utils::readFloat($this->read(4)); + $this->levelData["spawnY"] = Utils\Utils::readFloat($this->read(4)); + $this->levelData["spawnZ"] = Utils\Utils::readFloat($this->read(4)); if($this->levelData["version"] === 0){ $this->read(1); $this->levelData["height"] = ord($this->read(1)); @@ -124,11 +127,11 @@ class PMFLevel extends PMF{ if($this->levelData["height"] !== 8){ return false; } - $this->levelData["generator"] = $this->read(Utils::readShort($this->read(2), false)); - $this->levelData["generatorSettings"] = unserialize($this->read(Utils::readShort($this->read(2), false))); + $this->levelData["generator"] = $this->read(Utils\Utils::readShort($this->read(2), false)); + $this->levelData["generatorSettings"] = unserialize($this->read(Utils\Utils::readShort($this->read(2), false))); } - $this->levelData["extra"] = @zlib_decode($this->read(Utils::readShort($this->read(2), false))); + $this->levelData["extra"] = @zlib_decode($this->read(Utils\Utils::readShort($this->read(2), false))); $upgrade = false; if($this->levelData["version"] === 0){ @@ -151,7 +154,7 @@ class PMFLevel extends PMF{ $X = $index & 0x0F; $Z = $index >> 4; - $bitflags = Utils::readShort($this->read(2)); + $bitflags = Utils\Utils::readShort($this->read(2)); $oldPath = dirname($this->file)."/chunks/".$Z.".".$X.".pmc"; $chunkOld = gzopen($oldPath, "rb"); $newPath = dirname($this->file)."/chunks/".(($X ^ $Z) & 0xff)."/".$Z.".".$X.".pmc"; @@ -166,28 +169,28 @@ class PMFLevel extends PMF{ @unlink($oldPath); } $this->levelData["version"] = 1; - $this->levelData["generator"] = "NormalGenerator"; + $this->levelData["generator"] = "default"; $this->levelData["generatorSettings"] = ""; } private function upgrade_From1_To2(){ console("[NOTICE] Old PMF Level format version #1 detected, upgrading to version #2"); - $nbt = new NBT(NBT::BIG_ENDIAN); - $nbt->setData(new NBTTag_Compound("", array( - "Entities" => new NBTTag_List("Entities", array()), - "TileEntities" => new NBTTag_List("TileEntities", array()) + $nbt = new NBT(NBT\BIG_ENDIAN); + $nbt->setData(new NBT\Tag\Compound("", array( + "Entities" => new NBT\Tag\Enum("Entities", array()), + "TileEntities" => new NBT\Tag\Enum("TileEntities", array()) ))); - $nbt->Entities->setTagType(NBTTag::TAG_Compound); - $nbt->TileEntities->setTagType(NBTTag::TAG_Compound); + $nbt->Entities->setTagType(NBT\TAG_Compound); + $nbt->TileEntities->setTagType(NBT\TAG_Compound); $namedtag = $nbt->write(); - $namedtag = Utils::writeInt(strlen($namedtag)) . $namedtag; + $namedtag = Utils\Utils::writeInt(strlen($namedtag)) . $namedtag; foreach(glob(dirname($this->file)."/chunks/*/*.*.pmc") as $chunkFile){ $oldChunk = zlib_decode(file_get_contents($chunkFile)); $newChunk = substr($oldChunk, 0, 5); $newChunk .= $namedtag; $newChunk .= str_repeat("\x01", 256); //Biome indexes (all Plains) $newChunk .= substr($oldChunk, 5); - file_put_contents($chunkFile, zlib_encode($newChunk, PMFLevel::ZLIB_ENCODING, PMFLevel::ZLIB_LEVEL)); + file_put_contents($chunkFile, zlib_encode($newChunk, self::ZLIB_ENCODING, self::ZLIB_LEVEL)); } $this->levelData["version"] = 2; } @@ -212,7 +215,7 @@ class PMFLevel extends PMF{ @mkdir(dirname($path), 0755); } $this->initCleanChunk($X, $Z); - if($this->level instanceof Level){ + if($this->level instanceof Level\Level){ $ret = $this->level->generateChunk($X, $Z); $this->saveChunk($X, $Z); $this->populateChunk($X - 1, $Z); @@ -228,7 +231,7 @@ class PMFLevel extends PMF{ } public function populateChunk($X, $Z){ - if($this->level instanceof Level){ + if($this->level instanceof Level\Level){ if($this->isGenerating === 0 and $this->isChunkLoaded($X, $Z) and !$this->isPopulated($X, $Z) and @@ -271,12 +274,12 @@ class PMFLevel extends PMF{ $this->chunkInfo[$index] = array( 0 => ord($chunk{0}), - 1 => Utils::readInt(substr($chunk, 1, 4)), + 1 => Utils\Utils::readInt(substr($chunk, 1, 4)), ); $offset += 5; - $len = Utils::readInt(substr($chunk, $offset, 4)); + $len = Utils\Utils::readInt(substr($chunk, $offset, 4)); $offset += 4; - $nbt = new NBT(NBT::BIG_ENDIAN); + $nbt = new NBT(NBT\BIG_ENDIAN); $nbt->read(substr($chunk, $offset, $len)); $this->chunkInfo[$index][2] = $nbt; $offset += $len; @@ -393,13 +396,13 @@ class PMFLevel extends PMF{ 6 => 8192, 7 => 8192, ); - $nbt = new NBT(NBT::BIG_ENDIAN); - $nbt->setData(new NBTTag_Compound("", array( - "Entities" => new NBTTag_List("Entities", array()), - "TileEntities" => new NBTTag_List("TileEntities", array()) + $nbt = new NBT(NBT\BIG_ENDIAN); + $nbt->setData(new NBT\Tag\Compound("", array( + "Entities" => new NBT\Tag\Enum("Entities", array()), + "TileEntities" => new NBT\Tag\Enum("TileEntities", array()) ))); - $nbt->Entities->setTagType(NBTTag::TAG_Compound); - $nbt->TileEntities->setTagType(NBTTag::TAG_Compound); + $nbt->Entities->setTagType(NBT\TAG_Compound); + $nbt->TileEntities->setTagType(NBT\TAG_Compound); $this->chunkInfo[$index] = array( 0 => 0, 1 => 0, @@ -668,9 +671,9 @@ class PMFLevel extends PMF{ $this->chunkChange[$index][-1] = false; $chunk = b""; $chunk .= chr($bitmap); - $chunk .= Utils::writeInt($this->chunkInfo[$index][1]); + $chunk .= Utils\Utils::writeInt($this->chunkInfo[$index][1]); $namedtag = $this->chunkInfo[$index][2]->write(); - $chunk .= Utils::writeInt(strlen($namedtag)).$namedtag; + $chunk .= Utils\Utils::writeInt(strlen($namedtag)).$namedtag; $chunk .= $this->chunkInfo[$index][3]; //biomes for($Y = 0; $Y < 8; ++$Y){ $t = 1 << $Y; @@ -678,7 +681,7 @@ class PMFLevel extends PMF{ $chunk .= $this->chunks[$index][$Y]; } } - file_put_contents($path, zlib_encode($chunk, PMFLevel::ZLIB_ENCODING, PMFLevel::ZLIB_LEVEL)); + file_put_contents($path, zlib_encode($chunk, self::ZLIB_ENCODING, self::ZLIB_LEVEL)); return true; } diff --git a/src/pmf/PMF.php b/src/pmf/PMF.php index f22ee4d85..cbcf86c81 100644 --- a/src/pmf/PMF.php +++ b/src/pmf/PMF.php @@ -19,15 +19,17 @@ * */ -define("PMF_CURRENT_VERSION", 0x01); +namespace PocketMine\PMF class PMF{ + const VERSION = 0x01; + protected $fp; protected $file; private $version; private $type; - public function __construct($file, $new = false, $type = 0, $version = PMF_CURRENT_VERSION){ + public function __construct($file, $new = false, $type = 0, $version = PMF::VERSION){ if($new === true){ $this->create($file, $type, $version); }else{ @@ -88,7 +90,7 @@ class PMF{ } } - public function create($file, $type, $version = PMF_CURRENT_VERSION){ + public function create($file, $type, $version = PMF::VERSION){ $this->file = $file; @mkdir(dirname($this->file), 0755, true); if(!is_resource($this->fp)){ diff --git a/src/pmf/PMFPlugin.php b/src/pmf/Plugin.php similarity index 62% rename from src/pmf/PMFPlugin.php rename to src/pmf/Plugin.php index 25bd82749..9fc6a7e54 100644 --- a/src/pmf/PMFPlugin.php +++ b/src/pmf/Plugin.php @@ -19,13 +19,12 @@ * */ -/***REM_START***/ -require_once(FILE_PATH."/src/pmf/PMF.php"); -/***REM_END***/ +namespace PocketMine\PMF +use PocketMine; -define("PMF_CURRENT_PLUGIN_VERSION", 0x02); +class Plugin extends PMF{ + const VERSION = 0x02; -class PMFPlugin extends PMF{ private $pluginData = array(); public function __construct($file){ $this->load($file); @@ -43,21 +42,21 @@ class PMFPlugin extends PMF{ } $this->seek(5); $this->pluginData["fversion"] = ord($this->read(1)); - if($this->pluginData["fversion"] > PMF_CURRENT_PLUGIN_VERSION){ + if($this->pluginData["fversion"] > PMFPlugin::VERSION){ return false; } - $this->pluginData["name"] = $this->read(Utils::readShort($this->read(2), false)); - $this->pluginData["version"] = $this->read(Utils::readShort($this->read(2), false)); - $this->pluginData["author"] = $this->read(Utils::readShort($this->read(2), false)); + $this->pluginData["name"] = $this->read(Utils\Utils::readShort($this->read(2), false)); + $this->pluginData["version"] = $this->read(Utils\Utils::readShort($this->read(2), false)); + $this->pluginData["author"] = $this->read(Utils\Utils::readShort($this->read(2), false)); if($this->pluginData["fversion"] >= 0x01){ - $this->pluginData["apiversion"] = $this->read(Utils::readShort($this->read(2), false)); + $this->pluginData["apiversion"] = $this->read(Utils\Utils::readShort($this->read(2), false)); }else{ - $this->pluginData["apiversion"] = Utils::readShort($this->read(2), false); + $this->pluginData["apiversion"] = Utils\Utils::readShort($this->read(2), false); } - $this->pluginData["class"] = $this->read(Utils::readShort($this->read(2), false)); - $this->pluginData["identifier"] = $this->read(Utils::readShort($this->read(2), false)); //Will be used to check for updates + $this->pluginData["class"] = $this->read(Utils\Utils::readShort($this->read(2), false)); + $this->pluginData["identifier"] = $this->read(Utils\Utils::readShort($this->read(2), false)); //Will be used to check for updates if($this->pluginData["fversion"] >= 0x02){ - $data = explode(";", gzinflate($this->read(Utils::readInt($this->read(4))))); + $data = explode(";", gzinflate($this->read(Utils\Utils::readInt($this->read(4))))); $this->pluginData["extra"] = array(); foreach($data as $v){ $v = trim($v); @@ -69,7 +68,7 @@ class PMFPlugin extends PMF{ } }else{ - $this->pluginData["extra"] = gzinflate($this->read(Utils::readShort($this->read(2), false))); + $this->pluginData["extra"] = gzinflate($this->read(Utils\Utils::readShort($this->read(2), false))); } $this->pluginData["code"] = ""; while(!feof($this->fp)){ diff --git a/src/recipes/CraftingRecipes.php b/src/recipes/Crafting.php similarity index 98% rename from src/recipes/CraftingRecipes.php rename to src/recipes/Crafting.php index 8c9e2c3f1..27aef3406 100644 --- a/src/recipes/CraftingRecipes.php +++ b/src/recipes/Crafting.php @@ -19,7 +19,10 @@ * */ -class CraftingRecipes{ +namespace PocketMine\Recipes; +use PocketMine; + +abstract class Crafting{ private static $small = array(//Probably means craftable on crafting bench and in inventory. Name it better! //Building "CLAY:?x4=>CLAY_BLOCK:0x1", @@ -283,7 +286,7 @@ class CraftingRecipes{ $server = ServerAPI::request(); $result = $server->query("SELECT id FROM recipes WHERE type == ".$type." AND recipe == '".$recipeString."';"); - if($result instanceof SQLite3Result){ + if($result instanceof \SQLite3Result){ $continue = true; while(($r = $result->fetchArray(SQLITE3_NUM)) !== false){ $continue = true; diff --git a/src/recipes/FuelData.php b/src/recipes/Fuel.php similarity index 94% rename from src/recipes/FuelData.php rename to src/recipes/Fuel.php index e522abf8e..7d89b2560 100644 --- a/src/recipes/FuelData.php +++ b/src/recipes/Fuel.php @@ -19,8 +19,10 @@ * */ +namespace PocketMine\Recipes; +use PocketMine; -class FuelData{ +abstract class Fuel{ public static $duration = array( COAL => 80, COAL_BLOCK => 800, diff --git a/src/recipes/SmeltingData.php b/src/recipes/Smelt.php similarity index 95% rename from src/recipes/SmeltingData.php rename to src/recipes/Smelt.php index d29dc0138..73113e1e2 100644 --- a/src/recipes/SmeltingData.php +++ b/src/recipes/Smelt.php @@ -19,8 +19,10 @@ * */ +namespace PocketMine\Recipes; +use PocketMine; -class SmeltingData{ +class Smelt{ public static $product = array( COBBLESTONE => array(STONE, 0), SAND => array(GLASS, 0), @@ -38,5 +40,4 @@ class SmeltingData{ RED_MUSHROOM => array(DYE, 1), POTATO => array(BAKED_POTATO, 0), ); - } \ No newline at end of file diff --git a/src/tests/ServerSuiteTest.php b/src/tests/ServerSuiteTest.php index 6f5828611..f6ad4dc15 100644 --- a/src/tests/ServerSuiteTest.php +++ b/src/tests/ServerSuiteTest.php @@ -1,31 +1,32 @@ id = Tile::CHEST; parent::__construct($level, $nbt); } @@ -43,7 +41,7 @@ class ChestTile extends SpawnableTile{ public function getPair(){ if($this->isPaired()){ - return $this->level->getTile(new Vector3((int) $this->namedtag->pairx, $this->y, (int) $this->namedtag->pairz)); + return $this->level->getTile(new Math\Vector3((int) $this->namedtag->pairx, $this->y, (int) $this->namedtag->pairz)); } return false; } @@ -75,7 +73,7 @@ class ChestTile extends SpawnableTile{ $this->spawnToAll(); $this->server->handle("tile.update", $this); - if($tile instanceof ChestTile){ + if($tile instanceof Chest){ $tile->spawnToAll(); $this->server->handle("tile.update", $tile); } @@ -86,26 +84,26 @@ class ChestTile extends SpawnableTile{ return false; } - $nbt = new NBT(NBT::LITTLE_ENDIAN); + $nbt = new NBT(NBT\LITTLE_ENDIAN); if($this->isPaired()){ - $nbt->setData(new NBTTag_Compound("", array( - new NBTTag_String("id", Tile::CHEST), - new NBTTag_Int("x", (int) $this->x), - new NBTTag_Int("y", (int) $this->y), - new NBTTag_Int("z", (int) $this->z), - new NBTTag_Int("pairx", (int) $this->namedtag->pairx), - new NBTTag_Int("pairz", (int) $this->namedtag->pairz) + $nbt->setData(new NBT\Tag\Compound("", array( + new NBT\Tag\String("id", Tile::CHEST), + new NBT\Tag\Int("x", (int) $this->x), + new NBT\Tag\Int("y", (int) $this->y), + new NBT\Tag\Int("z", (int) $this->z), + new NBT\Tag\Int("pairx", (int) $this->namedtag->pairx), + new NBT\Tag\Int("pairz", (int) $this->namedtag->pairz) ))); }else{ - $nbt->setData(new NBTTag_Compound("", array( - new NBTTag_String("id", Tile::CHEST), - new NBTTag_Int("x", (int) $this->x), - new NBTTag_Int("y", (int) $this->y), - new NBTTag_Int("z", (int) $this->z) + $nbt->setData(new NBT\Tag\Compound("", array( + new NBT\Tag\String("id", Tile::CHEST), + new NBT\Tag\Int("x", (int) $this->x), + new NBT\Tag\Int("y", (int) $this->y), + new NBT\Tag\Int("z", (int) $this->z) ))); } - $pk = new EntityDataPacket; + $pk = new Network\Protocol\EntityDataPacket; $pk->x = $this->x; $pk->y = $this->y; $pk->z = $this->z; diff --git a/src/tile/ContainerTileTrait.php b/src/tile/Container.php similarity index 81% rename from src/tile/ContainerTileTrait.php rename to src/tile/Container.php index 40716e91a..ae8a18ce4 100644 --- a/src/tile/ContainerTileTrait.php +++ b/src/tile/Container.php @@ -19,9 +19,12 @@ * */ -trait ContainerTileTrait{ +namespace PocketMine\Tile; +use PocketMine; + +trait Container{ public function openInventory(Player $player){ - if($this instanceof ChestTile){ + if($this instanceof Chest){ $player->windowCnt++; $player->windowCnt = $id = max(2, $player->windowCnt % 99); if(($pair = $this->getPair()) !== false){ @@ -43,7 +46,7 @@ trait ContainerTileTrait{ $pk = new ContainerOpenPacket; $pk->windowid = $id; $pk->type = WINDOW_CHEST; - $pk->slots = is_array($player->windows[$id]) ? ChestTile::SLOTS << 1:ChestTile::SLOTS; + $pk->slots = is_array($player->windows[$id]) ? Chest::SLOTS << 1:Chest::SLOTS; $pk->x = $this->x; $pk->y = $this->y; $pk->z = $this->z; @@ -60,7 +63,7 @@ trait ContainerTileTrait{ $pk->case1 = 1; $pk->case2 = 2; Player::broadcastPacket($all, $pk); - for($s = 0; $s < ChestTile::SLOTS; ++$s){ + for($s = 0; $s < Chest::SLOTS; ++$s){ $slot = $ob->getSlot($s); if($slot->getID() > AIR and $slot->getCount() > 0){ $slots[] = $slot; @@ -77,7 +80,7 @@ trait ContainerTileTrait{ $pk->case1 = 1; $pk->case2 = 2; Player::broadcastPacket($this->level->getPlayers(), $pk); - for($s = 0; $s < ChestTile::SLOTS; ++$s){ + for($s = 0; $s < Chest::SLOTS; ++$s){ $slot = $this->getSlot($s); if($slot->getID() > AIR and $slot->getCount() > 0){ $slots[] = $slot; @@ -92,7 +95,7 @@ trait ContainerTileTrait{ $pk->slots = $slots; $player->dataPacket($pk); return true; - }elseif($this instanceof FurnaceTile){ + }elseif($this instanceof Furnace){ $player->windowCnt++; $player->windowCnt = $id = max(2, $player->windowCnt % 99); $player->windows[$id] = $this; @@ -100,14 +103,14 @@ trait ContainerTileTrait{ $pk = new ContainerOpenPacket; $pk->windowid = $id; $pk->type = WINDOW_FURNACE; - $pk->slots = FurnaceTile::SLOTS; + $pk->slots = Furnace::SLOTS; $pk->x = $this->x; $pk->y = $this->y; $pk->z = $this->z; $player->dataPacket($pk); $slots = array(); - for($s = 0; $s < FurnaceTile::SLOTS; ++$s){ + for($s = 0; $s < Furnace::SLOTS; ++$s){ $slot = $this->getSlot($s); if($slot->getID() > AIR and $slot->getCount() > 0){ $slots[] = $slot; @@ -141,19 +144,19 @@ trait ContainerTileTrait{ } } - public function setSlot($s, Item $item, $update = true, $offset = 0){ + public function setSlot($s, Item\Item $item, $update = true, $offset = 0){ $i = $this->getSlotIndex($s); - if($i === false or EventHandler::callEvent($ev = new TileInventoryChangeEvent($this, $this->getSlot($s), $item, $s, $offset)) === BaseEvent::DENY){ + if($i === false or Event\EventHandler::callEvent($ev = new Event\Tile\TileInventoryChangeEvent($this, $this->getSlot($s), $item, $s, $offset)) === Event\Event::DENY){ return false; } $item = $ev->getNewItem(); - $d = new NBTTag_Compound(false, array( - "Count" => new NBTTag_Byte("Count", $item->getCount()), - "Slot" => new NBTTag_Byte("Slot", $s), - "id" => new NBTTag_Short("id", $item->getID()), - "Damage" => new NBTTag_Short("Damage", $item->getMetadata()), + $d = new NBT\Tag\Compound(false, array( + "Count" => new NBT\Tag\Byte("Count", $item->getCount()), + "Slot" => new NBT\Tag\Byte("Slot", $s), + "id" => new NBT\Tag\Short("id", $item->getID()), + "Damage" => new NBT\Tag\Short("Damage", $item->getMetadata()), )); if($item->getID() === AIR or $item->getCount() <= 0){ diff --git a/src/tile/FurnaceTile.php b/src/tile/Furnace.php similarity index 94% rename from src/tile/FurnaceTile.php rename to src/tile/Furnace.php index 79d64d519..c29ba12f2 100644 --- a/src/tile/FurnaceTile.php +++ b/src/tile/Furnace.php @@ -18,17 +18,16 @@ * * */ -/***REM_START***/ -require_once("SpawnableTile.php"); -require_once("ContainerTileTrait.php"); -/***REM_END***/ -class FurnaceTile extends Tile{ - use ContainerTileTrait; +namespace PocketMine\Tile; +use PocketMine; + +class Furnace extends Tile{ + use Container; const SLOTS = 3; - public function __construct(Level $level, NBTTag_Compound $nbt){ + public function __construct(Level\Level $level, NBT\Tag\Compound $nbt){ $nbt->id = Tile::FURNACE; parent::__construct($level, $nbt); if(!isset($this->namedtag->BurnTime) or $this->namedtag->BurnTime < 0){ diff --git a/src/tile/SignTile.php b/src/tile/Sign.php similarity index 68% rename from src/tile/SignTile.php rename to src/tile/Sign.php index 86c16a05b..1787a46c3 100644 --- a/src/tile/SignTile.php +++ b/src/tile/Sign.php @@ -19,13 +19,12 @@ * */ -/***REM_START***/ -require_once("SpawnableTile.php"); -/***REM_END***/ +namespace PocketMine\Tile; +use PocketMine; -class SignTile extends SpawnableTile{ +class Sign extends Spawnable{ - public function __construct(Level $level, NBTTag_Compound $nbt){ + public function __construct(Level $level, NBT\Tag\Compound $nbt){ $nbt->id = Tile::SIGN; parent::__construct($level, $nbt); } @@ -54,18 +53,18 @@ class SignTile extends SpawnableTile{ return false; } - $nbt = new NBT(NBT::LITTLE_ENDIAN); - $nbt->setData(new NBTTag_Compound("", array( - new NBTTag_String("Text1", $this->namedtag->Text1), - new NBTTag_String("Text2", $this->namedtag->Text2), - new NBTTag_String("Text3", $this->namedtag->Text3), - new NBTTag_String("Text4", $this->namedtag->Text4), - new NBTTag_String("id", Tile::SIGN), - new NBTTag_Int("x", (int) $this->x), - new NBTTag_Int("y", (int) $this->y), - new NBTTag_Int("z", (int) $this->z) + $nbt = new NBT\NBT(NBT\LITTLE_ENDIAN); + $nbt->setData(new NBT\Tag\Compound("", array( + new NBT\Tag\String("Text1", $this->namedtag->Text1), + new NBT\Tag\String("Text2", $this->namedtag->Text2), + new NBT\Tag\String("Text3", $this->namedtag->Text3), + new NBT\Tag\String("Text4", $this->namedtag->Text4), + new NBT\Tag\String("id", Tile::SIGN), + new NBT\Tag\Int("x", (int) $this->x), + new NBT\Tag\Int("y", (int) $this->y), + new NBT\Tag\Int("z", (int) $this->z) ))); - $pk = new EntityDataPacket; + $pk = new Network\Protocol\EntityDataPacket; $pk->x = $this->x; $pk->y = $this->y; $pk->z = $this->z; diff --git a/src/tile/SpawnableTile.php b/src/tile/Spawnable.php similarity index 91% rename from src/tile/SpawnableTile.php rename to src/tile/Spawnable.php index e51474149..a0acc9e44 100644 --- a/src/tile/SpawnableTile.php +++ b/src/tile/Spawnable.php @@ -19,7 +19,10 @@ * */ -abstract class SpawnableTile extends Tile{ +namespace PocketMine\Tile; +use PocketMine; + +abstract class Spawnable extends Tile{ public abstract function spawnTo(Player $player); public function spawnToAll(){ diff --git a/src/Tile.php b/src/tile/Tile.php similarity index 93% rename from src/Tile.php rename to src/tile/Tile.php index 56c44c18a..655dd2079 100644 --- a/src/Tile.php +++ b/src/tile/Tile.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine\Tile; +use PocketMine; + abstract class Tile extends Position{ const SIGN = "Sign"; const CHEST = "Chest"; @@ -54,7 +57,7 @@ abstract class Tile extends Position{ } - public function __construct(Level $level, NBTTag_Compound $nbt){ + public function __construct(Level\Level $level, NBT\Tag\Compound $nbt){ $this->server = ServerAPI::request(); $this->level = $level; $this->namedtag = $nbt; @@ -67,7 +70,7 @@ abstract class Tile extends Position{ $this->y = (int) $this->namedtag->y; $this->z = (int) $this->namedtag->z; - $index = PMFLevel::getIndex($this->x >> 4, $this->z >> 4); + $index = PMF\Level::getIndex($this->x >> 4, $this->z >> 4); $this->chunkIndex = $index; $this->level->tiles[$this->id] = $this; $this->level->chunkTiles[$this->chunkIndex][$this->id] = $this; diff --git a/src/utils/Cache.php b/src/utils/Cache.php index d95876556..c8da0405d 100644 --- a/src/utils/Cache.php +++ b/src/utils/Cache.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine\Utils; +use PocketMine; + class Cache{ public static $cached = array(); diff --git a/src/utils/Config.php b/src/utils/Config.php index 373c0602d..1ad8b1fd0 100644 --- a/src/utils/Config.php +++ b/src/utils/Config.php @@ -19,7 +19,8 @@ * */ - +namespace PocketMine\Utils; +use PocketMine; /** * Class Config diff --git a/src/utils/Java.php b/src/utils/Java.php deleted file mode 100644 index a58640d27..000000000 --- a/src/utils/Java.php +++ /dev/null @@ -1,66 +0,0 @@ -value = (string) $string; - $this->count = strlen($this->value); - } - } - - public function __toString(){ - return $this->value; - } - - public function lenght(){ - return $this->count; - } - - public function isEmpty(){ - return $this->count === 0; - } - - public function charAt($index){ - $index = (int) $index; - if($index < 0 or $index >= $this->count){ - trigger_error("Undefined offset $index", E_USER_WARNING); - return false; - } - return $this->value{$index}; - } - - public function hashCode(){ - $h = $this->hash; - if($h === 0 and $this->count > 0){ - for($i = 0; $i < $this->count; ++$i){ - $h = (($h << 5) - $h) + ord($this->charAt($i)); - $h = $h & 0xFFFFFFFF; - $this->hash = $h; - } - $this->hash = $h; - } - return $h; - } -} \ No newline at end of file diff --git a/src/utils/MersenneTwister.php b/src/utils/MersenneTwister.php deleted file mode 100644 index ca9fef5ba..000000000 --- a/src/utils/MersenneTwister.php +++ /dev/null @@ -1,478 +0,0 @@ -bits32 = PHP_INT_MAX == 2147483647; - - if(func_num_args() == 1) { - $this->init_with_integer(func_get_arg(0)); - } - } - - function init_with_integer($integer_seed) { - $integer_seed = force_32_bit_int($integer_seed); - - $mt = &$this->mt; - $mti = &$this->mti; - - $mt = array_fill(0, N, 0); - - $mt[0] = $integer_seed; - - for($mti = 1; $mti < N; $mti++) { - $mt[$mti] = add_2(mul(1812433253, - ($mt[$mti - 1] ^ (($mt[$mti - 1] >> 30) & 3))), $mti); - /* - mt[mti] = - (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); - */ - } - } - - function init_with_array(array $integer_array) { - $integer_array = - array_map("force_32_bit_int", $integer_array); - - $mt = &$this->mt; - $mti = &$this->mti; - - $key_length = count($integer_array); - - $this->init_with_integer(19650218); - $i=1; $j=0; - $k = (N>$key_length ? N : $key_length); - for (; $k; $k--) { - $mt[$i] = add_3($mt[$i] ^ - mul_by_1664525($mt[$i-1] ^ (($mt[$i-1] >> 30) & 3)), - $integer_array[$j], $j); - /* - mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) - + init_key[j] + j; - */ - $i++; $j++; - if ($i>=N) { $mt[0] = $mt[N-1]; $i=1; } - if ($j>=$key_length){ $j=0; } - } - for ($k=N-1; $k; $k--) { - $mt[$i] = sub($mt[$i] ^ - mul($mt[$i-1] ^ (($mt[$i-1] >> 30) & 3), 1566083941), $i); - /* - mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) - - i; - */ - $i++; - if ($i>=N) { $mt[0] = $mt[N-1]; $i=1; } - } - - $mt[0] = (1 << 31); /* MSB is 1; assuring non-zero initial array */ - } - - function init_with_string($string) { - $remainder = strlen($string) % 4; - - if($remainder > 0){ - $string .= str_repeat("\0", 4 - $remainder); - } - - $integer_array = array_values(unpack("N*", $string)); - - $this->init_with_array($integer_array); - } - - function init_with_files(array $filenames, $max_ints = -1) { - $limit_applies = $max_ints !== -1; - - if($limit_applies){ - $limit = $max_ints * 4; # 32 bits is 4 characters - } - $data = ""; - - foreach ($filenames as $filename) { - $contents = - file_get_contents($filename, FALSE, NULL, 0, - $limit_applies? $limit - strlen($data): -1); - - if($contents === FALSE) { - throw new Exception("problem reading from $filename"); - } else { - $data .= $contents; - - if($limit_applies && strlen($data) == $limit) { - break; - } - } - } - - $this->init_with_string($data); - } - - function init_with_file($filename, $max_ints = -1) { - $this->init_with_files(array($filename), $max_ints); - } - - function int32() { - static $mag01 = array(0, MATRIX_A); - - $mt = &$this->mt; - $mti = &$this->mti; - - if ($mti >= N) { /* generate N words all at once */ - for ($kk=0;$kk> 1) & MASK31) ^ $mag01[$y & 1]; - } - for (;$kk> 1) & MASK31) ^ $mag01[$y & 1]; - } - $y = ($mt[N-1]&UPPER_MASK)|($mt[0]&LOWER_MASK); - $mt[N-1] = $mt[M-1] ^ (($y >> 1) & MASK31) ^ $mag01[$y & 1]; - - $mti = 0; - } - - $y = $mt[$mti++]; - - /* Tempering */ - $y ^= ($y >> 11) & MASK21; - $y ^= ($y << 7) & ((0x9d2c << 16) | 0x5680); - $y ^= ($y << 15) & (0xefc6 << 16); - $y ^= ($y >> 18) & MASK14; - - return $y; - } - - function int31() { - return $this->int32() & MASK31; - } - - /* generates a random number on [0,1]-real-interval */ - function real_closed() { - return signed2unsigned($this->int32()) * (1.0 / 4294967295.0); - } - - /* generates a random number on [0,1)-real-interval */ - function real_halfopen() { - return signed2unsigned($this->int32()) * (1.0 / 4294967296.0); - } - - /* generates a random number on (0,1)-real-interval */ - function real_open() { - return (signed2unsigned($this->int32()) + .5) * (1.0 / 4294967296.0); - } - - /* generates a random number on [0,1) with 53-bit resolution */ - function real_halfopen2() { - return ((($this->int32() & MASK27) * 67108864.0) + - ($this->int32() & MASK26)) * - (1.0 / 9007199254740992.0); - } - - function rangeint($lower_bound, $upper_bound) { - $lower_bound = intval($lower_bound); - $upper_bound = intval($upper_bound); - - if($this->bits32) { - $pow_2_32 = pow(2, 32); - - $size_of_range = $upper_bound - $lower_bound + 1; - - $remainder = fmod($pow_2_32, $size_of_range); - - if($remainder == 0) { - return $lower_bound + - ($this->int32() & unsigned2signed($size_of_range - 1)); - } else { - $start_of_partial_range = $pow_2_32 - $remainder; - $start_as_int = unsigned2signed($start_of_partial_range); - do { - $rand = $this->int32(); - } while($rand >= $start_as_int && $rand < 0); - - $result = $lower_bound + - fmod(signed2unsigned($rand), $size_of_range); - - return intval($result); - } - } else { - if($lower_bound == -PHP_INT_MAX - 1 && $upper_bound == PHP_INT_MAX) { - return ($this->int32() << 32) & $this->int32(); - } else { - $pow_2_32 = 1 << 32; - - $size_of_range = $upper_bound - $lower_bound + 1; - - if($size_of_range > $pow_2_32) { - $size_of_range >>= 32; - $shift = 32; - $low_bits = $this->int32(); - } else { - $shift = 0; - $low_bits = 0; - } - - $remainder = $pow_2_32 % $size_of_range; - - if($remainder == 0) { - $high_bits = $this->int32() & ($size_of_range - 1); - } else { - $start_of_partial_range = $pow_2_32 - $remainder; - do { - $rand = $this->int32(); - } while($rand >= $start_of_partial_range); - - $high_bits = $rand % $size_of_range; - } - - return $lower_bound + (($high_bits << $shift) | $low_bits); - } - } - } - - /* - in each of the next 3 functions, we loop until we have a number that - meets the function's post-condition. this may be more work than - is really necessary, but i am concerned about rounding errors. - - why no rangereal_closed? because, due to the aforementioned - rounding errors, i am unable to guarantee that $upper_bound - would be a possible return value of such a function. - */ - - function rangereal_open($lower_bound, $upper_bound) { - do { - $rand = $lower_bound + - $this->real_open() * ($upper_bound - $lower_bound); - } while($rand <= $lower_bound || $rand >= $upper_bound); - - return $rand; - } - - function rangereal_halfopen($lower_bound, $upper_bound) { - do { - $rand = $lower_bound + - $this->real_halfopen() * ($upper_bound - $lower_bound); - } while($rand >= $upper_bound); - /* - $rand cannot go any lower than $lower_bound, because - $this->real_halfopen() cannot go any lower than 0 - */ - - return $rand; - } - - function rangereal_halfopen2($lower_bound, $upper_bound) { - do { - $rand = $lower_bound + - $this->real_halfopen2() * ($upper_bound - $lower_bound); - } while($rand >= $upper_bound); - - return $rand; - } -} - -function signed2unsigned($signed_integer) { - ## assert(is_integer($signed_integer)); - ## assert(($signed_integer & ~MASK32) === 0); - - return $signed_integer >= 0? $signed_integer: - TWO_TO_THE_32 + $signed_integer; -} - -function unsigned2signed($unsigned_integer) { - ## assert($unsigned_integer >= 0); - ## assert($unsigned_integer < pow(2, 32)); - ## assert(floor($unsigned_integer) === floatval($unsigned_integer)); - - return intval($unsigned_integer < TWO_TO_THE_31? $unsigned_integer: - $unsigned_integer - TWO_TO_THE_32); -} - -function force_32_bit_int($x) { - /* - it would be un-PHP-like to require is_integer($x), - so we have to handle cases like this: - - $x === pow(2, 31) - $x === strval(pow(2, 31)) - - we are also opting to do something sensible (rather than dying) - if the seed is outside the range of a 32-bit unsigned integer. - */ - - if(is_integer($x)) { - /* - we mask in case we are on a 64-bit machine and at least one - bit is set between position 32 and position 63. - */ - return $x & MASK32; - } else { - $x = floatval($x); - - $x = $x < 0? ceil($x): floor($x); - - $x = fmod($x, TWO_TO_THE_32); - - if($x < 0){ - $x += TWO_TO_THE_32; - } - - return unsigned2signed($x); - } -} - -/* - takes 2 integers, treats them as unsigned 32-bit integers, - and adds them. - - it works by splitting each integer into - 2 "half-integers", then adding the high and low half-integers - separately. - - a slight complication is that the sum of the low half-integers - may not fit into 16 bits; any "overspill" is added to the sum - of the high half-integers. -*/ -function add_2($n1, $n2) { - $x = ($n1 & 0xffff) + ($n2 & 0xffff); - - return (((($n1 >> 16) & 0xffff) + - (($n2 >> 16) & 0xffff) + - ($x >> 16)) << 16) | ($x & 0xffff); -} - -# takes 2 integers, treats them as unsigned 32-bit integers, -# and adds them. -# -# for how it works, see the comment for add_2. -# -function add_3($n1, $n2, $n3) { - $x = ($n1 & 0xffff) + ($n2 & 0xffff) + ($n3 & 0xffff); - - return (((($n1 >> 16) & 0xffff) + - (($n2 >> 16) & 0xffff) + - (($n3 >> 16) & 0xffff) + - ($x >> 16)) << 16) | ($x & 0xffff); -} - -# takes 2 integers, treats them as unsigned 32-bit integers, -# and subtracts the second from the first. -# -# the explanation of why this works is too long to be -# included here, so it has been moved into the file why-sub-works.txt. -# -function sub($a, $b) { - return (($a & MASK31) - ($b & MASK31)) ^ - (($a ^ $b) & 0x80000000); -} - -function mul($a, $b) { - /* - a and b, considered as unsigned integers, can be expressed as follows: - - a = 2**16 * a1 + a2, - - b = 2**16 * b1 + b2, - - where - - 0 <= a2 < 2**16, - 0 <= b2 < 2**16. - - given those 2 equations, what this function essentially does is to - use the following identity: - - a * b = 2**32 * a1 * b1 + 2**16 * a1 * b2 + 2**16 * b1 * a2 + a2 * b2 - - note that the first term, i.e. 2**32 * a1 * b1, is unnecessary here, - so we don't compute it. - - we could make the following code clearer by using intermediate - variables, but that would probably hurt performance. - */ - - return unsigned2signed( - fmod( - TWO_TO_THE_16 * - /* - the next line of code calculates a1 * b2, - the line after that calculates b1 * a2, - and the line after that calculates a2 * b2. - */ - ((($a >> 16) & 0xffff) * ($b & 0xffff) + - (($b >> 16) & 0xffff) * ($a & 0xffff)) + - ($a & 0xffff) * ($b & 0xffff), - - TWO_TO_THE_32)); -} - -/* - mul_by_1664525($x) should be more efficient than mul(1664525, $x). -*/ -function mul_by_1664525($n) { - return unsigned2signed(fmod(1664525 * ($n >= 0? - $n: (TWO_TO_THE_32 + $n)), TWO_TO_THE_32)); -} - -function do_bc_op($bc_op, array $numbers) { - $modulus = pow(2, 32); - - $result = - call_user_func_array($bc_op, - array_map("signed2unsigned", $numbers)); - - $result = bcmod($result, $modulus); - - return unsigned2signed(bccomp($result, 0) < 0? - bcadd($result, $modulus): $result); -} - -function get_random_32bit_int() { - return rand(0, 0xffff) | (rand(0, 0xffff) << 16); -} diff --git a/src/utils/Random.php b/src/utils/Random.php index c2860624e..dc3b82fa3 100644 --- a/src/utils/Random.php +++ b/src/utils/Random.php @@ -19,6 +19,8 @@ * */ +namespace PocketMine\Utils; +use PocketMine; //Unsecure, not used for "Real Randomness" class Random{ diff --git a/src/utils/TextFormat.php b/src/utils/TextFormat.php index a95a808f8..5cb2c994f 100644 --- a/src/utils/TextFormat.php +++ b/src/utils/TextFormat.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine\Utils; +use PocketMine; + class TextFormat{ const BLACK = "§0"; const DARK_BLUE = "§1"; diff --git a/src/utils/Utils.php b/src/utils/Utils.php index 9720427f9..ac35ea1b0 100644 --- a/src/utils/Utils.php +++ b/src/utils/Utils.php @@ -19,18 +19,17 @@ * */ -define("BIG_ENDIAN", 0x00); -define("LITTLE_ENDIAN", 0x01); -define("ENDIANNESS", (pack("d", 1) === "\77\360\0\0\0\0\0\0" ? BIG_ENDIAN:LITTLE_ENDIAN)); +namespace PocketMine\Utils; +use PocketMine; class Utils{ + const BIG_ENDIAN = 0x00; + const LITTLE_ENDIAN = 0x01; + + public static $online = true; public static $ip = false; - public static function isOnline(){ - return ((@fsockopen("8.8.8.8", 80, $e = null, $n = null, 2) !== false or @fsockopen("www.linux.org", 80, $e = null, $n = null, 2) !== false or @fsockopen("www.php.net", 80, $e = null, $n = null, 2) !== false) ? true:false); - } - public static function getCallableIdentifier(callable $variable){ if(is_array($variable)){ return sha1(strtolower(get_class($variable[0]))."::".strtolower($variable[1])); @@ -535,21 +534,21 @@ class Utils{ } public static function readFloat($str){ - list(,$value) = ENDIANNESS === BIG_ENDIAN ? @unpack("f", $str):@unpack("f", strrev($str)); + list(,$value) = ENDIANNESS === Utils::BIG_ENDIAN ? @unpack("f", $str):@unpack("f", strrev($str)); return $value; } public static function writeFloat($value){ - return ENDIANNESS === BIG_ENDIAN ? pack("f", $value):strrev(pack("f", $value)); + return ENDIANNESS === Utils::BIG_ENDIAN ? pack("f", $value):strrev(pack("f", $value)); } public static function readLFloat($str){ - list(,$value) = ENDIANNESS === BIG_ENDIAN ? @unpack("f", strrev($str)):@unpack("f", $str); + list(,$value) = ENDIANNESS === Utils::BIG_ENDIAN ? @unpack("f", strrev($str)):@unpack("f", $str); return $value; } public static function writeLFloat($value){ - return ENDIANNESS === BIG_ENDIAN ? strrev(pack("f", $value)):pack("f", $value); + return ENDIANNESS === Utils::BIG_ENDIAN ? strrev(pack("f", $value)):pack("f", $value); } public static function printFloat($value){ @@ -557,21 +556,21 @@ class Utils{ } public static function readDouble($str){ - list(,$value) = ENDIANNESS === BIG_ENDIAN ? @unpack("d", $str):@unpack("d", strrev($str)); + list(,$value) = ENDIANNESS === Utils::BIG_ENDIAN ? @unpack("d", $str):@unpack("d", strrev($str)); return $value; } public static function writeDouble($value){ - return ENDIANNESS === BIG_ENDIAN ? pack("d", $value):strrev(pack("d", $value)); + return ENDIANNESS === Utils::BIG_ENDIAN ? pack("d", $value):strrev(pack("d", $value)); } public static function readLDouble($str){ - list(,$value) = ENDIANNESS === BIG_ENDIAN ? @unpack("d", strrev($str)):@unpack("d", $str); + list(,$value) = ENDIANNESS === Utils::BIG_ENDIAN ? @unpack("d", strrev($str)):@unpack("d", $str); return $value; } public static function writeLDouble($value){ - return ENDIANNESS === BIG_ENDIAN ? strrev(pack("d", $value)):pack("d", $value); + return ENDIANNESS === Utils::BIG_ENDIAN ? strrev(pack("d", $value)):pack("d", $value); } public static function readLong($x, $signed = true){ @@ -626,6 +625,4 @@ class Utils{ } -if(Utils::isOnline() === false){ - Utils::$online = false; -} +define('\ENDIANNESS', (pack("d", 1) === "\77\360\0\0\0\0\0\0" ? Utils::BIG_ENDIAN : Utils::LITTLE_ENDIAN)); \ No newline at end of file diff --git a/src/utils/VersionString.php b/src/utils/VersionString.php index 70dabcb22..260e01003 100644 --- a/src/utils/VersionString.php +++ b/src/utils/VersionString.php @@ -19,6 +19,9 @@ * */ +namespace PocketMine\Utils; +use PocketMine; + class VersionString{ public static $stageOrder = array( "alpha" => 0, @@ -34,7 +37,7 @@ class VersionString{ private $minor; private $development = false; private $generation; - public function __construct($version = MAJOR_VERSION){ + public function __construct($version = PocketMine\VERSION){ if(is_int($version)){ $this->minor = $version & 0x1F; $this->major = ($version >> 5) & 0x0F; diff --git a/src/utils/pthreads.php b/src/utils/pthreads.php index 2b96093e0..d1a9652ec 100644 --- a/src/utils/pthreads.php +++ b/src/utils/pthreads.php @@ -23,7 +23,7 @@ define("ASYNC_CURL_GET", 1); define("ASYNC_CURL_POST", 2); define("ASYNC_FUNCTION", 3); -class StackableArray extends Stackable{ +class StackableArray extends \Stackable{ public function __construct(){ foreach(func_get_args() as $n => $value){ if(is_array($value)){ diff --git a/src/wizard/Installer.php b/src/wizard/Installer.php index b117c5085..2492121dc 100644 --- a/src/wizard/Installer.php +++ b/src/wizard/Installer.php @@ -19,7 +19,9 @@ * */ -/***REM_START***/ +namespace PocketMine\Wizard; +use PocketMine\Utils\Config as Config; +use PocketMine; class Installer{ const DEFAULT_NAME = "Minecraft: PE Server"; @@ -82,7 +84,7 @@ LICENSE; } private function generateBaseConfig(){ - $config = new Config(DATA_PATH . "server.properties", Config::PROPERTIES); + $config = new Utils\Config(DATA . "server.properties", Utils\Config::PROPERTIES); echo "[?] ".$this->lang->name_your_server." (".self::DEFAULT_NAME."): "; $config->set("server-name", $this->getInput(self::DEFAULT_NAME)); echo "[*] ".$this->lang->port_warning."\n"; @@ -122,13 +124,13 @@ LICENSE; if($op === ""){ echo "[!] ".$this->lang->op_warning."\n"; }else{ - $ops = new Config(DATA_PATH."ops.txt", Config::ENUM); + $ops = new Utils\Config(DATA."ops.txt", Utils\Config::ENUM); $ops->set($op, true); $ops->save(); } echo "[*] ".$this->lang->whitelist_info."\n"; echo "[?] ".$this->lang->whitelist_enable." (y/N): "; - $config = new Config(DATA_PATH . "server.properties", Config::PROPERTIES); + $config = new Utils\Config(DATA . "server.properties", Utils\Config::PROPERTIES); if(strtolower($this->getInput("n")) === "y"){ echo "[!] ".$this->lang->whitelist_warning."\n"; $config->set("white-list", true); @@ -139,7 +141,7 @@ LICENSE; } private function networkFunctions(){ - $config = new Config(DATA_PATH . "server.properties", Config::PROPERTIES); + $config = new Utils\Config(DATA . "server.properties", Utils\Config::PROPERTIES); echo "[!] ".$this->lang->query_warning1."\n"; echo "[!] ".$this->lang->query_warning2."\n"; echo "[?] ".$this->lang->query_disable." (y/N): "; @@ -153,7 +155,7 @@ LICENSE; echo "[?] ".$this->lang->rcon_enable." (y/N): "; if(strtolower($this->getInput("n")) === "y"){ $config->set("enable-rcon", true); - $password = substr(base64_encode(Utils::getRandomBytes(20, false)), 3, 10); + $password = substr(base64_encode(Utils\Utils::getRandomBytes(20, false)), 3, 10); $config->set("rcon.password", $password); echo "[*] ".$this->lang->rcon_password.": ".$password."\n"; }else{ @@ -172,7 +174,7 @@ LICENSE; echo "[*] ".$this->lang->ip_get."\n"; - $externalIP = Utils::getIP(); + $externalIP = Utils\Utils::getIP(); $internalIP = gethostbyname(trim(`hostname`)); echo "[!] ".$this->lang->get("ip_warning", array("{{EXTERNAL_IP}}", "{{INTERNAL_IP}}"), array($externalIP, $internalIP))."\n"; @@ -193,95 +195,4 @@ LICENSE; } - } - - class InstallerLang{ - public static $languages = array( - "en" => "English", - "es" => "Español", - "zh" => "中文", - "ru" => "Pyccĸий", - "ja" => "日本語", - "de" => "Deutsch", - //"vi" => "Tiếng Việt", - "ko" => "한국어", - "fr" => "Français", - "it" => "Italiano", - //"lv" => "Latviešu", - "nl" => "Nederlands", - //"pt" => "Português", - "sv" => "Svenska", - "fi" => "Suomi", - "tr" => "Türkçe", - //"et" => "Eesti", - ); - private $texts = array(); - private $lang; - private $langfile; - public function __construct($lang = ""){ - if(file_exists(FILE_PATH."src/lang/Installer/".$lang.".ini")){ - $this->lang = $lang; - $this->langfile = FILE_PATH."src/lang/Installer/".$lang.".ini"; - }else{ - $l = glob(FILE_PATH."src/lang/Installer/".$lang."_*.ini"); - if(count($l) > 0){ - $files = array(); - foreach($l as $file){ - $files[$file] = filesize($file); - } - arsort($files); - reset($files); - $l = key($files); - $l = substr($l, strrpos($l, "/") + 1, -4); - $this->lang = isset(self::$languages[$l]) ? $l:$lang; - $this->langfile = FILE_PATH."src/lang/Installer/".$l.".ini"; - }else{ - $this->lang = "en"; - $this->langfile = FILE_PATH."src/lang/Installer/en.ini"; - } - } - - $this->loadLang(FILE_PATH."src/lang/Installer/en.ini", "en"); - if($this->lang !== "en"){ - $this->loadLang($this->langfile, $this->lang); - } - - } - - public function getLang(){ - return ($this->lang); - } - - public function loadLang($langfile, $lang = "en"){ - $this->texts[$lang] = array(); - $texts = explode("\n", str_replace(array("\r", "\/\/"), array("", "//"), file_get_contents($langfile))); - foreach($texts as $line){ - $line = trim($line); - if($line === ""){ - continue; - } - $line = explode("=", $line); - $this->texts[$lang][array_shift($line)] = str_replace(array("\\n", "\\N",), "\n", implode("=", $line)); - } - } - - public function get($name, $search = array(), $replace = array()){ - if(!isset($this->texts[$this->lang][$name])){ - if($this->lang !== "en" and isset($this->texts["en"][$name])){ - return $this->texts["en"][$name]; - }else{ - return $name; - } - }elseif(count($search) > 0){ - return str_replace($search, $replace, $this->texts[$this->lang][$name]); - }else{ - return $this->texts[$this->lang][$name]; - } - } - - public function __get($name){ - return $this->get($name); - } - - } -/***REM_END***/ + } \ No newline at end of file diff --git a/src/wizard/InstallerLang.php b/src/wizard/InstallerLang.php new file mode 100644 index 000000000..689391d98 --- /dev/null +++ b/src/wizard/InstallerLang.php @@ -0,0 +1,113 @@ + "English", + "es" => "Español", + "zh" => "中文", + "ru" => "Pyccĸий", + "ja" => "日本語", + "de" => "Deutsch", + //"vi" => "Tiếng Việt", + "ko" => "한국어", + "fr" => "Français", + "it" => "Italiano", + //"lv" => "Latviešu", + "nl" => "Nederlands", + //"pt" => "Português", + "sv" => "Svenska", + "fi" => "Suomi", + "tr" => "Türkçe", + //"et" => "Eesti", + ); + private $texts = array(); + private $lang; + private $langfile; + public function __construct($lang = ""){ + if(file_exists(PATH."src/lang/Installer/".$lang.".ini")){ + $this->lang = $lang; + $this->langfile = PATH."src/lang/Installer/".$lang.".ini"; + }else{ + $l = glob(PATH."src/lang/Installer/".$lang."_*.ini"); + if(count($l) > 0){ + $files = array(); + foreach($l as $file){ + $files[$file] = filesize($file); + } + arsort($files); + reset($files); + $l = key($files); + $l = substr($l, strrpos($l, "/") + 1, -4); + $this->lang = isset(self::$languages[$l]) ? $l:$lang; + $this->langfile = PATH."src/lang/Installer/".$l.".ini"; + }else{ + $this->lang = "en"; + $this->langfile = PATH."src/lang/Installer/en.ini"; + } + } + + $this->loadLang(PATH."src/lang/Installer/en.ini", "en"); + if($this->lang !== "en"){ + $this->loadLang($this->langfile, $this->lang); + } + + } + + public function getLang(){ + return ($this->lang); + } + + public function loadLang($langfile, $lang = "en"){ + $this->texts[$lang] = array(); + $texts = explode("\n", str_replace(array("\r", "\/\/"), array("", "//"), file_get_contents($langfile))); + foreach($texts as $line){ + $line = trim($line); + if($line === ""){ + continue; + } + $line = explode("=", $line); + $this->texts[$lang][array_shift($line)] = str_replace(array("\\n", "\\N",), "\n", implode("=", $line)); + } + } + + public function get($name, $search = array(), $replace = array()){ + if(!isset($this->texts[$this->lang][$name])){ + if($this->lang !== "en" and isset($this->texts["en"][$name])){ + return $this->texts["en"][$name]; + }else{ + return $name; + } + }elseif(count($search) > 0){ + return str_replace($search, $replace, $this->texts[$this->lang][$name]); + }else{ + return $this->texts[$this->lang][$name]; + } + } + + public function __get($name){ + return $this->get($name); + } + + } \ No newline at end of file diff --git a/src/world/generator/LevelGenerator.php b/src/world/generator/LevelGenerator.php deleted file mode 100644 index cdb6e07cf..000000000 --- a/src/world/generator/LevelGenerator.php +++ /dev/null @@ -1,37 +0,0 @@ -