Compare commits

..

69 Commits

Author SHA1 Message Date
b1b16bc366 Alpha 1.0.5 2013-01-06 14:05:57 +01:00
aa1a39adfc Fixed TABS 2013-01-06 13:38:28 +01:00
b3b38605b5 Multi-update system and version numeration 2013-01-06 13:31:30 +01:00
7030f9118d Fixes #31 Server crash in health regeneration 2013-01-06 02:28:58 +01:00
b150d4e001 Fixes #30 Server crash when a player dies 2013-01-06 01:53:13 +01:00
125f1c11b4 Added Furnace 2013-01-06 01:16:49 +01:00
82f2a0f2f8 Fixed creative crash when opening chests 2013-01-06 00:58:46 +01:00
700314d75a Starting to support Chest windows 2013-01-05 22:13:10 +01:00
54e6bd0ee9 Fixed death in Creative mode 2013-01-05 20:35:21 +01:00
fd1186061f Updated entity despawning 2013-01-05 19:39:12 +01:00
f03f376535 Fall damage 2013-01-05 19:37:01 +01:00
586f49994a Fixed entity despawn 2013-01-05 18:33:39 +01:00
c1aec49ad1 Changes in Entity events 2013-01-05 18:30:29 +01:00
683c05f206 Replace player spaces & handle more data packets 2013-01-05 17:13:12 +01:00
9ebe68294b Item Drop 2013-01-05 15:17:57 +01:00
c2a45212dd Fixed item spawning 2013-01-05 15:01:21 +01:00
344449fa12 Removed Raknet version & added Current MC version 2013-01-05 13:39:37 +01:00
732ee755e8 Updated to Alpha_1.0.4 2013-01-05 11:37:57 +01:00
f0393f9b93 /give command 2013-01-05 11:34:08 +01:00
f23c2f894d Merge pull request #27 from C0deH4cker/patch-1
Fixed typo [HUGE]
2013-01-05 01:32:41 -08:00
85dfb651bd Merge pull request #29 from C0deH4cker/patch-2
Added pause at the end
2013-01-05 01:31:09 -08:00
b5e6130214 Added pause at the end
Added pause so users can see any errors that occur instead of the command prompt window just closing.
2013-01-05 02:01:05 -05:00
957f24c1f3 Fixed typo 2013-01-04 23:08:39 -05:00
518afeae48 Item pickup 2013-01-05 03:16:11 +01:00
57282225d2 Fixed Sapling, flower placing 2013-01-05 02:40:29 +01:00
369f268b90 Improved compression 2013-01-04 21:47:36 +01:00
ab0abfab1c Alpha_1.0.3 2013-01-04 19:42:26 +01:00
a64f0c8bbe Entities despawning, half item pickup 2013-01-04 19:36:51 +01:00
8d9f9ed9ed Fixed item drop megaduplication 2013-01-04 19:02:54 +01:00
38eed99789 Fixed issues and sockets 2013-01-04 16:04:06 +01:00
284daff67f Removed quiet param 2013-01-04 15:53:52 +01:00
a1e6184c74 Updated ;) with removed one 2013-01-04 15:49:20 +01:00
a495e8f436 Added install scripts for linux 2013-01-04 15:46:29 +01:00
3e9afbdf54 Added world compression 2013-01-04 12:51:33 +01:00
3ba8662c2c NormalGenerator class 2013-01-04 11:29:08 +01:00
52b4220ade Fix for block updates 2013-01-04 01:32:06 +01:00
b9eca491e8 Updated triggers to handle or dhandle API method 2013-01-04 01:20:29 +01:00
d7b1ae4b47 Vectors 2013-01-03 23:39:57 +01:00
9b09ff4042 Added 0x03 unknown packet 2013-01-03 12:20:28 +01:00
f9c71f1800 Fixed unknown data folders 2013-01-03 12:07:08 +01:00
d71167f66c Added generator name to level.dat 2013-01-03 00:57:32 +01:00
4b641bba39 Changed base broadcasts frequency 2013-01-02 22:48:50 +01:00
00379bb2d1 Added command alias 2013-01-02 22:48:37 +01:00
b96070a53a Added PHP >= 5.5 notice 2013-01-02 19:44:52 +01:00
db1b7ec4f2 Line ending cleanup 2013-01-02 19:41:23 +01:00
aafd36859f Solve segfault killing the process 2013-01-02 19:10:05 +01:00
0bea6e8051 Detect Mac OS 2013-01-02 19:09:28 +01:00
96bac5aaec Added player hand distance check 2013-01-02 18:25:39 +01:00
a501020198 Fix for .DS_Store folders in Mac 2013-01-02 17:33:24 +01:00
19436d4953 Removed protocol Changing 2013-01-02 01:09:54 +01:00
6c8e283599 Function names 2012-12-30 20:49:04 +01:00
2b5c21d909 Updated deleted header 2012-12-30 19:55:52 +01:00
2370ca6fd4 Autoloading non-included extensions 2012-12-29 19:54:05 +01:00
04c3229835 Removed GC Collector 2012-12-29 19:12:38 +01:00
9cd5a0c030 Line endings ... 2012-12-29 19:10:55 +01:00
302c865f4e Use Console Thread for Async I/O 2012-12-29 19:10:04 +01:00
b3cc13d4f2 Async class 2012-12-29 18:06:10 +01:00
c922b073b5 Moved ToDo list to the Wiki 2012-12-29 16:21:03 +01:00
f1956464b0 Final merging changes 2012-12-29 16:14:59 +01:00
aa7d6b12b5 BlockIterator 2012-12-29 16:13:59 +01:00
9ea1a05536 More different trees, check grow space 2012-12-29 16:13:58 +01:00
29a5041ef1 Fix for placing blocks where no block exists 2012-12-29 16:13:57 +01:00
000ba5de52 Fix 2012-12-29 16:13:56 +01:00
637d1c313b Changed version to next release 2012-12-29 16:13:52 +01:00
3e392820f1 Readded pthreads dependency 2012-12-29 16:13:03 +01:00
3ab149cf58 Fix for not-placing action blocks 2012-12-29 13:58:33 +01:00
473f5ec01e Updated fopen error 2012-12-29 12:37:47 +01:00
cacf14df81 Nasty line endings :S 2012-12-29 03:27:40 +01:00
e20251eaf4 Fixed Linux bug 2012-12-29 03:23:02 +01:00
52 changed files with 1934 additions and 768 deletions

5
.gitattributes vendored
View File

@ -1,5 +1,10 @@
# Auto detect text files and perform LF normalization
* text=auto
*.php text eol=lf
*.sh text eol=lf
*.txt text eol=lf
*.properties text eol=lf
*.bat text eol=crlf
# Custom for Visual Studio
*.cs diff=csharp

View File

@ -3,6 +3,19 @@
/*
-
/ \
/ \
/ PocketMine \
/ MP \
|\ @shoghicp /|
|. \ / .|
| .. \ / .. |
| .. | .. |
| .. | .. |
\ | /
\ | /
\ | /
\ | /
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
@ -16,24 +29,11 @@ require_once("src/common/dependencies.php");
require_once("classes/PocketMinecraftServer.class.php");
require_once("API/ServerAPI.php");
while(true){
$server = new ServerAPI();
//You can add simple things here
if($server->start() !== true){
break;
}else{
console("[INFO] Cleaning up...");
hard_unset($server);
$excludeList = array("GLOBALS", "_FILES", "_COOKIE", "_POST", "_GET", "excludeList");
foreach(get_defined_vars() as $key => $value){
if(!in_array($key, $excludeList)){
$$key = null;
unset($$key);
}
}
$server = null;
unset($server);
console("[NOTICE] The server is restarting... (".gc_collect_cycles()." cycles collected)", true, true, 0);
}
$server = new ServerAPI();
if($server->start() !== true){
//Stop
}else{
//Restart
}
kill(getmypid()); //Fix for segfault

View File

@ -40,10 +40,6 @@ The entire server is done in PHP, and has been tested, profiled and optimized to
[FAQ: Frequently Asked Questions](https://github.com/shoghicp/PocketMine-MP/wiki/Frequently-Asked-Questions)
**Project Status: `ALPHA`**
**Tested in: `v4.0.0, v5.0.0`**
## Current features of the server:
@ -53,14 +49,6 @@ The entire server is done in PHP, and has been tested, profiled and optimized to
* Update Channels!! (stable / dev)
## How to contact me
* Email - <shoghicp@gmail.com>
* Twitter - [@shoghicp](https://twitter.com/shoghicp)
* Via IRC - #mcdevs or #mcpedevs on *irc.freenode.net* (or just /msg me there)
* [MinecraftForums profile](http://www.minecraftforum.net/user/1476633-shoghicp/)
## Third-party Libraries Used
* __[PHP cURL](http://php.net/manual/en/book.curl.php)__
* __[PHP Sockets](http://php.net/manual/en/book.sockets.php)__

35
TODO.md
View File

@ -1,35 +0,0 @@
__Check Milestones [here](https://github.com/shoghicp/PocketMine-MP/issues/milestones)__
## Not Fixing
- Random strips and chunks of different land not sticking (the ones shown before world chunks are loaded)
## Known Bugs
- Players jerk sometimes
- Some chunk columns doesn't get loaded
- Players don't despawn
- Players can often hear "echos" of their own block interactions' SFX (torch placed, block destroyed, etc. most noticeable when moving around as you place.)
### Alpha 1.1
* Threading
### Alpha 1.2
* Scheduled block updates for events like grow, grass spread
* Random Wheat growth
* Random Melon growth
* Random Sapling growth
* Random Cactus growth
* Random Sugarcane growth
## Beta (Survival)
- Mob spawning, item pick up
- Mob behavior
- Placing Paintings
- Inventory loading and saving
- Entity saving
- Mob interaction (hitting)
- Firing Arrows
- Eating
- Nether???

75
compile_php.sh Normal file
View File

@ -0,0 +1,75 @@
#!/bin/bash
echo "[INFO] PocketMine-MP PHP compiler for Linux - by @shoghicp v0.1"
if [ "$(whoami)" != 'root' ]; then
echo "[ERROR] You must be root to run this script"
exit 1;
fi
DIR=`pwd`
mkdir -m 0777 install_data
mkdir -m 0777 php5
cd install_data
apt-get -f -y install
apt-get -y install \
php5-cli \
php5-common \
php5-curl \
php5-gd \
php5-gmp \
php5-mcrypt \
build-essential \
git-core \
libxml2-dev \
libcurl4-openssl-dev \
libjpeg-dev \
libpng-dev \
libmysqlclient-dev \
libfreetype6-dev \
libmcrypt-dev \
libmhash-dev
wget ftp://ftp.gmplib.org/pub/gmp-5.1.0/gmp-5.1.0.tar.bz2 -O gmp-5.1.0.tar.bz2
tar -jxvf gmp-5.1.0.tar.bz2
cd gmp-5.1.0
./configure
make
make check
make install
wget http://php.net/get/php-5.4.10.tar.gz/from/this/mirror -O php-5.4.10.tar.gz
tar -zxvf php-5.4.10.tar.gz
cd php-5.4.10
cd ext
git clone https://github.com/krakjoe/pthreads.git
cd ../
./buildconf --force
./configure --prefix=$DIR/php5 \
--exec-prefix=$DIR/php5 \
--enable-embedded-mysqli \
--with-openssl \
--with-mcrypt \
--with-mhash \
--enable-exif \
--with-freetype-dir \
--enable-calendar \
--enable-soap \
--enable-mbstring \
--enable-bcmath \
--enable-gd-native-ttf \
--with-gmp \
--with-curl \
--enable-zip \
--with-gd \
--with-jpeg-dir \
--with-png-dir \
--with-mysql \
--with-mcrypt \
--with-zlib \
--enable-sockets \
--enable-pthreads \
--enable-maintainer-zts \
--enable-cli
make
echo "n" | make test
make install
cd $DIR
rm -r -f install_data/
rmdir install_data/
echo "[INFO] Compilation Completed!"

View File

@ -37,24 +37,60 @@ class BlockAPI{
function __construct(PocketMinecraftServer $server){
$this->server = $server;
}
public function init(){
$this->server->addHandler("world.block.update", array($this, "updateBlockRemote"), 1);
$this->server->addHandler("player.block.break", array($this, "blockBreak"), 1);
$this->server->addHandler("player.block.action", array($this, "blockAction"), 1);
$this->server->api->console->register("give", "Give items to a player", array($this, "commandHandler"));
}
public function commandHandler($cmd, $params){
switch($cmd){
case "give":
if(!isset($params[0]) or !isset($params[1])){
console("[INFO] Usage: /give <username> <item> [amount] [damage]");
break;
}
$username = $params[0];
$b = explode(":", $params[1]);
if(!isset($b[1])){
$meta = 0;
}else{
$meta = (int) $b[1];
}
$block = ((int) $b[0]) & 0xFFFF;
if(!isset($params[2])){
$amount = 64;
}else{
$amount = (int) $params[2];
}
if(isset($params[3])){
$meta = (int) $params[3];
}
if(($player = $this->server->api->player->get($username)) !== false){
$this->drop($player->entity->x - 0.5, $player->entity->y, $player->entity->z - 0.5, $block, $meta, $amount);
console("[INFO] Giving ".$amount." of ".$block.":".$meta." to ".$username);
}else{
console("[INFO] Unknown player");
}
break;
}
}
private function cancelAction($block){
$this->server->trigger("world.block.change", array(
$this->server->api->dhandle("world.block.change", array(
"x" => $block[2][0],
"y" => $block[2][1],
"z" => $block[2][2],
"block" => $block[0],
"meta" => $block[1],
"fake" => true,
));
return false;
}
public function blockBreak($data, $event){
if($event !== "player.block.break"){
return;
@ -136,7 +172,6 @@ class BlockAPI{
$data2 = $data;
--$data2["y"];
$this->server->trigger("player.block.break", $data2);
$this->updateBlocksAround($data2["x"], $data2["y"], $data2["z"], BLOCK_UPDATE_NORMAL);
}
}else{
$up = $this->server->api->level->getBlock($data["x"], $data["y"] + 1, $data["z"]);
@ -144,7 +179,6 @@ class BlockAPI{
$data2 = $data;
++$data2["y"];
$this->server->trigger("player.block.break", $data2);
$this->updateBlocksAround($data2["x"], $data2["y"], $data2["z"], BLOCK_UPDATE_NORMAL);
}
}
break;
@ -152,11 +186,10 @@ class BlockAPI{
if($drop !== false and $drop[0] !== 0 and $drop[2] > 0){
$this->drop($data["x"], $data["y"], $data["z"], $drop[0], $drop[1] & 0x0F, $drop[2] & 0xFF);
}
$this->server->trigger("player.block.break", $data);
$this->updateBlocksAround($data["x"], $data["y"], $data["z"], BLOCK_UPDATE_NORMAL);
$this->server->trigger("player.block.break", $data);
return false;
}
public function drop($x, $y, $z, $block, $meta, $stack = 1){
if($block === 0 or $stack <= 0 or $this->server->gamemode === 1){
return;
@ -169,12 +202,18 @@ class BlockAPI{
"stack" => $stack,
);
$data["x"] += mt_rand(2, 8) / 10;
$data["y"] += mt_rand(2, 8) / 10;
$data["y"] += 0.19;
$data["z"] += mt_rand(2, 8) / 10;
$e = $this->server->api->entity->add(ENTITY_ITEM, $block, $data);
$this->server->api->entity->spawnToAll($e->eid);
if($this->server->api->handle("block.drop", $data) !== false){
for($count = $stack; $count > 0; ){
$data["stack"] = min(64, $count);
$count -= $data["stack"];
$e = $this->server->api->entity->add(ENTITY_ITEM, $block, $data);
$this->server->api->entity->spawnToAll($e->eid);
}
}
}
public function blockAction($data, $event){
if($event !== "player.block.action"){
return;
@ -183,9 +222,38 @@ class BlockAPI{
return false;
}
$target = $this->server->api->level->getBlock($data["x"], $data["y"], $data["z"]);
if($target[0] === 0){ //If no block exists
$this->cancelAction($target);
$block = $this->server->api->level->getBlockFace($target, $data["face"]);
return $this->cancelAction($block);
}
$cancelPlace = false;
if(isset(Material::$activable[$target[0]])){
switch($target[0]){
case 54:
if($this->server->gamemode === 1){
break;
}
$this->server->api->player->getByEID($data["eid"])->dataPacket(MC_CONTAINER_OPEN, array(
"windowid" => 1,
"type" => WINDOW_CHEST,
"slots" => 27,
"title" => "Chest",
));
break;
case 61:
case 62:
if($this->server->gamemode === 1){
break;
}
$this->server->api->player->getByEID($data["eid"])->dataPacket(MC_CONTAINER_OPEN, array(
"windowid" => 1,
"type" => WINDOW_FURNACE,
"slots" => 3,
"title" => "Furnace",
));
break;
case 6:
if($data["block"] === 351 and $data["meta"] === 0x0F){ //Bonemeal
Sapling::growTree($this->server->api->level, $target, $target[1] & 0x03);
@ -197,8 +265,7 @@ class BlockAPI{
if($data["block"] === 292){ //Hoe
$data["block"] = 60;
$data["meta"] = 0;
$this->server->trigger("player.block.place", $data);
$this->updateBlocksAround($data["x"], $data["y"], $data["z"], BLOCK_UPDATE_NORMAL);
$this->server->handle("player.block.place", $data);
$cancelPlace = true;
}
case 59:
@ -206,10 +273,9 @@ class BlockAPI{
if($data["block"] === 351 and $data["meta"] === 0x0F){ //Bonemeal
$data["block"] = $target[0];
$data["meta"] = 0x07;
$this->server->trigger("player.block.place", $data);
$this->updateBlocksAround($data["x"], $data["y"], $data["z"], BLOCK_UPDATE_NORMAL);
$this->server->handle("player.block.place", $data);
$cancelPlace = true;
}
}
break;
case 64: //Door
if(($target[1] & 0x08) === 0x08){
@ -224,22 +290,23 @@ class BlockAPI{
"meta" => $down[1],
"eid" => $data["eid"],
);
$this->server->trigger("player.block.update", $data2);
$this->updateBlocksAround($data2["x"], $data2["y"], $data2["z"], BLOCK_UPDATE_NORMAL);
$this->updateBlocksAround($data["x"], $data["y"], $data["z"], BLOCK_UPDATE_NORMAL);
if($this->server->handle("player.block.update", $data2) !== false){
$this->updateBlocksAround($data["x"], $data["y"], $data["z"], BLOCK_UPDATE_NORMAL);
}
}
}else{
$data["block"] = $target[0];
$data["meta"] = $target[1] ^ 0x04;
$this->server->trigger("player.block.update", $data);
$up = $this->server->api->level->getBlock($data["x"], $data["y"] + 1, $data["z"]);
if($up[0] === 64){
$data2 = $data;
$data2["meta"] = $up[1];
++$data2["y"];
$this->updateBlocksAround($data2["x"], $data2["y"], $data2["z"], BLOCK_UPDATE_NORMAL);
if($this->server->handle("player.block.update", $data) !== false){
$up = $this->server->api->level->getBlock($data["x"], $data["y"] + 1, $data["z"]);
if($up[0] === 64){
$data2 = $data;
$data2["meta"] = $up[1];
++$data2["y"];
$this->updateBlocksAround($data2["x"], $data2["y"], $data2["z"], BLOCK_UPDATE_NORMAL);
}
$this->updateBlocksAround($data["x"], $data["y"], $data["z"], BLOCK_UPDATE_NORMAL);
}
$this->updateBlocksAround($data["x"], $data["y"], $data["z"], BLOCK_UPDATE_NORMAL);
}
$cancelPlace = true;
break;
@ -247,23 +314,19 @@ class BlockAPI{
case 107: //Fence gates
$data["block"] = $target[0];
$data["meta"] = $target[1] ^ 0x04;
$this->server->trigger("player.block.update", $data);
$this->updateBlocksAround($data["x"], $data["y"], $data["z"], BLOCK_UPDATE_NORMAL);
$this->server->handle("player.block.update", $data);
$cancelPlace = true;
break;
default:
$cancelPlace = true;
break;
}
}
}
if($cancelPlace === true){
$this->cancelAction($target);
BlockFace::setPosition($data, $data["face"]);
$target = $this->server->api->level->getBlock($data["x"], $data["y"], $data["z"]);
return $this->cancelAction($target);
return false;
}
$replace = false;
switch($target[0]){
case 44: //Slabs
@ -277,29 +340,29 @@ class BlockAPI{
}
break;
}
if($replace === false){
BlockFace::setPosition($data, $data["face"]);
}
if($data["y"] >= 127){
return false;
}
$block = $this->server->api->level->getBlock($data["x"], $data["y"], $data["z"]);
if($replace === false and !isset(Material::$replaceable[$block[0]])){
return $this->cancelAction($block);
}
if(isset(Material::$placeable[$data["block"]])){
$data["block"] = Material::$placeable[$data["block"]] === true ? $data["block"]:Material::$placeable[$data["block"]];
}else{
return $this->cancelAction($block);
}
$direction = $this->server->api->entity->get($data["eid"])->getDirection();
$direction = $this->server->api->entity->get($data["eid"])->getDirection();
switch($data["block"]){
case 6:
if($target[0] === 60){
@ -307,7 +370,7 @@ class BlockAPI{
}
case 37:
case 38:
if($target[0] !== 2 and $target[0] !== 3){
if(($target[0] !== 2 and $target[0] !== 3) or $data["face"] !== 1){
return false;
}
break;
@ -328,7 +391,7 @@ class BlockAPI{
$block2 = $this->server->api->level->getBlock($data["x"] + 1, $data["y"], $data["z"]);
$block3 = $this->server->api->level->getBlock($data["x"] - 1, $data["y"], $data["z"]);
if($block0[0] === 9 or $block0[0] === 8 or $block1[0] === 9 or $block1[0] === 8 or $block2[0] === 9 or $block2[0] === 8 or $block3[0] === 9 or $block3[0] === 8){
}else{
return false;
}
@ -395,8 +458,7 @@ class BlockAPI{
$data2["meta"] = 0x08;
$data["meta"] = $direction & 0x03;
++$data2["y"];
$this->server->trigger("player.block.place", $data2);
$this->updateBlocksAround($data2["x"], $data2["y"], $data2["z"], BLOCK_UPDATE_NORMAL);
$this->server->handle("player.block.place", $data2);
}
break;
case 54:
@ -426,8 +488,7 @@ class BlockAPI{
$data2["x"] = $next[2][0];
$data2["y"] = $next[2][1];
$data2["z"] = $next[2][2];
$this->server->trigger("player.block.place", $data2);
$this->updateBlocksAround($data2["x"], $data2["y"], $data2["z"], BLOCK_UPDATE_NORMAL);
$this->server->handle("player.block.place", $data2);
break;
case 65: //Ladder
if(isset(Material::$transparent[$target[0]])){
@ -463,16 +524,14 @@ class BlockAPI{
}
break;
}
$this->server->trigger("player.block.place", $data);
$this->updateBlock($data["x"], $data["y"], $data["z"], BLOCK_UPDATE_NORMAL);
$this->updateBlocksAround($data["x"], $data["y"], $data["z"], BLOCK_UPDATE_NORMAL);
$this->server->handle("player.block.place", $data);
return false;
}
public function blockScheduler($data){
$this->updateBlock($data["x"], $data["y"], $data["z"], BLOCK_UPDATE_SCHEDULED);
}
public function updateBlockRemote($data, $event){
if($event !== "world.block.update"){
return;
@ -500,7 +559,7 @@ class BlockAPI{
"z" => $spread[2][2],
"type" => BLOCK_UPDATE_NORMAL,
));
$this->server->api->level->setBlock($spread[2][0], $spread[2][1], $spread[2][2], $spread[0], $level | $down);
$this->server->api->level->setBlock($spread[2][0], $spread[2][1], $spread[2][2], $spread[0], $level | $down, false);
return true;
}
}elseif(isset(Material::$flowable[$spread[0]])){
@ -510,15 +569,15 @@ class BlockAPI{
"z" => $spread[2][2],
"type" => BLOCK_UPDATE_NORMAL,
));
$this->server->api->level->setBlock($spread[2][0], $spread[2][1], $spread[2][2], 10, $level | $down);
return true;
$this->server->api->level->setBlock($spread[2][0], $spread[2][1], $spread[2][2], 10, $level | $down, false);
return true;
}elseif(($source[1] & 0x08) === 0x08){
$this->server->api->level->setBlock($spread[2][0], $spread[2][1], $spread[2][2], $source[0], $source[1] & 0x07);
$this->server->api->level->setBlock($spread[2][0], $spread[2][1], $spread[2][2], $source[0], $source[1] & 0x07, false);
return true;
}
return false;
}
public function flowWaterOn($source, $face){
$down = 0;
if($face === BlockFace::BOTTOM){
@ -539,7 +598,7 @@ class BlockAPI{
"z" => $spread[2][2],
"type" => BLOCK_UPDATE_NORMAL,
));
$this->server->api->level->setBlock($spread[2][0], $spread[2][1], $spread[2][2], $spread[0], $level | $down);
$this->server->api->level->setBlock($spread[2][0], $spread[2][1], $spread[2][2], $spread[0], $level | $down, false);
return true;
}
}elseif(isset(Material::$flowable[$spread[0]])){
@ -549,15 +608,15 @@ class BlockAPI{
"z" => $spread[2][2],
"type" => BLOCK_UPDATE_NORMAL,
));
$this->server->api->level->setBlock($spread[2][0], $spread[2][1], $spread[2][2], 8, $level | $down);
return true;
$this->server->api->level->setBlock($spread[2][0], $spread[2][1], $spread[2][2], 8, $level | $down, false);
return true;
}elseif(($source[1] & 0x08) === 0x08){
$this->server->api->level->setBlock($spread[2][0], $spread[2][1], $spread[2][2], $source[0], $source[1] & 0x07);
$this->server->api->level->setBlock($spread[2][0], $spread[2][1], $spread[2][2], $source[0], $source[1] & 0x07, false);
return true;
}
return false;
}
public function updateBlock($x, $y, $z, $type = BLOCK_UPDATE_NORMAL){
$block = $this->server->api->level->getBlock($x, $y, $z);
$changed = false;
@ -631,7 +690,7 @@ class BlockAPI{
"z" => $block[2][2],
"type" => BLOCK_UPDATE_NORMAL,
));
$this->server->api->level->setBlock($block[2][0], $block[2][1], $block[2][2], 0, 0);
$this->server->api->level->setBlock($block[2][0], $block[2][1], $block[2][2], 0, 0, false);
}else{
$block[1] = ($block[1] & 0x08) | $level;
$this->server->schedule(10, array($this, "blockScheduler"), array(
@ -670,10 +729,10 @@ class BlockAPI{
"z" => $block[2][2],
"type" => BLOCK_UPDATE_NORMAL,
));
$this->server->api->level->setBlock($block[2][0], $block[2][1], $block[2][2], $block[0], $block[1]);
$this->server->api->level->setBlock($block[2][0], $block[2][1], $block[2][2], $block[0], $block[1], false);
}
}
}
}
break;
case 10:
case 11:
@ -743,7 +802,7 @@ class BlockAPI{
"z" => $block[2][2],
"type" => BLOCK_UPDATE_NORMAL,
));
$this->server->api->level->setBlock($block[2][0], $block[2][1], $block[2][2], 0, 0);
$this->server->api->level->setBlock($block[2][0], $block[2][1], $block[2][2], 0, 0, false);
}else{
$block[1] = ($block[1] & 0x08) | $level;
$this->server->schedule(20, array($this, "blockScheduler"), array(
@ -782,23 +841,23 @@ class BlockAPI{
"z" => $block[2][2],
"type" => BLOCK_UPDATE_NORMAL,
));
$this->server->api->level->setBlock($block[2][0], $block[2][1], $block[2][2], $block[0], $block[1]);
$this->server->api->level->setBlock($block[2][0], $block[2][1], $block[2][2], $block[0], $block[1], false);
}
}
}
break;
case 74:
if($type === BLOCK_UPDATE_SCHEDULED or $type === BLOCK_UPDATE_RANDOM){
$changed = true;
$this->server->api->level->setBlock($x, $y, $z, 73, $block[1]);
$this->server->api->level->setBlock($x, $y, $z, 73, $block[1], false);
$type = BLOCK_UPDATE_WEAK;
}
break;
case 73:
if($type === BLOCK_UPDATE_NORMAL){
$changed = true;
$this->server->api->level->setBlock($x, $y, $z, 74, $block[1]);
$this->server->api->level->setBlock($x, $y, $z, 74, $block[1], false);
$this->server->schedule(mt_rand(40, 100), array($this, "blockScheduler"), array(
"x" => $x,
"y" => $y,
@ -815,7 +874,7 @@ class BlockAPI{
$this->updateBlocksAround($x, $y, $z, $type);
}
}
public function updateBlocksAround($x, $y, $z, $type){
$this->updateBlock($x + 1, $y, $z, $type);
$this->updateBlock($x, $y + 1, $z, $type);

View File

@ -26,23 +26,27 @@ the Free Software Foundation, either version 3 of the License, or
*/
class ConsoleAPI{
private $input, $server, $event;
private $loop, $server, $event, $help, $cmds;
function __construct(PocketMinecraftServer $server){
$this->help = array();
$this->cmds = array();
$this->server = $server;
$this->input = fopen(FILE_PATH."logs/console.in", "w+b");
$this->last = microtime(true);
}
public function init(){
$this->event = $this->server->event("server.tick", array($this, "handle"));
$this->loop = new ConsoleLoop;
$this->loop->start();
}
function __destroy(){
function __destruct(){
$this->server->deleteEvent($this->event);
fclose($this->input);
$this->loop->stop = true;
$this->loop->notify();
$this->loop->join();
}
public function defaultCommands($cmd, $params){
switch($cmd){
case "invisible":
@ -74,6 +78,7 @@ class ConsoleAPI{
$this->server->api->setProperty("last-update", time());
break;
case "stop":
$this->loop->stop = true;
console("[INFO] Stopping the server...");
$this->server->close();
break;
@ -88,7 +93,7 @@ class ConsoleAPI{
case "pardon":
case "remove":
$ip = trim(implode($params));
$new = array();
$new = array();
foreach(explode("\n", str_replace(array("\r","\t"), "", file_get_contents(FILE_PATH."banned-ips.txt"))) as $i){
if($i == $ip){
console("[INFO] IP \"$ip\" removed from ban list");
@ -149,7 +154,7 @@ class ConsoleAPI{
switch($p){
case "remove":
$user = trim(implode(" ", $params));
$new = array();
$new = array();
foreach(explode("\n", str_replace(array("\r","\t"), "", file_get_contents(FILE_PATH."white-list.txt"))) as $u){
if($u == $user){
console("[INFO] Player \"$user\" removed from white-list");
@ -212,7 +217,7 @@ class ConsoleAPI{
console("[INFO] /stop: Stops the server");
//console("[INFO] /restart: Restarts the server");
foreach($this->help as $c => $h){
console("[INFO] /$c: ".$h[0]);
console("[INFO] /$c: ".$h);
}
break;
default:
@ -220,31 +225,50 @@ class ConsoleAPI{
break;
}
}
public function register($cmd, $help,$callback){
public function alias($alias, $cmd){
$this->cmds[strtolower(trim($alias))] = &$this->cmds[$cmd];
}
public function register($cmd, $help, $callback){
if(!is_callable($callback)){
return false;
}
$this->help[strtolower(trim($cmd))] = array($help, $callback);
}
public function handle($time){
while(($line = fgets($this->input)) !== false){
$line = trim($line);
if($line === ""){
continue;
}
$params = explode(" ", $line);
$cmd = strtolower(array_shift($params));
console("[INFO] Issued server command: /$cmd ".implode(" ", $params));
if(isset($this->help[$cmd]) and is_callable($this->help[$cmd][1])){
call_user_func($this->help[$cmd][1], $cmd, $params);
}elseif($this->server->trigger("api.console.command", array("cmd" => $cmd, "params" => $params)) !== false){
$this->defaultCommands($cmd, $params);
}
}
ftruncate($this->input, 0);
fseek($this->input, 0);
$cmd = strtolower(trim($cmd));
$this->cmds[$cmd] = $callback;
$this->help[$cmd] = $help;
}
public function handle($time){
if($this->loop->line !== false){
$line = trim($this->loop->line);
$this->loop->line = false;
if($line !== ""){
$params = explode(" ", $line);
$cmd = strtolower(array_shift($params));
console("[INFO] Issued server command: /$cmd ".implode(" ", $params));
if(isset($this->cmds[$cmd]) and is_callable($this->cmds[$cmd])){
call_user_func($this->cmds[$cmd], $cmd, $params);
}elseif($this->server->api->dhandle("api.console.command", array("cmd" => $cmd, "params" => $params)) !== false){
$this->defaultCommands($cmd, $params);
}
}
}else{
$this->loop->notify();
}
}
}
class ConsoleLoop extends Thread{
var $line = false, $stop = false;
public function run(){
$fp = fopen("php://stdin", "r");
while($this->stop === false and ($line = fgets($fp)) !== false){
$this->line = $line;
$this->wait();
$this->line = false;
}
exit(0);
}
}

View File

@ -30,12 +30,11 @@ class EntityAPI{
function __construct(PocketMinecraftServer $server){
$this->server = $server;
}
public function init(){
$this->server->addHandler("player.death", array($this, "handle"), 1);
$this->server->api->console->register("give", "Give items to a player [DUMMY]", array($this, "commandHandler"));
}
public function handle($data, $event){
switch($event){
case "player.death":
@ -59,13 +58,6 @@ class EntityAPI{
}
$this->server->chat(false, $message);
break;
}
}
public function commandHandler($cmd, $params){
switch($cmd){
case "give":
break;
}
}
@ -75,15 +67,15 @@ class EntityAPI{
}
return false;
}
public function getAll(){
return $this->server->entities;
}
public function heal($eid, $heal = 1, $cause){
$this->harm($eid, -$heal, $cause);
}
public function harm($eid, $attack = 1, $cause){
$e = $this->get($eid);
if($e === false or $e->dead === true){
@ -91,13 +83,13 @@ class EntityAPI{
}
$e->setHealth($e->getHealth()-$attack, $cause);
}
public function add($class, $type = 0, $data = array()){
$eid = $this->server->eidCnt++;
$this->server->entities[$eid] = new Entity($this->server, $eid, $class, $type, $data);
return $this->server->entities[$eid];
}
public function spawnTo($eid, $player){
$e = $this->get($eid);
if($e === false){
@ -105,7 +97,7 @@ class EntityAPI{
}
$e->spawn($player);
}
public function spawnToAll($eid){
$e = $this->get($eid);
if($e === false){
@ -117,17 +109,17 @@ class EntityAPI{
}
}
}
public function spawnAll($player){
foreach($this->getAll() as $e){
$e->spawn($player);
}
}
public function remove($eid){
if(isset($this->server->entities[$eid])){
$this->server->entities[$eid]->close();
unset($this->server->entities[$eid]);
}
}
}
}

View File

@ -32,13 +32,13 @@ class LevelAPI{
$this->map = $this->server->map;
$this->heightMap = array_fill(0, 256, array());
}
public function init(){
$this->server->event("player.block.break", array($this, "handle"));
$this->server->event("player.block.place", array($this, "handle"));
$this->server->event("player.block.update", array($this, "handle"));
}
public function handle($data, $event){
switch($event){
case "player.block.place":
@ -47,56 +47,61 @@ class LevelAPI{
$this->setBlock($data["x"], $data["y"], $data["z"], $data["block"], $data["meta"]);
break;
case "player.block.break":
$block = $this->getBlock($data["x"], $data["y"], $data["z"]);
console("[DEBUG] EID ".$data["eid"]." broke ".$block[0].":".$block[1]." at X ".$data["x"]." Y ".$data["y"]." Z ".$data["z"], true, true, 2);
if($block[0] === 0){
break;
}
$this->setBlock($data["x"], $data["y"], $data["z"], 0, 0);
$block = $this->getBlock($data["x"], $data["y"], $data["z"]);
console("[DEBUG] EID ".$data["eid"]." broke ".$block[0].":".$block[1]." at X ".$data["x"]." Y ".$data["y"]." Z ".$data["z"], true, true, 2);
if($block[0] === 0){
break;
}
$this->setBlock($data["x"], $data["y"], $data["z"], 0, 0);
break;
}
}
public function getSpawn(){
return $this->server->spawn;
}
public function getChunk($X, $Z){
return $this->map->map[$X][$Z];
return $this->map->map[$X][$Z];
}
public function getBlockFace($block, $face){
$data = array("x" => $block[2][0], "y" => $block[2][1], "z" => $block[2][2]);
BlockFace::setPosition($data, $face);
return $this->getBlock($data["x"], $data["y"], $data["z"]);
}
public function getBlock($x, $y, $z){
$b = $this->map->getBlock($x, $y, $z);
$b[2] = array($x, $y, $z);
return $b;
}
public function getFloor($x, $z){
if(!isset($this->heightMap[$z][$x])){
$this->heightMap[$z][$x] = $this->map->getFloor($x, $z);
}
return $this->heightMap[$z][$x];
}
public function setBlock($x, $y, $z, $block, $meta = 0){
public function setBlock($x, $y, $z, $block, $meta = 0, $update = true){
$this->map->setBlock($x, $y, $z, $block, $meta);
$this->heightMap[$z][$x] = $this->map->getFloor($x, $z);
$this->server->trigger("world.block.change", array(
if($this->server->api->dhandle("world.block.change", array(
"x" => $x,
"y" => $y,
"z" => $z,
"block" => $block,
"meta" => $meta,
));
)) !== false){
if($update === true){
$this->server->api->block->updateBlock($x, $y, $z, BLOCK_UPDATE_NORMAL);
$this->server->api->block->updateBlocksAround($x, $y, $z, BLOCK_UPDATE_NORMAL);
}
}
}
public function getOrderedChunk($X, $Z, $columnsPerPacket = 2){
$columnsPerPacket = max(1, (int) $columnsPerPacket);
$c = $this->getChunk($X, $Z);

View File

@ -30,7 +30,7 @@ class PlayerAPI{
function __construct(PocketMinecraftServer $server){
$this->server = $server;
}
public function init(){
$this->server->event("server.regeneration", array($this, "handle"));
$this->server->api->console->register("list", "Shows connected player list", array($this, "commandHandler"));
@ -38,20 +38,22 @@ class PlayerAPI{
$this->server->api->console->register("tppos", "Teleports a player to a position", array($this, "commandHandler"));
$this->server->api->console->register("tp", "Teleports a player to another player", array($this, "commandHandler"));
}
public function handle($data, $event){
switch($event){
case "server.regeneration":
$result = $this->server->query("SELECT ip,port FROM players WHERE EID = (SELECT EID FROM entities WHERE health < 20);", true);
$result = $this->server->query("SELECT EID FROM players WHERE EID = (SELECT EID FROM entities WHERE health < 20);");
if($result !== true and $result !== false){
while(false !== ($player = $result->fetchArray())){
$player->entity->setHealth(min(20, $player->entity->getHealth() + $data), "regeneration");
if(($player = $this->server->api->player->getByEID($player["EID"])) !== false){
$player->entity->setHealth(min(20, $player->entity->getHealth() + $data), "regeneration");
}
}
}
break;
}
}
public function commandHandler($cmd, $params){
switch($cmd){
case "tp":
@ -98,7 +100,7 @@ class PlayerAPI{
break;
}
}
public function teleport($name, $target){
$target = $this->get($target);
if($target !== false){
@ -106,7 +108,7 @@ class PlayerAPI{
}
return false;
}
public function tppos($name, $x, $y, $z){
$player = $this->get($name);
if($player !== false){
@ -122,7 +124,7 @@ class PlayerAPI{
}
return false;
}
public function get($name){
$CID = $this->server->query("SELECT ip,port FROM players WHERE name = '".str_replace("'", "", $name)."';", true);
$CID = $this->server->clientID($CID["ip"], $CID["port"]);
@ -131,11 +133,11 @@ class PlayerAPI{
}
return false;
}
public function getAll(){
return $this->server->clients;
}
public function getByEID($eid){
$eid = (int) $eid;
$CID = $this->server->query("SELECT ip,port FROM players WHERE EID = '".$eid."';", true);
@ -145,7 +147,7 @@ class PlayerAPI{
}
return false;
}
public function getByClientID($clientID){
$clientID = (int) $clientID;
$CID = $this->server->query("SELECT ip,port FROM players WHERE clientID = '".$clientID."';", true);
@ -153,9 +155,9 @@ class PlayerAPI{
if(isset($this->server->clients[$CID])){
return $this->server->clients[$CID];
}
return false;
return false;
}
public function online(){
$o = array();
foreach($this->server->clients as $p){
@ -165,7 +167,7 @@ class PlayerAPI{
}
return $o;
}
public function add($CID){
if(isset($this->server->clients[$CID])){
$player = $this->server->clients[$CID];
@ -174,7 +176,7 @@ class PlayerAPI{
$this->server->query("INSERT OR REPLACE INTO players (clientID, ip, port, name) VALUES (".$player->clientID.", '".$player->ip."', ".$player->port.", '".$player->username."');");
}
}
public function remove($CID){
if(isset($this->server->clients[$CID])){
$player = $this->server->clients[$CID];
@ -187,7 +189,7 @@ class PlayerAPI{
unset($this->server->clients[$player->CID]);
}
}
public function getOffline($name){
if(!file_exists(FILE_PATH."players/".$name.".dat")){
console("[NOTICE] Player data not found for \"".$name."\", creating new profile");
@ -208,9 +210,9 @@ class PlayerAPI{
$this->server->handle("api.player.offline.get", $data);
return $data;
}
public function saveOffline($name, $data){
$this->server->handle("api.player.offline.save", $data);
file_put_contents(FILE_PATH."players/".str_replace("/", "", $name).".dat", serialize($data));
}
}
}

View File

@ -32,7 +32,7 @@ class PluginAPI extends stdClass{
$this->plugins = array();
require_once("classes/Spyc.class.php"); //YAML parser
}
public function getList(){
$list = array();
foreach($this->plugins as $p){
@ -40,7 +40,7 @@ class PluginAPI extends stdClass{
}
return $list;
}
public function getInfo($className){
if(!isset($this->plugins[$className])){
return false;
@ -48,7 +48,7 @@ class PluginAPI extends stdClass{
$plugin = $this->plugins[$className];
return array($plugin[1], get_class_methods($plugin[0]));
}
public function load($file){
$content = file_get_contents($file);
$info = strstr($content, "*/", true);
@ -95,12 +95,12 @@ class PluginAPI extends stdClass{
$object->__destruct();
}
$object = null;
unset($object);
unset($object);
}else{
$this->plugins[$className] = array($object, $info);
}
}
public function get(Plugin $plugin){
foreach($this->plugins as &$p){
if($p[0] === $plugin){
@ -109,7 +109,7 @@ class PluginAPI extends stdClass{
}
return false;
}
public function createConfig(Plugin $plugin, $default = array()){
$p = $this->get($plugin);
if($p === false){
@ -127,7 +127,7 @@ class PluginAPI extends stdClass{
}
return $path;
}
private function fillDefaults($default, &$yaml){
foreach($default as $k => $v){
if(is_array($v)){
@ -140,24 +140,24 @@ class PluginAPI extends stdClass{
}
}
}
public function readYAML($file){
return Spyc::YAMLLoad(file_get_contents($file));
}
public function writeYAML($file, $data){
return file_put_contents($file, Spyc::YAMLDump($data));
}
public function init(){
$this->server->event("server.start", array($this, "loadAll"));
}
public function loadAll(){
console("[INFO] Loading Plugins...");
$dir = dir(FILE_PATH."plugins/");
while(false !== ($file = $dir->read())){
if($file !== "." and $file !== ".."){
if($file{0} !== "."){
if(strtolower(substr($file, -3)) === "php"){
$this->load(FILE_PATH."plugins/" . $file);
}

View File

@ -29,14 +29,12 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run
var $restart = false;
private $server, $config, $apiList = array();
function __construct(){
console("[INFO] Starting ServerAPI server handler...");
console("[DEBUG] Checking data folders...", true, true, 2);
@mkdir(FILE_PATH."logs/", 0777, true);
@mkdir(FILE_PATH."players/", 0777);
@mkdir(FILE_PATH."worlds/", 0777);
@mkdir(FILE_PATH."plugins/", 0777);
console("[INFO] Starting ServerAPI server handler...");
file_put_contents(FILE_PATH."logs/packets.log", "");
file_put_contents(FILE_PATH."logs/console.in", "");
if(!file_exists(FILE_PATH."logs/test.bin.log") or md5_file(FILE_PATH."logs/test.bin.log") !== TEST_MD5){
console("[NOTICE] Executing integrity tests...");
console("[INFO] OS: ".PHP_OS.", ".Utils::getOS());
@ -71,7 +69,7 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run
die();
}
}
if(!file_exists(FILE_PATH."white-list.txt")){
console("[NOTICE] No white-list.txt found, creating blank file");
file_put_contents(FILE_PATH."white-list.txt", "");
@ -86,11 +84,11 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run
console("[NOTICE] No server.properties found, using default settings");
copy(FILE_PATH."src/common/default.properties", FILE_PATH."server.properties");
}
console("[DEBUG] Loading server.properties...", true, true, 2);
$this->parseProperties();
define("DEBUG", $this->config["debug"]);
$this->server = new PocketMinecraftServer($this->getProperty("server-name"), $this->getProperty("gamemode"), false, CURRENT_PROTOCOL, $this->getProperty("port"), $this->getProperty("server-id"));
$this->server = new PocketMinecraftServer($this->getProperty("server-name"), $this->getProperty("gamemode"), false, $this->getProperty("port"), $this->getProperty("server-id"));
$this->server->api = $this;
if($this->getProperty("last-update") === false or ($this->getProperty("last-update") + 3600) < time()){
console("[INFO] Checking for new server version");
@ -100,7 +98,7 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run
$channel = "dev";
}
$this->setProperty("update-channel", $channel);
if($channel === "dev"){
$info = json_decode(Utils::curl_get("https://api.github.com/repos/shoghicp/PocketMine-MP"), true);
if($info === false or !isset($info["updated_at"])){
@ -123,19 +121,30 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run
if($info === false or !isset($info[0])){
console("[ERROR] GitHub API Error");
}else{
$info = $info[0];
if($info["name"] != MAJOR_VERSION){
$newest = new VersionString(MAJOR_VERSION);
$newest = array(-1, $newest->getNumber());
foreach($info as $i => $tag){
$update = new VersionString($tag["name"]);
$update = $update->getNumber();
if($update > $newest[1]){
$newest = array($i, $update);
}
}
if($newest[0] !== -1){
$target = $info[$newest[0]];
console("[NOTICE] A new STABLE version of PocketMine-MP has been released");
console("[NOTICE] Version \"".$info["name"]."\" [".substr($info["commit"]["sha"], 0, 10)."]");
console("[NOTICE] Download it at ".$info["zipball_url"]);
console("[NOTICE] This message will dissapear as soon as you update\"");
console("[NOTICE] Version \"".(new VersionString($newest[1]))."\" #".$newest[1]." [".substr($target["commit"]["sha"], 0, 10)."]");
console("[NOTICE] Download it at ".$target["zipball_url"]);
console("[NOTICE] This message will dissapear as soon as you update");
sleep(5);
}else{
$this->setProperty("last-update", time());
console("[INFO] This is the latest STABLE version");
}
}
}
}
if(file_exists(FILE_PATH."worlds/level.dat")){
@ -144,7 +153,7 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run
}
$this->server->mapName = $this->getProperty("level-name");
$this->server->mapDir = FILE_PATH."worlds/".$this->server->mapName."/";
if($this->server->mapName === false or trim($this->server->mapName) === "" or !file_exists($this->server->mapDir."chunks.dat")){
if($this->server->mapName === false or trim($this->server->mapName) === "" or (!file_exists($this->server->mapDir."chunks.dat") and !file_exists($this->server->mapDir."chunks.dat.gz"))){
if($this->server->mapName === false or trim($this->server->mapName) === ""){
$this->server->mapName = "world";
}
@ -165,12 +174,12 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run
}
$this->loadProperties();
$this->server->loadMap();
//Autoload all default APIs
console("[INFO] Loading default APIs");
$dir = dir(FILE_PATH."src/API/");
while(false !== ($file = $dir->read())){
if($file !== "." and $file !== ".."){
if($file{0} !== "."){ //Hidden and upwards folders
$API = basename($file, ".php");
if(strtolower($API) !== "serverapi"){
$name = strtolower(substr($API, 0, -3));
@ -183,10 +192,20 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run
$ob->init();
}
}
$this->server->loadEntities();
}
public function __destruct(){
foreach($this->apiList as $ob){
if(is_callable($ob, "__destruct")){
$ob->__destruct();
unset($this->apiList[$ob]);
}
}
}
private function loadProperties(){
if(isset($this->config["memory-limit"])){
@ini_set("memory_limit", $this->config["memory-limit"]);
@ -209,7 +228,7 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run
$this->server->reloadConfig();
}
}
private function writeProperties(){
if(is_object($this->server)){
$this->config["server-id"] = $this->server->serverID;
@ -223,7 +242,7 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run
}
file_put_contents(FILE_PATH."server.properties", $prop);
}
private function parseProperties(){
$prop = file_get_contents(FILE_PATH."server.properties");
$prop = explode("\n", str_replace("\r", "", $prop));
@ -272,44 +291,49 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run
$this->config[$n] = $v;
}
}
public function start(){
$this->server->start();
$this->server->init();
unregister_tick_function(array($this->server, "tick"));
$this->__destruct();
unset($this->server);
return $this->restart;
}
/*-------------------------------------------------------------*/
public function addHandler($e, $c, $p = 5){
return $this->server->addHandler($e, $c, $p);
}
public function dhandle($e, $d){
return $this->server->handle($e, $d);
}
public function handle($e, &$d){
return $this->server->handle($e, $d);
}
public function action($t, $c, $r = true){
return $this->server->action($t, $c, $r);
}
public function schedule($t, $c, $d, $r = false, $e = "server.schedule"){
return $this->server->schedule($t, $c, $d, $r, $e);
}
public function event($e, $d){
return $this->server->event($e, $d);
}
public function trigger($e, $d){
return $this->server->trigger($e, $d);
}
public function deleteEvent($id){
return $this->server->deleteEvent($id);
}
public function importMap($dir, $remove = false){
if(file_exists($dir."level.dat")){
$nbt = new NBT();
@ -317,7 +341,7 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run
console("[DEBUG] Importing map \"".$level["LevelName"]."\" gamemode ".$level["GameType"]." with seed ".$level["RandomSeed"], true, true, 2);
unset($level["Player"]);
$lvName = $level["LevelName"]."/";
@mkdir(FILE_PATH."worlds/".$lvName, 0777);
@mkdir(FILE_PATH."worlds/".$lvName, 0777);
file_put_contents(FILE_PATH."worlds/".$lvName."level.dat", serialize($level));
$entities = parseNBTData($nbt->loadFile($dir."entities.dat"));
file_put_contents(FILE_PATH."worlds/".$lvName."entities.dat", serialize($entities["Entities"]));
@ -326,7 +350,7 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run
}
file_put_contents(FILE_PATH."worlds/".$lvName."tileEntities.dat", serialize($entities["TileEntities"]));
console("[DEBUG] Imported ".count($entities["Entities"])." Entities and ".count($entities["TileEntities"])." TileEntities", true, true, 2);
if($remove === true){
rename($dir."chunks.dat", FILE_PATH."worlds/".$lvName."chunks.dat");
unlink($dir."level.dat");
@ -345,29 +369,29 @@ class ServerAPI extends stdClass{ //Yay! I can add anything to this class in run
$this->writeProperties();
}
console("[INFO] Map \"".$level["LevelName"]."\" importing done!");
unset($level, $entities, $nbt);
unset($level, $entities, $nbt);
return true;
}
return false;
}
public function getProperty($name){
if(isset($this->config[$name])){
return $this->config[$name];
}
return false;
}
public function setProperty($name, $value){
$this->config[$name] = $value;
$this->writeProperties();
$this->loadProperties();
}
public function getList(){
return $this->apiList;
}
public function loadAPI($name, $class, $dir = false){
if($dir === false){
$dir = FILE_PATH."src/API/";

View File

@ -36,11 +36,11 @@ class TimeAPI{
function __construct(PocketMinecraftServer $server){
$this->server = $server;
}
public function init(){
$this->server->api->console->register("time", "Manages server time", array($this, "commandHandler"));
}
public function commandHandler($cmd, $params){
switch($cmd){
case "time":
@ -74,7 +74,7 @@ class TimeAPI{
break;
}
}
public function night(){
$this->set("night");
}
@ -87,20 +87,20 @@ class TimeAPI{
public function sunset(){
$this->set("sunset");
}
public function get($raw = false){
return $raw === true ? $this->server->time:abs($this->server->time) % 19200;
}
public function add($time){
$this->server->time += (int) $time;
}
public function getDate($time = false){
$time = $time === false ? $this->get():$time;
return str_pad(strval((floor($time /800) + 6) % 24), 2, "0", STR_PAD_LEFT).":".str_pad(strval(floor(($time % 800) / 13.33)), 2, "0", STR_PAD_LEFT);
}
public function getPhase($time = false){
$time = $time === false ? $this->get():$time;
if($time < $this->phase["sunset"]){
@ -114,7 +114,7 @@ class TimeAPI{
}
return $time;
}
public function set($time){
if(is_string($time) and isset($this->phases[$time])){
$this->server->time = $this->phases[$time];
@ -122,6 +122,6 @@ class TimeAPI{
$this->server->time = (int) $time;
}
}
}

View File

@ -0,0 +1,71 @@
<?php
/*
-
/ \
/ \
/ PocketMine \
/ MP \
|\ @shoghicp /|
|. \ / .|
| .. \ / .. |
| .. | .. |
| .. | .. |
\ | /
\ | /
\ | /
\ | /
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
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
*/
class Async extends Thread {
/**
* Provide a passthrough to call_user_func_array
**/
public function __construct($method, $params = array()){
$this->method = $method;
$this->params = $params;
$this->result = null;
$this->joined = false;
}
/**
* The smallest thread in the world
**/
public function run(){
if(($this->result=call_user_func_array($this->method, $this->params))){
return true;
}else{
return false;
}
}
/**
* Static method to create your threads from functions ...
**/
public static function call($method, $params = array()){
$thread = new Async($method, $params);
if($thread->start()){
return $thread;
} /** else throw Nastyness **/
}
/**
* Do whatever, result stored in $this->result, don't try to join twice
**/
public function __toString(){
if(!$this->joined) {
$this->joined = true;
$this->join();
}
return $this->result;
}
}

View File

@ -9,7 +9,7 @@
*
* PHP versions 4 and 5
*
* {@internal (all DocBlock comments regarding implementation - such as the one that follows - refer to the
* {@internal (all DocBlock comments regarding implementation - such as the one that follows - refer to the
* {@link MATH_BIGINTEGER_MODE_INTERNAL MATH_BIGINTEGER_MODE_INTERNAL} mode)
*
* Math_BigInteger uses base-2**26 to perform operations such as multiplication and division and
@ -53,10 +53,10 @@
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@ -234,7 +234,7 @@ class Math_BigInteger {
/**
* Mode independant value used for serialization.
*
* If the bcmath or gmp extensions are installed $this->value will be a non-serializable resource, hence the need for
* If the bcmath or gmp extensions are installed $this->value will be a non-serializable resource, hence the need for
* a variable that'll be serializable regardless of whether or not extensions are being used. Unlike $this->value,
* however, $this->hex is only calculated when $this->__sleep() is called.
*
@ -750,7 +750,7 @@ class Math_BigInteger {
$vars[] = 'precision';
}
return $vars;
}
/**
@ -2237,7 +2237,7 @@ class Math_BigInteger {
/**
* Montgomery Multiply
*
* Interleaves the montgomery reduction and long multiplication algorithms together as described in
* Interleaves the montgomery reduction and long multiplication algorithms together as described in
* {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=13 HAC 14.36}
*
* @see _prepMontgomery()
@ -2317,7 +2317,7 @@ class Math_BigInteger {
* {@link http://groups.google.com/group/sci.crypt/msg/7a137205c1be7d85}
*
* As for why we do all the bitmasking... strange things can happen when converting from floats to ints. For
* instance, on some computers, var_dump((int) -4294967297) yields int(-1) and on others, it yields
* instance, on some computers, var_dump((int) -4294967297) yields int(-1) and on others, it yields
* int(-2147483648). To avoid problems stemming from this, we use bitmasks to guarantee that ints aren't
* auto-converted to floats. The outermost bitmask is present because without it, there's no guarantee that
* the "residue" returned would be the so-called "common residue". We use fmod, in the last step, because the
@ -3217,7 +3217,7 @@ class Math_BigInteger {
* @return Boolean
* @access public
* @internal Uses the
* {@link http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test Miller-Rabin primality test}. See
* {@link http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test Miller-Rabin primality test}. See
* {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=8 HAC 4.24}.
*/
function isPrime($t = false)
@ -3266,16 +3266,16 @@ class Math_BigInteger {
if (!isset($primes)) {
$primes = array(
3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137,
139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227,
229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509,
521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617,
619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727,
733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829,
839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947,
3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137,
139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227,
229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509,
521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617,
619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727,
733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829,
839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947,
953, 967, 971, 977, 983, 991, 997
);

View File

@ -30,11 +30,11 @@ class ChunkParser{
var $sectorLength = 4096; //16 * 16 * 16
var $chunkLength = 86016; //21 * $sectorLength
var $map;
function __construct(){
$map = array();
}
private function loadLocationTable(){
$this->location = array();
console("[DEBUG] Loading Chunk Location table...", true, true, 2);
@ -57,43 +57,52 @@ class ChunkParser{
++$chunkCnt;
}
}
public function loadFile($file){
if(!file_exists($file)){
if(ZLIB_EXTENSION === true and file_exists($file.".gz")){
$this->raw = gzinflate(file_get_contents($file.".gz"));
$r = @gzinflate($this->raw);
if($r !== false and $r != ""){
$this->raw = $r;
}
@unlink($file.".gz");
file_put_contents($file, $this->raw);
}elseif(!file_exists($file)){
return false;
}else{
$this->raw = file_get_contents($file);
}
$this->file = $file;
$this->raw = file_get_contents($file);
$this->chunkLength = $this->sectorLength * ord($this->raw{0});
return true;
}
public function loadRaw($raw, $file){
$this->file = $file;
$this->raw = $raw;
$this->chunkLength = $this->sectorLength * ord($this->raw{0});
return true;
}
private function getOffsetPosition($X, $Z){
$data = substr($this->raw, ($X << 2) + ($Z << 7), 4); //$X * 4 + $Z * 128
return array(ord($data{0}), ord($data{1}), ord($data{2}), ord($data{3}));
}
private function getOffset($X, $Z, $sectors = 21){
return 0x1000 + (($X * $sectors) << 12) + (($Z * $sectors) << 16);
}
private function getOffsetLocation($X, $Z){
return $X << 2 + $Z << 7;
}
public function getChunk($X, $Z){
$X = (int) $X;
$Z = (int) $Z;
return substr($this->raw, $this->getOffset($X, $Z), $this->chunkLength);
}
public function writeChunk($X, $Z){
$X = (int) $X;
$Z = (int) $Z;
@ -108,7 +117,7 @@ class ChunkParser{
}
return Utils::writeLInt(strlen($chunk)).$chunk;
}
public function parseChunk($X, $Z){
$X = (int) $X;
$Z = (int) $Z;
@ -130,7 +139,7 @@ class ChunkParser{
}
return $chunk;
}
public function loadMap(){
if($this->raw == ""){
return false;
@ -146,9 +155,10 @@ class ChunkParser{
$this->raw = b"";
console("[DEBUG] Chunks loaded!", true, true, 2);
}
public function saveMap(){
public function saveMap($final = false){
console("[DEBUG] Saving chunks...", true, true, 2);
$fp = fopen($this->file, "r+b");
flock($fp, LOCK_EX);
foreach($this->map as $x => $d){
@ -159,8 +169,17 @@ class ChunkParser{
}
flock($fp, LOCK_UN);
fclose($fp);
if(ZLIB_EXTENSION === true){
$original = filesize($this->file);
file_put_contents($this->file .".gz", gzdeflate(gzdeflate(file_get_contents($this->file),9),9)); //Double compression for flat maps
$compressed = filesize($this->file .".gz");
console("[DEBUG] Saved chunks.dat.gz with ".round(($compressed/$original)*100, 2)."% (".round($compressed/1024, 2)."KB) of the original size", true, true, 2);
if($final === true){
@unlink($this->file);
}
}
}
public function getFloor($x, $z){
$X = $x >> 4;
$Z = $z >> 4;
@ -174,7 +193,7 @@ class ChunkParser{
}
return $y;
}
public function getBlock($x, $y, $z){
$x = (int) $x;
$y = (int) $y;
@ -193,12 +212,12 @@ class ChunkParser{
}
return array($block, $meta);
}
public function getChunkColumn($X, $Z, $x, $z, $type = 0){
$index = $z + ($x << 4);
return $this->map[$X][$Z][$type][$index];
}
public function setBlock($x, $y, $z, $block, $meta = 0){
$x = (int) $x;
$y = (int) $y;

View File

@ -42,7 +42,7 @@ class CustomPacketHandler{
}
return $data;
}
public function __construct($pid, $raw = "", $data = array(), $create = false){
$this->raw = $raw;
$this->data = $data;
@ -54,10 +54,19 @@ class CustomPacketHandler{
$this->data["payload"] = Utils::readLong($this->get(8));
}else{
$this->raw .= Utils::writeLong($this->data["payload"]);
}
}
break;
case 0x03:
if($this->c === false){
$this->data["unknown1"] = Utils::readLong($this->get(8));
$this->data["unknown2"] = Utils::readLong($this->get(8));
}else{
$this->raw .= Utils::writeLong($this->data["unknown1"]);
$this->raw .= Utils::writeLong($this->data["unknown2"]);
}
break;
case MC_CLIENT_CONNECT:
if($this->c === false){
if($this->c === false){
$this->data["clientID"] = Utils::readLong($this->get(8));
$this->data["session"] = Utils::readLong($this->get(8));
$this->data["unknown2"] = $this->get(1);
@ -96,7 +105,7 @@ class CustomPacketHandler{
$this->raw .= "\x00\x00";
$this->raw .= Utils::writeLong($this->data["session"]);
$this->raw .= Utils::writeLong($this->data["session2"]);
}
}
break;
case MC_CLIENT_HANDSHAKE:
if($this->c === false){
@ -128,7 +137,7 @@ class CustomPacketHandler{
//null
break;
case MC_LOGIN:
if($this->c === false){
if($this->c === false){
$this->data["username"] = $this->get(Utils::readShort($this->get(2), false));
$this->data["maxX"] = Utils::readInt($this->get(4));
$this->data["maxY"] = Utils::readInt($this->get(4));
@ -138,35 +147,35 @@ class CustomPacketHandler{
}
break;
case MC_LOGIN_STATUS:
if($this->c === false){
if($this->c === false){
$this->data["status"] = Utils::readInt($this->get(4));
}else{
$this->raw .= Utils::writeInt($this->data["status"]);
}
break;
case MC_READY:
if($this->c === false){
if($this->c === false){
$this->data["status"] = ord($this->get(1));
}else{
$this->raw .= chr($this->data["status"]);
}
}
break;
case MC_CHAT:
if($this->c === false){
if($this->c === false){
$this->data["message"] = $this->get(Utils::readShort($this->get(2), false));
}else{
$this->raw .= Utils::writeShort(strlen($this->data["message"])).$this->data["message"];
}
break;
case MC_SET_TIME:
if($this->c === false){
if($this->c === false){
$this->data["time"] = Utils::readInt($this->get(4));
}else{
$this->raw .= Utils::writeInt($this->data["time"]);
}
break;
case MC_START_GAME:
if($this->c === false){
if($this->c === false){
$this->data["seed"] = Utils::readInt($this->get(4));
$this->data["unknown1"] = Utils::readInt($this->get(4));
$this->data["gamemode"] = Utils::readInt($this->get(4));
@ -182,9 +191,9 @@ class CustomPacketHandler{
$this->raw .= Utils::writeFloat($this->data["x"]);
$this->raw .= Utils::writeFloat($this->data["y"]);
$this->raw .= Utils::writeFloat($this->data["z"]);
}
}
break;
case MC_ADD_MOB:
case MC_ADD_MOB:
if($this->c === false){
$this->data["eid"] = Utils::readInt($this->get(4));
$this->data["type"] = Utils::readInt($this->get(4));
@ -205,7 +214,7 @@ class CustomPacketHandler{
));
}
break;
case MC_ADD_PLAYER:
case MC_ADD_PLAYER:
if($this->c === false){
$this->data["clientID"] = Utils::readLong($this->get(8));
$this->data["username"] = $this->get(Utils::readShort($this->get(2), false));
@ -279,8 +288,17 @@ class CustomPacketHandler{
$this->raw .= Utils::writeByte($this->data["roll"]);
}
break;
case MC_TAKE_ITEM_ENTITY:
if($this->c === false){
$this->data["target"] = Utils::readInt($this->get(4));
$this->data["eid"] = Utils::readInt($this->get(4));
}else{
$this->raw .= Utils::writeInt($this->data["target"]);
$this->raw .= Utils::writeInt($this->data["eid"]);
}
break;
case MC_MOVE_ENTITY:
if($this->c === false){
if($this->c === false){
$this->data["eid"] = Utils::readInt($this->get(4));
$this->data["x"] = Utils::readFloat($this->get(4));
$this->data["y"] = Utils::readFloat($this->get(4));
@ -293,7 +311,7 @@ class CustomPacketHandler{
}
break;
case MC_MOVE_ENTITY_POSROT:
if($this->c === false){
if($this->c === false){
$this->data["eid"] = Utils::readInt($this->get(4));
$this->data["x"] = Utils::readFloat($this->get(4));
$this->data["y"] = Utils::readFloat($this->get(4));
@ -310,7 +328,7 @@ class CustomPacketHandler{
}
break;
case MC_MOVE_PLAYER:
if($this->c === false){
if($this->c === false){
$this->data["eid"] = Utils::readInt($this->get(4));
$this->data["x"] = Utils::readFloat($this->get(4));
$this->data["y"] = Utils::readFloat($this->get(4));
@ -327,7 +345,7 @@ class CustomPacketHandler{
}
break;
case MC_PLACE_BLOCK:
if($this->c === false){
if($this->c === false){
$this->data["eid"] = Utils::readInt($this->get(4));
$this->data["x"] = Utils::readInt($this->get(4));
$this->data["z"] = Utils::readInt($this->get(4));
@ -343,10 +361,10 @@ class CustomPacketHandler{
$this->raw .= chr($this->data["block"]);
$this->raw .= chr($this->data["meta"]);
$this->raw .= chr($this->data["face"]);
}
}
break;
case MC_REMOVE_BLOCK:
if($this->c === false){
if($this->c === false){
$this->data["eid"] = Utils::readInt($this->get(4));
$this->data["x"] = Utils::readInt($this->get(4));
$this->data["z"] = Utils::readInt($this->get(4));
@ -356,7 +374,7 @@ class CustomPacketHandler{
$this->raw .= Utils::writeInt($this->data["x"]);
$this->raw .= Utils::writeInt($this->data["z"]);
$this->raw .= chr($this->data["y"]);
}
}
break;
case MC_UPDATE_BLOCK:
if($this->c === false){
@ -371,10 +389,10 @@ class CustomPacketHandler{
$this->raw .= chr($this->data["y"]);
$this->raw .= chr($this->data["block"]);
$this->raw .= chr($this->data["meta"]);
}
}
break;
case MC_REQUEST_CHUNK:
if($this->c === false){
if($this->c === false){
$this->data["x"] = Utils::readInt($this->get(4));
$this->data["z"] = Utils::readInt($this->get(4));
}else{
@ -383,7 +401,7 @@ class CustomPacketHandler{
}
break;
case MC_CHUNK_DATA:
if($this->c === false){
if($this->c === false){
$this->data["x"] = Utils::readInt($this->get(4));
$this->data["z"] = Utils::readInt($this->get(4));
$this->data["data"] = $this->get(true);
@ -394,7 +412,7 @@ class CustomPacketHandler{
}
break;
case MC_PLAYER_EQUIPMENT:
if($this->c === false){
if($this->c === false){
$this->data["eid"] = Utils::readInt($this->get(4));
$this->data["block"] = Utils::readShort($this->get(2), false);
$this->data["meta"] = Utils::readShort($this->get(2), false);
@ -402,10 +420,10 @@ class CustomPacketHandler{
$this->raw .= Utils::writeInt($this->data["eid"]);
$this->raw .= Utils::writeShort($this->data["block"]);
$this->raw .= Utils::writeShort($this->data["meta"]);
}
}
break;
case MC_INTERACT:
if($this->c === false){
if($this->c === false){
$this->data["action"] = Utils::readByte($this->get(1));
$this->data["eid"] = Utils::readInt($this->get(4));
$this->data["target"] = Utils::readInt($this->get(4));
@ -413,10 +431,10 @@ class CustomPacketHandler{
$this->raw .= Utils::writeByte($this->data["action"]);
$this->raw .= Utils::writeInt($this->data["eid"]);
$this->raw .= Utils::writeInt($this->data["target"]);
}
}
break;
case MC_USE_ITEM:
if($this->c === false){
if($this->c === false){
$this->data["x"] = Utils::readInt($this->get(4));
$this->data["y"] = Utils::readInt($this->get(4));
$this->data["z"] = Utils::readInt($this->get(4));
@ -431,33 +449,33 @@ class CustomPacketHandler{
/*$this->raw .= Utils::writeByte($this->data["action"]);
$this->raw .= Utils::writeInt($this->data["eid"]);
$this->raw .= Utils::writeInt($this->data["target"]);*/
}
}
break;
case MC_SET_ENTITY_DATA:
if($this->c === false){
if($this->c === false){
$this->data["eid"] = Utils::readInt($this->get(4));
}else{
$this->raw .= Utils::writeInt($this->data["eid"]);
$this->raw .= Utils::writeMetadata(array(
));
}
}
break;
case MC_SET_HEALTH:
if($this->c === false){
$this->data["health"] = ord($this->get(1));
if($this->c === false){
$this->data["health"] = Utils::readByte($this->get(1));
}else{
$this->raw .= chr($this->data["health"]);
$this->raw .= Utils::writeByte($this->data["health"]);
}
break;
case MC_ANIMATE:
if($this->c === false){
if($this->c === false){
$this->data["action"] = Utils::readByte($this->get(1));
$this->data["eid"] = Utils::readInt($this->get(4));
}else{
$this->raw .= Utils::writeByte($this->data["action"]);
$this->raw .= Utils::writeInt($this->data["eid"]);
}
}
break;
case MC_RESPAWN:
if($this->c === false){
@ -470,17 +488,67 @@ class CustomPacketHandler{
$this->raw .= Utils::writeFloat($this->data["x"]);
$this->raw .= Utils::writeFloat($this->data["y"]);
$this->raw .= Utils::writeFloat($this->data["z"]);
}
}
break;
case MC_DROP_ITEM:
if($this->c === false){
$this->data["eid"] = Utils::readInt($this->get(4));
$this->data["unknown1"] = ord($this->get(1));
$this->data["block"] = Utils::readShort($this->get(2), false);
$this->data["stack"] = ord($this->get(1));
$this->data["meta"] = Utils::readShort($this->get(2), false);
}else{
$this->raw .= Utils::writeInt($this->data["eid"]);
$this->raw .= chr($this->data["unknown1"]);
$this->raw .= Utils::writeShort($this->data["block"]);
$this->raw .= chr($this->data["stack"]);
$this->raw .= Utils::writeShort($this->data["meta"]);
}
break;
case MC_CONTAINER_OPEN:
if($this->c === false){
$this->data["windowid"] = ord($this->get(1));
$this->data["type"] = ord($this->get(1));
$this->data["slots"] = Utils::readShort($this->get(2), false);
$this->data["title"] = $this->get(Utils::readShort($this->get(2), false));
}else{
$this->raw .= chr($this->data["windowid"]);
$this->raw .= chr($this->data["type"]);
$this->raw .= Utils::writeShort($this->data["slots"]);
$this->raw .= Utils::writeShort(strlen($this->data["title"])).$this->data["title"];
}
break;
case MC_CONTAINER_CLOSE:
if($this->c === false){
$this->data["windowid"] = ord($this->get(1));
}else{
$this->raw .= chr($this->data["windowid"]);
}
break;
case MC_CONTAINER_SET_SLOT:
if($this->c === false){
$this->data["windowid"] = ord($this->get(1));
$this->data["slot"] = Utils::readShort($this->get(2), false);
$this->data["block"] = Utils::readShort($this->get(2), false);
$this->data["stack"] = ord($this->get(1));
$this->data["meta"] = Utils::readShort($this->get(2), false);
}else{
$this->raw .= chr($this->data["windowid"]);
$this->raw .= Utils::writeShort($this->data["slot"]);
$this->raw .= Utils::writeShort($this->data["block"]);
$this->raw .= chr($this->data["stack"]);
$this->raw .= Utils::writeShort($this->data["meta"]);
}
break;
case MC_CLIENT_MESSAGE:
if($this->c === false){
if($this->c === false){
$this->data["message"] = $this->get(Utils::readShort($this->get(2), false));
}else{
$this->raw .= Utils::writeShort(strlen($this->data["message"])).$this->data["message"];
}
break;
case MC_SIGN_UPDATE:
if($this->c === false){
if($this->c === false){
$this->data["x"] = Utils::readShort($this->get(2));
$this->data["y"] = ord($this->get(1));
$this->data["z"] = Utils::readShort($this->get(2));
@ -497,7 +565,7 @@ class CustomPacketHandler{
}
break;
case MC_ADVENTURE_SETTINGS:
if($this->c === false){
if($this->c === false){
$this->data["x"] = Utils::readShort($this->get(2));
$this->data["y"] = ord($this->get(1));
$this->data["z"] = Utils::readShort($this->get(2));
@ -507,7 +575,14 @@ class CustomPacketHandler{
}else{
$this->raw .= $this->data["unknown1"];
$this->raw .= $this->data["unknown2"];
}
}
break;
default:
if($this->c === false){
console("[DEBUG] Received unknown Data Packet ID 0x".dechex($pid), true, true, 2);
}else{
console("[DEBUG] Sent unknown Data Packet ID 0x".dechex($pid), true, true, 2);
}
break;
}
}

View File

@ -81,7 +81,7 @@ class Material{
);
static $unbreakable = array(
0 => true,
//7 => true,
7 => true,
8 => true,
9 => true,
10 => true,
@ -120,7 +120,7 @@ class Material{
102 => true,
105 => true,
107 => true,
108 => true,
108 => true,
);
static $replaceable = array(
0 => true,
@ -130,7 +130,7 @@ class Material{
11 => true,
31 => true,
51 => true,
78 => true,
78 => true,
);
static $activable = array(
2 => true,
@ -234,7 +234,7 @@ class Material{
4 => "Cobblestone",
5 => "Wooden Planks",
6 => "Sapling",
7 => "Bedrock",
7 => "Bedrock",
);

View File

@ -2,20 +2,20 @@
/*
-
/ \
/ \
-
/ \
/ \
/ PocketMine \
/ MP \
|\ @shoghicp /|
|. \ / .|
| .. \ / .. |
| .. | .. |
| .. | .. |
\ | /
\ | /
\ | /
\ | /
/ MP \
|\ @shoghicp /|
|. \ / .|
| .. \ / .. |
| .. | .. |
| .. | .. |
\ | /
\ | /
\ | /
\ | /
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
@ -34,7 +34,7 @@ define("ENTITY_PAINTING", 4);
class Entity extends stdClass{
var $eid, $type, $name, $x, $y, $z, $yaw, $pitch, $dead, $data, $class, $attach, $metadata, $closed, $player, $onTick;
private $ev, $server;
private $server;
function __construct($server, $eid, $class, $type = 0, $data = array()){
$this->server = $server;
$this->eid = (int) $eid;
@ -49,7 +49,7 @@ class Entity extends stdClass{
$this->closed = false;
$this->name = "";
$this->server->query("INSERT OR REPLACE INTO entities (EID, type, class, health) VALUES (".$this->eid.", ".$this->type.", ".$this->class.", ".$this->health.");");
$this->ev = $this->server->event("server.tick", array($this, "update"));
$this->server->schedule(20, array($this, "update"), array(), true);
$this->metadata = array();
$this->x = isset($this->data["x"]) ? $this->data["x"]:0;
$this->y = isset($this->data["y"]) ? $this->data["y"]:0;
@ -74,11 +74,24 @@ class Entity extends stdClass{
break;
}
}
public function update(){
if($this->class === ENTITY_ITEM and $this->closed === false){
$this->server->api->dhandle("entity.move", $this);
$player = $this->server->query("SELECT EID FROM entities WHERE class == ".ENTITY_PLAYER." AND abs(x - {$this->x}) <= 1.5 AND abs(y - {$this->y}) <= 1.5 AND abs(z - {$this->z}) <= 1.5 LIMIT 1;", true);
if($player !== true and $player !== false){
if($this->server->api->dhandle("player.item.pick", array(
"eid" => $player["EID"],
"block" => $this->type,
"meta" => $this->meta,
"target" => $this->eid
)) !== false){
$this->close();
}
}
}
}
public function getDirection(){
$rotation = ($this->yaw - 90) % 360;
if ($rotation < 0) {
@ -98,7 +111,7 @@ class Entity extends stdClass{
return null;
}
}
public function spawn($player){
if(!is_object($player)){
$player = $this->server->api->player->get($player);
@ -132,7 +145,7 @@ class Entity extends stdClass{
"meta" => $this->meta,
"stack" => $this->stack,
));
break;
break;
case ENTITY_MOB:
$player->dataPacket(MC_ADD_MOB, array(
"type" => $this->type,
@ -147,33 +160,33 @@ class Entity extends stdClass{
break;
}
}
public function close(){
if($this->closed === false){
$this->server->query("DELETE FROM entities WHERE EID = ".$this->eid.";");
$this->server->trigger("entity.remove", $this->eid);
$this->server->deleteEvent($this->ev);
$this->server->api->dhandle("entity.remove", $this);
$this->closed = true;
$this->__destruct();
}
}
public function __destruct(){
$this->close();
}
public function getEID(){
return $this->eid;
}
public function getName(){
return $this->name;
}
public function setName($name){
$this->name = $name;
$this->server->query("UPDATE entities SET name = '".str_replace("'", "", $this->name)."' WHERE EID = ".$this->eid.";");
}
public function look($pos2){
$pos = $this->getPosition();
$angle = Utils::angle3D($pos2, $pos);
@ -181,14 +194,14 @@ class Entity extends stdClass{
$this->pitch = $angle["pitch"];
$this->server->query("UPDATE entities SET pitch = ".$this->pitch.", yaw = ".$this->yaw." WHERE EID = ".$this->eid.";");
}
public function setCoords($x, $y, $z){
$this->x = $x;
$this->y = $y;
$this->z = $z;
$this->server->query("UPDATE entities SET x = ".$this->x.", y = ".$this->y.", z = ".$this->z." WHERE EID = ".$this->eid.";");
}
public function move($x, $y, $z, $yaw = 0, $pitch = 0){
$this->x += $x;
$this->y += $y;
@ -199,25 +212,25 @@ class Entity extends stdClass{
$this->pitch %= 90;
$this->server->query("UPDATE entities SET x = ".$this->x.", y = ".$this->y.", z = ".$this->z.", pitch = ".$this->pitch.", yaw = ".$this->yaw." WHERE EID = ".$this->eid.";");
}
public function setPosition($x, $y, $z, $yaw, $pitch){
$this->x = $x;
$this->y = $y;
$this->z = $z;
$this->yaw = $yaw;
$this->pitch = $pitch;
$this->server->query("UPDATE entities SET x = ".$this->x.", y = ".$this->y.", z = ".$this->z.", pitch = ".$this->pitch.", yaw = ".$this->yaw." WHERE EID = ".$this->eid.";");
$this->server->query("UPDATE entities SET x = ".$this->x.", y = ".$this->y.", z = ".$this->z.", pitch = ".$this->pitch.", yaw = ".$this->yaw." WHERE EID = ".$this->eid.";");
return true;
}
public function getPosition($round = false){
return !isset($this->position) ? false:($round === true ? array_map("floor", $this->position):$this->position);
}
public function setHealth($health, $cause = ""){
public function setHealth($health, $cause = ""){
$this->health = (int) $health;
$this->server->query("UPDATE entities SET health = ".$this->health." WHERE EID = ".$this->eid.";");
$this->server->trigger("entity.health.change", array("eid" => $this->eid, "health" => $health, "cause" => $cause));
$this->server->api->dhandle("entity.health.change", array("eid" => $this->eid, "health" => $health, "cause" => $cause));
if($this->player !== false){
$this->player->dataPacket(MC_SET_HEALTH, array(
"health" => $this->health,
@ -226,13 +239,13 @@ class Entity extends stdClass{
if($this->health <= 0 and $this->dead === false){
$this->dead = true;
if($this->player !== false){
$this->server->handle("player.death", array("name" => $this->name, "cause" => $cause));
$this->server->api->dhandle("player.death", array("name" => $this->name, "cause" => $cause));
}
}elseif($this->health > 0){
$this->dead = false;
}
}
public function getHealth(){
return $this->health;
}

View File

@ -26,21 +26,22 @@ the Free Software Foundation, either version 3 of the License, or
*/
class WorldGenerator{
private $gen, $seed, $raw;
private $gen, $seed, $genName, $raw;
public function __construct($genName, $seed){
$this->seed = (int) $seed;
$this->raw = b"";
$this->genName = $genName;
$this->gen = new $genName($this->seed);
}
public function getSpawn(){
return $this->gen->getSpawn();
}
public function set($name, $value){
$this->gen->set($name, $value);
}
public function init(){
$this->raw = "\x15\x01\x00\x00\x15\x16\x00\x00\x15\x2b\x00\x00\x15\x40\x00\x00". //Location Header
"\x15\x55\x00\x00\x15\x6a\x00\x00\x15\x7f\x00\x00\x15\x94\x00\x00".
@ -300,18 +301,18 @@ class WorldGenerator{
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
$this->gen->init();
}
public function generate(){
for($Z = 0; $Z < 16; ++$Z){
for($X = 0; $X < 16; ++$X){
$chunk = str_pad($this->getChunk($X, $Z), 86012, "\x00", STR_PAD_RIGHT);
$this->raw .= Utils::writeLInt(strlen($chunk)) . $chunk;
$this->raw .= Utils::writeLInt(strlen($chunk)) . $chunk;
}
console("[DEBUG] Generating level ".ceil(($Z + 1)/0.16)."%", true, true, 2);
}
return true;
}
private function getChunk($X, $Z){
$chunk = b"";
$columns = array();
@ -332,7 +333,7 @@ class WorldGenerator{
unset($columns);
return $chunk;
}
public function save($dir, $name){
@mkdir($dir, 0777, true);
file_put_contents($dir."chunks.dat", $this->raw);
@ -345,6 +346,7 @@ class WorldGenerator{
"Time" => 0,
"Gamemode" => 1,
"RandomSeed" => $this->seed,
"Generator" => $this->genName,
"SpawnX" => $s[0],
"SpawnY" => $s[1],
"SpawnZ" => $s[2],

View File

@ -28,26 +28,26 @@ the Free Software Foundation, either version 3 of the License, or
class Java_String{
private $value = "", $count = 0, $hash = 0;
public function __construct($string = false){
if($string !== false){
$this->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){
@ -56,7 +56,7 @@ class Java_String{
}
return $this->value{$index};
}
public function hashCode(){
$h = $this->hash;
if($h === 0 and $this->count > 0){
@ -68,13 +68,13 @@ class Java_String{
$this->hash = $h;
}
return $h;
}
}
}
class Java_Random{
private $haveNextNextGaussian, $nextNextGaussian, $seed, $n1, $n2, $n3, $zero;
public function __construct($seed = false){
$this->n1 = new Math_BigInteger(0x5DEECE66D);
$this->n2 = new Math_BigInteger(1);
@ -86,19 +86,19 @@ class Java_Random{
}
$this->setSeed($seed);
}
public function setSeed($seed){
$seed = new Math_BigInteger($seed);
$this->seed = $seed->bitwise_xor($this->n1)->bitwise_and($this->n2);
$this->haveNextNextGaussian = false;
}
protected function next($bits){
$bits = (int) $bits;
$this->seed = $this->seed->multiply($this->n1)->add($this->n3)->bitwise_and($this->n2);
return $this->_tripleRightShift($this->seed, (48 - $bits));
}
private function _tripleRightShift($number, $places){
if($number->compare($this->zero) >= 0){
return $number->bitwise_rightShift($places);
@ -106,7 +106,7 @@ class Java_Random{
$n1 = new Math_BigInteger(2);
return $number->bitwise_rightShift($places)->add($n1->bitwise_leftShift(~$places));
}
public function nextBytes($bytes){
$bytes = (int) $bytes;
$b = b"";

View File

@ -26,14 +26,13 @@ the Free Software Foundation, either version 3 of the License, or
*/
class MinecraftInterface{
var $pstruct, $name, $protocol, $client, $dataName;
var $pstruct, $name, $client, $dataName;
private $socket, $data;
function __construct($server, $protocol = CURRENT_PROTOCOL, $port = 25565, $listen = false, $client = true){
function __construct($server, $port = 25565, $listen = false, $client = true){
$this->socket = new UDPSocket($server, $port, (bool) $listen);
$this->protocol = (int) $protocol;
require("pstruct/RakNet.php");
require("pstruct/packetName.php");
require("pstruct/".$this->protocol.".php");
require("pstruct/protocol.php");
require("pstruct/dataName.php");
$this->pstruct = $pstruct;
$this->name = $packetName;
@ -42,18 +41,18 @@ class MinecraftInterface{
$this->client = (bool) $client;
$this->start = microtime(true);
}
public function close(){
return $this->socket->close();
}
protected function getStruct($pid){
if(isset($this->pstruct[$pid])){
return $this->pstruct[$pid];
}
return false;
}
protected function writeDump($pid, $raw, $data, $origin = "client", $ip = "", $port = 0){
if(LOG === true and DEBUG >= 3){
$p = "[".(microtime(true) - $this->start)."] [".((($origin === "client" and $this->client === true) or ($origin === "server" and $this->client === false)) ? "CLIENT->SERVER":"SERVER->CLIENT")." ".$ip.":".$port."]: ".(isset($data["id"]) ? "MC Packet ".$this->dataName[$pid]:$this->name[$pid])." (0x".Utils::strTohex(chr($pid)).") [length ".strlen($raw)."]".PHP_EOL;
@ -66,9 +65,9 @@ class MinecraftInterface{
$p .= PHP_EOL;
logg($p, "packets", false);
}
}
public function readPacket(){
$p = $this->popPacket();
if($p !== false){
@ -91,14 +90,13 @@ class MinecraftInterface{
logg($p, "packets", true, 2);
return false;
}
$packet = new Packet($pid, $struct, $data[0]);
$packet->protocol = $this->protocol;
$packet->parse();
$this->data[] = array($pid, $packet->data, $data[0], $data[1], $data[2]);
return $this->popPacket();
}
public function popPacket(){
if(count($this->data) > 0){
$p = array_shift($this->data);
@ -114,12 +112,11 @@ class MinecraftInterface{
}
return false;
}
public function writePacket($pid, $data = array(), $raw = false, $dest = false, $port = false){
$struct = $this->getStruct($pid);
if($raw === false){
$packet = new Packet($pid, $struct);
$packet->protocol = $this->protocol;
$packet->data = $data;
$packet->create();
$write = $this->socket->write($packet->raw, $dest, $port);
@ -127,10 +124,10 @@ class MinecraftInterface{
}else{
$write = $this->socket->write($data, $dest, $port);
$this->writeDump($pid, $data, false, "client", $dest, $port);
}
}
return true;
}
}
?>

View File

@ -1,7 +1,7 @@
<?php
/**
* Class for reading in NBT-format files.
*
*
* @author Justin Martin <frozenfire@thefrozenfire.com>
* @version 1.0
* MODIFIED BY @shoghicp
@ -12,7 +12,7 @@
class NBT {
public $root = array();
const TAG_END = 0;
const TAG_BYTE = 1;
const TAG_SHORT = 2;
@ -24,7 +24,7 @@ class NBT {
const TAG_STRING = 8;
const TAG_LIST = 9;
const TAG_COMPOUND = 10;
public function loadFile($filename) {
if(is_file($filename)) {
$fp = fopen($filename, "rb");
@ -44,7 +44,7 @@ class NBT {
$this->traverseTag($fp, $this->root);
return end($this->root);
}
public function traverseTag($fp, &$tree) {
if(feof($fp)) {
return false;
@ -59,7 +59,7 @@ class NBT {
return true;
}
}
public function readType($fp, $tagType) {
switch($tagType) {
case self::TAG_BYTE: // Signed byte (8 bit)

View File

@ -0,0 +1,66 @@
<?php
/*
-
/ \
/ \
/ PocketMine \
/ MP \
|\ @shoghicp /|
|. \ / .|
| .. \ / .. |
| .. | .. |
| .. | .. |
\ | /
\ | /
\ | /
\ | /
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
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
*/
class NormalGenerator{
private $config, $spawn, $structure;
public function __construct($seed){
$this->config = array(
"seed" => (int) $seed,
);
}
public function set($name, $value){
$this->config[$name] = $value;
}
public function init(){
$this->spawn = array(128, 128, 128);
}
public function getSpawn(){
return $this->spawn;
}
public function getColumn($x, $z){
$x = (int) $x;
$z = (int) $z;
$column = $this->structure;
if(floor(sqrt(pow($x - $this->spawn[0], 2) + pow($z - $this->spawn[2], 2))) <= $this->config["spawn-radius"]){
$column[0]{strlen($column[0])-1} = chr($this->config["spawn-surface"]);
}
if(($x % 8) === 0 and ($z % 8) === 0 and $this->config["torches"] == "1"){
$column[0] .= chr(50);
}
$column[0] .= str_repeat(chr(0), 128 - strlen($column[0]));
$column[1] .= str_repeat(chr(0), 64 - strlen($column[1]));
$column[2] .= str_repeat(chr(0), 64 - strlen($column[2]));
$column[3] .= str_repeat(chr(0), 64 - strlen($column[3]));
return $column;
}
}

View File

@ -29,8 +29,8 @@ the Free Software Foundation, either version 3 of the License, or
class Packet{
private $struct, $sock;
protected $pid, $packet;
public $data, $raw, $protocol;
public $data, $raw;
function __construct($pid, $struct, $data = ""){
$this->pid = $pid;
$this->offset = 1;
@ -42,7 +42,7 @@ class Packet{
$this->struct = $struct;
$this->sock = $sock;
}
public function create($raw = false){
foreach($this->struct as $field => $type){
if(!isset($this->data[$field])){
@ -75,7 +75,7 @@ class Packet{
case 0x40:
$reply = new CustomPacketHandler($this->data[$field]["id"], "", $this->data[$field], true);
$this->addRaw(Utils::writeShort((strlen($reply->raw) + 1) << 3));
$this->addRaw(Utils::writeTriad($this->data[$field]["count"]));
$this->addRaw(Utils::writeTriad(strrev($this->data[$field]["count"])));
$this->addRaw(chr($this->data[$field]["id"]));
$this->addRaw($reply->raw);
break;
@ -83,7 +83,7 @@ class Packet{
$reply = new CustomPacketHandler($this->data[$field]["id"], "", $this->data[$field], true);
$this->addRaw(Utils::writeShort((strlen($reply->raw) + 1) << 3));
$this->addRaw(chr($this->data[$field]["id"]));
$this->addRaw($reply->raw);
$this->addRaw($reply->raw);
break;
}
break;
@ -136,10 +136,10 @@ class Packet{
default:
$this->addRaw(Utils::writeByte($this->data[$field]));
break;
}
}
}
}
private function get($len = true){
if($len === true){
$data = substr($this->raw, $this->offset);
@ -150,12 +150,12 @@ class Packet{
$this->offset += $len;
return $data;
}
protected function addRaw($str){
$this->raw .= $str;
return $str;
}
public function parse(){
$continue = true;
foreach($this->struct as $field => $type){
@ -205,7 +205,7 @@ class Packet{
break;
case "byte":
$this->data[] = Utils::readByte($this->get(1));
break;
break;
case "ubyte":
$this->data[] = ord($this->get(1));
break;
@ -231,8 +231,8 @@ class Packet{
}
}
}
}

View File

@ -52,7 +52,7 @@ class Player{
$this->auth = false;
$this->counter = array(0, 0, 0);
}
public function onTick($time, $event){
if($event !== "server.tick"){
return;
@ -80,7 +80,7 @@ class Player{
}
}
}
public function save(){
if(is_object($this->entity)){
$this->data["spawn"] = array(
@ -90,7 +90,7 @@ class Player{
);
}
}
public function close($reason = "", $msg = true){
$reason = $reason == "" ? "server stop":$reason;
$this->save();
@ -105,14 +105,20 @@ class Player{
$this->connected = false;
if($msg === true){
$this->server->trigger("server.chat", $this->username." left the game");
$this->server->api->dhandle("server.chat", $this->username." left the game");
}
console("[INFO] Session with ".$this->ip.":".$this->port." Client ID ".$this->clientID." closed due to ".$reason);
$this->server->api->player->remove($this->CID);
}
public function eventHandler($data, $event){
public function eventHandler($data, $event){
switch($event){
case "player.item.pick":
if($data["eid"] === $this->eid){
$data["eid"] = 0;
}
$this->dataPacket(MC_TAKE_ITEM_ENTITY, $data);
break;
case "player.equipment.change":
if($data["eid"] === $this->eid){
break;
@ -123,25 +129,24 @@ class Player{
$this->dataPacket(MC_UPDATE_BLOCK, $data);
break;
case "entity.move":
if($data === $this->eid){
if($data->eid === $this->eid){
break;
}
$entity = $this->server->entities[$data];
$this->dataPacket(MC_MOVE_ENTITY_POSROT, array(
"eid" => $data,
"x" => $entity->x,
"y" => $entity->y,
"z" => $entity->z,
"yaw" => $entity->yaw,
"pitch" => $entity->pitch,
"eid" => $data->eid,
"x" => $data->x,
"y" => $data->y,
"z" => $data->z,
"yaw" => $data->yaw,
"pitch" => $data->pitch,
));
break;
case "entity.remove":
if($data === $this->eid){
if($data->eid === $this->eid){
break;
}
$this->dataPacket(MC_ENTITY_REMOVE, array(
"eid" => $data,
$this->dataPacket(MC_REMOVE_ENTITY, array(
"eid" => $data->eid,
));
break;
case "server.time.change":
@ -165,7 +170,7 @@ class Player{
break;
}
}
public function handle($pid, $data){
if($this->connected === true){
$this->timeout = microtime(true) + 25;
@ -205,11 +210,23 @@ class Player{
$data[3],
0,
));
break;
break;
case 0x80:
case 0x81:
case 0x82:
case 0x83:
case 0x84:
case 0x85:
case 0x86:
case 0x87:
case 0x88:
case 0x89:
case 0x8a:
case 0x8b:
case 0x8c:
case 0x8d:
case 0x8e:
case 0x8f:
if(isset($data[0])){
$diff = $data[0] - $this->counter[1];
if($diff > 1){ //Packet recovery
@ -223,6 +240,13 @@ class Player{
$this->send(0xc0, array(1, true, $data[0]));
}
switch($data["id"]){
case MC_KEEP_ALIVE:
break;
case 0x03:
break;
case MC_DISCONNECT:
$this->connected = false;
$this->close("client disconnect");
@ -235,13 +259,13 @@ class Player{
));
break;
case MC_CLIENT_HANDSHAKE:
break;
case MC_LOGIN:
$this->username = str_replace("/", "", $data["username"]);
$this->username = str_replace(array("\x00", "/", " ", "\r", "\n"), array("", "-", "_", "", ""), $data["username"]);
if($this->username == ""){
$this->close("bad username", false);
break;
break;
}
$o = $this->server->api->player->getOffline($this->username);
if($this->server->whitelist !== false and (!in_array($this->username, $this->server->whitelist)/* or ($o["lastID"] != 0 and $o["lastID"] != $this->clientID)*/)){
@ -275,38 +299,45 @@ class Player{
));
break;
case MC_READY:
if($this->spawned !== false){
break;
}
$this->spawned = true;
$this->entity = $this->server->api->entity->add(ENTITY_PLAYER, 0, array("player" => $this));
$this->eid = $this->entity->eid;
$this->server->query("UPDATE players SET EID = ".$this->eid." WHERE clientID = ".$this->clientID.";");
$this->entity->setName($this->username);
$this->entity->data["clientID"] = $this->clientID;
$this->server->api->entity->spawnAll($this);
$this->server->api->entity->spawnToAll($this->eid);
$this->evid[] = $this->server->event("server.time.change", array($this, "eventHandler"));
$this->evid[] = $this->server->event("server.chat", array($this, "eventHandler"));
$this->evid[] = $this->server->event("entity.remove", array($this, "eventHandler"));
$this->evid[] = $this->server->event("entity.move", array($this, "eventHandler"));
$this->evid[] = $this->server->event("entity.animate", array($this, "eventHandler"));
$this->evid[] = $this->server->event("player.equipment.change", array($this, "eventHandler"));
$this->evid[] = $this->server->event("world.block.change", array($this, "eventHandler"));
console("[DEBUG] Player with EID ".$this->eid." \"".$this->username."\" spawned!", true, true, 2);
$this->eventHandler($this->server->motd, "server.chat");
if($this->MTU <= 548){
$this->eventHandler("Your connection is bad, you may experience lag and slow map loading.", "server.chat");
switch($data["status"]){
case 1:
if($this->spawned !== false){
break;
}
$this->spawned = true;
$this->entity = $this->server->api->entity->add(ENTITY_PLAYER, 0, array("player" => $this));
$this->eid = $this->entity->eid;
$this->server->query("UPDATE players SET EID = ".$this->eid." WHERE clientID = ".$this->clientID.";");
$this->entity->setName($this->username);
$this->entity->data["clientID"] = $this->clientID;
$this->server->api->entity->spawnAll($this);
$this->server->api->entity->spawnToAll($this->eid);
$this->evid[] = $this->server->event("server.time.change", array($this, "eventHandler"));
$this->evid[] = $this->server->event("server.chat", array($this, "eventHandler"));
$this->evid[] = $this->server->event("entity.remove", array($this, "eventHandler"));
$this->evid[] = $this->server->event("entity.move", array($this, "eventHandler"));
$this->evid[] = $this->server->event("entity.animate", array($this, "eventHandler"));
$this->evid[] = $this->server->event("player.equipment.change", array($this, "eventHandler"));
$this->evid[] = $this->server->event("player.item.pick", array($this, "eventHandler"));
$this->evid[] = $this->server->event("world.block.change", array($this, "eventHandler"));
console("[DEBUG] Player with EID ".$this->eid." \"".$this->username."\" spawned!", true, true, 2);
$this->eventHandler($this->server->motd, "server.chat");
if($this->MTU <= 548){
$this->eventHandler("Your connection is bad, you may experience lag and slow map loading.", "server.chat");
}
break;
case 2://Chunk loaded?
break;
}
break;
case MC_MOVE_PLAYER:
if(is_object($this->entity)){
$this->entity->setPosition($data["x"], $data["y"], $data["z"], $data["yaw"], $data["pitch"]);
$this->server->trigger("entity.move", $this->eid);
$this->server->api->dhandle("entity.move", $this->entity);
}
break;
case MC_PLAYER_EQUIPMENT:
case MC_PLAYER_EQUIPMENT:
$data["eid"] = $this->eid;
if($this->server->handle("player.equipment.change", $data) !== false){
$this->equipment[0] = $data["block"];
@ -322,7 +353,7 @@ class Player{
$this->dataPacket(MC_CHUNK_DATA, array(
"x" => '.$data["x"].',
"z" => '.$data["z"].',
"data" => $d,
"data" => $d,
), true);
}
');
@ -330,47 +361,61 @@ class Player{
break;
case MC_USE_ITEM:
$data["eid"] = $this->eid;
if(Utils::distance($this->entity->position, $data) > 10){
break;
}
$this->server->handle("player.block.action", $data);
break;
case MC_PLACE_BLOCK:
break;
case MC_REMOVE_BLOCK:
$data["eid"] = $this->eid;
if(Utils::distance($this->entity->position, $data) > 8){
break;
}
$this->server->handle("player.block.break", $data);
break;
case MC_INTERACT:
if(isset($this->server->entities[$data["target"]]) and Utils::distance($this->entity->position, $this->server->entities[$data["target"]]->position) <= 8){
console("[DEBUG] EID ".$this->eid." attacked EID ".$data["target"], true, true, 2);
if($this->server->gamemode !== 1 and $this->server->difficulty > 0){
if($this->server->gamemode !== 1 and $this->server->difficulty > 0){
$this->server->api->entity->harm($data["target"], $this->server->difficulty, $this->eid);
}
}
break;
case MC_ANIMATE:
$this->server->trigger("entity.animate", array("eid" => $this->eid, "action" => $data["action"]));
$this->server->api->dhandle("entity.animate", array("eid" => $this->eid, "action" => $data["action"]));
break;
case MC_RESPAWN:
$this->entity->setHealth(20, "respawn");
$this->entity->setPosition($data["x"], $data["y"], $data["z"], 0, 0);
break;
case MC_SET_HEALTH:
if($this->server->gamemode === 1){
break;
}
$this->entity->setHealth($data["health"], "client");
break;
case MC_DROP_ITEM:
$this->server->api->block->drop($this->entity->x, $this->entity->y, $this->entity->z, $data["block"], $data["meta"], $data["stack"]);
break;
default:
console("[DEBUG] Unhandled 0x".dechex($data["id"])." Data Packet for Client ID ".$this->clientID.": ".print_r($data, true), true, true, 2);
break;
}
break;
}
}
}
public function send($pid, $data = array(), $raw = false){
if($this->connected === true){
$this->server->send($pid, $data, $raw, $this->ip, $this->port);
}
}
public function actionQueue($code){
$this->queue[] = array(1, $code);
}
public function dataPacket($id, $data = array(), $queue = false, $count = false){
if($queue === true){
$this->queue[] = array(0, $id, $data, $count);

View File

@ -26,11 +26,14 @@ the Free Software Foundation, either version 3 of the License, or
*/
class PocketMinecraftServer extends stdClass{
var $invisible, $tickMeasure, $preparedSQL, $seed, $protocol, $gamemode, $name, $maxClients, $clients, $eidCnt, $custom, $description, $motd, $timePerSecond, $responses, $spawn, $entities, $mapDir, $mapName, $map, $level, $tileEntities;
var $invisible, $tickMeasure, $preparedSQL, $seed, $gamemode, $name, $maxClients, $clients, $eidCnt, $custom, $description, $motd, $timePerSecond, $responses, $spawn, $entities, $mapDir, $mapName, $map, $level, $tileEntities;
private $database, $interface, $evCnt, $handCnt, $events, $handlers, $version, $serverType, $lastTick;
function __construct($name, $gamemode = 1, $seed = false, $protocol = CURRENT_PROTOCOL, $port = 19132, $serverID = false, $version = CURRENT_VERSION){
function __construct($name, $gamemode = 1, $seed = false, $port = 19132, $serverID = false){
$this->port = (int) $port; //19132 - 19135
console("[INFO] PocketMine-MP ".MAJOR_VERSION." by @shoghicp, LGPL License", true, true, 0);
$vNumber = new VersionString();
$vNumber = $vNumber->getNumber();
console("[INFO] PocketMine-MP ".MAJOR_VERSION." #".$vNumber." by @shoghicp, LGPL License", true, true, 0);
console("[DEBUG] Target Minecraft PE: ".CURRENT_MINECRAFT_VERSION, true, true, 2);
console("[INFO] Starting Minecraft PE Server at *:".$this->port);
if($this->port < 19132 or $this->port > 19135){
console("[WARNING] You've selected a not-standard port. Normal port range is from 19132 to 19135 included");
@ -38,7 +41,6 @@ class PocketMinecraftServer extends stdClass{
console("[INFO] Loading database...");
$this->startDatabase();
$this->gamemode = (int) $gamemode;
$this->version = (int) $version;
$this->name = $name;
$this->mapDir = false;
$this->mapName = false;
@ -64,45 +66,44 @@ class PocketMinecraftServer extends stdClass{
$this->serverID = $serverID === false ? Utils::readLong(Utils::getRandomBytes(8)):$serverID;
$this->seed = $seed === false ? Utils::readInt(Utils::getRandomBytes(4)):$seed;
$this->clients = array();
$this->protocol = (int) $protocol;
$this->spawn = array("x" => 128.5,"y" => 100,"z" => 128.5);
$this->time = 0;
$this->timePerSecond = 10;
$this->tickMeasure = array_fill(0, 40, 0);
$this->setType("normal");
$this->interface = new MinecraftInterface("255.255.255.255", $this->protocol, $this->port, true, false);
$this->interface = new MinecraftInterface("255.255.255.255", $this->port, true, false);
$this->reloadConfig();
console("[INFO] Server Name: ".$this->name);
console("[INFO] Server GUID: ".$this->serverID);
console("[INFO] Protocol Version: ".$this->protocol);
console("[INFO] Protocol Version: ".CURRENT_PROTOCOL);
console("[INFO] Max Clients: ".$this->maxClients);
$this->stop = false;
}
public function getTPS(){
$v = array_values($this->tickMeasure);
$tps = 40 / ($v[39] - $v[0]);
return round($tps, 4);
}
public function loadEvents(){
public function loadEvents(){
$this->event("server.chat", array($this, "eventHandler"));
$this->event("player.new", array($this, "eventHandler"));
$this->action(500000, '$this->time += (int) ($this->timePerSecond / 2);$this->trigger("server.time.change", $this->time);');
$this->action(5000000, 'if($this->difficulty < 2){$this->trigger("server.regeneration", 1);}');
$this->action(500000, '$this->time += (int) ($this->timePerSecond / 2);$this->api->dhandle("server.time.change", $this->time);');
$this->action(5000000, 'if($this->difficulty < 2){$this->api->dhandle("server.regeneration", 1);}');
$this->action(1000000 * 60, '$this->reloadConfig();');
$this->action(1000000 * 60 * 10, '$this->custom = array();');
if($this->api !== false){
$this->action(1000000 * 80, '$this->chat(false, count($this->clients)."/".$this->maxClients." online: ".implode(", ",$this->api->player->online()));');
$this->action(1000000 * 80, '$this->chat(false, "Online (".count($this->clients)."): ".implode(", ",$this->api->player->online()));');
}
$this->action(1000000 * 75, '$this->debugInfo(true);');
$this->action(1000000 * 120, '$this->debugInfo(true);');
}
public function startDatabase(){
$this->preparedSQL = new stdClass();
$this->database = new SQLite3(":memory:");
//$this->query("PRAGMA journal_mode = OFF;");
//$this->query("PRAGMA journal_mode = OFF;");
//$this->query("PRAGMA encoding = \"UTF-8\";");
//$this->query("PRAGMA secure_delete = OFF;");
$this->query("CREATE TABLE players (clientID INTEGER PRIMARY KEY, EID NUMERIC, ip TEXT, port NUMERIC, name TEXT UNIQUE);");
@ -117,7 +118,7 @@ class PocketMinecraftServer extends stdClass{
$this->preparedSQL->selectActions = $this->database->prepare("SELECT ID,code,repeat FROM actions WHERE last <= (:time - interval);");
$this->preparedSQL->updateActions = $this->database->prepare("UPDATE actions SET last = :time WHERE last <= (:time - interval);");
}
public function query($sql, $fetch = false){
console("[INTERNAL] [SQL] ".$sql, true, true, 3);
$result = $this->database->query($sql) or console("[ERROR] [SQL Error] ".$this->database->lastErrorMsg().". Query: ".$sql, true, true, 0);
@ -126,14 +127,14 @@ class PocketMinecraftServer extends stdClass{
}
return $result;
}
public function reloadConfig(){
if($this->whitelist === true or is_array($this->whitelist)){
$this->whitelist = explode("\n", str_replace(array("\t","\r"), "", file_get_contents(FILE_PATH."white-list.txt")));
}
$this->bannedIPs = explode("\n", str_replace(array(" ","\t","\r"), "", file_get_contents(FILE_PATH."banned-ips.txt")));
}
public function debugInfo($console = false){
$info = array();
$info["tps"] = $this->getTPS();
@ -151,26 +152,26 @@ class PocketMinecraftServer extends stdClass{
}
return $info;
}
public function close($reason = "stop"){
if($this->stop !== true){
$this->chat(false, "Stopping server...");
$this->save();
$this->save(true);
$this->stop = true;
$this->trigger("server.close");
$this->trigger("server.close", $reason);
$this->interface->close();
}
}
public function chat($owner, $text, $target = true){
$message = "";
if($owner !== false){
$message = "<".$owner."> ";
}
$message .= $text;
$this->trigger("server.chat", $message);
$this->handle("server.chat", $message);
}
public function setType($type = "normal"){
switch($type){
case "normal":
@ -180,9 +181,9 @@ class PocketMinecraftServer extends stdClass{
$this->serverType = "MCCPP;MINECON;";
break;
}
}
public function addHandler($event, $callable, $priority = 5){
if(!is_callable($callable)){
return false;
@ -193,14 +194,14 @@ class PocketMinecraftServer extends stdClass{
console("[INTERNAL] New handler ".(is_array($callable) ? get_class($callable[0])."::".$callable[1]:$callable)." to special event ".$event." (ID ".$this->handCnt.")", true, true, 3);
return $this->handCnt++;
}
public function handle($event, &$data){
$this->preparedSQL->selectHandlers->reset();
$this->preparedSQL->selectHandlers->clear();
$this->preparedSQL->selectHandlers->bindValue(":name", $event, SQLITE3_TEXT);
$handlers = $this->preparedSQL->selectHandlers->execute();
$result = true;
if($handlers !== false and $handlers !== true){
if($handlers !== false and $handlers !== true){
while(false !== ($hn = $handlers->fetchArray(SQLITE3_ASSOC)) and $result !== false){
$handler = $this->handlers[(int) $hn["ID"]];
if(is_array($handler)){
@ -209,7 +210,7 @@ class PocketMinecraftServer extends stdClass{
}else{
$result = $handler($data, $event);
}
}
}
}
$handlers->finalize();
if($result !== false){
@ -217,7 +218,7 @@ class PocketMinecraftServer extends stdClass{
}
return $result;
}
public function eventHandler($data, $event){
switch($event){
case "player.new":
@ -228,14 +229,14 @@ class PocketMinecraftServer extends stdClass{
break;
}
}
public function loadMap(){
if($this->mapName !== false and trim($this->mapName) !== ""){
if($this->mapName !== false and trim($this->mapName) !== ""){
$this->level = unserialize(file_get_contents($this->mapDir."level.dat"));
console("[INFO] Map: ".$this->level["LevelName"]);
$this->time = (int) $this->level["Time"];
$this->seed = (int) $this->level["RandomSeed"];
if(isset($this->level["SpawnX"])){
if(isset($this->level["SpawnX"])){
$this->spawn = array("x" => $this->level["SpawnX"], "y" => $this->level["SpawnY"], "z" => $this->level["SpawnZ"]);
}else{
$this->level["SpawnX"] = $this->spawn["x"];
@ -263,7 +264,7 @@ class PocketMinecraftServer extends stdClass{
console("[INFO] Gamemode: ".($this->gamemode === 0 ? "survival":"creative"));
}
}
public function loadEntities(){
if($this->map !== false){
console("[INFO] Loading entities...");
@ -287,27 +288,27 @@ class PocketMinecraftServer extends stdClass{
$e = $this->api->entity->add(ENTITY_MOB, $entity["id"]);
$e->setPosition($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2], $entity["Rotation"][0], $entity["Rotation"][1]);
$e->setHealth($entity["Health"]);
}
}
}
console("[DEBUG] Loaded ".count($this->entities)." Entities", true, true, 2);
$this->action(1000000 * 60 * 15, '$this->chat(false, "Forcing save...");$this->save();$this->chat(false, "Done");');
}
}
}
public function save(){
if($this->mapName !== false){
public function save($final = false){
if($this->mapName !== false){
file_put_contents($this->mapDir."level.dat", serialize($this->level));
$this->map->saveMap();
$this->map->saveMap($final);
console("[INFO] Saving entities...");
foreach($this->entities as $entity){
}
}
}
public function start(){
public function init(){
if($this->mapName !== false and $this->map === false){
$this->loadMap();
$this->loadEntities();
@ -321,21 +322,21 @@ class PocketMinecraftServer extends stdClass{
console("[INFO] Server started!");
$this->process();
}
public function tick(){
$time = microtime(true);
if($this->lastTick <= ($time - 0.05)){
array_shift($this->tickMeasure);
$this->tickMeasure[] = $this->lastTick = $time;
$this->tickMeasure[] = $this->lastTick = $time;
$this->tickerFunction($time);
$this->trigger("server.tick", $time);
}
}
public function clientID($ip, $port){
return md5($pi . $port, true);
return md5($ip . $port, true);
}
public function packetHandler($packet){
$data =& $packet["data"];
$CID = $this->clientID($packet["ip"], $packet["port"]);
@ -350,7 +351,7 @@ class PocketMinecraftServer extends stdClass{
$this->serverID,
MAGIC,
$this->serverType,
), false, $packet["ip"], $packet["port"]);
), false, $packet["ip"], $packet["port"]);
break;
}
if(in_array($packet["ip"], $this->bannedIPs)){
@ -397,9 +398,9 @@ class PocketMinecraftServer extends stdClass{
}
$version = $data[1];
$size = strlen($data[2]);
if($version !== $this->protocol){
if($version !== CURRENT_PROTOCOL){
$this->send(0x1a, array(
$this->protocol,
CURRENT_PROTOCOL,
MAGIC,
$this->serverID,
), false, $packet["ip"], $packet["port"]);
@ -440,11 +441,11 @@ class PocketMinecraftServer extends stdClass{
}
}
}
public function send($pid, $data = array(), $raw = false, $dest = false, $port = false){
$this->interface->writePacket($pid, $data, $raw, $dest, $port);
}
public function process(){
while($this->stop === false){
$packet = @$this->interface->readPacket();
@ -452,10 +453,10 @@ class PocketMinecraftServer extends stdClass{
$this->packetHandler($packet);
}else{
usleep(1);
}
}
}
}
public function trigger($event, $data = ""){
$this->preparedSQL->selectEvents->reset();
$this->preparedSQL->selectEvents->clear();
@ -485,7 +486,7 @@ class PocketMinecraftServer extends stdClass{
}
return false;
}
public function schedule($ticks, $callback, $data = array(), $repeat = false, $eventName = "server.schedule"){
if(!is_callable($callback)){
return false;
@ -495,10 +496,10 @@ class PocketMinecraftServer extends stdClass{
$add = ' unset($this->schedule['.$this->scheduleCnt.']);';
}
$this->schedule[$this->scheduleCnt] = array($callback, $data, $eventName);
$this->action(50000 * $ticks, '$schedule = $this->schedule['.$this->scheduleCnt.'];'.$add.' call_user_func($schedule[0], $schedule[1], $schedule[2]);', (bool) $repeat);
$this->action(50000 * $ticks, '$schedule = $this->schedule['.$this->scheduleCnt.'];'.$add.'if(!is_callable($schedule[0])){unset($this->schedule['.$this->scheduleCnt.']);return;} call_user_func($schedule[0], $schedule[1], $schedule[2]);', (bool) $repeat);
return $this->scheduleCnt++;
}
public function action($microseconds, $code, $repeat = true){
$this->query("INSERT INTO actions (interval, last, code, repeat) VALUES(".($microseconds / 1000000).", ".microtime(true).", '".base64_encode($code)."', ".($repeat === true ? 1:0).");");
console("[INTERNAL] Attached to action ".$microseconds, true, true, 3);
@ -510,7 +511,7 @@ class PocketMinecraftServer extends stdClass{
$this->preparedSQL->selectActions->clear();
$this->preparedSQL->selectActions->bindValue(":time", $time, SQLITE3_FLOAT);
$actions = $this->preparedSQL->selectActions->execute();
if($actions === false or $actions === true){
return;
}
@ -525,8 +526,8 @@ class PocketMinecraftServer extends stdClass{
$this->preparedSQL->updateActions->clear();
$this->preparedSQL->updateActions->bindValue(":time", $time, SQLITE3_FLOAT);
$this->preparedSQL->updateActions->execute();
}
}
public function event($event, $func){
if(!is_callable($func)){
return false;
@ -536,11 +537,11 @@ class PocketMinecraftServer extends stdClass{
console("[INTERNAL] Attached ".(is_array($func) ? get_class($func[0])."::".$func[1]:$func)." to event ".$event." (ID ".$this->evCnt.")", true, true, 3);
return $this->evCnt++;
}
public function deleteEvent($id){
$id = (int) $id;
unset($this->events[$id]);
$this->query("DELETE FROM events WHERE ID = ".$id.";");
}
}
}

View File

@ -42,7 +42,7 @@ class SerializedPacketHandler{
}
return $data;
}
public function __construct($pid, $raw = "", $data = array(), $create = false){
$this->raw = $raw;
$this->data = $data;
@ -54,15 +54,15 @@ class SerializedPacketHandler{
case 0x00:
if($this->c === false){
$this->data["packets"] = array();
$i = 0;
$i = 0;
while($this->offset < strlen($this->raw)){
if($i > 0){
$pid = ord($this->get(1));
}
$len = ceil(Utils::readShort($this->get(2), false) / 8); //Utils::readShort($this->get(2), false) >> 3;
if($pid !== 0x00){
$c = Utils::readTriad($this->get(3));
$c = Utils::readTriad(strrev($this->get(3)));
}
if($pid === 0x60 and $i === 0){
$this->data["unknown1"] = $this->get(4);

View File

@ -88,7 +88,7 @@ class Spyc {
/**
* Setting this to true will force YAMLDump to enclose any string value in
* quotes. False by default.
*
*
* @var bool
*/
public $setting_dump_force_quotes = false;
@ -168,7 +168,7 @@ class Spyc {
/**
* Load a string of YAML into a PHP array statically
*
* The load method, when supplied with a YAML string, will do its best
* The load method, when supplied with a YAML string, will do its best
* to convert YAML in a string into a PHP array. Pretty simple.
*
* Note: use this function if you don't want files from the file system
@ -257,7 +257,7 @@ class Spyc {
// Start at the base of the array and move through it.
if ($array) {
$array = (array)$array;
$array = (array)$array;
$previous_key = -1;
foreach ($array as $key => $value) {
if (!isset($first_key)) $first_key = $key;
@ -346,7 +346,7 @@ class Spyc {
if (is_bool($value)) {
$value = ($value) ? "true" : "false";
}
if ($value === null) $value = 'null';
if ($value === "'" . self::REMPTY . "'") $value = null;
@ -438,7 +438,7 @@ class Spyc {
$cnt = count($Source);
for ($i = 0; $i < $cnt; $i++) {
$line = $Source[$i];
$this->indent = strlen($line) - strlen(ltrim($line));
$tempPath = $this->getParentPathByIndent($this->indent);
$line = self::stripIndent($line, $this->indent);
@ -530,9 +530,9 @@ class Spyc {
return $this->returnArrayElement($line);
if ($this->isPlainArray($line))
return $this->returnPlainArray($line);
return $this->returnPlainArray($line);
return $this->returnKeyValuePair($line);
}
@ -558,7 +558,7 @@ class Spyc {
if ($is_quoted)
return strtr(substr ($value, 1, -1), array ('\\"' => '"', '\'\'' => '\'', '\\\'' => '\''));
if (strpos($value, ' #') !== false && !$is_quoted)
$value = preg_replace('/\s+#(.+)$/','',$value);
@ -585,7 +585,7 @@ class Spyc {
$value = $this->_toType($value);
return array($key => $value);
}
if ($first_character == '{' && $last_character == '}') {
$innerValue = trim(substr ($value, 1, -1));
if ($innerValue === '') return array();
@ -632,7 +632,7 @@ class Spyc {
$value = (float)$value;
return $value;
}
return $value;
}
@ -735,7 +735,7 @@ class Spyc {
if ($finished) break;
$i++;
if ($i > 10)
if ($i > 10)
break; // Prevent infinite loops.
}
@ -763,7 +763,7 @@ class Spyc {
private function addArrayInline ($array, $indent) {
$CommonGroupPath = $this->path;
if (empty ($array)) return false;
foreach ($array as $k => $_) {
$this->addArray(array($k => $_), $indent);
$this->path = $CommonGroupPath;
@ -777,7 +777,7 @@ class Spyc {
if (count ($incoming_data) > 1)
return $this->addArrayInline ($incoming_data, $incoming_indent);
$key = key ($incoming_data);
$value = isset($incoming_data[$key]) ? $incoming_data[$key] : null;
if ($key === '__!YAMLZero') $key = '0';
@ -793,7 +793,7 @@ class Spyc {
}
$history = array();
// Unfolding inner array tree.
$history[] = $_arr = $this->result;
@ -940,7 +940,7 @@ class Spyc {
if ($line[0] != '-') return false;
if (strlen ($line) > 3)
if (substr($line,0,3) == '---') return false;
return true;
}
@ -985,14 +985,14 @@ class Spyc {
private function startsMappedValue ($line) {
return (substr ($line, -1, 1) == ':');
}
private function isPlainArray ($line) {
return ($line[0] == '[' && substr ($line, -1, 1) == ']');
}
private function returnPlainArray ($line) {
return $this->_toType($line);
}
return $this->_toType($line);
}
private function returnKeyValuePair ($line) {
$array = array();
@ -1032,7 +1032,7 @@ class Spyc {
}
private function nodeContainsGroup ($line) {
private function nodeContainsGroup ($line) {
$symbolsForReference = 'A-z0-9_\-';
if (strpos($line, '&') === false && strpos($line, '*') === false) return false; // Please die fast ;-)
if ($line[0] == '&' && preg_match('/^(&['.$symbolsForReference.']+)/', $line, $matches)) return $matches[1];

View File

@ -38,14 +38,14 @@ class SuperflatGenerator{
);
$this->parsePreset();
}
public function set($name, $value){
$this->config[$name] = $value;
if($name === "preset"){
$this->parsePreset();
}
}
private function parsePreset(){
$this->structure = array(
0 => "",
@ -53,7 +53,7 @@ class SuperflatGenerator{
2 => str_repeat("\x00", 64),
3 => str_repeat("\x00", 64),
);
$preset = explode(";", trim($this->config["preset"]));
$preset = explode(";", trim($this->config["preset"]));
foreach($preset as $i => $data){
$num = 1;
if(preg_match('#([a-zA-Z\-_]*)\((.*)\)#', $data, $matches) > 0){ //Property
@ -78,15 +78,15 @@ class SuperflatGenerator{
$this->structure[2] = substr($this->structure[2], 0, 64);
$this->structure[3] = substr($this->structure[3], 0, 64);
}
public function init(){
$this->spawn = array(128, strlen($this->structure[0]), 128);
}
public function getSpawn(){
return $this->spawn;
}
public function getColumn($x, $z){
$x = (int) $x;
$z = (int) $z;

View File

@ -25,11 +25,12 @@ the Free Software Foundation, either version 3 of the License, or
*/
$fp = fopen(dirname(__FILE__)."/../../logs/console.in","wb");
while(true){
$l = fgets(STDIN);
fwrite($fp, $l);
if(strtolower(trim($l)) === "stop" and isset($argv[1]) and trim($argv[1]) == "1"){
die();
class TileEntity extends stdClass{
private $server;
function __construct(PocketMinecraftServer $server){
}
}
}
?>

View File

@ -42,7 +42,7 @@ class UDPSocket{
$this->unblock();
}else{
$this->sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($this->sock, SOL_SOCKET, SO_BROADCAST, 1);
socket_set_option($this->sock, SOL_SOCKET, SO_BROADCAST, 1);
if($listen !== true){
$this->connected = true;
$this->buffer = array();
@ -57,7 +57,7 @@ class UDPSocket{
}
}
}
function listenSocket(){
$sock = @socket_accept($this->sock);
if($sock !== false){
@ -67,7 +67,7 @@ class UDPSocket{
}
return false;
}
public function close($error = 125){
$this->connected = false;
if($error === false){
@ -77,7 +77,7 @@ class UDPSocket{
}
return @socket_close($this->sock);
}
public function block(){
socket_set_block($this->sock);
}
@ -85,18 +85,18 @@ class UDPSocket{
public function unblock(){
socket_set_nonblock($this->sock);
}
public function read(){
$source = false;
$port = 1;
$len = @socket_recvfrom($this->sock, $buf, 65536, 0, $source, $port);
return array($buf, $source, $port, $len);
}
public function write($data, $dest = false, $port = false){
return @socket_sendto($this->sock, $data, strlen($data), 0, ($dest === false ? $this->server:$dest), ($port === false ? $this->port:$port));
}
}
?>

View File

@ -36,31 +36,33 @@ define("LITTLE_ENDIAN", 0x01);
define("ENDIANNESS", (pack("d", 1) === "\77\360\0\0\0\0\0\0" ? BIG_ENDIAN:LITTLE_ENDIAN));
abstract class Utils{
public static function getOS(){
$uname = strtoupper(php_uname("s"));
if(strpos($uname, "WIN") !== false){
return "win";
}elseif(strpos($uname, "DARWIN") !== false){
return "mac";
}else{
return "linux";
}
}
public static function hexdump($bin){
$output = "";
$bin = str_split($bin, 16);
foreach($bin as $counter => $line){
$hex = chunk_split(chunk_split(str_pad(bin2hex($line), 32, " ", STR_PAD_RIGHT), 2, " "), 24, " ");
$ascii = preg_replace('#([^\x20-\x7E])#', ".", $line);
$output .= str_pad(dechex($counter << 4), 4, "0", STR_PAD_LEFT). " " . $hex . " " . $ascii . PHP_EOL;
$output .= str_pad(dechex($counter << 4), 4, "0", STR_PAD_LEFT). " " . $hex . " " . $ascii . PHP_EOL;
}
return $output;
}
public static function printable($str){
return preg_replace('#([^\x20-\x7E])#', '.', $str);
}
public static function readTriad($str){
list(,$unpacked) = unpack("N", "\x00".$str);
return (int) $unpacked;
@ -101,18 +103,18 @@ abstract class Utils{
$m .= Utils::writeLInt($data["value"][$i]);
}
break;
}
}
$m .= "\x7f";
return $m;
return $m;
}
public static function readMetadata($value, $types = false){
$offset = 0;
$m = array();
$b = ord($value{$offset});
++$offset;
++$offset;
while($b !== 127){
$bottom = $b & 0x1F;
$type = $b >> 5;
@ -155,7 +157,7 @@ abstract class Utils{
$offset += 4;
}
break;
}
if($types === true){
$m[$bottom] = array($r, $type);
@ -165,9 +167,9 @@ abstract class Utils{
$b = ord($value{$offset});
++$offset;
}
return $m;
return $m;
}
public static function readDataArray($str, $len = 10, &$offset = null){
$data = array();
$offset = 0;
@ -179,7 +181,7 @@ abstract class Utils{
}
return $data;
}
public static function writeDataArray($data){
$raw = "";
foreach($data as $v){
@ -188,7 +190,7 @@ abstract class Utils{
}
return $raw;
}
public static function getRandomBytes($length = 16, $secure = true, $raw = true, $startEntropy = "", &$rounds = 0, &$drop = 0){
$output = b"";
$length = abs((int) $length);
@ -225,7 +227,7 @@ abstract class Utils{
(string) disk_total_space("."),
uniqid(microtime(),true),
);
shuffle($weakEntropy);
$value = hash("sha256", implode($weakEntropy), true);
foreach($weakEntropy as $k => $c){ //mixing entropy values with XOR and hash randomness extractor
@ -235,7 +237,7 @@ abstract class Utils{
$value ^= hash("sha256", $c . microtime() . $k, true);
}
unset($weakEntropy);
if($secure === true){
$strongEntropy = array(
is_array($startEntropy) ? $startEntropy[($rounds + $drop) % count($startEntropy)]:$startEntropy, //Get a random index of the startEntropy, or just read it
@ -273,15 +275,15 @@ abstract class Utils{
}
return $raw === false ? bin2hex($output):$output;
}
public static function round($number){
return round($number, 0, PHP_ROUND_HALF_DOWN);
}
public static function distance($pos1, $pos2){
return sqrt(pow($pos1["x"] - $pos2["x"], 2) + pow($pos1["y"] - $pos2["y"], 2) + pow($pos1["z"] - $pos2["z"], 2));
}
public static function angle3D($pos1, $pos2){
$X = $pos1["x"] - $pos2["x"];
$Z = $pos1["z"] - $pos2["z"];
@ -291,17 +293,17 @@ abstract class Utils{
$vAngle = rad2deg(-atan2($Y, $dXZ));
return array("yaw" => $hAngle, "pitch" => $vAngle);
}
public static function sha1($input){
$number = new Math_BigInteger(sha1($input, true), -256);
$zero = new Math_BigInteger(0);
return ($zero->compare($number) <= 0 ? "":"-") . ltrim($number->toHex(), "0");
}
public static function microtime(){
return microtime(true);
}
public static function curl_get($page){
$ch = curl_init($page);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("User-Agent: Minecraft PHP Client 2"));
@ -315,7 +317,7 @@ abstract class Utils{
curl_close($ch);
return $ret;
}
public static function curl_post($page, $args, $timeout = 10){
$ch = curl_init($page);
curl_setopt($ch, CURLOPT_POST, 1);
@ -329,26 +331,26 @@ abstract class Utils{
curl_close($ch);
return $ret;
}
public static function strToHex($str){
return bin2hex($str);
}
public static function hexToStr($hex){
if(HEX2BIN === true){
return hex2bin($hex);
}
}
return pack("H*" , $hex);
}
public static function readBool($b){
return Utils::readByte($b, false) === 0 ? false:true;
}
public static function writeBool($b){
return Utils::writeByte($b === true ? 1:0);
}
public static function readByte($c, $signed = true){
$b = ord($c{0});
if($signed === true and ($b & 0x80) === 0x80){ //calculate Two's complement
@ -356,7 +358,7 @@ abstract class Utils{
}
return $b;
}
public static function writeByte($c){
if($c > 0xff){
return false;
@ -374,14 +376,14 @@ abstract class Utils{
}
return $unpacked;
}
public static function writeShort($value){
if($value < 0){
$value += 0x10000;
$value += 0x10000;
}
return pack("n", $value);
}
public static function readLShort($str, $signed = true){
list(,$unpacked) = unpack("v", $str);
if($unpacked > 0x7fff and $signed === true){
@ -389,10 +391,10 @@ abstract class Utils{
}
return $unpacked;
}
public static function writeLShort($value){
if($value < 0){
$value += 0x10000;
$value += 0x10000;
}
return pack("v", $value);
}
@ -404,14 +406,14 @@ abstract class Utils{
}
return (int) $unpacked;
}
public static function writeInt($value){
if($value < 0){
$value += 0x100000000;
$value += 0x100000000;
}
return pack("N", $value);
}
public static function readLInt($str){
list(,$unpacked) = unpack("V", $str);
if($unpacked >= 2147483648){
@ -419,50 +421,50 @@ abstract class Utils{
}
return (int) $unpacked;
}
public static function writeLInt($value){
if($value < 0){
$value += 0x100000000;
$value += 0x100000000;
}
return pack("V", $value);
}
public static function readFloat($str){
list(,$value) = ENDIANNESS === 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));
}
public static function readLFloat($str){
list(,$value) = ENDIANNESS === 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);
}
public static function printFloat($value){
return preg_replace("/(\.\d+?)0+$/", "$1", sprintf("%F", $value));
}
public static function readDouble($str){
list(,$value) = ENDIANNESS === 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));
}
public static function readLDouble($str){
list(,$value) = ENDIANNESS === 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);
}
@ -471,20 +473,20 @@ abstract class Utils{
$long = new Math_BigInteger($str, -256);
return $long->toString();
}
public static function writeLong($value){
$long = new Math_BigInteger($value, -10);
return str_pad($long->toBytes(true), 8, "\x00", STR_PAD_LEFT);
}
public static function readLLong($str){
$long = new Math_BigInteger(strrev($str), -256);
return $long->toString();
}
public static function writeLLong($value){
$long = new Math_BigInteger($value, -10);
return strrev(str_pad($long->toBytes(true), 8, "\x00", STR_PAD_LEFT));
}
}
}

View File

@ -25,17 +25,15 @@ the Free Software Foundation, either version 3 of the License, or
*/
//Protocol Version: 4
define("WINDOW_CHEST", 0);
define("WINDOW_WORKBENCH", 1);
define("WINDOW_FURNACE", 2);
class Window{
private $server;
public function __construct(PocketMinecraftServer $server){
define("MC_KEEP_ALIVE", 0x00);
define("MC_CLIENT_CONNECT", 0x09);
define("MC_SERVER_HANDSHAKE", 0x10);
define("MC_CLIENT_HANDSHAKE", 0x13);
define("MC_CLIENT_DISCONNECT", 0x15);
define("MC_LOGIN", 0x86);
define("MC_LOGIN_STATUS", 0x87);
define("MC_READY", 0x88);
define("MC_CHAT", 0x89);
define("MC_SET_TIME", 0x8a);
define("MC_START_GAME", 0x8b);
}
}
?>

View File

@ -34,10 +34,10 @@ ini_set("display_errors", 1);
ini_set('default_charset', 'utf-8');
define("FILE_PATH", dirname(__FILE__)."/../../");
set_include_path(get_include_path() . PATH_SEPARATOR . FILE_PATH . PATH_SEPARATOR . FILE_PATH . "/src/" . PATH_SEPARATOR . FILE_PATH . "/src/classes/");
ini_set("memory_limit", "256M");
define("CURRENT_PROTOCOL", 5);
define("CURRENT_VERSION", 1);
ini_set("memory_limit", "512M");
define("LOG", true);
define("MAGIC", "\x00\xff\xff\x00\xfe\xfe\xfe\xfe\xfd\xfd\xfd\xfd\x12\x34\x56\x78");
define("TEST_MD5", "5ca8eced50a5801619f7ae86d631a4e7");
define("MAJOR_VERSION", "Alpha_1.0.2");
define("MAJOR_VERSION", "Alpha_1.0.5");
define("CURRENT_PROTOCOL", 5);
define("CURRENT_MINECRAFT_VERSION", "v0.5.0 alpha");

View File

@ -25,7 +25,6 @@ the Free Software Foundation, either version 3 of the License, or
*/
require_once(dirname(__FILE__)."/config.php");
require_once("common/functions.php");
//set_error_handler("error_handler");
@ -35,6 +34,9 @@ $errors = 0;
if(version_compare("5.3.3", PHP_VERSION) > 0){
console("[ERROR] Use PHP >= 5.3.3", true, true, 0);
++$errors;
}elseif(version_compare("5.5.0", PHP_VERSION) <= 0){
console("[NOTICE] PocketMine-MP hasn't been tested with PHP >= 5.5", true, true, 0);
++$errors;
}
if(version_compare("5.4.0", PHP_VERSION) > 0){
@ -49,32 +51,39 @@ if(php_sapi_name() !== "cli"){
++$errors;
}
if(!extension_loaded("sockets")){
if(!extension_loaded("sockets") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "sockets." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find Socket extension", true, true, 0);
++$errors;
}
/*if(!extension_loaded("pthreads")){
if(!extension_loaded("pthreads") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "pthreads." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find pthreads extension. [https://github.com/krakjoe/pthreads]", true, true, 0);
++$errors;
}*/
}
if(!extension_loaded("curl")){
if(!extension_loaded("curl") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "curl." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find cURL extension", true, true, 0);
++$errors;
}
if(!extension_loaded("sqlite3")){
if(!extension_loaded("sqlite3") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "sqlite3." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find SQLite3 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 Zlib extension. Compressed worlds won't be loaded", true, true, 0);
define("ZLIB_EXTENSION", false);
}else{
define("ZLIB_EXTENSION", true);
}
if($errors > 0){
die();
}
require_once("classes/Async.class.php");
require_once("classes/Data.class.php");
require_once("classes/Player.class.php");
require_once("classes/Generator.class.php");
@ -83,6 +92,8 @@ require_once("classes/Utils.class.php");
require_once("classes/UDPSocket.class.php");
require_once("classes/Packet.class.php");
require_once("classes/Entity.class.php");
require_once("classes/TileEntity.class.php");
require_once("classes/Window.class.php");
require_once("classes/ChunkParser.class.php");
require_once("classes/NBT.class.php");
require_once("classes/Java.class.php");

View File

@ -26,6 +26,24 @@ the Free Software Foundation, either version 3 of the License, or
*/
function kill($pid){
switch(Utils::getOS()){
case "win":
ob_start();
passthru("%WINDIR%\\System32\\taskkill.exe /F /PID ".((int) $pid));
ob_end_clean();
break;
case "mac":
case "linux":
default:
ob_start();
passthru("kill -9 ".((int) $pid));
ob_end_clean();
}
}
function require_all($path, &$count = 0){
$dir = dir($path."/");
while(false !== ($file = $dir->read())){
@ -94,7 +112,7 @@ function arg($name, $default){
if(!isset($arguments)){
$arguments = arguments($argv);
}
if(isset($arguments["commands"][$name])){
return $arguments["commands"][$name];
}else{
@ -153,7 +171,7 @@ function console($message, $EOL = true, $log = true, $level = 1){
$message = date("H:i:s"). " ". $message;
if($log === true and (!defined("LOG") or LOG === true)){
logg($message, "console", false, $level);
}
}
echo $message;
}
}
@ -169,10 +187,10 @@ function logg($message, $name, $EOL = true, $level = 2, $close = false){
if(!isset($fpointers)){
$fpointers = array();
}
if(!isset($fpointers[$name])){
$fpointers[$name] = fopen(FILE_PATH."logs/".$name.".log", "ab");
if(!isset($fpointers[$name]) or $fpointers[$name] === false){
$fpointers[$name] = @fopen(FILE_PATH."logs/".$name.".log", "ab");
}
fwrite($fpointers[$name], $message);
@fwrite($fpointers[$name], $message);
if($close === true){
fclose($fpointers[$name]);
unset($fpointers[$name]);

View File

@ -0,0 +1,31 @@
<?php
/*
-
/ \
/ \
/ PocketMine \
/ MP \
|\ @shoghicp /|
|. \ / .|
| .. \ / .. |
| .. | .. |
| .. | .. |
\ | /
\ | /
\ | /
\ | /
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
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
*/
/*
class BlockIterator implements Iterator{
}*/

View File

@ -30,7 +30,7 @@ class Sapling{
const SPRUCE = 1;
const BIRCH = 2;
const BURN_TIME = 5;
public static function growTree(LevelAPI $level, $block, $type){
$type = $type & 0x03;
TreeObject::growTree($level, $block, $type);

110
src/misc/math/Vector2.php Normal file
View File

@ -0,0 +1,110 @@
<?php
/*
-
/ \
/ \
/ PocketMine \
/ MP \
|\ @shoghicp /|
|. \ / .|
| .. \ / .. |
| .. | .. |
| .. | .. |
\ | /
\ | /
\ | /
\ | /
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
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
*/
class Vector2{
public $x, $y;
public function __construct($x = 0, $y = 0){
if(($x instanceof Vector2) === true){
$this->__construct($x->x, $x->y);
}else{
$this->x = $x;
$this->y = $y;
}
}
public function getX(){
return $this->x;
}
public function getY(){
return $this->y;
}
public function getFloorX(){
return (int) $this->x;
}
public function getFloorY(){
return (int) $this->y;
}
public function add($x = 0, $y = 0){
if(($x instanceof Vector2) === true){
return $this->add($x->x, $x->y);
}else{
$this->x += $x;
$this->y += $y;
return new Vector3($this->x + $x, $this->y + $y);
}
}
public function subtract($x = 0, $y = 0){
if(($x instanceof Vector2) === true){
return $this->add(-$x->x, -$x->y);
}else{
return $this->add(-$x, -$y);
}
}
public function ceil(){
return new Vector2((int) ($this->x + 1), (int) ($this->y + 1));
}
public function floor(){
return new Vector2((int) $this->x, (int) $this->y);
}
public function round(){
return new Vector2(round($this->x), round($this->y));
}
public function abs(){
return new Vector2(abs($this->x), abs($this->y));
}
public function distance($x = 0, $y = 0){
if(($x instanceof Vector2) === true){
return sqrt($this->distanceSquared($x->x, $x->y));
}else{
return sqrt($this->distanceSquared($x, $y));
}
}
public function distanceSquared($x = 0, $y = 0){
if(($x instanceof Vector2) === true){
return $this->distanceSquared($x->x, $x->y);
}else{
return pow($this->x - $x, 2) + pow($this->y - $y, 2);
}
}
public function __toString(){
return "Vector2(x=".$this->x.",y=".$this->y.")";
}
}

140
src/misc/math/Vector3.php Normal file
View File

@ -0,0 +1,140 @@
<?php
/*
-
/ \
/ \
/ PocketMine \
/ MP \
|\ @shoghicp /|
|. \ / .|
| .. \ / .. |
| .. | .. |
| .. | .. |
\ | /
\ | /
\ | /
\ | /
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
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
*/
class Vector3{
public $x, $y, $z;
public function __construct($x = 0, $y = 0, $z = 0){
if(($x instanceof Vector3) === true){
$this->__construct($x->x, $x->y, $x->z);
}else{
$this->x = $x;
$this->y = $y;
$this->z = $z;
}
}
public function getX(){
return $this->x;
}
public function getY(){
return $this->y;
}
public function getZ(){
return $this->z;
}
public function getFloorX(){
return (int) $this->x;
}
public function getFloorY(){
return (int) $this->y;
}
public function getFloorZ(){
return (int) $this->z;
}
public function getRight(){
return $this->getX();
}
public function getUp(){
return $this->getY();
}
public function getForward(){
return $this->getZ();
}
public function getSouth(){
return $this->getX();
}
public function getWest(){
return $this->getZ();
}
public function add($x = 0, $y = 0, $z = 0){
if(($x instanceof Vector3) === true){
return $this->add($x->x, $x->y, $x->z);
}else{
$this->x += $x;
$this->y += $y;
$this->z += $z;
return new Vector3($this->x + $x, $this->y + $y, $this->z + $z);
}
}
public function subtract($x = 0, $y = 0, $z = 0){
if(($x instanceof Vector3) === true){
return $this->add(-$x->x, -$x->y, -$x->z);
}else{
return $this->add(-$x, -$y, -$z);
}
}
public function ceil(){
return new 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);
}
public function round(){
return new 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));
}
public function distance($x = 0, $y = 0, $z = 0){
if(($x instanceof Vector3) === true){
return sqrt($this->distanceSquared($x->x, $x->y, $x->z));
}else{
return sqrt($this->distanceSquared($x, $y, $z));
}
}
public function distanceSquared($x = 0, $y = 0, $z = 0){
if(($x instanceof 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);
}
}
public function __toString(){
return "Vector3(x=".$this->x.",y=".$this->y.",z=".$this->z.")";
}
}

View File

@ -0,0 +1,96 @@
<?php
/*
-
/ \
/ \
/ PocketMine \
/ MP \
|\ @shoghicp /|
|. \ / .|
| .. \ / .. |
| .. | .. |
| .. | .. |
\ | /
\ | /
\ | /
\ | /
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
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
*/
class VersionString{
public static $stageOrder = array(
"alpha" => 0,
"beta" => 1,
"final" => 2,
);
private $stage, $major, $release, $minor;
public function __construct($version = MAJOR_VERSION){
if(is_int($version)){
$this->minor = $version & 0x1F;
$this->major = ($version >> 5) & 0x0F;
$this->generation = ($version >> 9) & 0x0F;
$this->stage = array_search(($version >> 13) & 0x0F, VersionString::$stageOrder, true);
}else{
$version = preg_split("/([A-Za-z]*)[ _\-]([0-9]*)\.([0-9]*)\.{0,1}([0-9]*)/", $version, -1, PREG_SPLIT_DELIM_CAPTURE);
$this->stage = strtolower($version[1]); //0-15
$this->generation = (int) $version[2]; //0-15
$this->major = (int) $version[3]; //0-15
$this->minor = (int) $version[4]; //0-31
}
}
public function getNumber(){
return (int) (VersionString::$stageOrder[$this->stage] << 13) + ($this->generation << 9) + ($this->major << 5) + $this->minor;
}
public function getStage(){
return $this->stage;
}
public function getGeneration(){
return $this->generation;
}
public function getMajor(){
return $this->major;
}
public function getMinor(){
return $this->minor;
}
public function getRelease(){
return $this->generation . "." . $this->major . "." . $this->minor;
}
public function __toString(){
return ucfirst($this->stage) . "_" . $this->generation . "." . $this->major . "." . $this->minor;
}
public function compare($target, $diff = false){
if(($target instanceof VersionString) === false){
$target = new VersionString($target);
}
$number = $this->getNumber();
$tNumber = $target->getNumber();
if($diff === true){
return $tNumber - $number;
}
if($number > $tNumber){
return -1; //Target is older
}elseif($number < $tNumber){
return 1; //Target is newer
}else{
return 0; //Same version
}
}
}

View File

@ -0,0 +1,89 @@
<?php
/*
-
/ \
/ \
/ PocketMine \
/ MP \
|\ @shoghicp /|
|. \ / .|
| .. \ / .. |
| .. | .. |
| .. | .. |
\ | /
\ | /
\ | /
\ | /
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
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
*/
require_once("misc/world/generator/object/tree/TreeObject.php");
class BigTreeObject extends TreeObject{
private $trunkHeightMultiplier = 0.618;
private $trunkHeight;
private $leafAmount = 1;
private $leafDistanceLimit = 5;
private $widthScale = 1;
private $branchSlope = 0.381;
private $totalHeight = 6;
private $leavesHeight = 3;
protected $radiusIncrease = 0;
private $addLeavesVines = false;
private $addLogVines = false;
private $addCocoaPlants = false;
public function canPlaceObject(LevelAPI $level, $x, $y, $z){
return false;
}
public function placeObject(LevelAPI $level, $x, $y, $z, $type){
$this->trunkHeight = (int) ($this->totalHeight * $this->trunkHeightMultiplier);
$leaves = $this->getLeafGroupPoints($level, $x, $y, $z);
foreach($leaves as $leafGroup){
$groupX = $leafGroup->getBlockX();
$groupY = $leafGrou->getBlockY();
$groupZ = $leafGroup->getBlockZ();
for ($yy = $groupY; $yy < $groupY + $this->leafDistanceLimit; ++$yy) {
$this->generateGroupLayer($level, $groupX, $yy, $groupZ, $this->getLeafGroupLayerSize($yy - $groupY));
}
}
/*final BlockIterator trunk = new BlockIterator(new Point(w, x, y - 1, z), new Point(w, x, y + trunkHeight, z));
while (trunk.hasNext()) {
trunk.next().setMaterial(VanillaMaterials.LOG, logMetadata);
}
generateBranches(w, x, y, z, leaves);
$level->setBlock($x, $y - 1, $z, 3, 0);
$this->totalHeight += mt_rand(-1, 3);
$this->leavesHeight += mt_rand(0, 1);
for($yy = ($this->totalHeight - $this->leavesHeight); $yy < ($this->totalHeight + 1); ++$yy){
$yRadius = ($yy - $this->totalHeight);
$xzRadius = (int) (($this->radiusIncrease + 1) - $yRadius / 2);
for($xx = -$xzRadius; $xx < ($xzRadius + 1); ++$xx){
for($zz = -$xzRadius; $zz < ($xzRadius + 1); ++$zz){
if((abs($xx) != $xzRadius or abs($zz) != $xzRadius) and $yRadius != 0){
$level->setBlock($x + $xx, $y + $yy, $z + $zz, 18, $type);
}
}
}
}
for($yy = 0; $yy < ($this->totalHeight - 1); ++$yy){
$level->setBlock($x, $y + $yy, $z, 17, $type);
}
*/
}
}

View File

@ -0,0 +1,97 @@
<?php
/*
-
/ \
/ \
/ PocketMine \
/ MP \
|\ @shoghicp /|
|. \ / .|
| .. \ / .. |
| .. | .. |
| .. | .. |
\ | /
\ | /
\ | /
\ | /
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
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
*/
require_once("misc/world/generator/object/tree/TreeObject.php");
class PineTreeObject extends TreeObject{
var $type = 1;
private $totalHeight = 8;
private $leavesSizeY = -1;
private $leavesAbsoluteMaxRadius = -1;
public function canPlaceObject(LevelAPI $level, $x, $y, $z){
$this->findRandomLeavesSize();
$checkRadius = 0;
for($yy = 0; $yy < ($this->totalHeight + 2); ++$yy) {
if($yy === $this->leavesSizeY) {
$checkRadius = $this->leavesAbsoluteMaxRadius;
}
for($xx = -$checkRadius; $xx < ($checkRadius + 1); ++$xx){
for($zz = -$checkRadius; $zz < ($checkRadius + 1); ++$zz){
$block = $level->getBlock($x + $xx, $y + $yy, $z + $zz);
if(!isset($this->overridable[$block[0]])){
return false;
}
}
}
}
return true;
}
private function findRandomLeavesSize(){
$this->totalHeight += mt_rand(-1, 2);
$this->leavesSizeY = 1 + mt_rand(0,2);
$this->leavesAbsoluteMaxRadius = 2 + mt_rand(0, 2);
}
public function placeObject(LevelAPI $level, $x, $y, $z){
if($this->leavesSizeY === -1 or $this->leavesAbsoluteMaxRadius === -1) {
$this->findRandomLeavesSize();
}
$level->setBlock($x, $y - 1, $z, 3, 0);
$leavesRadius = mt_rand(0,2);
$leavesMaxRadius = 1;
$leavesBottomY = $this->totalHeight - $this->leavesSizeY;
$firstMaxedRadius = false;
for($leavesY = 0; $leavesY < ($leavesBottomY + 1); ++$leavesY) {
$yy = $this->totalHeight - $leavesY;
for ($xx = -$leavesRadius; $xx < ($leavesRadius + 1); ++$xx) {
for ($zz = -$leavesRadius; $zz < ($leavesRadius + 1); ++$zz) {
if (abs($xx) != $leavesRadius or abs($zz) != $leavesRadius or $leavesRadius <= 0) {
$level->setBlock($x + $xx, $y + $yy, $z + $zz, 18, $this->type);
}
}
}
if ($leavesRadius >= $leavesMaxRadius) {
$leavesRadius = $firstMaxedRadius ? 1 : 0;
$firstMaxedRadius = true;
if (++$leavesMaxRadius > $this->leavesAbsoluteMaxRadius) {
$leavesMaxRadius = $this->leavesAbsoluteMaxRadius;
}
}else{
++$leavesRadius;
}
}
$trunkHeightReducer = mt_rand(0,3);
for($yy = 0; $yy < ($this->totalHeight - $trunkHeightReducer); ++$yy){
$level->setBlock($x, $y + $yy, $z, 17, $this->type);
}
}
}

View File

@ -29,14 +29,33 @@ the Free Software Foundation, either version 3 of the License, or
require_once("misc/world/generator/object/tree/TreeObject.php");
class SmallTreeObject extends TreeObject{
var $type = 0;
private $totalHeight = 6;
private $leavesHeight = 3;
protected $radiusIncrease = 0;
private $addLeavesVines = false;
private $addLogVines = false;
private $addCocoaPlants = false;
public function placeObject(LevelAPI $level, $x, $y, $z, $type){
private $addCocoaPlants = false;
public function canPlaceObject(LevelAPI $level, $x, $y, $z){
$radiusToCheck = $this->radiusIncrease;
for ($yy = 0; $yy < $this->totalHeight + 2; ++$yy) {
if ($yy == 1 or $yy === $this->totalHeight - 1) {
++$radiusToCheck;
}
for($xx = -$radiusToCheck; $xx < ($radiusToCheck + 1); ++$xx){
for($zz = -$radiusToCheck; $zz < ($radiusToCheck + 1); ++$zz){
$block = $level->getBlock($x + $xx, $y + $yy, $z + $zz);
if(!isset($this->overridable[$block[0]])){
return false;
}
}
}
}
return true;
}
public function placeObject(LevelAPI $level, $x, $y, $z){
$level->setBlock($x, $y - 1, $z, 3, 0);
$this->totalHeight += mt_rand(-1, 3);
$this->leavesHeight += mt_rand(0, 1);
@ -46,14 +65,14 @@ class SmallTreeObject extends TreeObject{
for($xx = -$xzRadius; $xx < ($xzRadius + 1); ++$xx){
for($zz = -$xzRadius; $zz < ($xzRadius + 1); ++$zz){
if((abs($xx) != $xzRadius or abs($zz) != $xzRadius) and $yRadius != 0){
$level->setBlock($x + $xx, $y + $yy, $z + $zz, 18, $type);
$level->setBlock($x + $xx, $y + $yy, $z + $zz, 18, $this->type);
}
}
}
}
for($yy = 0; $yy < ($this->totalHeight - 1); ++$yy){
$level->setBlock($x, $y + $yy, $z, 17, $type);
}
$level->setBlock($x, $y + $yy, $z, 17, $this->type);
}
}

View File

@ -0,0 +1,88 @@
<?php
/*
-
/ \
/ \
/ PocketMine \
/ MP \
|\ @shoghicp /|
|. \ / .|
| .. \ / .. |
| .. | .. |
| .. | .. |
\ | /
\ | /
\ | /
\ | /
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
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
*/
require_once("misc/world/generator/object/tree/TreeObject.php");
class SpruceTreeObject extends TreeObject{
var $type = 1;
private $totalHeight = 8;
private $leavesBottomY = -1;
private $leavesMaxRadius = -1;
public function canPlaceObject(LevelAPI $level, $x, $y, $z){
$this->findRandomLeavesSize();
$checkRadius = 0;
for($yy = 0; $yy < $this->totalHeight + 2; ++$yy) {
if($yy === $this->leavesBottomY) {
$checkRadius = $this->leavesMaxRadius;
}
for($xx = -$checkRadius; $xx < ($checkRadius + 1); ++$xx){
for($zz = -$checkRadius; $zz < ($checkRadius + 1); ++$zz){
$block = $level->getBlock($x + $xx, $y + $yy, $z + $zz);
if(!isset($this->overridable[$block[0]])){
return false;
}
}
}
}
return true;
}
private function findRandomLeavesSize(){
$this->totalHeight += mt_rand(-1, 2);
$this->leavesBottomY = (int) ($this->totalHeight - mt_rand(1,2) - 3);
$this->leavesMaxRadius = 1 + mt_rand(0, 1);
}
public function placeObject(LevelAPI $level, $x, $y, $z){
if($this->leavesBottomY === -1 or $this->leavesMaxRadius === -1) {
$this->findRandomLeavesSize();
}
$level->setBlock($x, $y - 1, $z, 3, 0);
$leavesRadius = 0;
for($yy = $this->totalHeight; $yy >= $this->leavesBottomY; --$yy){
for ($xx = -$leavesRadius; $xx < ($leavesRadius + 1); ++$xx) {
for ($zz = -$leavesRadius; $zz < ($leavesRadius + 1); ++$zz) {
if (abs($xx) != $leavesRadius or abs($zz) != $leavesRadius or $leavesRadius <= 0) {
$level->setBlock($x + $xx, $y + $yy, $z + $zz, 18, $this->type);
}
}
}
if ($leavesRadius > 0 and $yy === ($y + $this->leavesBottomY + 1)) {
--$leavesRadius;
}elseif($leavesRadius < $this->leavesMaxRadius){
++$leavesRadius;
}
}
for($yy = 0; $yy < ($this->totalHeight - 1); ++$yy){
$level->setBlock($x, $y + $yy, $z, 17, $this->type);
}
}
}

View File

@ -27,14 +27,36 @@ the Free Software Foundation, either version 3 of the License, or
class TreeObject{
var $overridable = array(
0 => true,
6 => true,
17 => true,
18 => true,
);
public static function growTree(LevelAPI $level, $block, $type){
switch($type){
case Sapling::SPRUCE:
if(mt_rand(0,1) == 2){
$tree = new SpruceTreeObject();
}else{
$tree = new PineTreeObject();
}
break;
case Sapling::BIRCH:
$tree = new SmallTreeObject();
$tree->type = Sapling::BIRCH;
break;
default:
case Sapling::OAK:
$tree = new SmallTreeObject();
if(mt_rand(0,9) === 0){
$tree = new BigTreeObject();
}else{
$tree = new SmallTreeObject();
}
break;
}
$tree->placeObject($level, $block[2][0], $block[2][1], $block[2][2], $type);
if($tree->canPlaceObject($level, $block[2][0], $block[2][1], $block[2][2])){
$tree->placeObject($level, $block[2][0], $block[2][1], $block[2][2]);
}
}
}

View File

@ -30,20 +30,20 @@ $pstruct = array(
"long", //Ping ID
"magic",
),
0x05 => array(
"magic",
"byte", //Protocol Version
"special1", //MTU Size Null Lenght
),
0x06 => array(
"magic",
"long", //Server GUID
"byte", //Server Security
"short", //MTU Size
),
0x07 => array(
"magic",
5, //Security Cookie (idk why it's sent here)
@ -51,7 +51,7 @@ $pstruct = array(
"short", //MTU Size
"long", //Client GUID
),
0x08 => array(
"magic",
"long", //Server GUID
@ -59,20 +59,20 @@ $pstruct = array(
"short", //MTU Size
"byte", //Security
),
0x1a => array(
"byte", //Server Version
"magic",
"long", //Server GUID
),
0x1c => array(
"long", //Ping ID
"long", //Server GUID
"magic",
"string", //Data
),
0x1d => array(
"long", //Ping ID
"long", //Server GUID
@ -85,50 +85,50 @@ $pstruct = array(
"ubyte",
"customData",
),
0x81 => array(
"itriad",
"ubyte",
"customData",
),
0x82 => array(
"itriad",
"ubyte",
"customData",
),
0x83 => array(
"itriad",
"ubyte",
"customData",
),
0x84 => array(
"itriad",
"ubyte",
"customData",
),
0x85 => array(
"itriad",
"ubyte",
"customData",
),
0x86 => array(
"itriad",
"ubyte",
"customData",
),
0x87 => array(
"itriad",
"ubyte",
"customData",
),
0x88 => array(
"itriad",
"ubyte",
@ -140,52 +140,52 @@ $pstruct = array(
"ubyte",
"customData",
),
0x8a => array(
"itriad",
"ubyte",
"customData",
),
0x8b => array(
"itriad",
"ubyte",
"customData",
),
0x8c => array(
"itriad",
"ubyte",
"customData",
),
0x8d => array(
"itriad",
"ubyte",
"customData",
),
0x8e => array(
"itriad",
"ubyte",
"customData",
),
0x8f => array(
"itriad",
"ubyte",
"customData",
),
0xa0 => array(
"short",
"bool",
"itriad",
"special1",
),
0xc0 => array(
"short",
"bool",

View File

@ -27,43 +27,44 @@ the Free Software Foundation, either version 3 of the License, or
$dataName = array(
MC_KEEP_ALIVE => "KeepAlive",
MC_CLIENT_CONNECT => "ClientConnect",
MC_SERVER_HANDSHAKE => "ServerHandshake",
MC_CLIENT_HANDSHAKE => "ClientHandshake",
MC_DISCONNECT => "Disconnect",
0x18 => "Unknown",
MC_LOGIN => "Login",
MC_LOGIN_STATUS => "LoginStatus",
MC_READY => "Ready",
MC_CHAT => "Chat",
MC_SET_TIME => "SetTime",
MC_START_GAME => "StartGame",
MC_ADD_MOB => "AddMob",
MC_ADD_PLAYER => "AddPlayer",
MC_ADD_ENTITY => "AddEntity",
MC_REMOVE_ENTITY => "RemoveEntity",
MC_ADD_ITEM_ENTITY => "AddItemEntity",
MC_TAKE_ITEM_ENTITY => "TakeItemEntity",
MC_MOVE_ENTITY => "MoveEntity",
MC_MOVE_ENTITY_POSROT => "MoveEntity_PosRot",
MC_MOVE_PLAYER => "MovePlayer",
MC_PLACE_BLOCK => "PlaceBlock",
MC_PLACE_BLOCK => "PlaceBlock",
MC_REMOVE_BLOCK => "RemoveBlock",
MC_UPDATE_BLOCK => "UpdateBlock",
MC_REQUEST_CHUNK => "RequestChunk",
MC_CHUNK_DATA => "ChunkData",
MC_PLAYER_EQUIPMENT => "PlayerEquipment",
MC_INTERACT => "Interact",
MC_USE_ITEM => "UseItem",
MC_PLAYER_ACTION => "PlayerAction",
@ -73,7 +74,12 @@ $dataName = array(
MC_SET_SPAWN_POSITION => "SetSpawnPosition",
MC_ANIMATE => "Animate",
MC_RESPAWN => "Respawn",
MC_DROP_ITEM => "DropItem",
MC_CONTAINER_OPEN => "ContainerOpen",
MC_CONTAINER_CLOSE => "ContainerClose",
MC_CONTAINER_SET_SLOT => "ContainerSetSlot",
MC_CLIENT_MESSAGE => "ClientMessage",
MC_SIGN_UPDATE => "SignUpdate",
MC_ADVENTURE_SETTINGS => "AdventureSettings",

View File

@ -50,6 +50,7 @@ define("MC_ADD_PLAYER", 0x89);
define("MC_ADD_ENTITY", 0x8c);
define("MC_REMOVE_ENTITY", 0x8d);
define("MC_ADD_ITEM_ENTITY", 0x8e);
define("MC_TAKE_ITEM_ENTITY", 0x8f);
define("MC_MOVE_ENTITY", 0x90);
@ -74,6 +75,11 @@ define("MC_SET_SPAWN_POSITION", 0xa6);
define("MC_ANIMATE", 0xa7);
define("MC_RESPAWN", 0xa8);
define("MC_DROP_ITEM", 0xaa);
define("MC_CONTAINER_OPEN", 0xab);
define("MC_CONTAINER_CLOSE", 0xac);
define("MC_CONTAINER_SET_SLOT", 0xad);
define("MC_CLIENT_MESSAGE", 0xb1);
define("MC_SIGN_UPDATE", 0xb2);
define("MC_ADVENTURE_SETTINGS", 0xb3);

View File

@ -26,7 +26,6 @@ if not "%PHPOUTPUT%"=="1" (
echo [ERROR] Couldn't find PHP binary in PATH.
ping 127.0.0.1 -n 3 -w 1000>nul
) else (
START /B CMD /C CALL php PocketMine-MP.php
START /B /WAIT php src/common/input.php 1
ping 127.0.0.1 -n 5 -w 1000>nul
)
START /B /WAIT php -d enable_dl=On PocketMine-MP.php
)
pause

View File

@ -1,3 +1,8 @@
#!/bin/bash
php PocketMine-MP.php &
cat > src/console.in
DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR
if [ -f php5/bin/php ]; then
./php5/bin/php -d enable_dl=On PocketMine-MP.php
exit 0
fi
php -d enable_dl=On PocketMine-MP.php