This commit is contained in:
GameHerobrine 2024-07-19 10:34:38 +03:00
parent 469002c346
commit 1dadee1817
632 changed files with 1 additions and 39497 deletions

27
.gitattributes vendored
View file

@ -1,27 +0,0 @@
# 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
*.sln merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain

24
.gitignore vendored
View file

@ -1,24 +0,0 @@
players/*
worlds/*
plugins/*
logs/*
bin/*
.idea/*
*.log
*.pmf
*.txt
*.properties
############
## Windows
############
# Windows image file caches
Thumbs.db
# Folder config file
Desktop.ini
# Mac crap
.DS_Store

View file

@ -1,14 +0,0 @@
language: php
php:
- 5.4
before_script:
- pecl install channel://pecl.php.net/pthreads-0.0.44
script:
- php src/tests/ServerSuiteTest.php
notifications:
email: false
webhooks: http://n.tkte.ch/h/214/wsNvmG43-ncxUVRrFPwSM-r0

View file

@ -1,68 +0,0 @@
![](http://owouwu.ru/favicon.png)
# NostalgiaCore Contribution Guidelines
Before contributing to NostalgiaCore, please read this.
## I want to create an issue
* First, use the [Issue Search](https://github.com/kotyaralih/NostalgiaCore/search?ref=cmdform&type=Issues) to check if anyone has reported it.
* Is your issue related to a Plugin? If so, please contact their original author instead of reporting it here.
* And no, we won't update a Plugin because you need it.
* When reporting, give as much info as you can, and if the Issue is a crash, give the Crash Dump.
* Issues should be written in English.
## I want to contribute code
* Use the [Pull Request](https://github.com/kotyaralih/NostalgiaCore/pull/new) system, your request will be checked and discussed.
* __Create a single branch for that pull request__
* If you want to be part of NostalgiaCore, we will ask you to.
* Code using the syntax as in NostalgiaCore. See below for an example.
* The code must be clear and written in English, comments included.
__Thanks for contributing to NostalgiaCore!__
#### Code syntax
It is mainly [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md) with a few exceptions.
* Opening braces MUST go on the same line.
* `else if` MUST be written as `elseif`. _(It is in PSR-2, but using a SHOULD)_
* Control structure keywords or opening braces MUST NOT have one space after them.
* Code MUST use tabs for indenting.
* Long arrays MAY be split across multiple lines, where each subsequent line is indented once.
* Files MUST use only the `<?php` tag.
* Files MUST NOT have an ending `?>` tag.
* Code MUST NOT use namespaces. _(This restriction maybe will be lifted)_
* Strings SHOULD use the double quote `"` except when the single quote is required.
* Arrays SHOULD be declared using `[]`, not the `array()` shortcut.
* Argument lists MAY NOT be split across multiple lines, except long arrays.
```php
<?php
class ExampleClass{
const EXAMPLE_CLASS_CONSTANT = 1;
public $examplePublicVariable = "defaultValue";
private $examplePrivateVariable;
public function __construct($firstArgument, &$secondArgument = null){
if($firstArgument === "exampleValue"){ //Remember to use === instead == when possible
//do things
}elseif($firstArgument === "otherValue"){
$secondArgument = function(){
return [
0 => "value1",
1 => "value2",
2 => "value3",
3 => "value4",
4 => "value5",
5 => "value6"
];
}
}
}
}
```

165
LICENSE
View file

@ -1,165 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View file

@ -1,34 +0,0 @@
<?php
/**
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* 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.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
/***REM_START***/
require_once(dirname(__FILE__)."/src/config.php");
require_once(FILE_PATH."/src/functions.php");
require_once(FILE_PATH."/src/dependencies.php");
/***REM_END***/
$server = new ServerAPI();
$server->start();
kill(getmypid()); //Fix for ConsoleAPI being blocked
exit(0);

View file

@ -1,42 +1,2 @@
![](http://owouwu.ru/favicon.png)
# NostalgiaCore
NostalgiaCore is a fork of Legacy PocketMine-MP 1.3.12, which fixes bugs of Legacy PocketMine-MP, and adds new content
Supported MCPE versions: 0.9.5 and maybe other 0.9.x versions
(Special thx to GullCraft Network and DartMiner43)
<h2> Why should you use NostalgiaCore to run a Minecraft Pocket Edition 0.9.5 server?</h2>
You should not use it now.
<h3> Download Stable NostalgiaCore</h3>
https://github.com/kotyaralih/NostalgiaCore/releases/
<h3> PHP binaries download</h3>
* https://github.com/pmmp/PHP-Binaries/releases/tag/php-8.0-latest PHP8 (Use PM4 version)
* https://github.com/DaisukeDaisuke/AndroidPHP/releases/tag/8.0.28 PHP8 for ARMv8
<h3> How to use auto-restart?</h3>
Simply start your server using ./start.sh -l
<h3> Our discord server</h3>
https://discord.gg/uSHEWe6NC3
# Want to contribute?
* Check the [Contributing Guidelines](CONTRIBUTING.md)
# Third-party Libraries/Protocols Used
* __[PHP Sockets](http://php.net/manual/en/book.sockets.php)__
* __[PHP SQLite3](http://php.net/manual/en/book.sqlite3.php)__
* __[PHP BCMath](http://php.net/manual/en/book.bc.php)__
* __[PHP pthreads](https://github.com/krakjoe/pthreads)__ by _[krakjoe](https://github.com/krakjoe)_: Threading for PHP - Share Nothing, Do Everything.
* __[PHP YAML](https://code.google.com/p/php-yaml/)__ by _Bryan Davis_: The Yaml PHP Extension provides a wrapper to the LibYAML library.
* __[LibYAML](http://pyyaml.org/wiki/LibYAML)__ by _Kirill Simonov_: A YAML 1.1 parser and emitter written in C.
* __[mintty](https://code.google.com/p/mintty/)__ : xterm Terminal Emulator
* __[cURL](http://curl.haxx.se/)__: cURL is a command line tool for transferring data with URL syntax
* __[Zlib](http://www.zlib.net/)__: A Massively Spiffy Yet Delicately Unobtrusive Compression Library
* __[Source RCON Protocol](https://developer.valvesoftware.com/wiki/Source_RCON_Protocol)__
* __[UT3 Query Protocol](http://wiki.unrealadmin.org/UT3_query_protocol)__
## NostalgiaCore 0.9.5 was moved to https://github.com/oldminecraftcommunity/NostalgiaCore-0.9.5

View file

@ -1,203 +0,0 @@
<?php
class AchievementAPI{
public static $achievements = [
/*"openInventory" => array(
"name" => "Taking Inventory",
"requires" => array(),
),*/
"mineWood" => [
"name" => "Getting Wood",
"requires" => [
//"openInventory",
],
],
"buildWorkBench" => [
"name" => "Benchmarking",
"requires" => [
"mineWood",
],
],
"buildPickaxe" => [
"name" => "Time to Mine!",
"requires" => [
"buildWorkBench",
],
],
"buildFurnace" => [
"name" => "Hot Topic",
"requires" => [
"buildPickaxe",
],
],
"acquireIron" => [
"name" => "Acquire hardware",
"requires" => [
"buildFurnace",
],
],
"buildHoe" => [
"name" => "Time to Farm!",
"requires" => [
"buildWorkBench",
],
],
"makeBread" => [
"name" => "Bake Bread",
"requires" => [
"buildHoe",
],
],
"bakeCake" => [
"name" => "The Lie",
"requires" => [
"buildHoe",
],
],
"buildBetterPickaxe" => [
"name" => "Getting an Upgrade",
"requires" => [
"buildPickaxe",
],
],
"buildSword" => [
"name" => "Time to Strike!",
"requires" => [
"buildWorkBench",
],
],
"diamond" => [
"name" => "DIAMONDS!",
"requires" => [
"acquireIron",
],
],
"leather" => [
"name" => "Cow Tipper",
"requires" => [
"buildSword",
],
],
];
private $server;
function __construct(){
$this->server = ServerAPI::request();
}
/**
* Add an achievement
* @param string $achievementId
* @param string $achievementName
* @param array $requires
* @return boolean
*/
public static function addAchievement($achievementId, $achievementName, array $requires = []){
if(!isset(self::$achievements[$achievementId])){
self::$achievements[$achievementId] = [
"name" => $achievementName,
"requires" => $requires,
];
return true;
}
return false;
}
public static function grantAchievement(Player $player, $achievementId){
if(isset(self::$achievements[$achievementId]) and !self::hasAchievement($player, $achievementId)){
foreach(self::$achievements[$achievementId]["requires"] as $requerimentId){
if(!self::hasAchievement($player, $requerimentId)){
return false;
}
}
if(ServerAPI::request()->api->dhandle("achievement.grant", ["player" => $player, "achievementId" => $achievementId]) !== false){
$player->achievements[$achievementId] = true;
self::broadcastAchievement($player, $achievementId);
return true;
}else{
return false;
}
}
return false;
}
public static function hasAchievement(Player $player, $achievementId){
if(!isset(self::$achievements[$achievementId]) or !isset($player->achievements)){
$player->achievements = [];
return false;
}
if(!isset($player->achievements[$achievementId]) or $player->achievements[$achievementId] == false){
return false;
}
return true;
}
public static function broadcastAchievement(Player $player, $achievementId){
if(isset(self::$achievements[$achievementId])){
$result = ServerAPI::request()->api->dhandle("achievement.broadcast", ["player" => $player, "achievementId" => $achievementId]);
if($result !== false and $result !== true){
if(ServerAPI::request()->api->getProperty("announce-player-achievements") == true){
ServerAPI::request()->api->chat->broadcast($player->username . " has just earned the achievement [" . self::$achievements[$achievementId]["name"] . "]");
}else{
$player->sendChat("You have just earned the achievement [" . self::$achievements[$achievementId]["name"] . "]");
}
}
return true;
}
return false;
}
public static function removeAchievement(Player $player, $achievementId){
if(self::hasAchievement($player, $achievementId)){
$player->achievements[$achievementId] = false;
}
}
public function viewAchievements($cmd, $params, $issuer, $alias)
{
if(!($issuer instanceof Player) && !isset($params[0])){
return "Please enter a nickname.";
} else{
if(! ($issuer instanceof Player) || (isset($params[0]) && $this->server->api->ban->isOp($issuer->username))){
$player = $this->server->api->player->get($params[0]);
if($player instanceof Player){
$data = $player->data;
} else{
$data = $this->server->api->player->getOffline(trim($params[0]), false);
}
} else{
$data = $issuer->achievements;
}
}
if($data === false){
return "Player {$params[0]} is not found.";
}
if($data instanceof Config){
$achs = $data->get("achievements");
}else{
$achs = $data;
}
if(count($achs) <= 0){
return "Player {$params[0]} unlocked 0 achievements";
}
$output = "Unlocked Achievements(".count($achs)."/".count(self::$achievements)."): ";
foreach($achs as $achievement => $unlocked){
if($unlocked && isset(self::$achievements[$achievement])){
$info = self::$achievements[$achievement];
$output .= "{$info["name"]}, ";
}
}
return substr($output, 0, - 2);
}
public function init(){
$this->server->api->console->register("ach", "<player>", [$this, "viewAchievements"]);
$this->server->api->console->alias("getplayerachievements", "ach");
$this->server->api->console->cmdWhitelist("ach");
}
}

View file

@ -1,408 +0,0 @@
<?php
class BanAPI{
private $server;
/*
* I would use PHPDoc Template here but PHPStorm does not recognise it. - @sekjun9878
*/
/** @var Config */
private $whitelist;
/** @var Config */
private $banned;
/** @var Config */
private $ops;
/** @var Config */
private $bannedIPs;
public $cmdWhitelist = [];//Command WhiteList
function __construct(){
$this->server = ServerAPI::request();
}
public function init(){
$this->whitelist = new Config(DATA_PATH . "white-list.txt", CONFIG_LIST);//Open whitelist list file
$this->bannedIPs = new Config(DATA_PATH . "banned-ips.txt", CONFIG_LIST);//Open Banned IPs list file
$this->banned = new Config(DATA_PATH . "banned.txt", CONFIG_LIST);//Open Banned Usernames list file
$this->ops = new Config(DATA_PATH . "ops.txt", CONFIG_LIST);//Open list of OPs
$this->server->api->console->register("banip", "<add|remove|list|reload> [IP|player]", [$this, "commandHandler"]);
$this->server->api->console->register("ban", "<add|remove|list|reload> [username]", [$this, "commandHandler"]);
$this->server->api->console->register("kick", "<player> [reason ...]", [$this, "commandHandler"]);
$this->server->api->console->register("whitelist", "<on|off|list|add|remove|reload> [username]", [$this, "commandHandler"]);
$this->server->api->console->register("op", "<player>", [$this, "commandHandler"]);
$this->server->api->console->register("deop", "<player>", [$this, "commandHandler"]);
$this->server->api->console->register("sudo", "<player>", [$this, "commandHandler"]);
$this->server->api->console->alias("ban-ip", "banip add");
$this->server->api->console->alias("banlist", "ban list");
$this->server->api->console->alias("pardon", "ban remove");
$this->server->api->console->alias("pardon-ip", "banip remove");
$this->server->addHandler("console.command", [$this, "permissionsCheck"], 1);//Event handler when commands are issued. Used to check permissions of commands that go through the server.
$this->server->addHandler("player.block.break", [$this, "permissionsCheck"], 1);//Event handler for blocks
$this->server->addHandler("player.block.place", [$this, "permissionsCheck"], 1);//Event handler for blocks
$this->server->addHandler("player.flying", [$this, "permissionsCheck"], 1);//Flying Event
}
/**
* Whitelists a CMD so everyone can issue it - Even non OPs.
* @deprecated use ConsoleAPI::cmdWhitelist
* @see ConsoleAPI::cmdWhitelist
* @param string $cmd Command to Whitelist
*/
public function cmdWhitelist($cmd){
$this->server->api->console->cmdWhitelist($cmd);
}
/**
* @param mixed $data
* @param string $event
*
* @return boolean
*/
public function permissionsCheck($data, $event){
switch($event){
case "player.flying"://OPs can fly around the server.
if($this->isOp($data->iusername)){
return true;
}
break;
case "player.block.break":
/**
* @var Player $player
*/
$player = $data["player"];
if(!$this->isOp($player->iusername) && $player->level->getName() === $this->server->api->level->getDefault()){
$t = new Vector2($data["target"]->x, $data["target"]->z);
$s = new Vector2($this->server->spawn->x, $this->server->spawn->z);
if($t->distance($s) <= $this->server->api->getProperty("spawn-protection") and $this->server->api->dhandle($event . ".spawn", $data) !== true){
return false;
}
}
return;
case "player.block.place"://Spawn protection detection. Allows OPs to place/break blocks in the spawn area.
$player = $data["player"];
if(!$this->isOp($player->iusername) && $player->level->getName() === $this->server->api->level->getDefault()){
$t = new Vector2($data["block"]->x, $data["block"]->z);
$s = new Vector2($this->server->spawn->x, $this->server->spawn->z);
if($t->distance($s) <= $this->server->api->getProperty("spawn-protection") and $this->server->api->dhandle($event . ".spawn", $data) !== true){
return false;
}
}
return;
case "console.command"://Checks if a command is allowed with the current user permissions.
if(isset($this->cmdWhitelist[$data["cmd"]])){
return;
}
if($data["issuer"] instanceof Player){
if($this->server->api->handle("console.check", $data) === true or $this->isOp($data["issuer"]->iusername)){
return;
}
}elseif($data["issuer"] === "console" or $data["issuer"] === "rcon"){
return;
}
return false;
}
}
/**
* @param string $username
*
* @return boolean
*/
public function isOp($username){//Is a player op?
$username = strtolower($username);
if($this->server->api->dhandle("op.check", $username) === true){
return true;
}elseif($this->ops->exists($username)){
return true;
}
return false;
}
/**
* @param string $username
*/
public function ban($username){
$this->commandHandler("ban", ["add", $username], "console", "");
}
/**
* @param string $cmd
* @param array $params
* @param string $issuer
* @param string $alias
*
* @return string
*/
public function commandHandler($cmd, $params, $issuer, $alias){
$output = "";
switch($cmd){
case "sudo":
$target = strtolower(array_shift($params));
$player = $this->server->api->player->get($target);
if(!isset($params[0])){
$output .= "Usage: /sudo <player>\n";
break;
}
if(!($player instanceof Player)){
$output .= "Player not connected.\n";
break;
}
$this->server->api->console->run(implode(" ", $params), $player);
$output .= "Command ran as " . $player->username . ".\n";
break;
case "op":
if(!isset($params[0])){
$output .= "Usage: /op <player>\n";
break;
}
$user = strtolower($params[0]);
$player = $this->server->api->player->get($user);
if(!($player instanceof Player)){
$this->ops->set($user);
$this->ops->save($user);
$output .= $user . " is now op\n";
break;
}
$this->ops->set($player->iusername);
$this->ops->save();
$output .= $player->iusername . " is now op\n";
$this->server->api->chat->sendTo(false, "You are now op.", $player->iusername);
break;
case "deop":
if(!isset($params[0])){
$output .= "Usage: /deop <player>\n";
break;
}
$user = strtolower($params[0]);
$player = $this->server->api->player->get($user);
if(!($player instanceof Player)){
$this->ops->remove($user);
$this->ops->save();
$output .= $user . " is no longer op\n";
break;
}
$this->ops->remove($player->iusername);
$this->ops->save();
$output .= $player->iusername . " is no longer op\n";
$this->server->api->chat->sendTo(false, "You are no longer op.", $player->iusername);
break;
case "kick":
if(!isset($params[0])){
$output .= "Usage: /kick <player> [reason ...]\n";
}else{
$name = strtolower(array_shift($params));
$player = $this->server->api->player->get($name);
if($player === false){
$output .= "Player \"" . $name . "\" does not exist\n";
}else{
$reason = implode(" ", $params);
$reason = $reason == "" ? "No reason" : $reason;
$this->server->schedule(60, [$player, "close"], "You have been kicked: " . $reason); //Forces a kick
$player->blocked = true;
if($issuer instanceof Player){
$this->server->api->chat->broadcast($player->username . " has been kicked by " . $issuer->username . ": $reason");
}else{
$this->server->api->chat->broadcast($player->username . " has been kicked: $reason");
}
}
}
break;
case "whitelist":
$p = strtolower(array_shift($params));
switch($p){
case "remove":
$user = strtolower($params[0]);
$this->whitelist->remove($user);
$this->whitelist->save();
$output .= "Player \"$user\" removed from white-list\n";
break;
case "add":
$user = strtolower($params[0]);
$this->whitelist->set($user);
$this->whitelist->save();
$output .= "Player \"$user\" added to white-list\n";
break;
case "reload":
$this->whitelist = new Config(DATA_PATH . "white-list.txt", CONFIG_LIST);
break;
case "list":
$output .= "White-list: " . implode(", ", $this->whitelist->getAll(true)) . "\n";
break;
case "on":
case "true":
case "1":
$output .= "White-list turned on\n";
$this->server->api->setProperty("white-list", true);
break;
case "off":
case "false":
case "0":
$output .= "White-list turned off\n";
$this->server->api->setProperty("white-list", false);
break;
default:
$output .= "Usage: /whitelist <on|off|list|add|remove|reload> [username]\n";
break;
}
break;
case "banip":
$p = strtolower(array_shift($params));
switch($p){
case "pardon":
case "remove":
$ip = strtolower($params[0]);
$this->bannedIPs->remove($ip);
$this->bannedIPs->save();
$output .= "IP \"$ip\" removed from ban list\n";
break;
case "add":
case "ban":
$ip = strtolower($params[0]);
$player = $this->server->api->player->get($ip);
if($player instanceof Player){
$ip = $player->ip;
$player->close("banned");
}
$this->bannedIPs->set($ip);
$this->bannedIPs->save();
$output .= "IP \"$ip\" added to ban list\n";
break;
case "reload":
$this->bannedIPs = new Config(DATA_PATH . "banned-ips.txt", CONFIG_LIST);
break;
case "list":
$output .= "IP ban list: " . implode(", ", $this->bannedIPs->getAll(true)) . "\n";
break;
default:
$output .= "Usage: /banip <add|remove|list|reload> [IP|player]\n";
break;
}
break;
case "ban":
$p = strtolower(array_shift($params));
switch($p){
case "pardon":
case "remove":
$user = strtolower($params[0]);
$this->banned->remove($user);
$this->banned->save();
$output .= "Player \"$user\" removed from ban list\n";
break;
case "add":
case "ban":
$user = strtolower($params[0]);
$this->banned->set($user);
$this->banned->save();
$player = $this->server->api->player->get($user);
if($player !== false){
$player->close("You have been banned");
}
if($issuer instanceof Player){
$this->server->api->chat->broadcast($user . " has been banned by " . $issuer->username . "\n");
}else{
$this->server->api->chat->broadcast($user . " has been banned\n");
}
$this->kick($user, "Banned");
$output .= "Player \"$user\" added to ban list\n";
break;
case "reload":
$this->banned = new Config(DATA_PATH . "banned.txt", CONFIG_LIST);
break;
case "list":
$output .= "Ban list: " . implode(", ", $this->banned->getAll(true)) . "\n";
break;
default:
$output .= "Usage: /ban <add|remove|list|reload> [username]\n";
break;
}
break;
}
return $output;
}
/**
* @param string $username
* @param string $reason
*/
public function kick($username, $reason = "No Reason"){
$this->commandHandler("kick", [$username, $reason], "console", "");
}
/**
* @param string $username
*/
public function pardon($username){
$this->commandHandler("ban", ["pardon", $username], "console", "");
}
/**
* @param string $ip
*/
public function banIP($ip){
$this->commandHandler("banip", ["add", $ip], "console", "");
}
/**
* @param string $ip
*/
public function pardonIP($ip){
$this->commandHandler("banip", ["pardon", $ip], "console", "");
}
public function reload(){
$this->commandHandler("ban", ["reload"], "console", "");
$this->commandHandler("banip", ["reload"], "console", "");
$this->commandHandler("whitelist", ["reload"], "console", "");
}
/**
* @param string $ip
*
* @return boolean
*/
public function isIPBanned($ip){
if($this->server->api->dhandle("api.ban.ip.check", $ip) === false){
return true;
}elseif($this->bannedIPs->exists($ip, true)){
return true;
}else{
return false;
}
}
/**
* @param string $username
*
* @return boolean
*/
public function isBanned($username){
$username = strtolower($username);
if($this->server->api->dhandle("api.ban.check", $username) === false){
return true;
}elseif($this->banned->exists($username, true)){
return true;
}else{
return false;
}
}
/**
* @param string $username
*
* @return boolean
*/
public function inWhitelist($username){
$username = strtolower($username);
if($this->isOp($username)){
return true;
}elseif($this->server->api->dhandle("api.ban.whitelist.check", $username) === false){
return true;
}elseif($this->whitelist->exists($username, true)){
return true;
}
return false;
}
}

View file

@ -1,702 +0,0 @@
<?php
class BlockAPI{
public static $creative = [
//Building
[STONE, 0],
[STONE, 1],
[STONE, 2],
[STONE, 3],
[STONE, 4],
[STONE, 5],
[STONE, 6],
[COBBLESTONE, 0],
[STONE_BRICKS, 0],
[STONE_BRICKS, 1],
[STONE_BRICKS, 2],
[STONE_BRICKS, 3],
[MOSS_STONE, 0],
[WOODEN_PLANKS, 0],
[WOODEN_PLANKS, 1],
[WOODEN_PLANKS, 2],
[WOODEN_PLANKS, 3],
[WOODEN_PLANKS, 4],
[WOODEN_PLANKS, 5],
[BRICKS, 0],
[EMERALD_BLOCK, 0],
[EMERALD_ORE, 0],
[DIRT, 0],
[GRASS, 0],
[CLAY_BLOCK, 0],
[SANDSTONE, 0],
[SANDSTONE, 1],
[SANDSTONE, 2],
[LOG2, 0],
[LOG2, 1],
[SAND, 0],
[SAND, 1],
[GRAVEL, 0],
[TRUNK, 0],
[TRUNK, 1],
[TRUNK, 2],
[TRUNK, 3],
[NETHER_BRICKS, 0],
[NETHERRACK, 0],
[BEDROCK, 0],
[COBBLESTONE_STAIRS, 0],
[OAK_WOODEN_STAIRS, 0],
[SPRUCE_WOODEN_STAIRS, 0],
[BIRCH_WOODEN_STAIRS, 0],
[JUNGLE_WOODEN_STAIRS, 0],
[ACACIA_WOOD_STAIRS, 0],
[DARK_OAK_WOOD_STAIRS, 0],
[BRICK_STAIRS, 0],
[SANDSTONE_STAIRS, 0],
[STONE_BRICK_STAIRS, 0],
[NETHER_BRICKS_STAIRS, 0],
[QUARTZ_STAIRS, 0],
[SLAB, 0],
[SLAB, 1],
[WOODEN_SLAB, 0],
[WOODEN_SLAB, 1],
[WOODEN_SLAB, 2],
[WOODEN_SLAB, 3],
[WOODEN_SLAB, 4],
[WOODEN_SLAB, 5],
[SLAB, 3],
[SLAB, 4],
[SLAB, 5],
[SLAB, 6],
[QUARTZ_BLOCK, 0],
[QUARTZ_BLOCK, 1],
[QUARTZ_BLOCK, 2],
[COAL_ORE, 0],
[IRON_ORE, 0],
[GOLD_ORE, 0],
[DIAMOND_ORE, 0],
[LAPIS_ORE, 0],
[REDSTONE_ORE, 0],
[OBSIDIAN, 0],
[ICE, 0],
[SNOW_BLOCK, 0],
[BROWN_MUSHROOM_BLOCK, 0],
[BROWN_MUSHROOM_BLOCK, 14],
[BROWN_MUSHROOM_BLOCK, 15],
[RED_MUSHROOM_BLOCK, 14],
[MYCELIUM, 0],
[PODZOL, 0],
[STAINED_CLAY, 0],
[STAINED_CLAY, 1],
[STAINED_CLAY, 2],
[STAINED_CLAY, 3],
[STAINED_CLAY, 4],
[STAINED_CLAY, 5],
[STAINED_CLAY, 6],
[STAINED_CLAY, 7],
[STAINED_CLAY, 8],
[STAINED_CLAY, 9],
[STAINED_CLAY, 10],
[STAINED_CLAY, 11],
[STAINED_CLAY, 12],
[STAINED_CLAY, 13],
[STAINED_CLAY, 14],
[STAINED_CLAY, 15],
[HARDENED_CLAY, 0],
[END_STONE, 0],
//Decoration
[COBBLESTONE_WALL, 0],
[COBBLESTONE_WALL, 1],
[LILY_PAD, 0],
[GOLD_BLOCK, 0],
[IRON_BLOCK, 0],
[DIAMOND_BLOCK, 0],
[LAPIS_BLOCK, 0],
[COAL_BLOCK, 0],
[SNOW_LAYER, 0],
[GLASS, 0],
[GLOWSTONE_BLOCK, 0],
[VINES, 0],
[NETHER_REACTOR, 0],
[WOOL, 0],
[WOOL, 7],
[WOOL, 6],
[WOOL, 5],
[WOOL, 4],
[WOOL, 3],
[WOOL, 2],
[WOOL, 1],
[WOOL, 15],
[WOOL, 14],
[WOOL, 13],
[WOOL, 12],
[WOOL, 11],
[WOOL, 10],
[WOOL, 9],
[WOOL, 8],
[LADDER, 0],
[SPONGE, 0],
[GLASS_PANE, 0],
[WOODEN_DOOR, 0],
[TRAPDOOR, 0],
[FENCE, 0],
[FENCE_GATE, 0],
[IRON_BARS, 0],
[BED, 0],
[BOOKSHELF, 0],
[PAINTING, 0],
[WORKBENCH, 0],
[STONECUTTER, 0],
[CHEST, 0],
[FURNACE, 0],
[DANDELION, 0],
[CYAN_FLOWER, 0],
[CYAN_FLOWER, 1],
[CYAN_FLOWER, 2],
[CYAN_FLOWER, 3],
[CYAN_FLOWER, 4],
[CYAN_FLOWER, 5],
[CYAN_FLOWER, 6],
[CYAN_FLOWER, 7],
[CYAN_FLOWER, 8],
[BROWN_MUSHROOM, 0],
[RED_MUSHROOM, 0],
[CACTUS, 0],
[MELON_BLOCK, 0],
[PUMPKIN, 0],
[LIT_PUMPKIN, 0],
[COBWEB, 0],
[HAY_BALE, 0],
[TALL_GRASS, 1],
[TALL_GRASS, 2],
[DEAD_BUSH, 0],
[SAPLING, 0],
[SAPLING, 1],
[SAPLING, 2],
[SAPLING, 3],
[SAPLING, 4],
[SAPLING, 5],
[LEAVES, 0],
[LEAVES, 1],
[LEAVES, 2],
[LEAVES, 3],
[LEAVES2, 0],
[LEAVES2, 1],
[CAKE, 0],
[SIGN, 0],
[CARPET, 0],
[CARPET, 7],
[CARPET, 6],
[CARPET, 5],
[CARPET, 4],
[CARPET, 3],
[CARPET, 2],
[CARPET, 1],
[CARPET, 15],
[CARPET, 14],
[CARPET, 13],
[CARPET, 12],
[CARPET, 11],
[CARPET, 10],
[CARPET, 9],
[CARPET, 8],
[END_PORTAL_FRAME, 0],
[MONSTER_SPAWNER, 0],
//Tools
[RAIL, 0],
[POWERED_RAIL, 0],
[TORCH, 0],
[BUCKET, 0],
[BUCKET, 8],
[BUCKET, 10],
[TNT, 0],
[IRON_HOE, 0],
[IRON_SWORD, 0],
[BOW, 0],
[SHEARS, 0],
[FLINT_AND_STEEL, 0],
[CLOCK, 0],
[COMPASS, 0],
[MINECART, 0],
[SPAWN_EGG, MOB_CHICKEN],
[SPAWN_EGG, MOB_COW],
[SPAWN_EGG, MOB_PIG],
[SPAWN_EGG, MOB_SHEEP],
[SPAWN_EGG, MOB_VILLAGER],
[SPAWN_EGG, MOB_WOLF],
[SPAWN_EGG, MOB_MOOSHROOM],
[SPAWN_EGG, MOB_CREEPER],
[SPAWN_EGG, MOB_ENDERMAN],
[SPAWN_EGG, MOB_SILVERFISH],
[SPAWN_EGG, MOB_SKELETON],
[SPAWN_EGG, MOB_SLIME],
[SPAWN_EGG, MOB_SPIDER],
[SPAWN_EGG, MOB_ZOMBIE],
[SPAWN_EGG, MOB_PIGMAN],
//Seeds
[SUGARCANE, 0],
[WHEAT, 0],
[SEEDS, 0],
[MELON_SEEDS, 0],
[PUMPKIN_SEEDS, 0],
[CARROT, 0],
[POTATO, 0],
[BEETROOT_SEEDS, 0],
[EGG, 0],
[DYE, 0],
[DYE, 7],
[DYE, 6],
[DYE, 5],
[DYE, 4],
[DYE, 3],
[DYE, 2],
[DYE, 1],
[DYE, 15],
[DYE, 14],
[DYE, 13],
[DYE, 12],
[DYE, 11],
[DYE, 10],
[DYE, 9],
[DYE, 8],
[DOUBLE_PLANT, 0],
[DOUBLE_PLANT, 1],
[DOUBLE_PLANT, 2],
[DOUBLE_PLANT, 3],
[DOUBLE_PLANT, 4],
[DOUBLE_PLANT, 5],
];
private $server;
private $scheduledUpdates = [];
private $randomUpdates = [];
function __construct(){
$this->server = ServerAPI::request();
}
/**
* @param integer $id
* @param number $meta
* @param boolean $v
* @return GenericBlock
*/
public static function get($id, $meta = 0, $v = false){
if(isset(Block::$class[$id])){
$classname = Block::$class[$id];
$b = new $classname($meta);
}else{
$b = new GenericBlock((int) $id, $meta);
}
if($v instanceof Position){
$b->position($v);
}
return $b;
}
public function init(){
$this->server->schedule(1, [$this, "blockUpdateTick"], [], true);
$this->server->api->console->register("setblock", "<x> <y> <z> <block[:damage]>", [$this, "commandHandler"]);
$this->server->api->console->register("give", "<player> <item[:damage]> [amount]", [$this, "commandHandler"]);
$this->server->api->console->register("id", "Check id of item", [$this, "commandHandler"]);
$this->server->api->console->cmdWhitelist("id");
}
public function commandHandler($cmd, $args, $issuer, $alias){
$output = "";
switch($cmd){
case "id":
if(!($issuer instanceof Player)){
$output .= "Run this command in-game!";
break;
}
$itemheld = $issuer->getSlot($issuer->slot);
$output = self::getItem($itemheld->getID(), $itemheld->getMetadata())."";
break;
case "setblock":
if(!($issuer instanceof Player)){
if(count($args) < 5){
$output .= "Usage: /setblock <x> <y> <z> <level> <block[:damage]>";
break;
}else{
if(!is_numeric($args[0]) or !is_numeric($args[1]) or !is_numeric($args[2])){
$output .= "You need to use a numeric coords!";
break;
}
$level = $this->server->api->level->get($args[3]);
if($level === false){
$output .= "Unknown level";
break;
}
$block = self::fromString($args[4])->getBlock();
}
}else{
if(count($args) < 4){
$output .= "Usage: /setblock <x> <y> <z> <block[:damage]>";
break;
}
$level = $issuer->entity->level;
$block = self::fromString($args[3])->getBlock();
}
$coords = [];
for($i = 0; $i < 3; $i++){
if($args[$i] === '~'){
if($i === 0) $coord = $issuer->entity->x;
elseif($i === 1) $coord = $issuer->entity->y;
else $coord = $issuer->entity->z;
$coords[$i] = round($coord, 0);
}
elseif(is_numeric($args[$i])){
if($args[$i] > 0 and $args[$i] < 255){
$coords[$i] = $args[$i];
}
}
}
if(!isset($coords[2])){
$output .= "Usage: /setblock <x> <y> <z> <block[:damage]>";
break;
}
$pos = new Position($coords[0], $coords[1], $coords[2], $level);
if(!($block instanceof Block)){
$output .= "Usage: /setblock <x> <y> <z> <block[:damage]>";
break;
}else{
$level->setBlock($pos, $block, true, false, true);
$output .= "Placed $block in ".implode(", ", $coords).", w:".$level->getName();
}
break;
case "give":
$player = $this->server->api->player->get($args[0] ?? "");
if($player instanceof Player){
$item = self::fromString($args[1] ?? "");
if(($player->gamemode & 0x01) === 0x01){
$output .= "Player is in creative mode.";
break;
}
if($item->getID() === 0){
$output .= "You cannot give an air block to a player.";
break;
}
if(!isset($args[2])){
$item->count = $item->getMaxStackSize();
}else{
$item->count = (int) $args[2];
}
$player->addItem($item->getID(), $item->getMetadata(), $item->count);
$output .= "Giving ".$item->count." of ".$item->getName()." (".$item->getID().":".$item->getMetadata().") to ".$player->username;
break;
}else{
$item = self::fromString($args[0] ?? "");
if(!($issuer instanceof Player)){
return "You cant give an item to a non-player.";
}
if(($issuer->gamemode & 0x01) === 0x01){
$output .= "You are in creative mode.";
break;
}
if($item->getID() === 0){
$output .= "You cannot give an air block to a player.";
break;
}
if(!isset($args[1])){
$item->count = $item->getMaxStackSize();
}else{
$item->count = (int) $args[1];
}
$issuer->addItem($item->getID(), $item->getMetadata(), $item->count);
$output .= "Giving ".$item->count." of ".$item->getName()." (".$item->getID().":".$item->getMetadata().") to ".$issuer->username;
break;
}
break;
}
return $output;
}
public static function fromString($str, $multiple = false){
if($multiple === true){
$blocks = [];
foreach(explode(",", $str) as $b){
$blocks[] = BlockAPI::fromString($b, false);
}
return $blocks;
}else{
$b = explode(":", str_replace(" ", "_", trim($str)));
if(!isset($b[1])){
$meta = 0;
}else{
$meta = ((int) $b[1]) & 0xFFFF;
}
if(defined(strtoupper($b[0]))){
$explodedString = explode(":", constant(strtoupper($b[0])));
if(count($explodedString) === 2){
$meta = (int) $explodedString[1];
}
$item = BlockAPI::getItem(constant(strtoupper($b[0])), $meta);
if($item->getID() === AIR and strtoupper($b[0]) !== "AIR"){
$item = BlockAPI::getItem(((int) $b[0]) & 0xFFFF, $meta);
}
}else{
$item = BlockAPI::getItem(((int) $b[0]) & 0xFFFF, $meta);
}
return $item;
}
}
public static function getItem($id, $meta = 0, $count = 1){
$id = (int) $id;
if(isset(Item::$class[$id])){
$classname = Item::$class[$id];
$i = new $classname($meta, $count);
}else{
$i = new Item($id, $meta, $count);
}
return $i;
}
public function playerBlockBreak(Player $player, Vector3 $vector){
$target = $player->level->getBlock($vector);
$item = $player->getSlot($player->slot);
if($this->server->api->dhandle("player.block.touch", ["type" => "break", "player" => $player, "target" => $target, "item" => $item]) === false){
if($this->server->api->dhandle("player.block.break.bypass", ["player" => $player, "target" => $target, "item" => $item]) !== true){
return $this->cancelAction($target, $player, false);
}
}
if((!$target->isBreakable($item, $player) and $this->server->api->dhandle("player.block.break.invalid", ["player" => $player, "target" => $target, "item" => $item]) !== true) or ($player->gamemode & 0x02) === 0x02 or (($player->lastBreak - $player->getLag() / 1000) + $target->getBreakTime($item, $player) - 0.2) >= microtime(true)){
if($this->server->api->dhandle("player.block.break.bypass", ["player" => $player, "target" => $target, "item" => $item]) !== true){
return $this->cancelAction($target, $player, false);
}
}
$player->lastBreak = microtime(true);
if($this->server->api->dhandle("player.block.break", ["player" => $player, "target" => $target, "item" => $item]) !== false){
$drops = $target->getDrops($item, $player);
if($target->onBreak($item, $player) === false){
return $this->cancelAction($target, $player, false);
}
if(($player->gamemode & 0x01) === 0 and $item->useOn($target) and $item->getMetadata() >= $item->getMaxDurability()){
$player->setSlot($player->slot, new Item(AIR, 0, 0), false);
}
}else{
return $this->cancelAction($target, $player, false);
}
if(is_array($drops) && ($player->gamemode & 0x01) === 0x00 and count($drops) > 0){
foreach($drops as $drop){
$this->server->api->entity->drop(new Position($target->x + 0.5, $target->y, $target->z + 0.5, $target->level), BlockAPI::getItem($drop[0] & 0xFFFF, $drop[1] & 0xFFFF, $drop[2]));
}
}
return false;
}
private function cancelAction(Block $block, Player $player, $send = true){
$pk = new UpdateBlockPacket;
$pk->x = $block->x;
$pk->y = $block->y;
$pk->z = $block->z;
$pk->block = $block->getID();
$pk->meta = $block->getMetadata();
$player->dataPacket($pk);
if($send === true){
$player->sendInventorySlot($player->slot);
}
return false;
}
public function playerBlockAction(Player $player, Vector3 $vector, $face, $fx, $fy, $fz){
if($face < 0 or $face > 5){
return false;
}
$target = $player->level->getBlock($vector);
$block = $target->getSide($face);
$item = $player->getSlot($player->slot);
if($target->getID() === AIR and $this->server->api->dhandle("player.block.place.invalid", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){ //If no block exists or not allowed in CREATIVE
if($this->server->api->dhandle("player.block.place.bypass", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){
$this->cancelAction($target, $player);
return $this->cancelAction($block, $player);
}
}
if($this->server->api->dhandle("player.block.touch", ["type" => "place", "player" => $player, "block" => $block, "target" => $target, "item" => $item]) === false){
if($this->server->api->dhandle("player.block.place.bypass", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){
return $this->cancelAction($block, $player);
}
}
$this->blockUpdate($target, BLOCK_UPDATE_TOUCH);
if($target->isActivable === true){
if($this->server->api->dhandle("player.block.activate", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== false and $target->onActivate($item, $player) === true){
return false;
}
}
if(($player->gamemode & 0x02) === 0x02){ //Adventure mode!!
if($this->server->api->dhandle("player.block.place.bypass", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){
return $this->cancelAction($block, $player, false);
}
}
if($block->y > 127 or $block->y < 0){
return false;
}
if($item->isActivable === true and $item->onActivate($player->level, $player, $block, $target, $face, $fx, $fy, $fz) === true){
if($item->count <= 0){
$player->setSlot($player->slot, BlockAPI::getItem(AIR, 0, 0), false);
}
return false;
}
if($item->isPlaceable()){
$hand = $item->getBlock();
$hand->position($block);
}elseif($block->getID() === FIRE){
$player->level->setBlock($block, new AirBlock(), true, false, true);
return false;
}else{
return $this->cancelAction($block, $player, false);
}
if(!($block->isReplaceable === true or ($hand->getID() === SLAB and $block->getID() === SLAB))){
return $this->cancelAction($block, $player, false);
}
if($target->isReplaceable === true){
$block = $target;
$hand->position($block);
//$face = -1;
}
if($hand->isSolid === true and $player->entity->inBlock($block)){
return $this->cancelAction($block, $player, false); //Entity in block
}
if($this->server->api->dhandle("player.block.place", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) === false){
return $this->cancelAction($block, $player);
}elseif($hand->place($item, $player, $block, $target, $face, $fx, $fy, $fz) === false){
return $this->cancelAction($block, $player, false);
}
if($hand->getID() === SIGN_POST or $hand->getID() === WALL_SIGN){
$t = $this->server->api->tile->addSign($player->level, $block->x, $block->y, $block->z);
$t->data["creator"] = $player->username;
}
if(($player->gamemode & 0x01) === 0x00){
--$item->count;
if($item->count <= 0){
$player->setSlot($player->slot, BlockAPI::getItem(AIR, 0, 0), false);
}
}
return false;
}
public function blockUpdate(Position $pos, $type = BLOCK_UPDATE_NORMAL){
if(!($pos instanceof Block)){
$block = $pos->level->getBlock($pos);
}else{
$pos = new Position($pos->x, $pos->y, $pos->z, $pos->level);
$block = $pos->level->getBlock($pos);
}
if($block === false){
return false;
}
$level = $block->onUpdate($type);
if($level === BLOCK_UPDATE_NORMAL){
$this->blockUpdateAround($block, $level);
$this->server->api->entity->updateRadius($pos, 1);
}elseif($level === BLOCK_UPDATE_RANDOM){
//$this->nextRandomUpdate($pos); old version, change back if any issues will start to happen with this one(please note that old version makes a lot of lag)
$this->scheduleBlockUpdate($pos, (mt_rand(25, 75) + Utils::getRandomUpdateTicks() * 0.05) / 0.05, BLOCK_UPDATE_RANDOM);
}
return $level;
}
public function blockUpdateAround(Position $pos, $type = BLOCK_UPDATE_NORMAL, $delay = false){
if($delay !== false){
$this->scheduleBlockUpdate($pos->getSide(0), $delay, $type);
$this->scheduleBlockUpdate($pos->getSide(1), $delay, $type);
$this->scheduleBlockUpdate($pos->getSide(2), $delay, $type);
$this->scheduleBlockUpdate($pos->getSide(3), $delay, $type);
$this->scheduleBlockUpdate($pos->getSide(4), $delay, $type);
$this->scheduleBlockUpdate($pos->getSide(5), $delay, $type);
}else{
$this->blockUpdate($pos->getSide(0), $type);
$this->blockUpdate($pos->getSide(1), $type);
$this->blockUpdate($pos->getSide(2), $type);
$this->blockUpdate($pos->getSide(3), $type);
$this->blockUpdate($pos->getSide(4), $type);
$this->blockUpdate($pos->getSide(5), $type);
}
}
public function scheduleBlockUpdate(Position $pos, $delay, $type = BLOCK_UPDATE_SCHEDULED){
$type = (int) $type;
if($delay < 0){
return false;
}
$index = $pos->x . "." . $pos->y . "." . $pos->z . "." . $pos->level->getName() . "." . $type;
$delay = microtime(true) + $delay * 0.05;
if(!isset($this->scheduledUpdates[$index])){
$this->scheduledUpdates[$index] = $pos;
$this->server->query("INSERT INTO blockUpdates (x, y, z, level, type, delay) VALUES (" . $pos->x . ", " . $pos->y . ", " . $pos->z . ", '" . $pos->level->getName() . "', " . $type . ", " . $delay . ");");
return true;
}
return false;
}
public function nextRandomUpdate(Position $pos){
if(!isset($this->scheduledUpdates[$pos->x . "." . $pos->y . "." . $pos->z . "." . $pos->level->getName() . "." . BLOCK_UPDATE_RANDOM])){
$time = microtime(true);
$offset = 0;
while(true){
$t = $offset + Utils::getRandomUpdateTicks() * 0.05;
$update = $this->server->query("SELECT COUNT(*) FROM blockUpdates WHERE level = '" . $pos->level->getName() . "' AND type = " . BLOCK_UPDATE_RANDOM . " AND delay >= " . ($time + $t - 1) . " AND delay <= " . ($time + $t + 1) . ";");
if($update instanceof SQLite3Result){
$update = $update->fetchArray(SQLITE3_NUM);
if($update[0] < 3){
break;
}
}else{
break;
}
$offset += mt_rand(25, 75);
}
$this->scheduleBlockUpdate($pos, $t / 0.05, BLOCK_UPDATE_RANDOM);
}
}
public function blockUpdateTick(){
$time = microtime(true);
if(count($this->scheduledUpdates) > 0){
$update = $this->server->query("SELECT x,y,z,level,type FROM blockUpdates WHERE delay <= " . $time . ";");
if($update instanceof SQLite3Result){
$upp = [];
while(($up = $update->fetchArray(SQLITE3_ASSOC)) !== false){
$index = $up["x"] . "." . $up["y"] . "." . $up["z"] . "." . $up["level"] . "." . $up["type"];
if(isset($this->scheduledUpdates[$index])){
$upp[] = [(int) $up["type"], $this->scheduledUpdates[$index]];
unset($this->scheduledUpdates[$index]);
}
}
$this->server->query("DELETE FROM blockUpdates WHERE delay <= " . $time . ";");
foreach($upp as $b){
$this->blockUpdate($b[1], $b[0]);
}
}
}
}
}

View file

@ -1,142 +0,0 @@
<?php
class ChatAPI{
private $server;
function __construct(){
$this->server = ServerAPI::request();
}
public function init(){
$this->server->api->console->register("tell", "<player> <private message ...>", [$this, "commandHandler"]);
$this->server->api->console->register("me", "<action ...>", [$this, "commandHandler"]);
$this->server->api->console->register("say", "<message ...>", [$this, "commandHandler"]);
$this->server->api->console->cmdWhitelist("tell");
$this->server->api->console->cmdWhitelist("me");
$this->server->api->console->alias("msg", "tell");
}
/**
* @param string $cmd
* @param array $params
* @param string $issuer
* @param string $alias
*
* @return string
*/
public function commandHandler($cmd, $params, $issuer, $alias){
$output = "";
switch($cmd){
case "say":
$s = implode(" ", $params);
if(trim($s) == ""){
$output .= "Usage: /say <message>\n";
break;
}
$sender = ($issuer instanceof Player) ? "Server" : ucfirst($issuer);
$this->server->api->chat->broadcast("[$sender] " . $s);
break;
case "me":
$s = implode(" ", $params);
if(trim($s) == ""){
$output .= "Usage: /me <message>\n";
break;
}
if(!($issuer instanceof Player)){
if($issuer === "rcon"){
$sender = "Rcon";
}else{
$sender = ucfirst($issuer);
}
}else{
$sender = $issuer->username;
}
$this->broadcast("* $sender " . implode(" ", $params));
break;
case "tell":
if(!isset($params[0]) or !isset($params[1])){
$output .= "Usage: /$cmd <player> <message>\n";
break;
}
if(!($issuer instanceof Player)){
$sender = ucfirst($issuer);
}else{
$sender = $issuer->username;
}
$n = array_shift($params);
$target = $this->server->api->player->get($n);
if($target instanceof Player){
$target = $target->username;
}else{
$target = strtolower($n);
if($target === "server" or $target === "console" or $target === "rcon"){
$target = "Console";
}else{
return "The player is offline.";
}
}
if(strtolower($target) === strtolower($issuer)){
return "You can't send message to yourself.";
}
$mes = implode(" ", $params);
$output .= "You're whispering to " . $target . ": " . $mes . "\n";
if($target !== "Console" and $target !== "Rcon"){
$this->sendTo(false, $sender . " whispers to you: " . $mes, $target);
}
if($target === "Console" or $sender === "Console"){
console("[INFO] " . $sender . " whispers to " . $target . ": " . $mes);
}
break;
}
return $output;
}
/**
* @param string $message
*/
public function broadcast($message){
$this->send(false, $message);
$this->server->send2Discord($message);
}
/**
* @param mixed $owner Can be either Player object or string username. Boolean false for broadcast.
* @param string $text
* @param $whitelist
* @param $blacklist
*/
public function send($owner, $text, $whitelist = false, $blacklist = false){
$message = [
"player" => $owner,
"message" => $text,
];
if($owner !== false){
if($owner instanceof Player){
if($whitelist === false){
console("[INFO] <" . $owner->username . "> " . $text);
}
}else{
if($whitelist === false){
console("[INFO] <" . $owner . "> " . $text);
}
}
}else{
if($whitelist === false){
console("[INFO] $text");
}
$message["player"] = "";
}
$container = new Container($message, $whitelist, $blacklist);
$this->server->handle("server.chat", $container);
}
/**
* @param string $owner
* @param string $text
* @param mixed $player Can be either Player object or string username. Boolean false for broadcast.
*/
public function sendTo($owner, $text, $player){
$this->send($owner, $text, [$player]);
}
}

View file

@ -1,340 +0,0 @@
<?php
class ConsoleAPI{
private $loop, $server, $event, $help, $cmds, $alias;
public $last;
function __construct(){
$this->help = [];
$this->cmds = [];
$this->alias = [];
$this->server = ServerAPI::request();
$this->last = microtime(true);
}
public function init(){
$this->server->schedule(2, [$this, "handle"], [], true);
if(!defined("NO_THREADS")){
$this->loop = new ConsoleLoop();
}
$this->register("help", "[page|command name]", [$this, "defaultCommands"]);
$this->register("status", "", [$this, "defaultCommands"]);
$this->register("difficulty", "<0|1|2|3>", [$this, "defaultCommands"]);
$this->register("stop", "", [$this, "defaultCommands"]);
$this->register("defaultgamemode", "<mode>", [$this, "defaultCommands"]);
$this->cmdWhitelist("help");
$this->cmdWhitelist("status");
}
/**
* Whitelists a CMD so everyone can issue it - Even non OPs.
* @param string $cmd Command to Whitelist
*/
public function cmdWhitelist($cmd){
$this->server->api->ban->cmdWhitelist[strtolower(trim($cmd))] = true;
}
public function register($cmd, $help, $callback){
if(!is_callable($callback)){
return false;
}
$cmd = strtolower(trim($cmd));
$this->cmds[$cmd] = $callback;
$this->help[$cmd] = $help;
ksort($this->help, SORT_NATURAL | SORT_FLAG_CASE);
}
function __destruct(){
$this->server->deleteEvent($this->event);
if(!defined("NO_THREADS")){
$this->loop->stop();
$this->loop->notify();
//@fclose($this->loop->fp);
usleep(50000);
//$this->loop->join();
}
}
public function alias($alias, $cmd){
$this->alias[strtolower(trim($alias))] = trim($cmd);
return true;
}
public function handle($time){
if(defined("NO_THREADS")){
return;
}
$line = $this->loop->line;
if($line !== false){
$line = preg_replace("#\\x1b\\x5b([^\\x1b]*\\x7e|[\\x40-\\x50])#", "", trim($line));
$this->loop->line = false;
$output = $this->run($line, "console");
if($output != ""){
$mes = explode("\n", trim($output));
foreach($mes as $m){
console("[CMD] " . $m);
}
}
}else{
$this->loop->notify();
}
}
public function run($line = "", $issuer = "console", $alias = false){
if($line != ""){
$output = "";
$end = strpos($line, " ");
if($end === false){
$end = strlen($line);
}
$cmd = strtolower(substr($line, 0, $end));
$params = (string) substr($line, $end + 1);
if(isset($this->alias[$cmd])){
return $this->run($this->alias[$cmd] . ($params !== "" ? " " . $params : ""), $issuer, $cmd);
}
if(preg_match_all('#@([@a-z]{1,})#', $params, $matches, PREG_OFFSET_CAPTURE) > 0){
$offsetshift = 0;
foreach($matches[1] as $selector){
if($selector[0][0] === "@"){ //Escape!
$params = substr_replace($params, $selector[0], $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1);
--$offsetshift;
continue;
}
switch(strtolower($selector[0])){
case "u":
case "player":
case "username":
$p = ($issuer instanceof Player) ? $issuer->username : $issuer;
$params = substr_replace($params, $p, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1);
$offsetshift -= strlen($selector[0]) - strlen($p) + 1;
break;
case "w":
case "world":
$p = ($issuer instanceof Player) ? $issuer->level->getName() : $this->server->api->level->getDefault()->getName();
$params = substr_replace($params, $p, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1);
$offsetshift -= strlen($selector[0]) - strlen($p) + 1;
break;
case "a":
case "all":
if($issuer instanceof Player){
if($this->server->api->ban->isOp($issuer->username)){
$output = "";
foreach($this->server->api->player->getAll() as $p){
$output .= $this->run($cmd . " " . substr_replace($params, $p->username, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1), $issuer, $alias);
}
}else{
$issuer->sendChat("You don't have permissions to use this command.\n");
}
}else{
$output = "";
foreach($this->server->api->player->getAll() as $p){
$output .= $this->run($cmd . " " . substr_replace($params, $p->username, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1), $issuer, $alias);
}
}
return $output;
case "r":
case "random":
$l = [];
foreach($this->server->api->player->getAll() as $p){
if($p !== $issuer){
$l[] = $p;
}
}
if(count($l) === 0){
return;
}
$p = $l[mt_rand(0, count($l) - 1)]->username;
$params = substr_replace($params, $p, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1);
$offsetshift -= strlen($selector[0]) - strlen($p) + 1;
break;
}
}
}
$params = explode(" ", $params);
if(count($params) === 1 and $params[0] === ""){
$params = [];
}
if(($d1 = $this->server->api->dhandle("console.command." . $cmd, ["cmd" => $cmd, "parameters" => $params, "issuer" => $issuer, "alias" => $alias])) === false
or ($d2 = $this->server->api->dhandle("console.command", ["cmd" => $cmd, "parameters" => $params, "issuer" => $issuer, "alias" => $alias])) === false){
if(in_array(strtolower($cmd), array_keys($this->cmds))){
$output = "You don't have permissions to use this command.\n";
}else{
$output = "Command doesn't exist! Use /help\n";
}
}elseif($d1 !== true and (!isset($d2) or $d2 !== true)){
if(isset($this->cmds[$cmd]) and is_callable($this->cmds[$cmd])){
$output = @call_user_func($this->cmds[$cmd], $cmd, $params, $issuer, $alias);
}elseif($this->server->api->dhandle("console.command.unknown", ["cmd" => $cmd, "params" => $params, "issuer" => $issuer, "alias" => $alias]) !== false){
$output = $this->defaultCommands($cmd, $params, $issuer, $alias);
}
}
if($output != "" and ($issuer instanceof Player)){
$issuer->sendChat(trim($output));
}
return $output;
}
}
public function defaultCommands($cmd, $params, $issuer, $alias){
$output = "";
switch($cmd){
case "defaultgamemode":
$gms = [
"0" => SURVIVAL,
"survival" => SURVIVAL,
"s" => SURVIVAL,
"1" => CREATIVE,
"creative" => CREATIVE,
"c" => CREATIVE,
"2" => ADVENTURE,
"adventure" => ADVENTURE,
"a" => ADVENTURE,
"3" => VIEW,
"view" => VIEW,
"viewer" => VIEW,
"spectator" => VIEW,
"v" => VIEW,
];
if(!isset($params[0]) or !isset($gms[strtolower($params[0])])){
$output .= "Usage: /$cmd <mode>\n";
break;
}
$this->server->api->setProperty("gamemode", $gms[strtolower($params[0])]);
$output .= "Default Gamemode is now " . strtoupper($this->server->getGamemode()) . ".\n";
break;
case "status":
if(!($issuer instanceof Player) and $issuer === "console"){
$this->server->debugInfo(true);
}
$info = $this->server->debugInfo();
$output .= "TPS: " . $info["tps"] . ", Memory usage: " . $info["memory_usage"] . " (Peak " . $info["memory_peak_usage"] . ")\n";
break;
case "stop":
$this->loop->stop = true;
$output .= "Stopping the server\n";
$this->server->close();
break;
case "difficulty":
$s = trim(array_shift($params));
if($s === "" or (((int) $s) > 3 and ((int) $s) < 0)){
$output .= "Usage: /difficulty <0|1|2|3>\n";
break;
}
$this->server->api->setProperty("difficulty", (int) $s);
$output .= "Difficulty changed to " . $this->server->difficulty . "\n";
break;
case "?":
if($issuer !== "console" and $issuer !== "rcon"){
break;
}
case "help":
if(isset($params[0]) and !is_numeric($params[0])){
$c = trim(strtolower($params[0]));
if(isset($this->help[$c]) or isset($this->alias[$c])){
$c = isset($this->help[$c]) ? $c : $this->alias[$c];
if($this->server->api->dhandle("console.command." . $c, ["cmd" => $c, "parameters" => [], "issuer" => $issuer, "alias" => false]) === false or $this->server->api->dhandle("console.command", ["cmd" => $c, "parameters" => [], "issuer" => $issuer, "alias" => false]) === false){
break;
}
$output .= "Usage: /$c " . $this->help[$c] . "\n";
break;
}
}
$cmds = [];
foreach($this->help as $c => $h){
if($this->server->api->dhandle("console.command." . $c, ["cmd" => $c, "parameters" => [], "issuer" => $issuer, "alias" => false]) === false or $this->server->api->dhandle("console.command", ["cmd" => $c, "parameters" => [], "issuer" => $issuer, "alias" => false]) === false){
continue;
}
$cmds[$c] = $h;
}
$max = ceil(count($cmds) / 5);
$page = (int) (isset($params[0]) ? min($max, max(1, intval($params[0]))) : 1);
$output .= FORMAT_RED . "-" . FORMAT_RESET . " Showing help page $page of $max (/help <page>) " . FORMAT_RED . "-" . FORMAT_RESET . "\n";
$current = 1;
foreach($cmds as $c => $h){
$curpage = (int) ceil($current / 5);
if($curpage === $page){
$output .= "/$c " . $h . "\n";
}elseif($curpage > $page){
break;
}
++$current;
}
break;
default:
$output .= "Command doesn't exist! Use /help\n";
break;
}
return $output;
}
public static function debug($msg){
console("[DEBUG] ".$msg, true, true, 2);
}
public static function notice($msg){
console("[NOTICE] ".$msg);
}
public static function info($msg){
console("[INFO] ".$msg);
}
public static function warn($msg){
console("[WARNING] ".$msg);
}
public static function error($msg){
console("[ERROR] ".$msg);
}
}
class ConsoleLoop extends Thread{
public $line;
public $stop;
public $base;
public $ev;
public $fp;
public function __construct(){
$this->line = false;
$this->stop = false;
$this->start();
}
public function stop(){
$this->stop = true;
}
public function run(){
if(!extension_loaded("readline")){
$this->fp = fopen("php://stdin", "r");
}
while(!$this->stop){
$this->line = $this->readLine();
$this->synchronized(function($t) {
$this->wait();
$this->line = false;
}, $this);
}
if(!extension_loaded("readline")){
@fclose($this->fp);
}
exit(0);
}
private function readLine(){
if($this->fp){
$line = trim(fgets($this->fp));
}else{
$line = trim(readline(""));
if($line != ""){
readline_add_history($line);
}
}
return $line;
}
}

View file

@ -1,303 +0,0 @@
<?php
class EntityAPI{
public $entities;
private $server;
private $eCnt = 1;
public $serverSpawnAnimals, $serverSpawnMobs;
function __construct(){
$this->entities = [];
$this->server = ServerAPI::request();
$this->serverSpawnAnimals = $this->server->api->getProperty("spawn-animals");
$this->serverSpawnMobs = $this->server->api->getProperty("spawn-mobs");
}
public function init(){
$this->server->api->console->register("summon", "<mob>", [$this, "commandHandler"]);
$this->server->api->console->register("spawnmob", "<mob>", [$this, "commandHandler"]);
$this->server->api->console->register("despawn", "", [$this, "CommandHandler"]);
$this->server->api->console->register("entcnt", "", [$this, "CommandHandler"]);
}
public function commandHandler($cmd, $args, $issuer, $alias){
//todo "MOB_".strtoupper($args[0]);
$mob = [
"chicken" => 10,
"cow" => 11,
"pig" => 12,
"sheep" => 13,
"wolf" => 14,
"villager" => 15,
"mooshroom" => 16,
"zombie" => 32,
"creeper" => 33,
"skeleton" => 34,
"spider" => 35,
"pigman" => 36,
"slime" => 37,
"enderman" => 38,
"silverfish" => 39,
];
$output = "";
switch($cmd){
case "entcnt":
return "Total amount of entities: ". count($this->entities);
case "summon":
case "spawnmob":
if(!($issuer instanceof Player)){
return "Please run this command in-game.";
}
if((count($args) < 1) or (count($args) > 3)){
return "Usage: /$cmd <mob> [amount] [baby]";
}
if(is_int($args[0])) $type = $args[0];
elseif(isset($mob[strtolower($args[0])])) $type = $mob[strtolower($args[0])];
else return "Unknown mob.";
if($type < 10 || $type > 39){
return "Unknown mob.";
}
$mobName = ucfirst(array_flip($mob)[$type]);
if(((isset($args[1]) && strtolower($args[1]) === "baby") || (isset($args[2]) && strtolower($args[2]) === "baby")) && !Utils::in_range($type, 10, 13)){
return "$mobName cannot be a baby!";
}
$x = round($issuer->entity->x, 2, PHP_ROUND_HALF_UP);
$y = round($issuer->entity->y, 2, PHP_ROUND_HALF_UP);
$z = round($issuer->entity->z, 2, PHP_ROUND_HALF_UP);
$level = $issuer->entity->level;
$pos = new Position($x, $y, $z, $level);
if(count($args) === 1){//summon <mob>
$this->summon($pos, ENTITY_MOB, $type);
return "$mobName spawned in $x, $y, $z.";
}
elseif(is_numeric($args[1])){//summon <mob> [amount]
$amount = (int) $args[1];
if($amount > 100){
return "Cannot spawn > 100 mobs";
}
$isBaby = false;
if(isset($args[2]) and strtolower($args[2]) === 'baby'){//summon <mob> [amount] [baby]
$isBaby = true;
}
for($cnt = $amount; $cnt > 0; --$cnt){
$this->summon($pos, ENTITY_MOB, $type, ["IsBaby" => $isBaby]);
}
return "$amount ".($isBaby === 1 ? "Baby" : "")." $mobName(s) spawned in $x, $y, $z.";
}
elseif(strtolower($args[1]) == "baby"){//summon <mob> [baby]
$this->summon($pos, ENTITY_MOB, $type, ["IsBaby" => 1]);
return "Baby $mobName spawned in $x, $y, $z.";
}
break;
case "despawn":
$cnt = 0;
if(!isset($args[0])){
return "/despawn <all|mobs|objects|items|fallings|minecarts>";
}
$despawnclass = 0;
$despawntype = 0;
switch($args[0]){
case "all":
foreach($this->entities as $entity){
if($entity instanceof Entity && !$entity->isPlayer()){
$entity->close();
++$cnt;
}
}
break;
case "minecarts":
$despawntype = OBJECT_MINECART;
break;
case "mobs":
$despawnclass = ENTITY_MOB;
break;
case "objects":
$despawnclass = ENTITY_OBJECT;
break;
case "items":
$despawnclass = ENTITY_ITEM;
break;
case "fallings":
$despawnclass = ENTITY_FALLING;
break;
}
if($despawnclass){
foreach($this->entities as $entity){
if($entity instanceof Entity && !$entity->isPlayer() && $entity->class === $despawnclass){
$entity->close();
++$cnt;
}
}
}
if($despawntype){
foreach($this->entities as $entity){
if($entity instanceof Entity && !$entity->isPlayer() && $entity->type === $despawntype){
$entity->close();
++$cnt;
}
}
}
return "$cnt entities have been despawned!";
}
return $output;
}
public function summon(Position $pos, $class, $type, array $data = []){
$entity = $this->add($pos->level, $class, $type, [
"x" => $pos->x,
"y" => $pos->y,
"z" => $pos->z
] + $data);
$this->spawnToAll($entity, $pos->level);
}
public function add(Level $level, $class, $type = 0, $data = []){
$eid = $this->eCnt++;
$efl = EntityRegistry::$entityList->getEntityFromTypeAndClass($type, $class);
if($efl instanceof PropertyEntity){
$class = $efl->getEntityName();
$this->entities[$eid] = new $class($level, $eid, $efl->getEntityClass(), $efl->getEntityType(), $data);
}else{
$this->entities[$eid] = new Entity($level, $eid, $class, $type, $data);
}
$level->entityList[$eid] = &$this->entities[$eid];
$this->server->handle("entity.add", $this->entities[$eid]);
return $this->entities[$eid];
}
public function spawnToAll(Entity $e){
foreach($this->server->api->player->getAll($e->level) as $player){
if($player->eid !== false and $player->eid !== $e->eid and $e->class !== ENTITY_PLAYER and $e instanceof Entity){
$e->spawn($player);
}
}
}
public function get($eid){
return $this->entities[$eid] ?? false;
}
public function remove($eid){
if(isset($this->entities[$eid])){
$this->entities[$eid]->closed = true;
if($this->entities[$eid]->isPlayer()){
$pk = new RemovePlayerPacket;
$pk->eid = $eid;
$pk->clientID = 0;
$this->server->api->player->broadcastPacket($this->server->api->player->getAll(), $pk);
}else{
$pk = new RemoveEntityPacket;
$pk->eid = $eid;
$this->server->api->player->broadcastPacket($this->entities[$eid]->level->players, $pk);
}
$this->server->api->dhandle("entity.remove", $this->entities[$eid]);
unset($this->entities[$eid]->level->entityList[$eid]);
unset($this->entities[$eid]);
$this->server->query("DELETE FROM entities WHERE EID = " . $eid . ";");
}
}
public function updateRadius(Position $center, $radius = 15, $class = false){
$this->server->query("UPDATE entities SET hasUpdate = 1 WHERE level = '" . $center->level->getName() . "' " . ($class !== false ? "AND class = $class " : "") . "AND abs(x - {$center->x}) <= $radius AND abs(y - {$center->y}) <= $radius AND abs(z - {$center->z}) <= $radius;");
}
public function getRadius(Position $center, $radius = 15, $class = false){
$entities = [];
$l = $this->server->query("SELECT EID FROM entities WHERE level = '" . $center->level->getName() . "' " . ($class !== false ? "AND class = $class " : "") . "AND abs(x - {$center->x}) <= $radius AND abs(y - {$center->y}) <= $radius AND abs(z - {$center->z}) <= $radius;");
if($l !== false and $l !== true){
while(($e = $l->fetchArray(SQLITE3_ASSOC)) !== false){
$e = $this->get($e["EID"]);
if($e instanceof Entity){
$entities[$e->eid] = $e;
}
}
}
return $entities;
}
public function heal($eid, $heal, $cause){
$this->harm($eid, -$heal, $cause);
}
public function harm($eid, $attack, $cause, $force = false){
$e = $this->get($eid);
if($e === false or $e->dead === true){
return false;
}
$e->setHealth($e->getHealth() - $attack, $cause, $force);
}
public function dropRawPos(Position $pos, $item, $speedX, $speedY, $speedZ){
if($item->getID() === AIR or $item->count <= 0){
return;
}
$data = [
"x" => $pos->x,
"y" => $pos->y,
"z" => $pos->z,
"level" => $pos->level,
"speedX" => $speedX,
"speedY" => $speedY,
"speedZ" => $speedZ,
"item" => $item,
];
if($this->server->api->handle("item.drop", $data) !== false){
for($count = $item->count; $count > 0;){
$item->count = min($item->getMaxStackSize(), $count);
$count -= $item->count;
$e = $this->add($pos->level, ENTITY_ITEM, $item->getID(), $data);
$this->spawnToAll($e);
$this->server->api->handle("entity.motion", $e);
}
}
}
public function drop(Position $pos, Item $item){
if($item->getID() === AIR or $item->count <= 0){
return;
}
$data = [
"x" => $pos->x + mt_rand(-10, 10) / 50,
"y" => $pos->y + 0.19,
"z" => $pos->z + mt_rand(-10, 10) / 50,
"level" => $pos->level,
"speedX" => lcg_value() * 0.2 - 0.1,
"speedY" => 0.2,
"speedZ" => lcg_value() * 0.2 - 0.1,
"item" => $item,
];
if($this->server->api->handle("item.drop", $data) !== false){
for($count = $item->count; $count > 0;){
$item->count = min($item->getMaxStackSize(), $count);
$count -= $item->count;
$e = $this->add($pos->level, ENTITY_ITEM, $item->getID(), $data);
$this->spawnToAll($e);
$this->server->api->handle("entity.motion", $e);
}
}
}
public function spawnAll(Player $player){
foreach($this->getAll($player->level) as $e){
if($e->class !== ENTITY_PLAYER){
$e->spawn($player);
}
}
}
public function getAll($level = null){
if($level instanceof Level){
return $level->entityList;
}
return $this->entities;
}
}

View file

@ -1,266 +0,0 @@
<?php
class LevelAPI{
/**
* @var Level[]
*/
public $levels;
private $server, $default;
public static $defaultLevelType = "DEFAULT";
public function __construct(){
$this->server = ServerAPI::request();
$this->levels = [];
}
public function init(){
$this->server->api->console->register("seed", "[world]", [$this, "commandHandler"]);
$this->server->api->console->register("save-all", "", [$this, "commandHandler"]);
$this->server->api->console->register("save-on", "", [$this, "commandHandler"]);
$this->server->api->console->register("save-off", "", [$this, "commandHandler"]);
$this->server->api->console->register("setwspawn", "Set the spawn position for your current world. ", [$this, "commandHandler"]);
$this->server->api->console->register("place", "", [$this, "commandHandler"]);
$this->default = $this->server->api->getProperty("level-name");
if($this->loadLevel($this->default) === false){
$this->generateLevel($this->default, $this->server->seed);
$this->loadLevel($this->default);
}
$this->server->spawn = $this->getDefault()->getSafeSpawn();
}
public function loadLevel($name){
if($this->get($name) !== false){
return true;
}elseif($this->levelExists($name) === false){
console("[NOTICE] Level \"" . $name . "\" not found");
return false;
}
$path = DATA_PATH . "worlds/" . $name . "/";
console("[INFO] Preparing level \"" . $name . "\"");
$level = new PMFLevel($path . "level.pmf");
if(!$level->isLoaded){
console("[ERROR] Could not load level \"" . $name . "\"");
return false;
}
$entities = new Config($path . "entities.yml", CONFIG_YAML);
if(file_exists($path . "tileEntities.yml")){
@rename($path . "tileEntities.yml", $path . "tiles.yml");
}
$tiles = new Config($path . "tiles.yml", CONFIG_YAML);
$blockUpdates = new Config($path . "bupdates.yml", CONFIG_YAML);
$this->levels[$name] = new Level($level, $entities, $tiles, $blockUpdates, $name);
foreach($entities->getAll() as $entity){
if(!isset($entity["id"])){
break;
}
$entity["x"] = $entity["Pos"][0];
$entity["y"] = $entity["Pos"][1];
$entity["z"] = $entity["Pos"][2];
$entity["yaw"] = $entity["Rotation"][0];
$entity["pitch"] = $entity["Rotation"][1];
if($entity["id"] === 64){ //Item Drop
$e = $this->server->api->entity->add($this->levels[$name], ENTITY_ITEM, $entity["Item"]["id"], [
"meta" => $entity["Item"]["Damage"],
"stack" => $entity["Item"]["Count"],
"x" => $entity["Pos"][0],
"y" => $entity["Pos"][1],
"z" => $entity["Pos"][2],
"yaw" => $entity["Rotation"][0],
"pitch" => $entity["Rotation"][1],
]);
}elseif($entity["id"] === FALLING_SAND){
$e = $this->server->api->entity->add($this->levels[$name], ENTITY_FALLING, $entity["id"], $entity);
//$e->setPosition(new Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]);
$e->setHealth($entity["Health"]);
}elseif(Utils::getEntityTypeByID($entity["id"]) === ENTITY_OBJECT){ //Object
$e = $this->server->api->entity->add($this->levels[$name], ENTITY_OBJECT, $entity["id"], $entity);
//$e->setPosition(new Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]);
$e->setHealth(1);
}else{
$e = $this->server->api->entity->add($this->levels[$name], ENTITY_MOB, $entity["id"], $entity);
//$e->setPosition(new Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]);
$e->setHealth($entity["Health"]);
}
}
foreach($tiles->getAll() as $tile){
if(!isset($tile["id"])){
break;
}
$t = $this->server->api->tile->add($this->levels[$name], $tile["id"], $tile["x"], $tile["y"], $tile["z"], $tile);
}
$timeu = microtime(true);
foreach($blockUpdates->getAll() as $bupdate){
$this->server->api->block->scheduleBlockUpdate(new Position((int) $bupdate["x"], (int) $bupdate["y"], (int) $bupdate["z"], $this->levels[$name]), (float) $bupdate["delay"], (int) $bupdate["type"]);
}
return true;
}
public function get($name){
if(isset($this->levels[$name])){
return $this->levels[$name];
}
return false;
}
public function levelExists($name){
if($name === ""){
return false;
}
$path = DATA_PATH . "worlds/" . $name . "/";
if($this->get($name) === false and !file_exists($path . "level.pmf")){
$level = new LevelImport($path);
if($level->import() === false){
return false;
}
}
return true;
}
public static function createGenerator($type, $options = []){
return match($type){
"FLAT" => new SuperflatGenerator(),
"EXPERIMENTAL" => new ExperimentalGenerator($options),
"HELL", "NETHER" => new HellGenerator($options),
"END" => new EndGenerator($options),
default => new NormalGenerator($options)
};
}
public function generateLevel($name, $seed = false, $generator = false){
if($this->levelExists($name)){
return false;
}
$options = [];
if($this->server->api->getProperty("generator-settings") !== false and trim($this->server->api->getProperty("generator-settings")) != ""){
$options["preset"] = $this->server->api->getProperty("generator-settings");
}
if($generator !== false and class_exists($generator)){
$generator = new $generator($options);
}else{
$type = strtoupper($this->server->api->getProperty("level-type"));
$generator = $this->createGenerator($type, $options);
}
$gen = new WorldGenerator($generator, $name, $seed === false ? Utils::readInt(Utils::getRandomBytes(4, false)) : (int) $seed);
$gen->generate();
$gen->close();
return true;
}
public function getDefault(){
return $this->levels[$this->default];
}
public function commandHandler($cmd, $params, $issuer, $alias){
$output = "";
switch($cmd){
case "place":
if(!isset($params[0]) or $params[0] == "") return "/$cmd <feature class>";
$class = $params[0];
(new $class())->build($issuer->entity->level, $issuer->entity->x, $issuer->entity->y, $issuer->entity->z);
break;
case "setwspawn":
if(!($issuer instanceof Player)){
return ("Please run this command in-game. ");
}
$issuer->entity->level->setSpawn(new Vector3($issuer->entity->x, $issuer->entity->y, $issuer->entity->z));
return ("Spawn set!");
break;
case "save-all":
$output .= "Saving...\n";
$save = $this->server->saveEnabled;
$this->server->saveEnabled = true;
$this->saveAll();
$this->server->saveEnabled = $save;
$output .= "Saved the world";
break;
case "save-on":
$this->server->saveEnabled = true;
break;
case "save-off":
$this->server->saveEnabled = false;
break;
case "seed":
if(!isset($params[0]) and ($issuer instanceof Player)){
$output .= "Seed: " . $issuer->level->getSeed() . "\n";
}elseif(isset($params[0])){
if(($lv = $this->server->api->level->get(trim(implode(" ", $params)))) !== false){
$output .= "Seed: " . $lv->getSeed() . "\n";
}
}else{
$output .= "Seed: " . $this->server->api->level->getDefault()->getSeed() . "\n";
}
}
return $output;
}
public function saveAll(){
foreach($this->levels as $level){
$level->save();
}
}
public function handle($data, $event){
switch($event){
}
}
public function __destruct(){
$this->saveAll();
foreach($this->levels as $level){
$this->unloadLevel($level, true);
}
}
public function unloadLevel(Level $level, $force = false){
$name = $level->getName();
if($name === $this->default and $force !== true){
return false;
}
console("[INFO] Unloading level \"" . $name . "\"");
$level->nextSave = PHP_INT_MAX;
$level->save();
foreach($this->server->api->player->getAll($level) as $player){
$player->teleport($this->server->spawn);
}
foreach($this->server->api->entity->getAll($level) as $entity){
if($entity->class !== ENTITY_PLAYER){
$entity->close();
}
}
foreach($this->server->api->tile->getAll($level) as $tile){
$tile->close();
}
$level->close();
unset($this->levels[$name]);
return true;
}
public function getSpawn(){
return $this->server->spawn;
}
public function loadMap(){
if($this->mapName !== false and trim($this->mapName) !== ""){
if(!file_exists($this->mapDir . "level.pmf")){
$level = new LevelImport($this->mapDir);
$level->import();
}
$this->level = new PMFLevel($this->mapDir . "level.pmf");
console("[INFO] Preparing level \"" . $this->level->getData("name") . "\"");
$this->time = (int) $this->level->getData("time");
$this->seed = (int) $this->level->getData("seed");
$this->spawn = $this->level->getSpawn();
}
}
public function getAll(){
return $this->levels;
}
}

View file

@ -1,501 +0,0 @@
<?php
class PlayerAPI{
private $server;
function __construct(){
$this->server = ServerAPI::request();
}
public function init(){
$this->server->schedule(20 * 15, [$this, "handle"], 1, true, "server.regeneration");
$this->server->addHandler("player.death", [$this, "handle"], 1);
$this->registerCmd("list");
$this->registerCmd("kill", "<player>");
$this->registerCmd("gamemode", "<mode> [player]", [$this, "commandHandler"]);
$this->registerCmd("tp", "[target player] <destination player|w:world> OR /tp [target player] <x> <y> <z>");
$this->registerCmd("spawnpoint", "[player] [x] [y] [z]");
$this->registerCmd("spawn");
$this->registerCmd("ping");
$this->registerCmd("loc");
$this->server->api->console->alias("lag", "ping");
$this->server->api->console->alias("gm", "gamemode");
$this->server->api->console->alias("who", "list");
$this->server->api->console->alias("suicide", "kill");
$this->server->api->console->alias("tppos", "tp");
$this->server->api->console->alias("xyz", "loc");
$this->server->api->console->alias("coords", "loc");
$this->server->api->console->cmdWhitelist("list");
$this->server->api->console->cmdWhitelist("ping");
$this->server->api->console->cmdWhitelist("spawn");
$this->server->api->console->cmdWhitelist("loc");
$this->server->preparedSQL->selectPlayersToHeal = $this->server->database->prepare("SELECT EID FROM entities WHERE class = " . ENTITY_PLAYER . " AND health < 20;");
}
public function registerCmd($cmd, $help = ""){
$this->server->api->console->register($cmd, $help, [$this, "commandHandler"]);
}
public function handle($data, $event){
switch($event){
case "server.regeneration":
if($this->server->difficulty === 0){
$result = $this->server->preparedSQL->selectPlayersToHeal->execute();
if($result !== false){
while(($player = $result->fetchArray()) !== false){
if(($player = $this->server->api->entity->get($player["EID"])) !== false){
if($player->getHealth() <= 0){
continue;
}
$player->setHealth(min(20, $player->getHealth() + $data), "regeneration");
}
}
return true;
}
}
break;
case "player.death":
if(is_numeric($data["cause"])){
$e = $this->server->api->entity->get($data["cause"]);
if($e instanceof Entity){
switch($e->class){
case ENTITY_PLAYER:
$message = " was killed by " . $e->name;
break;
default:
$message = " was killed by {$e->getName()}";
break;
}
}
}else{
switch($data["cause"]){
case "cactus":
$message = " was pricked to death";
break;
case "lava":
$message = " tried to swim in lava";
break;
case "fire":
$message = " went up in flames";
break;
case "burning":
$message = " burned to death";
break;
case "suffocation":
$message = " suffocated in a wall";
break;
case "water":
$message = " drowned";
break;
case "void":
$message = " fell out of the world";
break;
case "fall":
$message = " hit the ground too hard";
break;
case "explosion":
$message = " blew up";
break;
default:
$message = " died";
break;
}
}
$this->server->api->chat->broadcast($data["player"]->username . $message);
return true;
break;
}
}
public function commandHandler($cmd, $args, $issuer, $alias){
$output = "";
switch($cmd){
case "spawnpoint":
if(!($issuer instanceof Player)){
return "Please run this command in-game.";
}
if(count($args) === 1 or count($args) === 4){
$target = $this->server->api->player->get(array_shift($args));
}else{
$target = $issuer;
}
if(!($target instanceof Player)){
return "That player cannot be found.";
}
if(count($args) === 3){
$spawn = new Position(floatval(array_shift($args)), floatval(array_shift($args)), floatval(array_shift($args)), $issuer->level);
}else{
$spawn = new Position($issuer->entity->x, $issuer->entity->y, $issuer->entity->z, $issuer->entity->level);
}
$target->setSpawn($spawn);
return "Spawnpoint set correctly!\n";
case "spawn":
if(!($issuer instanceof Player)){
return "Please run this command in-game.";
}
$issuer->teleport($this->server->spawn);
return "You were teleported to the spawn.";
case "ping":
if(!($issuer instanceof Player)){
return "Please run this command in-game.";
}
return "ping " . round($issuer->getLag(), 2) . "ms, packet loss " . round($issuer->getPacketLoss() * 100, 2) . "%, " . round($issuer->getBandwidth() / 1024, 2) . " KB/s\n";
case "gamemode":
$player = false;
$setgm = false;
$gms = [
"0" => SURVIVAL,
"survival" => SURVIVAL,
"s" => SURVIVAL,
"1" => CREATIVE,
"creative" => CREATIVE,
"c" => CREATIVE,
"2" => ADVENTURE,
"adventure" => ADVENTURE,
"a" => ADVENTURE,
"3" => VIEW,
"view" => VIEW,
"viewer" => VIEW,
"spectator" => VIEW,
"v" => VIEW,
];
if($issuer instanceof Player){
$player = $issuer;
}
if(count($args) == 1){
$setgm = $args[0];
}elseif(isset($args[1])){
if($this->server->api->player->get($args[1]) instanceof Player){
$player = $this->server->api->player->get($args[1]);
$setgm = $args[0];
}elseif($this->server->api->player->get($args[0]) instanceof Player){
$player = $this->server->api->player->get($args[0]);
$setgm = $args[1];
}else{
return "Usage: /$cmd <mode> [player] or /$cmd [player] <mode>\n";
}
}
if(!($player instanceof Player) or !isset($gms[strtolower($setgm)])){
return "Usage: /$cmd <mode> [player] or /$cmd [player] <mode>\n";
}
if($player->setGamemode($gms[strtolower($setgm)])){
return "Gamemode of " . $player->username . " changed to " . $player->getGamemode() . "\n";
}
break;
case "tp":
if(count($args) <= 2 or substr($args[0], 0, 2) === "w:" or substr($args[1], 0, 2) === "w:"){
if((!isset($args[1]) or substr($args[0], 0, 2) === "w:") and isset($args[0]) and ($issuer instanceof Player)){
$name = $issuer->username;
$target = implode(" ", $args);
}elseif(isset($args[1]) and isset($args[0])){
$name = array_shift($args);
$target = implode(" ", $args);
}else{
return "Usage: /$cmd [target player] <destination player>\n";
}
if($this->teleport($name, $target) !== false){
return "\"$name\" teleported to \"$target\"\n";
}else{
return "Couldn't teleport.\n";
}
}else{
if(!isset($args[3]) and isset($args[2]) and isset($args[1]) and isset($args[0]) and ($issuer instanceof Player)){
$name = $issuer->username;
$x = $args[0];
$y = $args[1];
$z = $args[2];
}elseif(isset($args[3]) and isset($args[2]) and isset($args[1]) and isset($args[0])){
$name = $args[0];
$x = $args[1];
$y = $args[2];
$z = $args[3];
}else{
return "Usage: /$cmd [player] <x> <y> <z>\n";
}
if($this->tppos($name, $x, $y, $z)){
return "\"$name\" teleported to ($x, $y, $z)\n";
}else{
return "Couldn't teleport.\n";
}
}
case "kill":
case "suicide":
if(!isset($args[0]) and ($issuer instanceof Player)){
$player = $issuer;
}else{
$player = $this->get($args[0]);
}
if($player instanceof Player){
$player->entity->harm(PHP_INT_MAX, "console", true);
return "Ouch. That looks like it hurt.\n";
}else{
return "Usage: /$cmd [player]\n";
}
break;
case "list":
$output .= "There are " . count($this->server->clients) . "/" . $this->server->maxClients . " players online:\n";
if(count($this->server->clients) == 0){
break;
}
foreach($this->server->clients as $c){
$output .= $c->username . ", ";
}
return substr($output, 0, -2) . "\n";
break;
case "loc":
if(!($issuer instanceof Player)) return "Please run this command in-game.";
$x = round($issuer->entity->x, 1, PHP_ROUND_HALF_UP);
$y = round($issuer->entity->y, 1, PHP_ROUND_HALF_UP);
$z = round($issuer->entity->z, 1, PHP_ROUND_HALF_UP);
$level = $issuer->entity->level->getName();
$compass = [0 => "X+", 1 => "Z+", 2 => "X-", 3 => "Z-", null => "null"];
$direction = $compass[$issuer->entity->getDirection()];
return "Your coordinates: X: $x, Y: $y, Z: $z, world: $level.\nDirection: $direction";
}
return $output;
}
public function get($name, $alike = true, $multiple = false){
$name = trim(strtolower($name));
if($name === ""){
return false;
}
$query = $this->server->query("SELECT ip,port,name FROM players WHERE name " . ($alike === true ? "LIKE '" . $name . "%'" : "= '" . $name . "'") . ";");
$players = [];
if($query !== false and $query !== true){
while(($d = $query->fetchArray(SQLITE3_ASSOC)) !== false){
$CID = PocketMinecraftServer::clientID($d["ip"], $d["port"]);
if(isset($this->server->clients[$CID])){
$players[$CID] = $this->server->clients[$CID];
if($multiple === false and $d["name"] === $name){
return $players[$CID];
}
}
}
}
if($multiple === false){
if(count($players) > 0){
return array_shift($players);
}else{
return false;
}
}else{
return $players;
}
}
public function teleport(&$name, &$target){
if(substr($target, 0, 2) === "w:"){
$lv = $this->server->api->level->get(substr($target, 2));
if($lv instanceof Level){
$origin = $this->get($name);
if($origin instanceof Player){
$name = $origin->username;
return $origin->teleport($lv->getSafeSpawn());
}
}else{
return false;
}
}
$player = $this->get($target);
if(($player instanceof Player) and ($player->entity instanceof Entity)){
$target = $player->username;
$origin = $this->get($name);
if($origin instanceof Player){
$name = $origin->username;
return $origin->teleport($player->entity);
}
}
return false;
}
public function tppos(&$name, &$x, &$y, &$z){
$player = $this->get($name);
if(($player instanceof Player) and ($player->entity instanceof Entity)){
$name = $player->username;
$x = $x[0] === "~" ? $player->entity->x + floatval(substr($x, 1)) : floatval($x);
$y = $y[0] === "~" ? $player->entity->y + floatval(substr($y, 1)) : floatval($y);
$z = $z[0] === "~" ? $player->entity->z + floatval(substr($z, 1)) : floatval($z);
$player->teleport(new Vector3($x, $y, $z));
return true;
}
return false;
}
public function broadcastPacket(array $players, RakNetDataPacket $packet){
foreach($players as $p){
$p->dataPacket(clone $packet);
}
}
public function online(){
$o = [];
foreach($this->server->clients as $p){
if($p->auth === true){
$o[] = $p->username;
}
}
return $o;
}
public function add($CID){
if(isset($this->server->clients[$CID])){
$player = $this->server->clients[$CID];
$player->data = $this->getOffline($player->username);
$player->gamemode = $player->data->get("gamemode");
if(($player->level = $this->server->api->level->get($player->data->get("position")["level"])) === false){
$player->level = $this->server->api->level->getDefault();
$player->data->set("position", [
"level" => $player->level->getName(),
"x" => $player->level->getSpawn()->x,
"y" => $player->level->getSpawn()->y,
"z" => $player->level->getSpawn()->z,
]);
}
$this->server->query("INSERT OR REPLACE INTO players (CID, ip, port, name) VALUES (" . $player->CID . ", '" . $player->ip . "', " . $player->port . ", '" . strtolower($player->username) . "');");
}
}
public function getOffline($name, $create = true){
$iname = strtolower($name);
$default = [
"caseusername" => $name,
"position" => [
"level" => $this->server->spawn->level->getName(),
"x" => $this->server->spawn->x,
"y" => $this->server->spawn->y,
"z" => $this->server->spawn->z,
],
"spawn" => [
"level" => $this->server->spawn->level->getName(),
"x" => $this->server->spawn->x,
"y" => $this->server->spawn->y,
"z" => $this->server->spawn->z,
],
"inventory" => array_fill(0, PLAYER_SURVIVAL_SLOTS, [AIR, 0, 0]),
"hotbar" => [0, -1, -1, -1, -1, -1, -1, -1, -1],
"armor" => array_fill(0, 4, [AIR, 0]),
"gamemode" => $this->server->gamemode,
"health" => 20,
"lastIP" => "",
"lastID" => 0,
"achievements" => [],
];
if(!file_exists(DATA_PATH . "players/" . $iname . ".yml")){
if($this->server->extraprops->get("save-player-data") && $create){
console("[NOTICE] Player data not found for \"" . $iname . "\", creating new profile");
$data = new Config(DATA_PATH . "players/" . $iname . ".yml", CONFIG_YAML, $default);
$data->save();
}else{
return false;
}
}
$data = new Config(DATA_PATH . "players/" . $iname . ".yml", CONFIG_YAML, $default);
if(($data->get("gamemode") & 0x01) === 1){
$data->set("health", 20);
}
$this->server->handle("player.offline.get", $data);
return $data;
}
public function spawnAllPlayers(Player $player){
foreach($this->getAll() as $p){
if($p !== $player and ($p->entity instanceof Entity)){
$p->entity->spawn($player);
if($p->level !== $player->level){
$pk = new MoveEntityPacket_PosRot;
$pk->eid = $p->entity->eid;
$pk->x = -256;
$pk->y = 128;
$pk->z = -256;
$pk->yaw = 0;
$pk->pitch = 0;
$player->dataPacket($pk);
}
}
}
}
public function getAll($level = null){
if($level instanceof Level){
$clients = [];
$l = $this->server->query("SELECT EID FROM entities WHERE level = '" . $level->getName() . "' AND class = '" . ENTITY_PLAYER . "';");
if($l !== false and $l !== true){
while(($e = $l->fetchArray(SQLITE3_ASSOC)) !== false){
$e = $this->getByEID($e["EID"]);
if($e instanceof Player){
$clients[$e->CID] = $e;
}
}
} return $clients;
}
return $this->server->clients;
}
public function getByEID($eid){
$eid = (int) $eid;
$CID = $this->server->query("SELECT ip,port FROM players WHERE EID = '" . $eid . "';", true);
$CID = is_array($CID) ? PocketMinecraftServer::clientID($CID["ip"], $CID["port"]) : false;
if(isset($this->server->clients[$CID])){
return $this->server->clients[$CID];
}
return false;
}
public function spawnToAllPlayers(Player $player){
foreach($this->getAll() as $p){
if($p !== $player and ($p->entity instanceof Entity) and ($player->entity instanceof Entity)){
$player->entity->spawn($p);
if($p->level !== $player->level){
$pk = new MoveEntityPacket_PosRot;
$pk->eid = $player->entity->eid;
$pk->x = -256;
$pk->y = 128;
$pk->z = -256;
$pk->yaw = 0;
$pk->pitch = 0;
$p->dataPacket($pk);
}
}
}
}
public function remove($CID){
if(isset($this->server->clients[$CID])){
$player = $this->server->clients[$CID];
$player->close();
if($player->username != "" and ($player->data instanceof Config)){
$this->saveOffline($player->data);
}
$this->server->query("DELETE FROM players WHERE name = '" . $player->username . "';");
$this->server->api->entity->remove($player->eid);
unset($this->server->clients[$CID]);
if($player->entity instanceof Entity){
unset($player->entity->player);
//unset($player->entity);
}
$player = null;
unset($player);
}
}
public function saveOffline(Config $data){
if($this->server->extraprops->get("save-player-data")){
$this->server->handle("player.offline.save", $data);
$data->save();
}
}
}

View file

@ -1,313 +0,0 @@
<?php
class PluginAPI extends stdClass{
private $server;
public $plugins = []; //specially for DevTools
private $randomNonce;
public function __construct(){
$this->server = ServerAPI::request();
$this->randomNonce = Utils::getRandomBytes(16, false);
$this->server->api->console->register("plugins", "", [$this, "commandHandler"]);
$this->server->api->console->register("version", "", [$this, "commandHandler"]);
$this->server->api->console->cmdWhitelist("version");
if($this->server->extraprops->get("query-plugins")){ //allow players to also view plugins ingame, since query makes names public
$this->server->api->console->cmdWhitelist("plugins");
}
$this->server->api->console->alias("pl", "plugins");
$this->server->api->console->alias("ver", "version");
$this->server->api->console->alias("about", "version");
}
public function commandHandler($cmd, $params, $issuer, $alias){
$output = "";
switch($cmd){
case "plugins":
$output = "Plugins (" . count($this->plugins) . "): ";
foreach($this->getList() as $plugin){
$output .= $plugin["name"] . " v" . $plugin["version"] . ", ";
}
$output = $output === "Plugins (0): " ? "No plugins installed." : substr($output, 0, -2);
break;
case "version":
$output = "This server is running NostalgiaCore version: " . MAJOR_VERSION .", PHP version: ". PHP_VERSION . "\n(Implementing API version #" . CURRENT_API_VERSION . " for Minecraft: PE " . CURRENT_MINECRAFT_VERSION . ")";
if(GIT_COMMIT !== str_repeat("00", 20)){
$output .= " (git " . GIT_COMMIT . ")";
}
break;
}
return $output;
}
public function getList(){
$list = [];
foreach($this->plugins as $p){
$list[] = $p[1];
}
return $list;
}
public function __destruct(){
foreach($this->plugins as $p){
if(method_exists($p[0], "__destruct")){$p[0]->__destruct();};
}
unset($this->plugins);
}
public function getAll(){
return $this->plugins;
}
public function createConfig(Plugin $plugin, $default = []){
$p = $this->get($plugin);
if($p === false){
return false;
}
$path = $this->configPath($plugin);
$cnf = new Config($path . "config.yml", CONFIG_YAML, $default);
$cnf->save();
return $path;
}
public function get($identifier){
if($identifier instanceof Plugin){
foreach($this->plugins as $p){
if($p[0] === $identifier){
return $p;
}
}
return false;
}
if(isset($this->plugins[$identifier])){
return $this->plugins[$identifier];
}
return false;
}
public function configPath(Plugin $plugin){
$p = $this->get($plugin);
$identifier = $this->getIdentifier($p[1]["name"], $p[1]["author"]);
if($p === false){
return false;
}
$path = $this->pluginsPath() . $p[1]["name"] . DIRECTORY_SEPARATOR;
$this->plugins[$identifier][1]["path"] = $path;
if(!file_exists($path)){
mkdir($path, 0777);
}
return $path;
}
public function pluginsPath(){
$path = join(DIRECTORY_SEPARATOR, [DATA_PATH . "plugins", ""]);
if(!file_exists($path)){
mkdir($path, 0777);
}
return $path;
}
public function readYAML($file){
return yaml_parse(preg_replace("#^([ ]*)([a-zA-Z_]{1}[^\:]*)\:#m", "$1\"$2\":", file_get_contents($file)));
}
public function writeYAML($file, $data){
return file_put_contents($file, yaml_emit($data, YAML_UTF8_ENCODING));
}
public function init(){
$this->server->event("server.start", [$this, "initAll"]);
$this->loadAll();
}
private function loadAll(){
$pharCnt = 0;
$dir = dir($this->pluginsPath());
while(false !== ($file = $dir->read())){
if($file[0] !== "."){
$ext = strtolower(substr($file, -3));
$ext2 = strtolower(substr($file, -4));
if($ext === "php" or $ext === "pmf"){
$this->load($dir->path . $file);
}
if($ext2 === "phar"){
++$pharCnt;
$pluginInfo = []; //TODO: A PluginInfo class?
$filePath = $this->pluginsPath().$file;
$p = new Phar($this->pluginsPath().$file, 0);
foreach (new RecursiveIteratorIterator($p) as $file) {
$name = $file->getFileName();
$content = file_get_contents($file->getPathName());
if($name === "plugin.cfg"){
$pluginInfo = PharUtils::readMainConfig($content);
break;
}
}
console("[INFO] Loading PHAR plugin \"".FORMAT_GREEN.$pluginInfo["name"].FORMAT_RESET."\" ".FORMAT_AQUA.$pluginInfo["version"].FORMAT_RESET." by ".FORMAT_AQUA.$pluginInfo["author"].FORMAT_RESET);
$aver = CURRENT_API_VERSION;
if(!in_array((string) CURRENT_API_VERSION, $pluginInfo["api"])){
if(is_array($pluginInfo)) $s = implode(",",$pluginInfo["api"]);
else $s = $pluginInfo["api"];
console("[WARNING] API is not the same as Core, might cause bugs({$s} != {$aver})");
}
$phr = "phar://$filePath/";
include($phr."/src/".$pluginInfo["classLoader"]);
$class = $pluginInfo["CLClass"];
$loader = new $class();
$loader->loadAll($phr);
$pluginName = PharUtils::getNameSpaceClass($pluginInfo["mainFile"]);
include($phr."/src/".$pluginInfo["mainFile"]);
$plugin = new $pluginName($this->server->api, false);
if(!($plugin instanceof Plugin)){
console("[ERROR] Plugin \"" . $pluginInfo["name"] . "\" doesn't use the Plugin Interface");
$plugin->__destruct();
unset($plugin);
continue;
}
$identifier = $this->getIdentifier($pluginInfo["name"], $pluginInfo["author"]);
$this->plugins[$identifier] = [$plugin, $pluginInfo];
}
}
}
if($pharCnt > 0){
console("[WARNING] PHAR Plugin format is experemental and might cause bugs.");
}
}
public function load($file){
if(is_link($file) or is_dir($file) or !file_exists($file)){
console("[ERROR] " . basename($file) . " is not a file");
return false;
}
if(strtolower(substr($file, -3)) === "pmf"){
$pmf = new PMFPlugin($file);
$info = $pmf->getPluginInfo();
}else{
$content = file_get_contents($file);
$info = strstr($content, "*/", true);
$content = str_repeat(PHP_EOL, substr_count($info, "\n")) . substr(strstr($content, "*/"), 2);
if(preg_match_all('#([a-zA-Z0-9\-_]*)=([^\r\n]*)#u', $info, $matches) == 0){ //false or 0 matches
console("[ERROR] Failed parsing of " . basename($file));
return false;
}
$info = [];
foreach($matches[1] as $k => $i){
$v = $matches[2][$k];
switch(strtolower($v)){
case "on":
case "true":
case "yes":
$v = true;
break;
case "off":
case "false":
case "no":
$v = false;
break;
}
$info[$i] = $v;
}
$info["code"] = $content;
$info["class"] = trim(strtolower($info["class"]));
}
if(!isset($info["name"]) or !isset($info["version"]) or !isset($info["class"]) or !isset($info["author"])){
console("[ERROR] Failed parsing of " . basename($file));
return false;
}
console("[INFO] Loading plugin \"" . FORMAT_GREEN . $info["name"] . FORMAT_RESET . "\" " . FORMAT_AQUA . $info["version"] . FORMAT_RESET . " by " . FORMAT_AQUA . $info["author"] . FORMAT_RESET);
if($info["class"] !== "none" and class_exists($info["class"])){
console("[ERROR] Failed loading plugin: class already exists");
return false;
}
if(((!isset($pmf) and (include $file) === false) or (isset($pmf) and eval($info["code"]) === false)) and $info["class"] !== "none" and !class_exists($info["class"])){
console("[ERROR] Failed loading {$info['name']}: evaluation error");
return false;
}
$className = $info["class"];
$apiversion = array_map("floatval", explode(",", (string) $info["apiversion"]));
if(!in_array((string) CURRENT_API_VERSION, $apiversion)){
console("[WARNING] Plugin \"" . $info["name"] . "\" may not be compatible with the API (" . $info["apiversion"] . " != " . CURRENT_API_VERSION . ")! It can crash or corrupt the server!");
}
$identifier = $this->getIdentifier($info["name"], $info["author"]);
if($info["class"] !== "none"){
$object = new $className($this->server->api, false);
if(!($object instanceof Plugin)){
console("[ERROR] Plugin \"" . $info["name"] . "\" doesn't use the Plugin Interface");
if(method_exists($object, "__destruct")){
$object->__destruct();
}
$object = null;
unset($object);
}else{
$this->plugins[$identifier] = [$object, $info];
}
}else{
$this->plugins[$identifier] = [new DummyPlugin($this->server->api, false), $info];
}
return true;
}
public function getIdentifier($name, $author){
return sha1(trim(strtolower($name)), true) ^ sha1(trim(strtolower($author)), true) ^ sha1($this->randomNonce, true);
}
public function initAll(){
console("[INFO] Starting plugins...");
$names = [];
$versions = [];
foreach($this->plugins as $p){
$names[] = $p[1]["name"];
$versions[] = $p[1]["version"];
}
foreach($this->plugins as $p){
if($p[0] instanceof OtherPluginRequirement){
foreach($p[0]->getRequiredPlugins() as $required){
if(in_array($required->pluginName, $names)){
if(!in_array($required->version, $versions) && $required->version !== false){
console("[WARNING] Plugin \"" . $required->pluginName . "\" needed by \"" . $p[1]["name"] . "\" is incorrect version.");
}
}else{
console("[ERROR] Plugin \"" . $required->pluginName . "\" needed by \"" . $p[1]["name"] . "\" is not found.");
ServerAPI::request()->close();
}
}
}
$p[0]->init(); //ARGHHH!!! Plugin loading randomly fails!!
}
}
private function fillDefaults($default, &$yaml){
foreach($default as $k => $v){
if(is_array($v)){
if(!isset($yaml[$k]) or !is_array($yaml[$k])){
$yaml[$k] = [];
}
$this->fillDefaults($v, $yaml[$k]);
}elseif(!isset($yaml[$k])){
$yaml[$k] = $v;
}
}
}
}
class RequiredPluginEntry{ //Use this as object of requirements array
public $pluginName;
public $version;
public function __construct($name, $version = false){
$this->pluginName = $name;
$this->version = $version;
}
}

View file

@ -1,42 +0,0 @@
<?php
class QueryAPI{
public static $NOT_FOUND_VALUE;
private $queryData;
private $server;
public function __construct(){
$this->server = ServerAPI::request();
QueryAPI::$NOT_FOUND_VALUE = new NFV();
$this->updateQueryData("splitnum", chr(128));
$this->updateQueryData("hostname", $this->server->name);
$this->updateQueryData("gametype", ($this->server->gamemode & 0x01) === 0 ? "SMP" : "CMP");
$this->updateQueryData("game_id", "MINECRAFTPE");
$this->updateQueryData("version", CURRENT_MINECRAFT_VERSION);
$this->updateQueryData("server_engine", "NostalgiaCore " . MAJOR_VERSION);
$this->addToQuery("plugins");
$this->addToQuery("map");
$this->addToQuery("numplayers");
$this->updateQueryData("maxplayers", $this->server->maxClients);
$this->updateQueryData("whitelist", $this->server->api->getProperty("white-list") === true ? "on" : "off");
$this->updateQueryData("hostport", $this->server->api->getProperty("server-port"));
$this->addToQuery("tps");
}
public function updateQueryData($name, $value){
$this->queryData[$name] = $value;
}
public function addToQuery($name){
$this->updateQueryData($name, QueryAPI::$NOT_FOUND_VALUE);
}
public function getQueryData(){
return $this->queryData;
}
}
class NFV{
}

View file

@ -1,414 +0,0 @@
<?php
class ServerAPI{
private static $serverRequest = false;
public $restart = false;
/**
* @var QueryAPI
*/
public $queryAPI;
/**
* @var ConsoleAPI
*/
public $console;
/**
* @var LevelAPI
*/
public $level;
/**
* @var BlockAPI
*/
public $block;
/**
* @var ChatAPI
*/
public $chat;
/**
* @var BanAPI
*/
public $ban;
/**
* @var EntityAPI
*/
public $entity;
//TODO: Instead of hard-coding functions, use PHPDoc-compatible methods to load APIs.
/**
* @var TimeAPI
*/
public $time;
/**
* @var PlayerAPI
*/
public $player;
/**
* @var TileAPI
*/
public $tile;
/**
* @var AchievementAPI
*/
public $achievement;
/**
* @var PluginAPI
*/
public $plugin;
/**
* @var QueryHandler
*/
public $query;
private $asyncCalls = [];
private $server;
private $config;
private $apiList = [];
private $asyncCnt = 0;
private $rcon;
/**
* @return PocketMinecraftServer
*/
public static function request(){
return self::$serverRequest;
}
public function start(){
return $this->run();
}
public function run(){
$this->load();
return $this->init();
}
public function load(){
if(!file_exists(DATA_PATH . "worlds/")){
mkdir(DATA_PATH . "worlds/", 0777);
}
if(!file_exists(DATA_PATH . "players/")){
mkdir(DATA_PATH . "players/", 0777);
}
if(!file_exists(DATA_PATH . "plugins/")){
mkdir(DATA_PATH . "plugins/", 0777);
}
//Init all the events
foreach(get_declared_classes() as $class){
if(is_subclass_of($class, "BaseEvent") and property_exists($class, "handlers") and property_exists($class, "handlerPriority")){
$class::unregisterAll();
}
}
$version = new VersionString();
console("[INFO] Starting Minecraft PE server version " . FORMAT_AQUA . CURRENT_MINECRAFT_VERSION);
console("[INFO] Loading properties...");
$this->config = new Config(DATA_PATH . "server.properties", CONFIG_PROPERTIES, [
"server-name" => "Minecraft: PE Server",
"description" => "Server made using NostalgiaCore",
"motd" => "Welcome @player to this server!",
"server-ip" => "",
"server-port" => 19132,
"server-type" => "normal",
"memory-limit" => "128M",
"white-list" => false,
"announce-player-achievements" => true,
"spawn-protection" => 16,
"view-distance" => 10,
"max-players" => 20,
"allow-flight" => false,
"spawn-animals" => true,
"spawn-mobs" => true,
"mobs-amount" => 50,
"gamemode" => SURVIVAL,
"hardcore" => false,
"pvp" => true,
"difficulty" => 1,
"generator-settings" => "",
"level-name" => "world",
"level-seed" => "",
"level-type" => "DEFAULT",
"enable-query" => true,
"enable-rcon" => false,
"rcon.password" => substr(base64_encode(Utils::getRandomBytes(20, false)), 3, 10),
"auto-save" => true,
"chunk-send-delay-ticks" => PocketMinecraftServer::$chukSendDelay,
"chunk-loading-radius" => PocketMinecraftServer::$chunkLoadingRadius,
]);
Biome::init();
$this->parseProperties();
MobSpawner::$MOB_LIMIT = $this->getProperty("mobs-amount", 50);
LevelAPI::$defaultLevelType = $this->getProperty("level-type");
//Load advanced properties
define("DEBUG", $this->getProperty("debug", 1));
define("ADVANCED_CACHE", $this->getProperty("enable-advanced-cache", false));
//define("MAX_CHUNK_RATE", 20 / $this->getProperty("max-chunks-per-second", 8)); //Default rate ~512 kB/s
if(ADVANCED_CACHE == true){
console("[INFO] Advanced cache enabled");
}
MobSpawner::$spawnAnimals = $this->getProperty("spawn-animals");
MobSpawner::$spawnMobs = $this->getProperty("spawn-mobs");
PocketMinecraftServer::$chukSendDelay = $this->getProperty("chunk-send-delay-ticks");
PocketMinecraftServer::$chunkLoadingRadius = $this->getProperty("chunk-loading-radius");
if(PocketMinecraftServer::$chunkLoadingRadius < 4){
ConsoleAPI::warn("Players may not be able to join if chunk loading radius is less than 4!");
}
if($this->getProperty("upnp-forwarding") == true){
console("[INFO] [UPnP] Trying to port forward...");
UPnP_PortForward($this->getProperty("server-port"));
}
$this->server = new PocketMinecraftServer($this->getProperty("server-name"), $this->getProperty("gamemode"), ($seed = $this->getProperty("level-seed")) != "" ? (int) $seed : false, $this->getProperty("server-port"), ($ip = $this->getProperty("server-ip")) != "" ? $ip : "0.0.0.0");
$this->server->api = $this;
self::$serverRequest = $this->server;
$this->server->send2Discord("[INFO] Starting Minecraft PE server version " . CURRENT_MINECRAFT_VERSION);
console("[INFO] This server is running NostalgiaCore version " . ($version->isDev() ? FORMAT_YELLOW : "") . MAJOR_VERSION . FORMAT_RESET . " \"" . CODENAME . "\" (MCPE: " . CURRENT_MINECRAFT_VERSION . ") (API " . CURRENT_API_VERSION . ") (PHP " . PHP_VERSION . ")", true, true, 0);
console("[INFO] NostalgiaCore is distributed under the LGPL License", true, true, 0);
$this->loadProperties();
$this->loadAPI("console", "ConsoleAPI");
$this->loadAPI("level", "LevelAPI");
$this->loadAPI("block", "BlockAPI");
$this->loadAPI("chat", "ChatAPI");
$this->loadAPI("ban", "BanAPI");
$this->loadAPI("entity", "EntityAPI");
$this->loadAPI("tile", "TileAPI");
$this->loadAPI("player", "PlayerAPI");
$this->loadAPI("time", "TimeAPI");
$this->loadAPI("queryAPI", "QueryAPI");
$this->loadAPI("achievement", "AchievementAPI");
foreach($this->apiList as $ob){
if(is_callable([$ob, "init"])){
$ob->init(); //Fails sometimes!!!
}
}
$this->loadAPI("plugin", "PluginAPI"); //fix :(
$this->plugin->init();
}
private function parseProperties(){
foreach($this->config->getAll() as $n => $v){
switch($n){
case "gamemode":
case "max-players":
case "server-port":
case "debug":
case "difficulty":
$v = (int) $v;
break;
case "server-id":
if($v !== false){
$v = preg_match("/[^0-9\-]/", $v) > 0 ? Utils::readInt(substr(md5($v, true), 0, 4)) : $v;
}
break;
}
$this->config->set($n, $v);
}
if($this->getProperty("hardcore") == 1 and $this->getProperty("difficulty") < 3){
$this->setProperty("difficulty", 3);
}
}
public function getProperty($name, $default = false){
if(($v = arg($name)) !== false){ //Allow for command-line arguments
switch(strtolower(trim($v))){
case "on":
case "true":
case "yes":
$v = true;
break;
case "off":
case "false":
case "no":
$v = false;
break;
}
switch($name){
case "gamemode":
case "max-players":
case "server-port":
case "debug":
case "difficulty":
case "time-per-second":
$v = (int) $v;
break;
case "server-id":
if($v !== false){
$v = preg_match("/[^0-9\-]/", $v) > 0 ? Utils::readInt(substr(md5($v, true), 0, 4)) : $v;
}
break;
}
return $v;
}
return ($this->config->exists($name) ? $this->config->get($name) : $default);
}
public function setProperty($name, $value, $save = true){
$this->config->set($name, $value);
if($save == true){
$this->writeProperties();
}
$this->loadProperties();
}
private function writeProperties(){
$this->config->save();
}
private function loadProperties(){
if(($memory = str_replace("B", "", strtoupper($this->getProperty("memory-limit")))) !== false){
$value = ["M" => 1, "G" => 1024];
$real = ((int) substr($memory, 0, -1)) * $value[substr($memory, -1)];
if($real < 128){
console("[WARNING] NostalgiaCore may not work right with less than 128MB of RAM", true, true, 0);
}
@ini_set("memory_limit", $memory);
}else{
$this->setProperty("memory-limit", "128M");
}
if($this->server instanceof PocketMinecraftServer){
$this->server->setType($this->getProperty("server-type"));
$this->server->maxClients = $this->getProperty("max-players");
$this->server->description = $this->getProperty("description");
$this->server->motd = $this->getProperty("motd");
$this->server->gamemode = $this->getProperty("gamemode");
$this->server->difficulty = $this->getProperty("difficulty");
$this->server->whitelist = $this->getProperty("white-list");
}
}
public function loadAPI($name, $class, $dir = false){
if(isset($this->$name)){
return false;
}elseif(!class_exists($class)){
$internal = false;
if($dir === false){
$internal = true;
$dir = FILE_PATH . "src/API/";
}
$file = $dir . $class . ".php";
if(!file_exists($file)){
console("[ERROR] API " . $name . " [" . $class . "] in " . $dir . " doesn't exist", true, true, 0);
return false;
}
require_once($file);
}else{
$internal = true;
}
$this->$name = new $class();
$this->apiList[] = $this->$name;
console("[" . ($internal === true ? "INTERNAL" : "DEBUG") . "] API \x1b[36m" . $name . "\x1b[0m [\x1b[30;1m" . $class . "\x1b[0m] loaded", true, true, ($internal === true ? 3 : 2));
}
public function init(){
if(!(self::$serverRequest instanceof PocketMinecraftServer)){
self::$serverRequest = $this->server;
}
if($this->getProperty("auto-save") === true){
$this->server->schedule(18000, [$this, "autoSave"], [], true);
}
if(!defined("NO_THREADS") and $this->getProperty("enable-rcon") === true){
$this->rcon = new RCON($this->getProperty("rcon.password", ""), $this->getProperty("rcon.port", $this->getProperty("server-port")), ($ip = $this->getProperty("server-ip")) != "" ? $ip : "0.0.0.0", $this->getProperty("rcon.threads", 1), $this->getProperty("rcon.clients-per-thread", 50));
}
if($this->getProperty("enable-query") === true){
$this->query = new QueryHandler();
}
CraftingRecipes::init();
$this->server->init();
unregister_tick_function([$this->server, "tick"]);
$this->console->__destruct();
if($this->rcon instanceof RCON){
$this->rcon->stop();
}
$this->__destruct();
if($this->getProperty("upnp-forwarding") === true){
console("[INFO] [UPnP] Removing port forward...");
UPnP_RemovePortForward($this->getProperty("server-port"));
}
return $this->restart;
}
public function __destruct(){
foreach($this->apiList as $i => $ob){
if(method_exists($ob, "__destruct")){
$ob->__destruct();
unset($this->apiList[$i]);
}
}
}
/*-------------------------------------------------------------*/
public function async(callable $callable, $params = [], $remove = false){
$cnt = $this->asyncCnt++;
$this->asyncCalls[$cnt] = new Async($callable, $params);
return $remove === true ? $this->getAsync($cnt) : $cnt;
}
public function getAsync($id){
if(!isset($this->asyncCalls[$id])){
return false;
}
$ob = $this->asyncCalls[$id];
unset($this->asyncCalls[$id]);
return $ob;
}
public function autoSave(){
console("[DEBUG] Saving....", true, true, 2);
$this->server->api->level->saveAll();
}
public function asyncOperation($t, $d, $c = null){
return $this->server->asyncOperation($t, $d, $c);
}
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 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 getProperties(){
return $this->config->getAll();
}
public function getList(){
return $this->apiList;
}
}

View file

@ -1,99 +0,0 @@
<?php
class TileAPI{
private $server;
private $tiles;
private $tCnt = 1;
function __construct(){
$this->tiles = [];
$this->server = ServerAPI::request();
}
public function get(Position $pos){
$tile = $this->server->query("SELECT * FROM tiles WHERE level = '" . $pos->level->getName() . "' AND x = {$pos->x} AND y = {$pos->y} AND z = {$pos->z};", true);
if($tile !== false and $tile !== true and ($tile = $this->getByID($tile["ID"])) !== false){
return $tile;
}
return false;
}
public function getByID($id){
if($id instanceof Tile){
return $id;
}elseif(isset($this->tiles[$id])){
return $this->tiles[$id];
}
return false;
}
public function init(){
}
public function addSign(Level $level, $x, $y, $z, $lines = ["", "", "", ""]){
return $this->add($level, TILE_SIGN, $x, $y, $z, $data = [
"id" => "Sign",
"x" => $x,
"y" => $y,
"z" => $z,
"Text1" => $lines[0],
"Text2" => $lines[1],
"Text3" => $lines[2],
"Text4" => $lines[3],
]);
}
public function add(Level $level, $class, $x, $y, $z, $data = []){
$id = $this->tCnt++;
$this->tiles[$id] = new Tile($level, $id, $class, $x, $y, $z, $data);
$this->spawnToAll($this->tiles[$id]);
return $this->tiles[$id];
}
public function spawnToAll(Tile $t){
foreach($this->server->api->player->getAll($t->level) as $player){
if($player->eid !== false){
$t->spawn($player);
}
}
}
public function spawnAll(Player $player){
foreach($this->getAll($player->level) as $t){
$t->spawn($player);
}
}
public function getAll($level = null){
if($level instanceof Level){
$tiles = [];
$l = $this->server->query("SELECT ID FROM tiles WHERE level = '" . $level->getName() . "';");
if($l !== false and $l !== true){
while(($t = $l->fetchArray(SQLITE3_ASSOC)) !== false){
$t = $this->getByID($t["ID"]);
if($t instanceof Tile){
$tiles[$t->id] = $t;
}
}
}
return $tiles;
}
return $this->tiles;
}
public function remove($id){
if(isset($this->tiles[$id])){
$t = $this->tiles[$id];
$this->tiles[$id] = null;
unset($this->tiles[$id]);
$t->closed = true;
$t->close();
$this->server->query("DELETE FROM tiles WHERE ID = " . $id . ";");
$this->server->api->dhandle("tile.remove", $t);
$t = null;
unset($t);
}
}
}

View file

@ -1,180 +0,0 @@
<?php
class TimeAPI{
public static $phases = [
"day" => 0,
"sunset" => 9500,
"night" => 10900,
"sunrise" => 17800,
];
private $server;
function __construct(){
$this->server = ServerAPI::request();
}
public function init(){
$this->server->api->console->register("time", "<check|set|add> [time]", [$this, "commandHandler"]);
}
public function commandHandler($cmd, $args, $issuer, $alias){
$output = "";
switch($cmd){
case "time":
$level = false;
if($issuer instanceof Player){
$level = $issuer->level;
}else{
$level = $this->server->api->level->getDefault();
}
$p = strtolower(array_shift($args));
switch($p){
case "check":
if(substr($args[0] ?? "", 0, 2) === "w:"){
$levelName = preg_replace("/w:/", "", $args[0]);
$level = $this->server->api->level->get($levelName);
if($level instanceof Level){
$world = " in world \"$levelName\"";
}else{
$output .= "World \"$levelName\" doesn't exist or loaded!";
break;
}
}else $world = " in world \"" . $level->getName() . "\"";
$output .= "Time" . $world . ": " . $this->getDate($level) . ", " . $this->getPhase($level) . " (" . $this->get(true, $level) . " ticks)\n";
break;
case "add":
if(substr($args[1] ?? "", 0, 2) === "w:"){
$levelName = preg_replace("/w:/", "", $args[1]);
$level = $this->server->api->level->get($levelName);
if($level instanceof Level){
$world = " to the time of world \"$levelName\"";
}else{
$output .= "World \"$levelName\" doesn't exist or loaded!";
break;
}
}else $world = " to the time of world \"" . $level->getName() . "\"";
$addTime = array_shift($args);
if(!is_numeric($addTime)){
$output .= "Time must be an integer!";
break;
}
$addTime = (int) $addTime;
$this->add($addTime, $level);
$output .= "Added $addTime ticks" . $world . "\n";
break;
case "set":
if(isset($args[1]) and substr($args[1], 0, 2) === "w:"){
$levelName = preg_replace("/w:/", "", $args[1]);
$level = $this->server->api->level->get($levelName);
if($level instanceof Level){
$world = " in world \"$levelName\"";
}else{
$output .= "World \"$levelName\" doesn't exist or loaded!";
break;
}
}else $world = " in world \"" . $level->getName() . "\"";
$setTime = array_shift($args);
if(is_numeric($setTime)){
$setTime = (int) $setTime;
}elseif($setTime == 'sunrise' or $setTime == 'day' or $setTime == 'sunset' or $setTime == 'night')
;
else{
$output .= "Wrong time!";
break;
}
$this->set($setTime, $level);
$output .= "Set the time to " . $setTime . $world . "\n";
break;
case "sunrise":
case "day":
case "sunset":
case "night":
if(count($args) > 1 && substr($args[1], 0, 2) === "w:"){
$levelName = preg_replace("/w:/", "", $args[1]);
$level = $this->server->api->level->get($levelName);
if($level instanceof Level){
$world = " in world \"$levelName\"";
}else{
$output .= "World \"$levelName\" doesn't exist or loaded!";
break;
}
}else $world = " in world \"" . $level->getName() . "\"";
$this->set($p, $level);
$output .= "Set the time to " . $p . $world . "\n";
break;
default:
$output .= "Usage: /time <check|set|add> [time] [w:world]\n";
break;
}
break;
}
return $output;
}
public function getDate($time = false){
$time = !is_integer($time) ? $this->get(false, $time) : $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 get($raw = false, $level = false){
if(!($level instanceof Level)){
$level = $this->server->api->level->getDefault();
}
return $raw === true ? $level->getTime() : abs($level->getTime()) % 19200;
}
public function getPhase($time = false){
$time = !is_integer($time) ? $this->get(false, $time) : $time;
if($time < TimeAPI::$phases["sunset"]){
$time = "day";
}elseif($time < TimeAPI::$phases["night"]){
$time = "sunset";
}elseif($time < TimeAPI::$phases["sunrise"]){
$time = "night";
}else{
$time = "sunrise";
}
return $time;
}
public function add($time, $level = false){
if(!($level instanceof Level)){
$level = $this->server->api->level->getDefault();
}
$level->setTime($level->getTime() + (int) $time);
}
public function set($time, $level = false){
if(!($level instanceof Level)){
$level = $this->server->api->level->getDefault();
}
if(is_string($time) and isset(TimeAPI::$phases[$time])){
$level->setTime(TimeAPI::$phases[$time]);
}else{
$level->setTime((int) $time);
}
return $level->getTime();
}
public function night(){
return $this->set("night");
}
public function day(){
return $this->set("day");
}
public function sunrise(){
return $this->set("sunrise");
}
public function sunset(){
return $this->set("sunset");
}
}

View file

@ -1,116 +0,0 @@
<?php
abstract class BaseEvent{
const ALLOW = 0;
const DENY = 1;
const NORMAL = 2;
const FORCE = 0x80000000;
/**
* Any callable event must declare the static variables
*
* public static $handlers;
* public static $handlerPriority;
*
* Not doing so will deny the proper event initialization
*/
protected $eventName = null;
private $status = BaseEvent::NORMAL;
private $prioritySlot;
public static function getHandlerList(){
return static::$handlers;
}
public static function getPriorityList(){
return static::$handlerPriority;
}
public static function unregisterAll(){
static::$handlers = [];
static::$handlerPriority = [];
}
public static function register(callable $handler, $priority = EventPriority::NORMAL){
if($priority < EventPriority::MONITOR or $priority > EventPriority::LOWEST){
return false;
}
$identifier = Utils::getCallableIdentifier($handler);
if(isset(static::$handlers[$identifier])){ //Already registered
return false;
}else{
static::$handlers[$identifier] = $handler;
if(!isset(static::$handlerPriority[(int) $priority])){
static::$handlerPriority[(int) $priority] = [];
krsort(static::$handlerPriority);
}
static::$handlerPriority[(int) $priority][$identifier] = $handler;
return true;
}
}
public static function unregister(callable $handler, $priority = EventPriority::NORMAL){
$identifier = Utils::getCallableIdentifier($handler);
if(isset(static::$handlers[$identifier])){
if(isset(static::$handlerPriority[(int) $priority][$identifier])){
unset(static::$handlerPriority[(int) $priority][$identifier]);
}else{
for($priority = EventPriority::MONITOR; $priority <= EventPriority::LOWEST; ++$priority){
unset(static::$handlerPriority[$priority][$identifier]);
if(count(static::$handlerPriority[$priority]) === 0){
unset(static::$handlerPriority[$priority]);
}
}
}
unset(static::$handlers[$identifier]);
return true;
}else{
return false;
}
}
final public function getEventName(){
return $this->eventName !== null ? get_class($this) : $this->eventName;
}
final public function getPrioritySlot(){
return (int) $this->prioritySlot;
}
final public function setPrioritySlot($slot){
$this->prioritySlot = (int) $slot;
}
public function isAllowed(){
return ($this->status & 0x7FFFFFFF) === BaseEvent::ALLOW;
}
public function setAllowed($forceAllow = false){
$this->status = BaseEvent::ALLOW | ($forceAllow === true ? BaseEvent::FORCE : 0);
}
public function isCancelled(){
return ($this->status & 0x7FFFFFFF) === BaseEvent::DENY;
}
public function setCancelled($forceCancel = false){
if($this instanceof CancellableEvent){
$this->status = BaseEvent::DENY | ($forceCancel === true ? BaseEvent::FORCE : 0);
}
return false;
}
public function isNormal(){
return $this->status === BaseEvent::NORMAL;
}
public function setNormal(){
$this->status = BaseEvent::NORMAL;
}
public function isForced(){
return ($this->status & BaseEvent::FORCE) > 0;
}
}

View file

@ -1,15 +0,0 @@
<?php
class Deprecation{
public static $events = [
"server.tick" => "ServerAPI::schedule()",
"server.time" => "time.change",
"world.block.change" => "block.change",
"block.drop" => "item.drop",
"api.op.check" => "op.check",
"api.player.offline.get" => "player.offline.get",
"api.player.offline.save" => "player.offline.save",
];
}

File diff suppressed because it is too large Load diff

View file

@ -1,756 +0,0 @@
<?php
class PocketMinecraftServer{
public static $chukSendDelay = 5, $chunkLoadingRadius = 4;
public $tCnt, $ticks;
public $extraprops, $serverID, $interface, $database, $version, $invisible, $tickMeasure, $preparedSQL, $seed, $gamemode, $name, $maxClients, $clients, $eidCnt, $custom, $description, $motd, $port, $saveEnabled;
/**
* @var ServerAPI
*/
public $api;
private $serverip, $evCnt, $handCnt, $events, $eventsID, $handlers, $serverType, $lastTick, $memoryStats, $async = [], $asyncID = 0;
public $levelData, $doTick, $difficulty, $tiles, $entities, $schedule, $scheduleCnt, $whitelist, $spawn, $asyncThread, $stop;
function __construct($name, $gamemode = SURVIVAL, $seed = false, $port = 19132, $serverip = "0.0.0.0"){
$this->port = (int) $port;
$this->doTick = true;
$this->gamemode = (int) $gamemode;
$this->name = $name;
$this->motd = "Welcome to " . $name;
$this->serverID = false;
$this->seed = $seed;
$this->serverip = $serverip;
$this->load();
}
private function load(){
global $dolog;
$this->version = new VersionString();
/*if(defined("DEBUG") and DEBUG >= 0){
@cli_set_process_title("NostalgiaCore ".MAJOR_VERSION);
}*/
console("[INFO] Starting Minecraft PE server on " . ($this->serverip === "0.0.0.0" ? "*" : $this->serverip) . ":" . $this->port);
EntityRegistry::registerEntities();
Structures::initialize();
Feature::init();
StaticBlock::init();
define("BOOTUP_RANDOM", Utils::getRandomBytes(16));
$this->serverID = $this->serverID === false ? Utils::readLong(substr(Utils::getUniqueID(true, $this->serverip . $this->port), 8)) : $this->serverID;
$this->seed = $this->seed === false ? Utils::readInt(Utils::getRandomBytes(4, false)) : $this->seed;
$this->startDatabase();
$this->api = false;
$this->tCnt = 1;
$this->events = [];
$this->eventsID = [];
$this->handlers = [];
$this->invisible = false;
$this->levelData = false;
$this->difficulty = 1;
$this->tiles = [];
$this->entities = [];
$this->custom = [];
$this->evCnt = 1;
$this->handCnt = 1;
$this->eidCnt = 1;
$this->maxClients = 20;
$this->schedule = [];
$this->scheduleCnt = 1;
$this->description = "";
$this->whitelist = false;
$this->memoryStats = [];
$this->clients = [];
$this->spawn = false;
$this->saveEnabled = true;
$this->tickMeasure = array_fill(0, 40, 0);
$this->setType("normal");
$this->interface = new MinecraftInterface("255.255.255.255", $this->port, $this->serverip);
$this->stop = false;
$this->ticks = 0;
if(!defined("NO_THREADS")){
$this->asyncThread = new AsyncMultipleQueue();
}
console("[INFO] Loading extra.properties...");
$this->extraprops = new Config(DATA_PATH . "extra.properties", CONFIG_PROPERTIES, [
"version" => "5",
"experemental-mob-features" => true,
"enable-mob-ai" => false,
"enable-nether-reactor" => true,
"enable-explosions" => true,
"enable-rail-connection" => true,
"save-player-data" => true,
"save-console-data" => true,
"query-plugins" => false,
"discord-msg" => false,
"discord-ru-smiles" => false,
"discord-webhook-url" => "none",
"discord-bot-name" => "NostalgiaCore Logger",
"despawn-mobs" => true,
"mob-despawn-ticks" => 18000,
]);
Living::$despawnMobs = $this->extraprops->get("despawn-mobs");
Living::$despawnTimer = $this->extraprops->get("mob-despawn-ticks");
Entity::$allowedAI = $this->extraprops->get("enable-mob-ai");
Entity::$updateOnTick = $this->extraprops->get("experemental-mob-features");
if(Entity::$updateOnTick){
console("[WARNING] Experemental mob features are enabled. Unpredictable behavior.");
}
Explosion::$enableExplosions = $this->extraprops->get("enable-explosions");
RailBlock::$shouldconnectrails = $this->extraprops->get("enable-rail-connection"); //Rail connection in config
NetherReactorBlock::$enableReactor = $this->extraprops->get("enable-nether-reactor");
if($this->extraprops->get("discord-msg") == true){
if($this->extraprops->get("discord-webhook-url") !== "none"){
console("[INFO] Discord Logger is enabled.");
}else{
console("[WARNING] Discord Logger is enabled in extra.properties,");
console("[WARNING] but you didn't put the webhook url, so it won't work.");
}
}elseif($this->extraprops->get("version") == null){
console("[WARNING] Your extra.properties file is corrupted!");
console("[WARNING] To fix it - just remove it! Server will generate it again automatically.");
}
$dolog = $this->extraprops->get("save-console-data");
}
public function onShutdown(){
console("[INFO] Saving...");
$save = $this->saveEnabled;
$this->saveEnabled = true;
$this->api->level->saveAll();
$this->saveEnabled = $save;
//$this->send2Discord('[INFO] Server stopped!');
}
public function startDatabase(){
$this->preparedSQL = new stdClass();
$this->preparedSQL->entity = new stdClass();
$this->database = new SQLite3(":memory:");
$this->query("PRAGMA journal_mode = OFF;");
$this->query("PRAGMA encoding = \"UTF-8\";");
$this->query("PRAGMA secure_delete = OFF;");
$this->query("CREATE TABLE players (CID INTEGER PRIMARY KEY, EID NUMERIC, ip TEXT, port NUMERIC, name TEXT UNIQUE COLLATE NOCASE);");
$this->query("CREATE TABLE entities (EID INTEGER PRIMARY KEY, level TEXT, type NUMERIC, class NUMERIC, hasUpdate NUMERIC, name TEXT, x NUMERIC, y NUMERIC, z NUMERIC, yaw NUMERIC, pitch NUMERIC, health NUMERIC);");
$this->query("CREATE TABLE tiles (ID INTEGER PRIMARY KEY, level TEXT, class TEXT, x NUMERIC, y NUMERIC, z NUMERIC, spawnable NUMERIC);");
$this->query("CREATE TABLE actions (ID INTEGER PRIMARY KEY, interval NUMERIC, last NUMERIC, code TEXT, repeat NUMERIC);");
$this->query("CREATE TABLE handlers (ID INTEGER PRIMARY KEY, name TEXT, priority NUMERIC);");
$this->query("CREATE TABLE blockUpdates (level TEXT, x INTEGER, y INTEGER, z INTEGER, type INTEGER, delay NUMERIC);");
$this->query("CREATE TABLE recipes (id INTEGER PRIMARY KEY, type NUMERIC, recipe TEXT);");
$this->query("PRAGMA synchronous = OFF;");
$this->preparedSQL->selectHandlers = $this->database->prepare("SELECT DISTINCT ID FROM handlers WHERE name = :name ORDER BY priority DESC;");
$this->preparedSQL->selectActions = $this->database->prepare("SELECT ID,code,repeat FROM actions WHERE last <= (:time - interval);");
$this->preparedSQL->updateAction = $this->database->prepare("UPDATE actions SET last = :time WHERE ID = :id;");
$this->preparedSQL->entity->setPosition = $this->database->prepare("UPDATE entities SET x = :x, y = :y, z = :z, pitch = :pitch, yaw = :yaw WHERE EID = :eid ;");
$this->preparedSQL->entity->setLevel = $this->database->prepare("UPDATE entities SET level = :level WHERE EID = :eid ;");
}
public function query($sql, $fetch = false){
$result = $this->database->query($sql) or console("[ERROR] [SQL Error] " . $this->database->lastErrorMsg() . ". Query: " . $sql, true, true, 0);
if($fetch === true and ($result instanceof SQLite3Result)){
$result = $result->fetchArray(SQLITE3_ASSOC);
}
return $result;
}
public function setType($type = "normal"){
switch(trim(strtolower($type))){
case "normal":
case "demo":
$this->serverType = "MCCPP;Demo;";
break;
case "minecon":
$this->serverType = "MCCPP;MINECON;";
break;
}
}
public function titleTick(){
$time = microtime(true);
if(defined("DEBUG") and DEBUG >= 0){
echo "\x1b]0;NostalgiaCore " . MAJOR_VERSION . " | Online " . count($this->clients) . "/" . $this->maxClients . " | RAM " . round((memory_get_usage() / 1024) / 1024, 2) . "MB | U " . round(($this->interface->bandwidth[1] / max(1, $time - $this->interface->bandwidth[2])) / 1024, 2) . " D " . round(($this->interface->bandwidth[0] / max(1, $time - $this->interface->bandwidth[2])) / 1024, 2) . " kB/s | TPS " . $this->getTPS() . "\x07";
}
$this->interface->bandwidth = [0, 0, $time];
}
/**
* @return float
*/
public function getTPS(){
$v = array_values($this->tickMeasure);
$divval = ($v[39] - $v[0]);
if($divval === 0){
return 0;
}
$tps = 40 / $divval;
return round($tps, 4);
}
public function checkTicks(){
if($this->getTPS() < 12){
console("[WARNING] Can't keep up! Is the server overloaded?");
}
}
/**
* @param string $reason
*/
public function close($reason = "server stop"){
usleep(2);
$this->onShutdown();
if($this->stop !== true){
if(is_int($reason)){
$reason = "signal stop";
}
if(($this->api instanceof ServerAPI) === true){
if(($this->api->chat instanceof ChatAPI) === true){
$this->api->chat->send(false, "Stopping server...");
new StopMessageThread($this, "[INFO] Stopping server..."); //broadcast didnt want to send message to discord for some reason
}
}
$this->stop = true;
$this->trigger("server.close", $reason);
$this->interface->close();
if(!defined("NO_THREADS")){
@$this->asyncThread->stop = true;
}
}
}
public function send2Discord($msg){
if($this->extraprops->get("discord-msg") == true and $this->extraprops->get("discord-webhook-url") !== "none"){
$url = $this->extraprops->get("discord-webhook-url");
$name = $this->extraprops->get("discord-bot-name");
$this->asyncOperation(ASYNC_CURL_POST, [
"url" => $url,
"data" => [
"username" => $name,
"content" => $this->extraprops->get("discord-ru-smiles") ? str_replace("@", " ", str_replace("Û", "<:imp_cool:1151085500396998719>", str_replace("Ü", "<:imp_badphp5:1151085478410457120>", str_replace("Ú", "<:imp_gudjava:1151085431962742784>", str_replace("¨", "<:imp_wut:1151085524241621012>", $msg))))) : str_replace("@", "", $msg)
],
], null);
}
}
public function asyncOperation($type, array $data, callable $callable = null){
if(defined("NO_THREADS")){
return false;
}
$d = "";
$type = (int) $type;
switch($type){
case ASYNC_CURL_GET:
if(isset($data["headers"])){
$jsstr = json_encode($data["headers"]);
}
$d .= Utils::writeShort(strlen($data["url"])) . $data["url"] . (isset($data["timeout"]) ? Utils::writeShort($data["timeout"]) : Utils::writeShort(10)) . (isset($data["headers"]) ? Utils::writeShort(strlen($jsstr)) . $jsstr : Utils::writeShort(1) . " ");
break;
case ASYNC_CURL_POST:
$d .= Utils::writeShort(strlen($data["url"])) . $data["url"] . (isset($data["timeout"]) ? Utils::writeShort($data["timeout"]) : Utils::writeShort(10));
$d .= Utils::writeShort(count($data["data"]));
foreach($data["data"] as $key => $value){
$d .= Utils::writeShort(strlen($key)) . $key . Utils::writeInt(strlen($value)) . $value;
}
break;
default:
return false;
}
$ID = $this->asyncID++;
$this->async[$ID] = $callable;
$this->asyncThread->input .= Utils::writeInt($ID) . Utils::writeShort($type) . $d;
return $ID;
}
public function trigger($event, $data = ""){
if(isset($this->events[$event])){
foreach($this->events[$event] as $evid => $ev){
if(!is_callable($ev)){
$this->deleteEvent($evid);
continue;
}
if(is_array($ev)){
$method = $ev[1];
$ev[0]->$method($data, $event);
}else{
$ev($data, $event);
}
}
}elseif(isset(Deprecation::$events[$event])){
$sub = "";
if(Deprecation::$events[$event] !== false){
$sub = " Substitute \"" . Deprecation::$events[$event] . "\" found.";
}
console("[ERROR] Event \"$event\" has been deprecated.$sub [Trigger]");
}
}
public function deleteEvent($id){
$id = (int) $id;
if(isset($this->eventsID[$id])){
$ev = $this->eventsID[$id];
$this->eventsID[$id] = null;
unset($this->eventsID[$id]);
$this->events[$ev][$id] = null;
unset($this->events[$ev][$id]);
if(count($this->events[$ev]) === 0){
unset($this->events[$ev]);
}
}
}
public function asyncOperationChecker(){
if(defined("NO_THREADS")){
return false;
}
if(isset($this->asyncThread->output[5])){
$offset = 0;
$ID = Utils::readInt(substr($this->asyncThread->output, $offset, 4));
$offset += 4;
$type = Utils::readShort(substr($this->asyncThread->output, $offset, 2));
$offset += 2;
$data = [];
switch($type){
case ASYNC_CURL_GET:
case ASYNC_CURL_POST:
$len = Utils::readInt(substr($this->asyncThread->output, $offset, 4));
$offset += 4;
$data["result"] = substr($this->asyncThread->output, $offset, $len);
$this->dhandle("async.curl.get", ["response" => $data["result"]]);
$offset += $len;
break;
}
$this->asyncThread->output = substr($this->asyncThread->output, $offset);
if(isset($this->async[$ID]) and $this->async[$ID] !== null and is_callable($this->async[$ID])){
if(is_array($this->async[$ID])){
$method = $this->async[$ID][1];
$result = $this->async[$ID][0]->$method($data, $type, $ID);
}else{
$result = $this->async[$ID]($data, $type, $ID);
}
}
unset($this->async[$ID]);
}
}
/**
* @param string $event
* @param callable $callable
* @param integer $priority
*
* @return boolean
*/
public function addHandler($event, callable $callable, $priority = 5){
if(!is_callable($callable)){
return false;
}elseif(isset(Deprecation::$events[$event])){
$sub = "";
if(Deprecation::$events[$event] !== false){
$sub = " Substitute \"" . Deprecation::$events[$event] . "\" found.";
}
console("[ERROR] Event \"$event\" has been deprecated.$sub [Adding handle to " . (is_array($callable) ? get_class($callable[0]) . "::" . $callable[1] : $callable) . "]");
}
$priority = (int) $priority;
$hnid = $this->handCnt++;
$this->handlers[$hnid] = $callable;
$this->query("INSERT INTO handlers (ID, name, priority) VALUES (" . $hnid . ", '" . str_replace("'", "\\'", $event) . "', " . $priority . ");");
//console("[INTERNAL] New handler " . (is_array($callable) ? get_class($callable[0]) . "::" . $callable[1] : $callable) . " to special event " . $event . " (ID " . $hnid . ")", true, true, 3);
return $hnid;
}
public function dhandle($e, $d){
return $this->handle($e, $d);
}
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 = null;
if($handlers instanceof SQLite3Result){
$call = [];
while(($hn = $handlers->fetchArray(SQLITE3_ASSOC)) !== false){
$call[(int) $hn["ID"]] = true;
}
$handlers->finalize();
foreach($call as $hnid => $boolean){
if($result !== false and $result !== true){
$called[$hnid] = true;
$handler = $this->handlers[$hnid];
if(is_array($handler)){
$method = $handler[1];
$result = $handler[0]->$method($data, $event);
}else{
$result = $handler($data, $event);
}
}else{
break;
}
}
}elseif(isset(Deprecation::$events[$event])){
$sub = "";
if(Deprecation::$events[$event] !== false){
$sub = " Substitute \"" . Deprecation::$events[$event] . "\" found.";
}
console("[ERROR] Event \"$event\" has been deprecated.$sub [Handler]");
}
if($result !== false){
$this->trigger($event, $data);
}
return $result;
}
public function eventHandler($data, $event){
switch($event){
}
}
public function init(){
register_tick_function([$this, "tick"]);
declare(ticks=5000); //Minimum TPS for main thread locks
$this->loadEvents();
register_shutdown_function([$this, "dumpError"]);
register_shutdown_function([$this, "close"]);
if(function_exists("pcntl_signal")){
pcntl_signal(SIGTERM, [$this, "close"]);
pcntl_signal(SIGINT, [$this, "close"]);
pcntl_signal(SIGHUP, [$this, "close"]);
}
console("[INFO] Default game type: " . strtoupper($this->getGamemode()));
$this->trigger("server.start", microtime(true));
console('[INFO] Done (' . round(microtime(true) - START_TIME, 3) . 's)! For help, type "help" or "?"');
$this->process();
}
public function loadEvents(){
if(ENABLE_ANSI === true){
$this->schedule(30, [$this, "titleTick"], [], true);
}
$this->schedule(20 * 15, [$this, "checkTicks"], [], true);
$this->schedule(20 * 60, [$this, "checkMemory"], [], true);
$this->schedule(20 * 45, "Cache::cleanup", [], true);
$this->schedule(20, [$this, "asyncOperationChecker"], [], true);
}
public function schedule($ticks, callable $callback, $data = [], $repeat = false, $eventName = "server.schedule"){
if(!is_callable($callback)){
return false;
}
$chcnt = $this->scheduleCnt++;
$this->schedule[$chcnt] = [$callback, $data, $eventName];
$this->query("INSERT INTO actions (ID, interval, last, repeat) VALUES(" . $chcnt . ", " . ($ticks / 20) . ", " . microtime(true) . ", " . (((bool) $repeat) === true ? 1 : 0) . ");");
return $chcnt;
}
/**
* @return string
*/
public function getGamemode(){
switch($this->gamemode){
case SURVIVAL:
return "survival";
case CREATIVE:
return "creative";
case ADVENTURE:
return "adventure";
case VIEW:
return "view";
}
}
public function process()
{
$lastLoop = 0;
while($this->stop === false){
$packet = $this->interface->readPacket();
if($packet instanceof Packet){
$this->packetHandler($packet);
$lastLoop = 0;
} elseif($this->tick() > 0){
$lastLoop = 0;
} else{
++ $lastLoop;
if($lastLoop < 16){
usleep(1);
} elseif($lastLoop < 128){
usleep(100);
} elseif($lastLoop < 256){
usleep(512);
} else{
usleep(10000);
}
}
$this->tick();
}
}
public function packetHandler(Packet $packet){
$data =& $packet;
$CID = PocketMinecraftServer::clientID($packet->ip, $packet->port);
if(isset($this->clients[$CID])){
$this->clients[$CID]->handlePacket($packet);
}else{
if($this->handle("server.noauthpacket." . $packet->pid(), $packet) === false){
return;
}
switch($packet->pid()){
case RakNetInfo::UNCONNECTED_PING:
case RakNetInfo::UNCONNECTED_PING_OPEN_CONNECTIONS:
if($this->invisible === true){
$pk = new RakNetPacket(RakNetInfo::UNCONNECTED_PONG);
$pk->pingID = $packet->pingID;
$pk->serverID = $this->serverID;
$pk->serverType = $this->serverType;
$pk->ip = $packet->ip;
$pk->port = $packet->port;
$this->send($pk);
break;
}
if(!isset($this->custom["times_" . $CID])){
$this->custom["times_" . $CID] = 0;
}
$ln = 15;
if($this->description == "" or substr($this->description, -1) != " "){
$this->description .= " ";
}
$txt = substr($this->description, $this->custom["times_" . $CID], $ln);
$txt .= substr($this->description, 0, $ln - strlen($txt));
$pk = new RakNetPacket(RakNetInfo::UNCONNECTED_PONG);
$pk->pingID = $packet->pingID;
$pk->serverID = $this->serverID;
$pk->serverType = $this->serverType . $this->name . " [" . count($this->clients) . "/" . $this->maxClients . "] " . $txt;
$pk->ip = $packet->ip;
$pk->port = $packet->port;
$this->send($pk);
$this->custom["times_" . $CID] = ($this->custom["times_" . $CID] + 1) % strlen($this->description);
break;
case RakNetInfo::OPEN_CONNECTION_REQUEST_1:
if($packet->structure !== RakNetInfo::STRUCTURE){
console("[DEBUG] Incorrect structure #" . $packet->structure . " from " . $packet->ip . ":" . $packet->port, true, true, 2);
$pk = new RakNetPacket(RakNetInfo::INCOMPATIBLE_PROTOCOL_VERSION);
$pk->serverID = $this->serverID;
$pk->ip = $packet->ip;
$pk->port = $packet->port;
$this->send($pk);
}else{
$pk = new RakNetPacket(RakNetInfo::OPEN_CONNECTION_REPLY_1);
$pk->serverID = $this->serverID;
$pk->mtuSize = strlen($packet->buffer);
$pk->ip = $packet->ip;
$pk->port = $packet->port;
$this->send($pk);
}
break;
case RakNetInfo::OPEN_CONNECTION_REQUEST_2:
if($this->invisible === true){
break;
}
$this->clients[$CID] = new Player($packet->clientID, $packet->ip, $packet->port, $packet->mtuSize); //New Session!
$pk = new RakNetPacket(RakNetInfo::OPEN_CONNECTION_REPLY_2);
$pk->serverID = $this->serverID;
$pk->port = $this->port;
$pk->mtuSize = $packet->mtuSize;
$pk->ip = $packet->ip;
$pk->port = $packet->port;
$this->send($pk);
break;
}
}
}
public static function clientID($ip, $port){
return crc32($ip . $port) ^ crc32($port . $ip . BOOTUP_RANDOM);
//return $ip . ":" . $port;
}
public function send(Packet $packet){
return $this->interface->writePacket($packet);
}
public function tick(){
$time = microtime(true);
if($this->lastTick <= ($time - 0.05)){
$this->tickMeasure[] = $this->lastTick = $time;
unset($this->tickMeasure[key($this->tickMeasure)]);
++$this->ticks;
foreach($this->api->level->levels as $l){
$l->onTick($this);
}
return $this->tickerFunction($time);
}
return 0;
}
public function tickerFunction($time){
//actions that repeat every x time will go here
$this->preparedSQL->selectActions->reset();
$this->preparedSQL->selectActions->bindValue(":time", $time, SQLITE3_FLOAT);
$actions = $this->preparedSQL->selectActions->execute();
$actionCount = 0;
if($actions instanceof SQLite3Result){
while(($action = $actions->fetchArray(SQLITE3_ASSOC)) !== false){
$cid = $action["ID"];
$this->preparedSQL->updateAction->reset();
$this->preparedSQL->updateAction->bindValue(":time", $time, SQLITE3_FLOAT);
$this->preparedSQL->updateAction->bindValue(":id", $cid, SQLITE3_INTEGER);
$this->preparedSQL->updateAction->execute();
if(!isset($this->schedule[$cid]) || !isset($this->schedule[$cid][0]) || !@is_callable($this->schedule[$cid][0])){
$return = false;
}else{
++$actionCount;
$return = call_user_func($this->schedule[$cid][0], $this->schedule[$cid][1], $this->schedule[$cid][2]);
}
if($action["repeat"] == 0 or $return === false){
$this->query("DELETE FROM actions WHERE ID = " . $action["ID"] . ";");
$this->schedule[$cid] = null;
unset($this->schedule[$cid]);
}
}
$actions->finalize();
}
return $actionCount;
}
public function dumpError(){
if($this->stop === true){
return;
}
ini_set("memory_limit", "-1"); //Fix error dump not dumped on memory problems
console("[SEVERE] An unrecovereable has ocurred and the server has crashed. Creating an error dump");
$dump = "```\r\n# NostalgiaCore Error Dump " . date("D M j H:i:s T Y") . "\r\n";
$er = error_get_last();
$errorConversion = [
E_ERROR => "E_ERROR",
E_WARNING => "E_WARNING",
E_PARSE => "E_PARSE",
E_NOTICE => "E_NOTICE",
E_CORE_ERROR => "E_CORE_ERROR",
E_CORE_WARNING => "E_CORE_WARNING",
E_COMPILE_ERROR => "E_COMPILE_ERROR",
E_COMPILE_WARNING => "E_COMPILE_WARNING",
E_USER_ERROR => "E_USER_ERROR",
E_USER_WARNING => "E_USER_WARNING",
E_USER_NOTICE => "E_USER_NOTICE",
E_STRICT => "E_STRICT",
E_RECOVERABLE_ERROR => "E_RECOVERABLE_ERROR",
E_DEPRECATED => "E_DEPRECATED",
E_USER_DEPRECATED => "E_USER_DEPRECATED",
];
$er["type"] = isset($errorConversion[$er["type"]]) ? $errorConversion[$er["type"]] : $er["type"];
$dump .= "Error: " . var_export($er, true) . "\r\n\r\n";
if(stripos($er["file"], "plugin") !== false){
$dump .= "THIS ERROR WAS CAUSED BY A PLUGIN. REPORT IT TO THE PLUGIN DEVELOPER.\r\n";
}
$dump .= "Code: \r\n";
$file = @file($er["file"], FILE_IGNORE_NEW_LINES);
for($l = max(0, $er["line"] - 10); $l < $er["line"] + 10; ++$l){
$dump .= "[" . ($l + 1) . "] " . @$file[$l] . "\r\n";
}
$dump .= "\r\n\r\n";
$dump .= "Backtrace: \r\n";
foreach(getTrace() as $line){
$dump .= "$line\r\n";
}
$dump .= "\r\n\r\n";
$dump .= "NostalgiaCore version: " . MAJOR_VERSION . " [Protocol " . ProtocolInfo::CURRENT_PROTOCOL . "; API " . CURRENT_API_VERSION . "]\r\n";
$dump .= "Git commit: " . GIT_COMMIT . "\r\n";
$dump .= "Source SHA1 sum: " . SOURCE_SHA1SUM . "\r\n";
$dump .= "uname -a: " . php_uname("a") . "\r\n";
$dump .= "PHP Version: " . phpversion() . "\r\n";
$dump .= "Zend version: " . zend_version() . "\r\n";
$dump .= "OS : " . PHP_OS . ", " . Utils::getOS() . "\r\n";
$dump .= "Debug Info: " . var_export($this->debugInfo(false), true) . "\r\n\r\n\r\n";
global $arguments;
$dump .= "Parameters: " . var_export($arguments, true) . "\r\n\r\n\r\n";
$p = $this->api->getProperties();
if($p["rcon.password"] != ""){
$p["rcon.password"] = "******";
}
$dump .= "server.properties: " . var_export($p, true) . "\r\n\r\n\r\n";
if($this->api->plugin instanceof PluginAPI){
$plist = $this->api->plugin->getList();
$dump .= "Loaded plugins:\r\n";
foreach($plist as $p){
$dump .= $p["name"] . " " . $p["version"] . " by " . $p["author"] . "\r\n";
}
$dump .= "\r\n\r\n";
}
$extensions = [];
foreach(get_loaded_extensions() as $ext){
$extensions[$ext] = phpversion($ext);
}
$dump .= "Loaded Modules: " . var_export($extensions, true) . "\r\n";
$this->checkMemory();
$dump .= "Memory Usage Tracking: \r\n" . chunk_split(base64_encode(gzdeflate(implode(";", $this->memoryStats), 9))) . "\r\n";
ob_start();
phpinfo();
$dump .= "\r\nphpinfo(): \r\n" . chunk_split(base64_encode(gzdeflate(ob_get_contents(), 9))) . "\r\n";
ob_end_clean();
$dump .= "\r\n```";
$name = "Error_Dump_" . date("D_M_j-H.i.s-T_Y");
logg($dump, $name, true, 0, true);
console("[SEVERE] Please submit the \"{$name}.log\" file to the Bug Reporting page. Give as much info as you can.", true, true, 0);
}
public function debugInfo($console = false){
$info = [];
$info["tps"] = $this->getTPS();
$info["memory_usage"] = round((memory_get_usage() / 1024) / 1024, 2) . "MB";
$info["memory_peak_usage"] = round((memory_get_peak_usage() / 1024) / 1024, 2) . "MB";
$info["entities"] = $this->query("SELECT count(EID) as count FROM entities;", true);
$info["entities"] = $info["entities"]["count"];
$info["players"] = $this->query("SELECT count(CID) as count FROM players;", true);
$info["players"] = $info["players"]["count"];
$info["events"] = count($this->eventsID);
$info["handlers"] = $this->query("SELECT count(ID) as count FROM handlers;", true);
$info["handlers"] = $info["handlers"]["count"];
$info["actions"] = $this->query("SELECT count(ID) as count FROM actions;", true);
$info["actions"] = $info["actions"]["count"];
$info["garbage"] = gc_collect_cycles();
$this->handle("server.debug", $info);
if($console === true){
console("[DEBUG] TPS: " . $info["tps"] . ", Memory usage: " . $info["memory_usage"] . " (Peak " . $info["memory_peak_usage"] . "), Entities: " . $info["entities"] . ", Events: " . $info["events"] . ", Handlers: " . $info["handlers"] . ", Actions: " . $info["actions"] . ", Garbage: " . $info["garbage"], true, true, 2);
}
return $info;
}
public function checkMemory(){
$info = $this->debugInfo();
$data = $info["memory_usage"] . "," . $info["players"] . "," . $info["entities"];
$i = count($this->memoryStats) - 1;
if($i < 0 or $this->memoryStats[$i] !== $data){
$this->memoryStats[] = $data;
}
}
public function event($event, callable $func){
if(!is_callable($func)){
return false;
}elseif(isset(Deprecation::$events[$event])){
$sub = "";
if(Deprecation::$events[$event] !== false){
$sub = " Substitute \"" . Deprecation::$events[$event] . "\" found.";
}
console("[ERROR] Event \"$event\" has been deprecated.$sub [Attach to " . (is_array($func) ? get_class($func[0]) . "::" . $func[1] : $func) . "]");
}
$evid = $this->evCnt++;
if(!isset($this->events[$event])){
$this->events[$event] = [];
}
$this->events[$event][$evid] = $func;
$this->eventsID[$evid] = $event;
console("[INTERNAL] Attached " . (is_array($func) ? get_class($func[0]) . "::" . $func[1] : $func) . " to event " . $event . " (ID " . $evid . ")", true, true, 3);
return $evid;
}
}

View file

@ -1,7 +0,0 @@
<?php
interface IElement
{
public function __toString();
}

View file

@ -1,7 +0,0 @@
<?php
interface ITileNavigator
{
public function navigate(PathTile $from, PathTile $to, $maxDist);
}

View file

@ -1,12 +0,0 @@
<?php
class PHPUtils
{
public static function removeElementFromArray(&$arr, $element, $reindex = true){
if (($key = array_search($element, $arr)) !== false) {
unset($arr[$key]);
if($reindex) $arr = array_values($arr);
}
}
}

View file

@ -1,27 +0,0 @@
<?php
class PathTile implements IElement
{
public $x, $y;
public function __construct($x, $y){
$this->x = $x;
$this->y = $y;
}
public function equals(PathTile $t){
return $t->x === $this->x && $t->y === $this->y;
}
public function addOffset($offset){
$this->x += $offset[0];
$this->y += $offset[1];
return $this;
}
public function __toString(){
return $this->x.":".$this->y;
}
}

View file

@ -1,39 +0,0 @@
<?php
class PathTileXYZ extends PathTile
{
public $x, $y, $z;
/**
* @var Level
*/
public $level;
public function __construct($x, $y, $z, $level){
$this->x = floor($x);
$this->y = floor($y);
$this->z = floor($z);
$this->level = $level;
}
public function equals(PathTile $t){
return $t->x === $this->x && $t->y === $this->y && $t->z === $this->z;
}
public function asVector(){
return new Vector3($this->x, $this->y, $this->z);
}
public function asArray(){
return ["x" => $this->x, "y" => $this->y, "z" => $this->z];
}
public function addOffset($offset){
return new PathTileXYZ($this->x + $offset[0], $this->y + $offset[1], $this->z + $offset[2], $this->level);
}
public function __toString(){
return $this->x.":".$this->y.":".$this->z;
}
}

View file

@ -1,82 +0,0 @@
<?php
class TileNavigator implements ITileNavigator
{
private $blockedProvider, $neighborProvider, $distanceAlgorithm;
public static $pathfinderAccessed = 0;
public function __construct(IBlockedProvider $blockedProvider, INeighborProvider $neighborProvider, IDistanceAlgorithm $distanceAlgorithm){
$this->blockedProvider = $blockedProvider;
$this->neighborProvider = $neighborProvider;
$this->distanceAlgorithm = $distanceAlgorithm;
}
public function reconstructPath($path, $current){
$totalPath = [$current];
while (isset($path[(string)$current]))
{
$current = $path[(string)$current];
$totalPath[] = $current;
}
//foreach(array_unique($path) as $k => $p) console($k.":".$p);
//foreach($totalPath as $k => $p) console($k.":".$p);
array_pop($totalPath);
return array_reverse($totalPath);
}
public function navigate(PathTile $from, PathTile $to, $maxDist)
{
$open = new SplPriorityQueue();
$open->insert($from, 0);
$path = [];
$gScore = [];
$gScore[(string) $from] = 0;
$has = [(string)$from, true];
if($this->blockedProvider->isBlocked($to)){
return null;
}
$visited = [];
$maxDist*=$maxDist; //no square root
while(!$open->isEmpty())
{
$current = $open->top();
$open->next();
if ($current == $to){
return $this->reconstructPath($path, $current);
}
foreach($this->neighborProvider->getNeighbors($current) as $neighbor)
{
if(!Utils::in_range(Utils::distance_noroot($neighbor->asArray(), $from->asArray()), -$maxDist, $maxDist)){
continue;
}
if(isset($visited[(string)$neighbor])){
continue;
}
$visited[(string)$neighbor] = $neighbor;
$distbetweenCost = $this->distanceAlgorithm->calculate($current, $neighbor);
$tentativeG = $gScore[(string) $current] + $distbetweenCost;
if (!isset($has[(string)$neighbor]))
{
$open->insert($neighbor, -$tentativeG);
$has[(string)$neighbor] = true;
}
else if ($tentativeG >= $gScore[(string) $neighbor])
{
continue;
}
if(!isset($gScore[(string) $neighbor]) || $distbetweenCost < $gScore[(string) $neighbor]){
$path[(string) $neighbor] = $current;
}
$gScore[(string) $neighbor] = $tentativeG;
}
}
return null;
}
}

View file

@ -1,7 +0,0 @@
<?php
interface IDistanceAlgorithm
{
public function calculate(PathTile $from, PathTile $to);
}

View file

@ -1,14 +0,0 @@
<?php
class ManhattanHeuristic3D implements IDistanceAlgorithm
{
public function calculate(PathTile $from, PathTile $to)
{
if($from instanceof PathTileXYZ && $to instanceof PathTileXYZ){
return Utils::manh_distance($from->asArray(), $to->asArray());
}
return 666;
}
}

View file

@ -1,16 +0,0 @@
<?php
/**
* No sqrt distance
*/
class Pythagoras3D implements IDistanceAlgorithm
{
public function calculate(PathTile $from, PathTile $to)
{
if($from instanceof PathTileXYZ && $to instanceof PathTileXYZ){
return Utils::distance_noroot($from->asArray(), $to->asArray());
}
return INF;
}
}

View file

@ -1,12 +0,0 @@
<?php
interface IBlockedProvider
{
/**
* @param Tile $tile
*
* @return boolean
*/
public function isBlocked(PathTile $tile);
}

View file

@ -1,7 +0,0 @@
<?php
interface INeighborProvider
{
public function getNeighbors(PathTile $tile);
}

View file

@ -1,16 +0,0 @@
<?php
class MCBlockedProvider implements IBlockedProvider
{
public function isBlocked(PathTile $tile)
{
if($tile instanceof PathTileXYZ){
$b = $tile->level->getBlockWithoutVector($tile->x, $tile->y, $tile->z);
return $b instanceof Block && $b->isSolid;
}
return false;
}
}

View file

@ -1,34 +0,0 @@
<?php
class MCDiagonalProvider implements INeighborProvider
{
private static $neighbors = array([ 0, 0, -1 ], [ 1, 0, 0 ], [ 0, 0, 1 ], [ -1, 0, 0 ]);
private static $jumpOffset = [0, 1, 0];
private static $moveDownOffset = [0, -1, 0];
public function getNeighbors(PathTile $tile)
{
if($tile instanceof PathTileXYZ){
$pnts = [];
foreach(MCDiagonalProvider::$neighbors as $offset){
$pnt = $tile->addOffset($offset);
if(!$tile->level->getBlockWithoutVector($pnt->x, $pnt->y, $pnt->z, false)->isSolid){
if(!$tile->level->getBlockWithoutVector($pnt->x, $pnt->y - 1, $pnt->z, false)->isSolid){
--$pnt->y;
}
$pnts[] = $pnt;
}else{
if(!$tile->level->getBlockWithoutVector($pnt->x, $pnt->y + 1, $pnt->z, false)->isSolid){
++$pnt->y;
$pnts[] = $pnt;
}
}
}
return $pnts;
}
return [];
}
}

View file

@ -1,389 +0,0 @@
#!/bin/bash
COMPILER_VERSION="0.16"
PHP_VERSION="5.5.9"
ZEND_VM="GOTO"
LIBEDIT_VERSION="0.3"
ZLIB_VERSION="1.2.8"
PTHREADS_VERSION="0.1.0"
PHPYAML_VERSION="1.1.1"
YAML_VERSION="0.1.4"
CURL_VERSION="curl-7_35_0"
echo "[PocketMine] PHP installer and compiler for Linux & Mac"
DIR="$(pwd)"
date > "$DIR/install.log" 2>&1
uname -a >> "$DIR/install.log" 2>&1
echo "[INFO] Checking dependecies"
type make >> "$DIR/install.log" 2>&1 || { echo >&2 "[ERROR] Please install \"make\""; read -p "Press [Enter] to continue..."; exit 1; }
type autoconf >> "$DIR/install.log" 2>&1 || { echo >&2 "[ERROR] Please install \"autoconf\""; read -p "Press [Enter] to continue..."; exit 1; }
type automake >> "$DIR/install.log" 2>&1 || { echo >&2 "[ERROR] Please install \"automake\""; read -p "Press [Enter] to continue..."; exit 1; }
type libtool >> "$DIR/install.log" 2>&1 || { echo >&2 "[ERROR] Please install \"libtool\""; read -p "Press [Enter] to continue..."; exit 1; }
type m4 >> "$DIR/install.log" 2>&1 || { echo >&2 "[ERROR] Please install \"m4\""; read -p "Press [Enter] to continue..."; exit 1; }
type wget >> "$DIR/install.log" 2>&1 || type curl >> "$DIR/install.log" 2>&1 || { echo >&2 "[ERROR] Please install \"wget\" or \"curl\""; read -p "Press [Enter] to continue..."; exit 1; }
type getconf >> "$DIR/install.log" 2>&1 || { echo >&2 "[ERROR] Please install \"getconf\""; read -p "Press [Enter] to continue..."; exit 1; }
#Needed to use aliases
shopt -s expand_aliases
type wget >> "$DIR/install.log" 2>&1
if [ $? -eq 0 ]; then
alias download_file="wget --no-check-certificate -q -O -"
else
type curl >> "$DIR/install.log" 2>&1
if [ $? -eq 0 ]; then
alias download_file="curl --insecure --silent --location"
else
echo "error, curl or wget not found"
fi
fi
export CC="gcc"
COMPILE_FOR_ANDROID=no
RANLIB=ranlib
HAVE_MYSQLI="--with-mysqli=mysqlnd"
if [ "$1" == "rpi" ]; then
[ -z "$march" ] && march=armv6zk;
[ -z "$mtune" ] && mtune=arm1176jzf-s;
[ -z "$CFLAGS" ] && CFLAGS="-mfloat-abi=hard -mfpu=vfp";
echo "[INFO] Compiling for Raspberry Pi ARMv6zk hard float"
elif [ "$1" == "mac" ]; then
[ -z "$march" ] && march=prescott;
[ -z "$mtune" ] && mtune=generic;
[ -z "$CFLAGS" ] && CFLAGS="-fomit-frame-pointer";
echo "[INFO] Compiling for Intel MacOS"
elif [ "$1" == "ios" ]; then
[ -z "$march" ] && march=armv6;
[ -z "$mtune" ] && mtune=cortex-a8;
echo "[INFO] Compiling for iOS ARMv6"
elif [ "$1" == "crosscompile" ]; then
HAVE_MYSQLI="--without-mysqli"
if [ "$2" == "android" ] || [ "$2" == "android-armv6" ]; then
COMPILE_FOR_ANDROID=yes
[ -z "$march" ] && march=armv6;
[ -z "$mtune" ] && mtune=arm1136jf-s;
TOOLCHAIN_PREFIX="arm-unknown-linux-uclibcgnueabi"
export CC="$TOOLCHAIN_PREFIX-gcc"
CONFIGURE_FLAGS="--host=$TOOLCHAIN_PREFIX --enable-static-link --disable-ipv6"
CFLAGS="-uclibc --static $CFLAGS";
LDFLAGS="--static"
echo "[INFO] Cross-compiling for Android ARMv6"
elif [ "$2" == "android-armv7" ]; then
COMPILE_FOR_ANDROID=yes
[ -z "$march" ] && march=armv7-a;
[ -z "$mtune" ] && mtune=cortex-a8;
TOOLCHAIN_PREFIX="arm-unknown-linux-uclibcgnueabi"
export CC="$TOOLCHAIN_PREFIX-gcc"
CONFIGURE_FLAGS="--host=$TOOLCHAIN_PREFIX --enable-static-link --disable-ipv6"
CFLAGS="-uclibc --static $CFLAGS";
LDFLAGS="--static"
echo "[INFO] Cross-compiling for Android ARMv7"
elif [ "$2" == "rpi" ]; then
TOOLCHAIN_PREFIX="arm-linux-gnueabihf"
[ -z "$march" ] && march=armv6zk;
[ -z "$mtune" ] && mtune=arm1176jzf-s;
[ -z "$CFLAGS" ] && CFLAGS="-mfloat-abi=hard -mfpu=vfp";
export CC="$TOOLCHAIN_PREFIX-gcc"
CONFIGURE_FLAGS="--host=$TOOLCHAIN_PREFIX"
[ -z "$CFLAGS" ] && CFLAGS="-uclibc";
echo "[INFO] Cross-compiling for Raspberry Pi ARMv6zk hard float"
elif [ "$2" == "mac" ]; then
[ -z "$march" ] && march=prescott;
[ -z "$mtune" ] && mtune=generic;
[ -z "$CFLAGS" ] && CFLAGS="-fomit-frame-pointer";
TOOLCHAIN_PREFIX="i686-apple-darwin10"
export CC="$TOOLCHAIN_PREFIX-gcc"
CONFIGURE_FLAGS="--host=$TOOLCHAIN_PREFIX"
#zlib doesn't use the correct ranlib
RANLIB=$TOOLCHAIN_PREFIX-ranlib
echo "[INFO] Cross-compiling for Intel MacOS"
elif [ "$2" == "ios" ] || [ "$2" == "ios-armv6" ]; then
[ -z "$march" ] && march=armv6;
[ -z "$mtune" ] && mtune=generic-armv6;
CONFIGURE_FLAGS="--target=arm-apple-darwin10"
elif [ "$2" == "ios-armv7" ]; then
[ -z "$march" ] && march=armv7-a;
[ -z "$mtune" ] && mtune=generic-armv7-a;
CONFIGURE_FLAGS="--target=arm-apple-darwin10"
else
echo "Please supply a proper platform [android android-armv6 android-armv7 rpi mac ios ios-armv6 ios-armv7] to cross-compile"
exit 1
fi
elif [ -z "$CFLAGS" ]; then
if [ `getconf LONG_BIT` = "64" ]; then
echo "[INFO] Compiling for current machine using 64-bit"
CFLAGS="-m64 $CFLAGS"
else
echo "[INFO] Compiling for current machine using 32-bit"
CFLAGS="-m32 $CFLAGS"
fi
fi
cat > test.c <<'CTEST'
#include <stdio.h>
main(){
printf("Hello world\n");
}
CTEST
type $CC >> "$DIR/install.log" 2>&1 || { echo >&2 "[ERROR] Please install \"$CC\""; read -p "Press [Enter] to continue..."; exit 1; }
[ -z "$THREADS" ] && THREADS=1;
[ -z "$march" ] && march=native;
[ -z "$mtune" ] && mtune=native;
[ -z "$CFLAGS" ] && CFLAGS="";
[ -z "$LDFLAGS" ] && LDFLAGS="";
[ -z "$CONFIGURE_FLAGS" ] && CONFIGURE_FLAGS="";
if [ "$mtune" != "none" ]; then
$CC -march=$march -mtune=$mtune $CFLAGS -o test test.c >> "$DIR/install.log" 2>&1
if [ $? -eq 0 ]; then
CFLAGS="-march=$march -mtune=$mtune -fno-gcse $CFLAGS"
fi
else
$CC -march=$march $CFLAGS -o test test.c >> "$DIR/install.log" 2>&1
if [ $? -eq 0 ]; then
CFLAGS="-march=$march -fno-gcse $CFLAGS"
fi
fi
rm test >> "$DIR/install.log" 2>&1
rm test.c >> "$DIR/install.log" 2>&1
export CFLAGS="-O2 $CFLAGS"
export LDFLAGS="$LDFLAGS"
rm -r -f install_data/ >> "$DIR/install.log" 2>&1
rm -r -f bin/ >> "$DIR/install.log" 2>&1
mkdir -m 0777 install_data >> "$DIR/install.log" 2>&1
mkdir -m 0777 bin >> "$DIR/install.log" 2>&1
cd install_data
set -e
#PHP 5
echo -n "[PHP] downloading $PHP_VERSION..."
download_file "http://php.net/get/php-$PHP_VERSION.tar.gz/from/this/mirror" | tar -zx >> "$DIR/install.log" 2>&1
mv php-$PHP_VERSION php
echo " done!"
if [ 1 ] || [ "$1" == "crosscompile" ] || [ "$1" == "rpi" ]; then
HAVE_LIBEDIT="--without-libedit"
else
#libedit
echo -n "[libedit] downloading $LIBEDIT_VERSION..."
download_file "http://download.sourceforge.net/project/libedit/libedit/libedit-$LIBEDIT_VERSION/libedit-$LIBEDIT_VERSION.tar.gz" | tar -zx >> "$DIR/install.log" 2>&1
echo -n " checking..."
cd libedit
./configure --prefix="$DIR/install_data/php/ext/libedit" --enable-static >> "$DIR/install.log" 2>&1
echo -n " compiling..."
if make -j $THREADS >> "$DIR/install.log" 2>&1; then
echo -n " installing..."
make install >> "$DIR/install.log" 2>&1
HAVE_LIBEDIT="--with-libedit=\"$DIR/install_data/php/ext/libedit\""
else
echo -n " disabling..."
HAVE_LIBEDIT="--without-libedit"
fi
echo -n " cleaning..."
cd ..
rm -r -f ./libedit
echo " done!"
fi
#zlib
echo -n "[zlib] downloading $ZLIB_VERSION..."
download_file "http://zlib.net/zlib-$ZLIB_VERSION.tar.gz" | tar -zx >> "$DIR/install.log" 2>&1
mv zlib-$ZLIB_VERSION zlib
echo -n " checking..."
cd zlib
RANLIB=$RANLIB ./configure --prefix="$DIR/install_data/php/ext/zlib" \
--static >> "$DIR/install.log" 2>&1
echo -n " compiling..."
make -j $THREADS >> "$DIR/install.log" 2>&1
echo -n " installing..."
make install >> "$DIR/install.log" 2>&1
echo -n " cleaning..."
cd ..
rm -r -f ./zlib
echo " done!"
if [ "$(uname -s)" == "Darwin" ] && [ "$1" != "crosscompile" ] && [ "$2" != "curl" ]; then
HAVE_CURL="shared,/usr"
else
#curl
echo -n "[cURL] downloading $CURL_VERSION..."
download_file "https://github.com/bagder/curl/archive/$CURL_VERSION.tar.gz" | tar -zx >> "$DIR/install.log" 2>&1
mv curl-$CURL_VERSION curl
echo -n " checking..."
cd curl
if [ ! -f ./configure ]; then
./buildconf --force >> "$DIR/install.log" 2>&1
fi
./configure --disable-dependency-tracking \
--enable-ipv6 \
--enable-optimize \
--enable-http \
--enable-ftp \
--disable-dict \
--enable-file \
--disable-gopher \
--disable-imap \
--disable-pop3 \
--disable-rtsp \
--disable-smtp \
--disable-telnet \
--disable-tftp \
--disable-ldap \
--disable-ldaps \
--without-libidn \
--enable-threaded-resolver \
--prefix="$DIR/install_data/php/ext/curl" \
--disable-shared \
--enable-static \
$CONFIGURE_FLAGS >> "$DIR/install.log" 2>&1
echo -n " compiling..."
make -j $THREADS >> "$DIR/install.log" 2>&1
echo -n " installing..."
make install >> "$DIR/install.log" 2>&1
echo -n " cleaning..."
cd ..
rm -r -f ./curl
echo " done!"
HAVE_CURL="$DIR/install_data/php/ext/curl"
fi
#pthreads
echo -n "[PHP pthreads] downloading $PTHREADS_VERSION..."
download_file "http://pecl.php.net/get/pthreads-$PTHREADS_VERSION.tgz" | tar -zx >> "$DIR/install.log" 2>&1
mv pthreads-$PTHREADS_VERSION "$DIR/install_data/php/ext/pthreads"
echo " done!"
#PHP YAML
echo -n "[PHP YAML] downloading $PHPYAML_VERSION..."
download_file "http://pecl.php.net/get/yaml-$PHPYAML_VERSION.tgz" | tar -zx >> "$DIR/install.log" 2>&1
mv yaml-$PHPYAML_VERSION "$DIR/install_data/php/ext/yaml"
echo " done!"
#YAML
echo -n "[YAML] downloading $YAML_VERSION..."
download_file "http://pyyaml.org/download/libyaml/yaml-$YAML_VERSION.tar.gz" | tar -zx >> "$DIR/install.log" 2>&1
mv yaml-$YAML_VERSION yaml
echo -n " checking..."
cd yaml
RANLIB=$RANLIB ./configure \
--prefix="$DIR/install_data/php/ext/yaml" \
--enable-static \
--disable-shared \
$CONFIGURE_FLAGS >> "$DIR/install.log" 2>&1
echo -n " compiling..."
make -j $THREADS >> "$DIR/install.log" 2>&1
echo -n " installing..."
make install >> "$DIR/install.log" 2>&1
echo -n " cleaning..."
cd ..
rm -r -f ./yaml
echo " done!"
echo -n "[PHP]"
set +e
if which free >/dev/null; then
MAX_MEMORY=$(free -m | awk '/^Mem:/{print $2}')
else
MAX_MEMORY=$(top -l 1 | grep PhysMem: | awk '{print $10}' | tr -d 'a-zA-Z')
fi
if [ $MAX_MEMORY -gt 512 ] && [ "$1" != "crosscompile" ]; then
echo -n " enabling optimizations..."
OPTIMIZATION="--enable-inline-optimization "
else
OPTIMIZATION="--disable-inline-optimization "
fi
set -e
echo -n " checking..."
cd php
rm -rf ./aclocal.m4 >> "$DIR/install.log" 2>&1
rm -rf ./autom4te.cache/ >> "$DIR/install.log" 2>&1
rm -f ./configure >> "$DIR/install.log" 2>&1
./buildconf --force >> "$DIR/install.log" 2>&1
if [ "$1" == "crosscompile" ]; then
sed -i 's/pthreads_working=no/pthreads_working=yes/' ./configure
export LIBS="-lpthread -ldl"
CONFIGURE_FLAGS="$CONFIGURE_FLAGS --enable-opcache=no"
fi
./configure $OPTIMIZATION--prefix="$DIR/bin/php5" \
--exec-prefix="$DIR/bin/php5" \
--with-curl="$HAVE_CURL" \
--with-zlib="$DIR/install_data/php/ext/zlib" \
--with-zlib-dir="$DIR/install_data/php/ext/zlib" \
--with-yaml="$DIR/install_data/php/ext/yaml" \
$HAVE_LIBEDIT \
--disable-libxml \
--disable-xml \
--disable-dom \
--disable-simplexml \
--disable-xmlreader \
--disable-xmlwriter \
--disable-cgi \
--disable-session \
--disable-debug \
--disable-phar \
--disable-pdo \
--without-pear \
--without-iconv \
--without-pdo-sqlite \
--enable-ctype \
--enable-sockets \
--enable-shared=no \
--enable-static=yes \
--enable-shmop \
--enable-pcntl \
--enable-pthreads \
--enable-maintainer-zts \
--enable-zend-signals \
$HAVE_MYSQLI \
--enable-embedded-mysqli \
--enable-bcmath \
--enable-cli \
--enable-zip \
--with-zend-vm=$ZEND_VM \
$CONFIGURE_FLAGS >> "$DIR/install.log" 2>&1
echo -n " compiling..."
if [ $COMPILE_FOR_ANDROID == "yes" ]; then
sed -i 's/-export-dynamic/-all-static/g' Makefile
fi
make -j $THREADS >> "$DIR/install.log" 2>&1
echo -n " installing..."
make install >> "$DIR/install.log" 2>&1
echo " generating php.ini..."
TIMEZONE=$(date +%Z)
touch "$DIR/bin/php5/lib/php.ini"
if [ "$1" != "crosscompile" ]; then
OPCACHE_PATH=$(find "$DIR/bin/php5" -name opcache.so)
echo "zend_extension=\"$OPCACHE_PATH\"" >> "$DIR/bin/php5/lib/php.ini"
echo "opcache.enable=1" >> "$DIR/bin/php5/lib/php.ini"
echo "opcache.enable_cli=1" >> "$DIR/bin/php5/lib/php.ini"
echo "opcache.save_comments=0" >> "$DIR/bin/php5/lib/php.ini"
echo "opcache.fast_shutdown=1" >> "$DIR/bin/php5/lib/php.ini"
echo "opcache.max_accelerated_files=4096" >> "$DIR/bin/php5/lib/php.ini"
echo "opcache.interned_strings_buffer=8" >> "$DIR/bin/php5/lib/php.ini"
echo "opcache.memory_consumption=128" >> "$DIR/bin/php5/lib/php.ini"
echo "opcache.optimization_level=0xffffffff" >> "$DIR/bin/php5/lib/php.ini"
fi
if [ "$HAVE_CURL" == "shared,/usr" ]; then
echo "extension=curl.so" >> "$DIR/bin/php5/lib/php.ini"
fi
echo "date.timezone=$TIMEZONE" >> "$DIR/bin/php5/lib/php.ini"
echo "short_open_tag=0" >> "$DIR/bin/php5/lib/php.ini"
echo "asp_tags=0" >> "$DIR/bin/php5/lib/php.ini"
echo " done!"
cd "$DIR"
echo -n "[INFO] Cleaning up..."
rm -r -f install_data/ >> "$DIR/install.log" 2>&1
date >> "$DIR/install.log" 2>&1
echo " done!"
echo "[PocketMine] You should start the server now using \"./start.sh.\""
echo "[PocketMine] If it doesn't work, please send the \"install.log\" file to the Bug Tracker."

View file

@ -1,61 +0,0 @@
#!/bin/bash
echo "==================================="
echo "NostalgiaCore Installer"
echo "==================================="
echo "["$(date +%k:%M)"] Downloading NostalgiaCore..."
apt install git
git clone https://github.com/kotyaralih/NostalgiaCore
echo "["$(date +%k:%M)"] Extracting..."
cd NostalgiaCore
mv * ../
cd ../
rm -r NostalgiaCore
rm bin.7z
echo "["$(date +%k:%M)"] Downloading PHP..."
arch=$(uname -m)
if [[ $arch == x86_64* ]]; then
echo "X64 Architecture"
wget https://owouwu.ru/NC_bin.tar.gz > /dev/null
tar -xvf NC_bin.tar.gz
rm NC_bin.tar.gz
elif [[ $arch == i*86 ]]; then
echo "X32 Architecture"
wget https://owouwu.ru/NC_bin.tar.gz > /dev/null
tar -xvf NC_bin.tar.gz
rm NC_bin.tar.gz
elif [[ $arch == arm* ]] || [[ $arch = aarch* ]]; then
echo "ARM Architecture"
wget https://owouwu.ru/NCArm_bin.tar.gz > /dev/null
tar -xvf NCArm_bin.tar.gz
rm NCArm_bin.tar.gz
fi
if [ $(./bin/php5/bin/php -r 'echo "yes";' 2>/dev/null) == "yes" ]; then
OPCACHE_PATH="$(find $(pwd) -name opcache.so)"
XDEBUG_PATH="$(find $(pwd) -name xdebug.so)"
echo "" > "./bin/php5/bin/php.ini"
#UOPZ_PATH="$(find $(pwd) -name uopz.so)"
#echo "zend_extension=\"$UOPZ_PATH\"" >> "./bin/php5/bin/php.ini"
echo "zend_extension=\"$OPCACHE_PATH\"" >> "./bin/php5/bin/php.ini"
echo "zend_extension=\"$XDEBUG_PATH\"" >> "./bin/php5/bin/php.ini"
echo "opcache.enable=1" >> "./bin/php5/bin/php.ini"
echo "opcache.enable_cli=1" >> "./bin/php5/bin/php.ini"
echo "opcache.save_comments=0" >> "./bin/php5/bin/php.ini"
echo "opcache.fast_shutdown=1" >> "./bin/php5/bin/php.ini"
echo "opcache.max_accelerated_files=4096" >> "./bin/php5/bin/php.ini"
echo "opcache.interned_strings_buffer=8" >> "./bin/php5/bin/php.ini"
echo "opcache.memory_consumption=128" >> "./bin/php5/bin/php.ini"
echo "opcache.optimization_level=0xffffffff" >> "./bin/php5/bin/php.ini"
echo "date.timezone=$TIMEZONE" >> "./bin/php5/bin/php.ini"
echo "short_open_tag=0" >> "./bin/php5/bin/php.ini"
echo "asp_tags=0" >> "./bin/php5/bin/php.ini"
echo "phar.readonly=0" >> "./bin/php5/bin/php.ini"
echo "phar.require_hash=1" >> "./bin/php5/bin/php.ini"
echo "done"
alldone=yes
else
echo "Invalid PHP build detected"
fi
echo "Done, starting..."
echo "Wait >15 seconds..."
chmod +x start.sh
bash start.sh

View file

@ -1,182 +0,0 @@
#!/bin/bash -x
export PATH=/opt/arm-2013.05/bin:/opt/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian/bin:/opt/arm-unknown-linux-uclibcgnueabi/bin:$PATH
export THREADS=2
#Needed to use aliases
shopt -s expand_aliases
type wget > /dev/null 2>&1
if [ $? -eq 0 ]; then
alias download_file="wget --no-check-certificate -q -O -"
else
type curl >> /dev/null 2>&1
if [ $? -eq 0 ]; then
alias download_file="curl --insecure --silent --location"
else
echo "error, curl or wget not found"
fi
fi
rm -rf $WORKSPACE/compile.sh
download_file "https://github.com/PocketMine/PocketMine-MP/raw/master/src/build/compile.sh" > $WORKSPACE/compile.sh
chmod +x $WORKSPACE/compile.sh
SCRIPT="$WORKSPACE/compile.sh"
ARCHIVE=$WORKSPACE/archive
COMPILEDIR=$WORKSPACE/compile
rm -rf $ARCHIVE $COMPILEDIR
mkdir -p $ARCHIVE
mkdir -p $COMPILEDIR
if [ "$COMPILE_LINUX_32BIT" = "true" ];
then
mkdir -p {$COMPILEDIR,$ARCHIVE}/linux/32bit
cd $COMPILEDIR/linux/32bit
CFLAGS=-m32 march=i686 mtune=generic $SCRIPT
cp -r $COMPILEDIR/linux/32bit/{install.log,bin/*,install_data/*} $ARCHIVE/linux/32bit/
if [ ! -f $COMPILEDIR/linux/32bit/bin/php5/bin/php ]; then
exit 1
fi
fi
if [ "$COMPILE_LINUX_64BIT" = "true" ];
then
mkdir -p {$COMPILEDIR,$ARCHIVE}/linux/64bit
cd $COMPILEDIR/linux/64bit
$SCRIPT
cp -r $COMPILEDIR/linux/64bit/{install.log,bin/*,install_data/*} $ARCHIVE/linux/64bit/
if [ ! -f $COMPILEDIR/linux/64bit/bin/php5/bin/php ]; then
exit 1
fi
fi
if [ "$COMPILE_MAC" = "true" ];
then
mkdir -p {$COMPILEDIR,$ARCHIVE}/mac
cd $COMPILEDIR/mac
curl -L http://ftpmirror.gnu.org/libtool/libtool-2.4.2.tar.gz | tar -xz > /dev/null
cd libtool-2.4.2
./configure --prefix="$COMPILEDIR/mac/libtool" > /dev/null
make > /dev/null
make install
cd ../
rm -rf libtool-2.4.2
export LIBTOOL="$COMPILEDIR/mac/libtool/bin/libtool"
export LIBTOOLIZE="$COMPILEDIR/mac/libtool/bin/libtoolize"
$SCRIPT mac curl
cp -r $COMPILEDIR/mac/{install.log,bin/*,install_data/*} $ARCHIVE/mac/
if [ ! -f $COMPILEDIR/mac/bin/php5/bin/php ]; then
exit 1
fi
fi
if [ "$COMPILE_RPI" = "true" ];
then
mkdir -p {$COMPILEDIR,$ARCHIVE}/rpi
cd $COMPILEDIR/rpi
$SCRIPT rpi
cp -r $COMPILEDIR/rpi/{install.log,bin/*,install_data/*} $ARCHIVE/rpi/
if [ ! -f $COMPILEDIR/rpi/bin/php5/bin/php ]; then
exit 1
fi
fi
if [ "$CROSSCOMPILE_ANDROID_ARMV6" = "true" ];
then
mkdir -p {$COMPILEDIR,$ARCHIVE}/crosscompile/android-armv6
cd $COMPILEDIR/crosscompile/android-armv6
$SCRIPT crosscompile android-armv6
cp -r $COMPILEDIR/crosscompile/android-armv6/{install.log,bin/*,install_data/*} $ARCHIVE/crosscompile/android-armv6/
if [ ! -f $COMPILEDIR/crosscompile/android-armv6/bin/php5/bin/php ]; then
exit 1
fi
fi
if [ "$CROSSCOMPILE_ANDROID_ARMV7" = "true" ];
then
mkdir -p {$COMPILEDIR,$ARCHIVE}/crosscompile/android-armv7
cd $COMPILEDIR/crosscompile/android-armv7
$SCRIPT crosscompile android-armv7
cp -r $COMPILEDIR/crosscompile/android-armv7/{install.log,bin/*,install_data/*} $ARCHIVE/crosscompile/android-armv7/
if [ ! -f $COMPILEDIR/crosscompile/android-armv7/bin/php5/bin/php ]; then
exit 1
fi
fi
if [ "$CROSSCOMPILE_IOS_ARMV6" = "true" ];
then
mkdir -p {$COMPILEDIR,$ARCHIVE}/crosscompile/ios-armv6
cd $COMPILEDIR/crosscompile/ios-armv6
curl -L http://ftpmirror.gnu.org/libtool/libtool-2.4.2.tar.gz | tar -xz > /dev/null
cd libtool-2.4.2
./configure --prefix="$COMPILEDIR/crosscompile/ios-armv6/libtool" > /dev/null
make > /dev/null
make install
cd ../
rm -rf libtool-2.4.2
export LIBTOOL="$COMPILEDIR/crosscompile/ios-armv6/libtool/bin/libtool"
export LIBTOOLIZE="$COMPILEDIR/crosscompile/ios-armv6/libtool/bin/libtoolize"
PATH="/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:$PATH" $SCRIPT crosscompile ios-armv6
cp -r $COMPILEDIR/crosscompile/ios-armv6/{install.log,bin/*,install_data/*} $ARCHIVE/crosscompile/ios-armv6/
if [ ! -f $COMPILEDIR/crosscompile/ios-armv6/bin/php5/bin/php ]; then
exit 1
fi
fi
if [ "$CROSSCOMPILE_IOS_ARMV7" = "true" ];
then
mkdir -p {$COMPILEDIR,$ARCHIVE}/crosscompile/ios-armv7
cd $COMPILEDIR/crosscompile/ios-armv7
curl -L http://ftpmirror.gnu.org/libtool/libtool-2.4.2.tar.gz | tar -xz > /dev/null
cd libtool-2.4.2
./configure --prefix="$COMPILEDIR/crosscompile/ios-armv7/libtool" > /dev/null
make > /dev/null
make install
cd ../
rm -rf libtool-2.4.2
export LIBTOOL="$COMPILEDIR/crosscompile/ios-armv7/libtool/bin/libtool"
export LIBTOOLIZE="$COMPILEDIR/crosscompile/ios-armv7/libtool/bin/libtoolize"
PATH="/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:$PATH" $SCRIPT crosscompile ios-armv7
cp -r $COMPILEDIR/crosscompile/ios-armv7/{install.log,bin/*,install_data/*} $ARCHIVE/crosscompile/ios-armv7/
if [ ! -f $COMPILEDIR/crosscompile/ios-armv7/bin/php5/bin/php ]; then
exit 1
fi
fi
if [ "$CROSSCOMPILE_RPI" = "true" ];
then
mkdir -p {$COMPILEDIR,$ARCHIVE}/crosscompile/rpi
cd $COMPILEDIR/crosscompile/rpi
$SCRIPT crosscompile rpi
cp -r $COMPILEDIR/crosscompile/rpi/{install.log,bin/*,install_data/*} $ARCHIVE/crosscompile/rpi/
if [ ! -f $COMPILEDIR/crosscompile/rpi/bin/php5/bin/php ]; then
exit 1
fi
fi
if [ "$CROSSCOMPILE_MAC" = "true" ];
then
mkdir -p {$COMPILEDIR,$ARCHIVE}/crosscompile/mac
cd $COMPILEDIR/crosscompile/mac
$SCRIPT crosscompile mac curl
cp -r $COMPILEDIR/crosscompile/mac/{install.log,bin/*,install_data/*} $ARCHIVE/crosscompile/mac/
if [ ! -f $COMPILEDIR/crosscompile/mac/bin/php5/bin/php ]; then
exit 1
fi
fi

View file

@ -1,61 +0,0 @@
<?php
set_time_limit(0);
if(ini_get("date.timezone") == ""){ //No Timezone set
date_default_timezone_set("GMT");
if(strpos(" " . strtoupper(php_uname("s")), " WIN") !== false){
$time = time();
$time -= $time % 60;
//TODO: Parse different time & date formats by region. ¬¬ world
//Example: USA
exec("time.exe /T", $hour);
$i = array_map("intval", explode(":", trim($hour[0])));
exec("date.exe /T", $date);
$j = array_map("intval", explode(substr($date[0], 2, 1), trim($date[0])));
$offset = round((mktime($i[0], $i[1], 0, $j[1], $j[0], $j[2]) - $time) / 60) * 60;
}else{
exec("date +%s", $t);
$offset = round((intval(trim($t[0])) - time()) / 60) * 60;
}
$daylight = (int) date("I");
$d = timezone_name_from_abbr("", $offset, $daylight);
@ini_set("date.timezone", $d);
date_default_timezone_set($d);
}else{
$d = @date_default_timezone_get();
if(strpos($d, "/") === false){
$d = timezone_name_from_abbr($d);
@ini_set("date.timezone", $d);
date_default_timezone_set($d);
}
}
gc_enable();
error_reporting(E_ALL | E_STRICT);
ini_set("allow_url_fopen", 1);
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
ini_set("default_charset", "utf-8");
if(defined("POCKETMINE_COMPILE") and POCKETMINE_COMPILE === true){
define("FILE_PATH", realpath(dirname(__FILE__)) . "/");
}else{
define("FILE_PATH", realpath(dirname(__FILE__) . "/../") . "/");
}
set_include_path(get_include_path() . PATH_SEPARATOR . FILE_PATH);
ini_set("memory_limit", "256M"); //Default
define("LOG", true);
define("START_TIME", microtime(true));
define("MAJOR_VERSION", "2.0.0dev");
define("CODENAME", "Breadfence"); //i'm not very creative - kotyaralih
define("CURRENT_MINECRAFT_VERSION", "v0.9.5 alpha");
define("CURRENT_API_VERSION", '13.1');
define("CURRENT_PHP_VERSION", "8.0");
$gitsha1 = false;
if(file_exists(FILE_PATH . ".git/refs/heads/master")){ //Found Git information!
define("GIT_COMMIT", strtolower(trim(file_get_contents(FILE_PATH . ".git/refs/heads/master"))));
}else{ //Unknown :(
define("GIT_COMMIT", str_repeat("00", 20));
}

View file

@ -1,50 +0,0 @@
<?php
//0.9.5 adds 2 new biomes, ExtremeHills+ and JungleM(Modified Jungle)
define("BIOME_OCEAN", 0);
define("BIOME_PLAINS", 1);
define("BIOME_DESERT", 2);
define("BIOME_EXTREME_HILLS", 3); //extreme_hills
define("BIOME_FOREST", 4);
define("BIOME_TAIGA", 5);
define("BIOME_SWAMP", 6);
define("BIOME_RIVER", 7);
define("BIOME_HELL", 8); //yes it is a biome in 0.9
//id 9 found, not sure about name, maybe sky
define("BIOME_FROZEN_OCEAN", 10);
define("BIOME_FROZEN_RIVER", 11);
define("BIOME_ICE_PLAINS", 12);
define("BIOME_ICE_MOUNTAINS", 13); //snow covered, temp&fall->0.0, 0.5
define("BIOME_MUSHROOM_ISLAND", 14);
define("BIOME_MUSHROOM_ISLAND_SHORE", 15);
define("BIOME_BEACH", 16);
define("BIOME_DESERT_HILLS", 17);
define("BIOME_FOREST_HILLS", 18);
define("BIOME_TAIGA_HILLS", 19);
define("BIOME_EXTREME_HILLS_EDGE", 20);
define("BIOME_JUNGLE", 21);
define("BIOME_JUNGLE_HILLS", 22);
define("BIOME_JUNGLE_EDGE", 23);
define("BIOME_DEEP_OCEAN", 24);
define("BIOME_STONE_BEACH", 25);
define("BIOME_COLD_BEACH", 26);
define("BIOME_BIRCH_FOREST", 27);
define("BIOME_BIRCH_FOREST_HILLS", 28);
define("BIOME_ROOFED_FOREST", 29);
define("BIOME_COLD_TAIGA", 30);
define("BIOME_COLD_TAIGA_HILLS", 31);
define("BIOME_MEGA_TAIGA", 32);
define("BIOME_MEGA_TAIGA_HILLS", 33);
define("BIOME_EXTREME_HILLS_PLUS", 34);
define("BIOME_SAVANNA", 35);
define("BIOME_SAVANNA_PLATEAU", 36);
define("BIOME_MESA", 37);
define("BIOME_MESA_PLATEAU_F", 38);
define("BIOME_MESA_PLATEAU", 39);
//define("BIOME_SUNFLOWER_PLAINS", 129); metioning not found
//define("BIOME_ICE_PLAINS_SPIKES", 140); metioning not found
define("BIOME_REDWOOD_TAIGA_MUTATED", 160); //mentioned, but cannot check id
define("BIOME_MAX_BIOMES", 256);

View file

@ -1,13 +0,0 @@
<?php
//TileEntities
define("TILE_SIGN", "Sign");
define("TILE_CHEST", "Chest");
define("CHEST_SLOTS", 27);
define("TILE_FURNACE", "Furnace");
define("FURNACE_SLOTS", 3);
define("TILE_MOB_SPAWNER", "MobSpawner");

View file

@ -1,260 +0,0 @@
<?php
define("AIR", 0);
define("STONE", 1);
define("GRANITE", "1:1");
define("POLISHED_GRANITE", "1:2");
define("DIORITE", "1:3");
define("POLISHED_DIORITE", "1:4");
define("ANDESITE", "1:5");
define("POLISHED_ANDESITE", "1:6");
define("GRASS", 2);
define("DIRT", 3);
define("GRASSLESS_DIRT", "3:1");
define("COBBLESTONE", 4);
define("COBBLE", 4);
define("PLANK", 5);
define("PLANKS", 5);
define("WOODEN_PLANK", 5);
define("WOODEN_PLANKS", 5);
define("SPRUCE_WOODEN_PLANKS", "5:1");
define("BIRCH_WOODEN_PLANKS", "5:2");
define("JUNGLE_WOODEN_PLANKS", "5:3");
define("ACACIA_WOODEN_PLANKS", "5:4");
define("DARK_OAK_WOODEN_PLANKS", "5:5");
define("SAPLING", 6);
define("SAPLINGS", 6);
define("SPRUCE_SAPLING", "6:1");
define("BIRCH_SAPLING", "6:2");
define("JUNGLE_SAPLING", "6:3");
define("ACACIA_SAPLING", "6:4");
define("DARK_OAK_SAPLING", "6:5");
define("BEDROCK", 7);
define("WATER", 8);
define("STILL_WATER", 9);
define("LAVA", 10);
define("STILL_LAVA", 11);
define("SAND", 12);
define("RED_SAND", "12:1");
define("GRAVEL", 13);
define("GOLD_ORE", 14);
define("IRON_ORE", 15);
define("COAL_ORE", 16);
define("WOOD", 17);
define("TRUNK", 17);
define("SPRUCE_WOOD", "17:1");
define("BIRCH_WOOD", "17:2");
define("JUNGLE_WOOD", "17:3");
define("LEAVES", 18);
define("LEAVE", 18);
define("SPRUCE_LEAVES", "18:1");
define("BIRCH_LEAVES", "18:2");
define("JUNGLE_LEAVES", "18:3");
define("SPONGE", 19);
define("GLASS", 20);
define("LAPIS_ORE", 21);
define("LAPIS_BLOCK", 22);
define("SANDSTONE", 24);
define("BED_BLOCK", 26);
define("POWERED_RAIL", 27);
define("COBWEB", 30);
define("TALL_GRASS", 31); //shrub?
define("BUSH", 32);
define("DEAD_BUSH", 32);
define("WOOL", 35);
define("WHITE_WOOL", 35);
define("ORANGE_WOOL", "35:1");
define("MAGENTA_WOOL", "35:2");
define("LIGHT_BLUE_WOOL", "35:3");
define("YELLOW_WOOL", "35:4");
define("LIME_WOOL", "35:5");
define("PINK_WOOL", "35:6");
define("GRAY_WOOL", "35:7");
define("LIGHT_GRAY_WOOL", "35:8");
define("CYAN_WOOL", "35:9");
define("PURPLE_WOOL", "35:10");
define("BLUE_WOOL", "35:11");
define("BROWN_WOOL", "35:12");
define("GREEN_WOOL", "35:13");
define("RED_WOOL", "35:14");
define("BLACK_WOOL", "35:15");
define("DANDELION", 37);
define("YELLOW_FLOWER", 37);
define("ROSE", 38);
define("MULTIFLOWER", 38);
define("CYAN_FLOWER", 38); //NO
define("RED_FLOWER", 38);
define("BLUE_ORCHID", "38:1");
define("ALLIUM", "38:2");
define("AZURE_BLUET", "38:3");
define("RED_TULIP", "38:4");
define("ORANGE_TULIP", "38:5");
define("wHITE_TULIP", "38:6");
define("PINK_TULIP", "38:7");
define("OXEYE_DAISY", "38:8");
define("BROWN_MUSHROOM", 39);
define("RED_MUSHROOM", 40);
define("GOLD_BLOCK", 41);
define("IRON_BLOCK", 42);
define("DOUBLE_SLAB", 43);
define("DOUBLE_SLABS", 43);
//ANOTHER DOUBLE SLABS
define("SLAB", 44);
define("SLABS", 44);
//ANOTHER SLABS
define("BRICKS", 45);
define("BRICKS_BLOCK", 45);
define("TNT", 46);
define("BOOKSHELF", 47);
define("MOSS_STONE", 48);
define("MOSSY_COBBLESTONE", 48);
define("MOSSY_STONE", 48);
define("OBSIDIAN", 49);
define("TORCH", 50);
define("FIRE", 51);
define("MONSTER_SPAWNER", 52);
define("WOOD_STAIRS", 53);
define("WOODEN_STAIRS", 53);
define("OAK_WOOD_STAIRS", 53);
define("OAK_WOODEN_STAIRS", 53);
define("CHEST", 54);
define("DIAMOND_ORE", 56);
define("DIAMOND_BLOCK", 57);
define("CRAFTING_TABLE", 58);
define("WORKBENCH", 58);
define("WHEAT_BLOCK", 59);
define("FARMLAND", 60);
define("FURNACE", 61);
define("BURNING_FURNACE", 62);
define("LIT_FURNACE", 62);
define("SIGN_POST", 63);
define("DOOR_BLOCK", 64);
define("WOODEN_DOOR_BLOCK", 64);
define("WOOD_DOOR_BLOCK", 64);
define("LADDER", 65);
define("RAIL", 66);
define("COBBLE_STAIRS", 67);
define("COBBLESTONE_STAIRS", 67);
define("WALL_SIGN", 68);
define("IRON_DOOR_BLOCK", 71);
define("REDSTONE_ORE", 73);
define("GLOWING_REDSTONE_ORE", 74);
define("LIT_REDSTONE_ORE", 74);
define("SNOW", 78);
define("SNOW_LAYER", 78);
define("ICE", 79);
define("SNOW_BLOCK", 80);
define("CACTUS", 81);
define("CLAY_BLOCK", 82);
define("REEDS", 83);
define("SUGARCANE_BLOCK", 83);
define("FENCE", 85);
define("PUMPKIN", 86);
define("NETHERRACK", 87);
define("SOUL_SAND", 88);
define("GLOWSTONE", 89);
define("GLOWSTONE_BLOCK", 89);
define("LIT_PUMPKIN", 91);
define("JACK_O_LANTERN", 91);
define("CAKE_BLOCK", 92);
define("INVISIBLE_BEDROCK", 95);
define("TRAPDOOR", 96);
define("STONE_BRICKS", 98);
define("STONE_BRICK", 98);
//ANOTHER STONE BRICKS
define("BROWN_MUSHROOM_BLOCK", 99);
define("RED_MUSHROOM_BLOCK", 100);
define("IRON_BAR", 101);
define("IRON_BARS", 101);
define("GLASS_PANE", 102);
define("GLASS_PANEL", 102);
define("MELON_BLOCK", 103);
define("PUMPKIN_STEM", 104);
define("MELON_STEM", 105);
define("VINES", 106);
define("FENCE_GATE", 107);
define("BRICK_STAIRS", 108);
define("STONE_BRICK_STAIRS", 109);
define("MYCELIUM", 110);
define("LILY_PAD", 111);
define("NETHER_BRICKS", 112);
define("NETHER_BRICK_BLOCK", 112);
define("NETHER_BRICKS_STAIRS", 114);
define("END_PORTAL_FRAME", 120);
define("END_STONE", 121);
define("COCOA", 127);
define("SANDSTONE_STAIRS", 128);
define("EMERALD_ORE", 129);
define("EMERALD_BLOCK", 133);
define("SPRUCE_WOOD_STAIRS", 134);
define("SPRUCE_WOODEN_STAIRS", 134);
define("BIRCH_WOOD_STAIRS", 135);
define("BIRCH_WOODEN_STAIRS", 135);
define("JUNGLE_WOOD_STAIRS", 136);
define("JUNGLE_WOODEN_STAIRS", 136);
define("COBBLE_WALL", 139);
define("STONE_WALL", 139);
define("COBBLESTONE_WALL", 139);
define("MOSSY_COBBLESTONE_WALL", "139:1");
define("CARROT_BLOCK", 141);
define("POTATO_BLOCK", 142);
define("QUARTZ_BLOCK", 155);
define("QUARTZ_STAIRS", 156);
define("DOUBLE_WOOD_SLAB", 157);
define("DOUBLE_WOODEN_SLAB", 157);
define("DOUBLE_WOOD_SLABS", 157);
define("DOUBLE_WOODEN_SLABS", 157);
define("WOOD_SLAB", 158);
define("WOODEN_SLAB", 158);
define("WOOD_SLABS", 158);
define("WOODEN_SLABS", 158);
define("STAINED_CLAY", 159);
//ANOTHER STAINED CLAY
define("LEAVES2", 161);
define("ACACIA_LEAVES", 161);
define("DARK_OAK_LEAVES", "161:1");
define("LOG2", 162);
define("TRUNK2", 162);
define("ACACIA_WOOD", "162:0");
define("DARK_OAK_WOOD", "162:1");
define("ACACIA_WOOD_STAIRS", 163);
define("DARK_OAK_WOOD_STAIRS", 164);
define("HAY_BALE", 170);
define("CARPET", 171);
//ANOTHER CARPET
define("HARDENED_CLAY", 172);
define("COAL_BLOCK", 173);
define("PACKED_ICE", 174);
define("DOUBLE_PLANT", 175);
define("PODZOL", 243);
define("BEETROOT_BLOCK", 244);
define("STONECUTTER", 245);
define("GLOWING_OBSIDIAN", 246);
define("NETHER_REACTOR", 247);
define("INFO_UPDATE", 248);
define("INFO_UPDATE2", 249);
define("RESERVED6", 255);

View file

@ -1,36 +0,0 @@
<?php
//Entities
define("ENTITY_PLAYER", 1);
define("ENTITY_MOB", 2);
define("MOB_CHICKEN", 10);
define("MOB_COW", 11);
define("MOB_PIG", 12);
define("MOB_SHEEP", 13);
define("MOB_WOLF", 14);
define("MOB_VILLAGER", 15);
define("MOB_MOOSHROOM", 16);
define("MOB_ZOMBIE", 32);
define("MOB_CREEPER", 33);
define("MOB_SKELETON", 34);
define("MOB_SPIDER", 35);
define("MOB_PIGMAN", 36);
define("MOB_SLIME", 37);
define("MOB_ENDERMAN", 38);
define("MOB_SILVERFISH", 39);
define("ENTITY_OBJECT", 3);
define("OBJECT_TRIPOD_CAMERA", 62);
define("OBJECT_PRIMEDTNT", 65);
define("OBJECT_ARROW", 80);
define("OBJECT_SNOWBALL", 81);
define("OBJECT_EGG", 82);
define("OBJECT_PAINTING", 83);
define("OBJECT_MINECART", 84);
define("ENTITY_ITEM", 4);
define("ENTITY_FALLING", 5);
define("FALLING_SAND", 66);

View file

@ -1,33 +0,0 @@
<?php
define("PMF_LEVEL_DEFLATE_LEVEL", 6);
//Gamemodes
define("SURVIVAL", 0);
define("CREATIVE", 1);
define("ADVENTURE", 2);
define("VIEW", 3);
define("VIEWER", 3);
define("SPECTATOR", 3);
//Players
define("MAX_CHUNK_RATE", 2);
define("PLAYER_MAX_QUEUE", 1024);
define("PLAYER_SURVIVAL_SLOTS", 36);
define("PLAYER_CREATIVE_SLOTS", 112); //hum?
//Block Updates
define("BLOCK_UPDATE_NORMAL", 1);
define("BLOCK_UPDATE_RANDOM", 2);
define("BLOCK_UPDATE_SCHEDULED", 3);
define("BLOCK_UPDATE_WEAK", 4);
define("BLOCK_UPDATE_TOUCH", 5);
//Block Sides
define("SIDE_DOWN", 0);
define("SIDE_UP", 1);
define("SIDE_ZNEG", 2);
define("SIDE_ZPOS", 3);
define("SIDE_XNEG", 4);
define("SIDE_XPOS", 5);

View file

@ -1,153 +0,0 @@
<?php
define("IRON_SHOVEL", 256);
define("IRON_PICKAXE", 257);
define("IRON_AXE", 258);
define("FLINT_STEEL", 259);
define("FLINT_AND_STEEL", 259);
define("APPLE", 260);
define("BOW", 261);
define("ARROW", 262);
define("COAL", 263);
define("DIAMOND", 264);
define("IRON_INGOT", 265);
define("GOLD_INGOT", 266);
define("IRON_SWORD", 267);
define("WOODEN_SWORD", 268);
define("WOODEN_SHOVEL", 269);
define("WOODEN_PICKAXE", 270);
define("WOODEN_AXE", 271);
define("STONE_SWORD", 272);
define("STONE_SHOVEL", 273);
define("STONE_PICKAXE", 274);
define("STONE_AXE", 275);
define("DIAMOND_SWORD", 276);
define("DIAMOND_SHOVEL", 277);
define("DIAMOND_PICKAXE", 278);
define("DIAMOND_AXE", 279);
define("STICK", 280);
define("STICKS", 280);
define("BOWL", 281);
define("MUSHROOM_STEW", 282);
define("GOLD_SWORD", 283);
define("GOLD_SHOVEL", 284);
define("GOLD_PICKAXE", 285);
define("GOLD_AXE", 286);
define("GOLDEN_SWORD", 283);
define("GOLDEN_SHOVEL", 284);
define("GOLDEN_PICKAXE", 285);
define("GOLDEN_AXE", 286);
define("STRING", 287);
define("FEATHER", 288);
define("GUNPOWDER", 289);
define("WOODEN_HOE", 290);
define("STONE_HOE", 291);
define("IRON_HOE", 292);
define("DIAMOND_HOE", 293);
define("GOLD_HOE", 294);
define("GOLDEN_HOE", 294);
define("SEEDS", 295);
define("WHEAT_SEEDS", 295);
define("WHEAT", 296);
define("BREAD", 297);
define("LEATHER_CAP", 298);
define("LEATHER_TUNIC", 299);
define("LEATHER_PANTS", 300);
define("LEATHER_BOOTS", 301);
define("CHAIN_HELMET", 302);
define("CHAIN_CHESTPLATE", 303);
define("CHAIN_LEGGINGS", 304);
define("CHAIN_BOOTS", 305);
define("IRON_HELMET", 306);
define("IRON_CHESTPLATE", 307);
define("IRON_LEGGINGS", 308);
define("IRON_BOOTS", 309);
define("DIAMOND_HELMET", 310);
define("DIAMOND_CHESTPLATE", 311);
define("DIAMOND_LEGGINGS", 312);
define("DIAMOND_BOOTS", 313);
define("GOLD_HELMET", 314);
define("GOLDEN_HELMET", 314);
define("GOLD_CHESTPLATE", 315);
define("GOLDEN_CHESTPLATE", 315);
define("GOLD_LEGGINGS", 316);
define("GOLDEN_LEGGINGS", 316);
define("GOLD_BOOTS", 317);
define("GOLDEN_BOOTS", 317);
define("FLINT", 318);
define("RAW_PORKCHOP", 319);
define("COOKED_PORKCHOP", 320);
define("PAINTING", 321);
define("GOLDEN_APPLE", 322);
define("SIGN", 323);
define("WOODEN_DOOR", 324);
define("BUCKET", 325);
define("WATER_BUCKET", "325:8");
define("LAVA_BUCKET", "325:10");
define("MILK_BUCKET", "325:1");
define("MINECART", 328);
define("SADDLE", 329);
define("IRON_DOOR", 330);
define("REDSTONE", 331);
define("REDSTONE_DUST", 331);
define("SNOWBALL", 332);
define("LEATHER", 334);
define("BRICK", 336);
define("CLAY", 337);
define("SUGARCANE", 338);
define("SUGAR_CANE", 338);
define("SUGAR_CANES", 338);
define("REED", 338);
define("PAPER", 339);
define("BOOK", 340);
define("SLIMEBALL", 341);
define("EGG", 344);
define("COMPASS", 345);
define("CLOCK", 347);
define("GLOWSTONE_DUST", 348);
define("DYE", 351);
define("BONE", 352);
define("SUGAR", 353);
define("CAKE", 354);
define("BED", 355);
define("COOKIE", 357);
define("COOKIES", 357);
define("SHEARS", 359);
define("MELON", 360);
define("MELON_SLICE", 360);
define("PUMPKIN_SEEDS", 361);
define("MELON_SEEDS", 362);
define("RAW_BEEF", 363);
define("BEEF", 363);
define("STEAK", 364);
define("COOKED_BEEF", 364);
define("RAW_CHICKEN", 365);
define("COOKED_CHICKEN", 366);
define("SPAWN_EGG", 383);
define("EMERALD", 388);
define("CARROT", 391);
define("POTATO", 392);
define("BAKED_POTATO", 393);
define("PUMPKIN_PIE", 400);
define("NETHER_BRICK", 405);
define("QUARTZ", 406);
define("NETHER_QUARTZ", 406);
define("CAMERA", 456);
define("BEETROOT", 457);
define("BEETROOT_SEEDS", 458);
define("BEETROOT_SEED", 458);
define("BEETROOT_SOUP", 459);

View file

@ -1,180 +0,0 @@
<?php
/***REM_START***/
require_once(dirname(__FILE__) . "/config.php");
require_once(FILE_PATH . "/src/utils/TextFormat.php");
require_once(FILE_PATH . "/src/functions.php");
/***REM_END***/
define("DATA_PATH", realpath(arg("data-path", FILE_PATH)) . "/");
if(arg("enable-ansi", strpos(strtoupper(php_uname("s")), "WIN") === 0 ? false : true) === true and arg("disable-ansi", false) !== true){
define("ENABLE_ANSI", true);
}else{
define("ENABLE_ANSI", false);
}
set_error_handler("error_handler", E_ALL);
$errors = 0;
if(version_compare("8.0.0", PHP_VERSION) > 0){
console("[ERROR] Use PHP >= 8.0.0", true, true, 0);
++$errors;
}
define("USE_NATIVE_RANDOM", version_compare("8.2.0", PHP_VERSION) <= 0);
if(php_sapi_name() !== "cli"){
console("[ERROR] You must run NostalgiaCore using the CLI.", true, true, 0);
++$errors;
}
if(!extension_loaded("sockets") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_" : "") . "sockets." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find the Socket extension.", true, true, 0);
++$errors;
}
if(!extension_loaded("pthreads") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_" : "") . "pthreads." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find the pthreads extension.", true, true, 0);
++$errors;
}else{
$pthreads_version = phpversion("pthreads");
if(substr_count($pthreads_version, ".") < 2){
$pthreads_version = "0.$pthreads_version";
}
if(version_compare($pthreads_version, "0.1.0") < 0){
console("[ERROR] pthreads >= 0.1.0 is required, while you have $pthreads_version.", true, true, 0);
++$errors;
}
}
if(!extension_loaded("curl") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_" : "") . "curl." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find the cURL extension.", true, true, 0);
++$errors;
}
if(!extension_loaded("sqlite3") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_" : "") . "sqlite3." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find the SQLite3 extension.", true, true, 0);
++$errors;
}
if(!extension_loaded("yaml") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_" : "") . "yaml." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find the YAML extension.", true, true, 0);
++$errors;
}
if(!extension_loaded("zlib") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_" : "") . "zlib." . PHP_SHLIB_SUFFIX) === false){
console("[ERROR] Unable to find the Zlib extension.", true, true, 0);
++$errors;
}
if($errors > 0){
console("[ERROR] Please use the installer provided on the homepage, or recompile PHP again.", true, true, 0);
exit(1); //Exit with error
}
$sha1sum = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
/***REM_START***/
require_once(FILE_PATH . "/src/math/Vector3.php");
require_once(FILE_PATH . "/src/math/AxisAlignedBB.php");
require_once(FILE_PATH . "/src/world/Position.php");
require_once(FILE_PATH . "/src/pmf/PMF.php");
require_once(FILE_PATH . "/src/astarnavigator/IElement.php");
require_once(FILE_PATH . "/src/astarnavigator/PHPUtils.php");
require_once(FILE_PATH . "/src/astarnavigator/PathTile.php");
require_once(FILE_PATH . "/src/astarnavigator/algorithms/IDistanceAlgorithm.php");
require_once(FILE_PATH . "/src/astarnavigator/algorithms/Pythagoras3D.php");
require_once(FILE_PATH . "/src/astarnavigator/algorithms/ManhattanHeuristic3D.php");
require_once(FILE_PATH . "/src/astarnavigator/providers/INeighborProvider.php");
require_once(FILE_PATH . "/src/astarnavigator/providers/MCDiagonalProvider.php");
require_once(FILE_PATH . "/src/astarnavigator/providers/IBlockedProvider.php");
require_once(FILE_PATH . "/src/astarnavigator/providers/MCBlockedProvider.php");
require_once(FILE_PATH . "/src/astarnavigator/ITileNavigator.php");
require_once(FILE_PATH . "/src/astarnavigator/TileNavigator.php");
require_once(FILE_PATH . "/src/nbt/tag/NamedTag.php");
require_once(FILE_PATH . "/src/entity/ai/tasks/TaskBase.php");
require_once(FILE_PATH. "/src/entity/ai/tasks/TaskTempt.php");
require_once(FILE_PATH . "/src/entity/Rideable.php");
require_once(FILE_PATH . "/src/entity/Attachable.php");
require_once(FILE_PATH . "/src/entity/Damageable.php");
require_once(FILE_PATH . "/src/entity/Breedable.php");
require_once(FILE_PATH . "/src/entity/Damageable.php");
require_once(FILE_PATH . "/src/entity/Pathfindable.php");
require_once(FILE_PATH . "/src/entity/Entity.php");
require_once(FILE_PATH . "/src/entity/Living.php");
require_once(FILE_PATH . "/src/entity/Creature.php");
require_once(FILE_PATH . "/src/entity/Ageable.php");
require_once(FILE_PATH . "/src/entity/Animal.php");
require_once(FILE_PATH . "/src/world/MobSpawner.php");
require_once(FILE_PATH . "/src/material/Item.php");
require_once(FILE_PATH . "/src/material/item/base/ItemTool.php");
require_once(FILE_PATH . "/src/material/item/base/ItemHoe.php");
require_once(FILE_PATH . "/src/material/item/base/ItemPickaxe.php");
require_once(FILE_PATH . "/src/material/item/base/ItemAxe.php");
require_once(FILE_PATH . "/src/material/item/base/ItemShovel.php");
require_once(FILE_PATH . "/src/material/item/base/ItemSword.php");
require_once(FILE_PATH . "/src/material/item/armor/ArmorItem.php");
require_once(FILE_PATH . "/src/structure/Structure.php");
require_once(FILE_PATH . "/src/world/generator/Populator.php");
require_once(FILE_PATH . "/src/world/generator/LevelGenerator.php");
require_once(FILE_PATH . "/src/world/generator/structure/StructureBase.php");
require_once(FILE_PATH . "/src/world/generator/structure/StructureGenerator.php");
require_once(FILE_PATH . "/src/plugin/Plugin.php");
require_once(FILE_PATH . "/src/plugin/OtherPluginRequirement.php");
require_once(FILE_PATH . "/src/plugin/DummyPlugin.php");
require_once(FILE_PATH . "/src/plugin/phar/IClassLoader.php");
require_once(FILE_PATH . "/src/plugin/phar/PharUtils.php");
require_once(FILE_PATH . "/src/world/generator/LevelGenerator.php");
require_once(FILE_PATH . "/src/world/generator/NewLevelGenerator.php");
require_once(FILE_PATH . "/src/world/generator/biome/BiomeDecorator.php");
require_once(FILE_PATH . "/src/world/generator/biome/Biome.php");
require_once(FILE_PATH . "/src/world/generator/biome/BiomeSelector.php");
require_once(FILE_PATH . "/src/world/generator/biome/NormalGeneratorBiomeSelector.php");
require_once(FILE_PATH . "/src/world/generator/biome/biomes/BiomeWithGrass.php");
require_once(FILE_PATH . "/src/world/generator/biome/biomes/BiomeWithSand.php");
require_once(FILE_PATH . "/src/world/generator/biome/biomes/BiomeWithSnow.php");
require_once(FILE_PATH . "/src/world/generator/biome/biomes/BiomeExtremeHills.php");
require_once(FILE_PATH . "/src/world/generator/populator/TreePopulator.php");
require_all(FILE_PATH . "src/");
$inc = get_included_files();
$inc[] = array_shift($inc);
$srcdir = realpath(FILE_PATH . "src/");
foreach($inc as $s){
if(strpos(realpath(dirname($s)), $srcdir) === false and strtolower(basename($s)) !== "pocketmine-mp.php"){
continue;
}
$sha1sum ^= sha1_file($s, true);
}
/***REM_END***/
ini_set("opcache.mmap_base", bin2hex(Utils::getRandomBytes(8, false))); //Fix OPCache address errors
define("SOURCE_SHA1SUM", bin2hex($sha1sum));
/***REM_START***/
if(!file_exists(DATA_PATH . "server.properties") and arg("no-wizard", false) != true){
$installer = new Installer();
}
/***REM_END***/

View file

@ -1,14 +0,0 @@
<?php
interface Ageable{
public function isBaby();
/**
* Get Entity Age. It can be negative.
*/
public function getAge();
/**
* Set Entity age.
* @param int $i
*/
public function setAge($i);
}

View file

@ -1,113 +0,0 @@
<?php
/*
TODO:
move methods
*/
abstract class Animal extends Creature implements Ageable, Breedable{
public $parent;
public $inLove; //do NOT add it into metadata, it doesnt send it to player
public $age;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->setAge(isset($data["Age"]) ? $data["Age"] : 0);
if(isset($this->data["IsBaby"]) && $this->data["IsBaby"] && $this->getAge() >= 0){
$this->setAge(-24000);
}
$this->ai->addTask(new TaskTempt());
$this->ai->addTask(new TaskPanic());
}
public function harm($dmg, $cause = "generic", $force = false){
$ret = parent::harm($dmg, $cause, $force);
$this->inPanic |= ($ret && is_numeric($cause));
$this->inLove = false;
return $ret;
}
public function isBaby(){
return $this->getAge() < 0;
}
public function breed(){
$c = $this->spawnChild();
if($this->server->dhandle("entity.animal.breed", ["parent" => $this, "child" => $c]) !== false){
$c->parent = &$this;
$this->server->api->entity->spawnToAll($c);
}
}
public function update(){
parent::update();
$age = $this->getAge() + 1; //100 - fast. debug, 1 - normal
if($age >= 0 && $this->isBaby()){
$this->setAge($age);
$this->updateMetadata();
}else{
$this->setAge($age);
}
}
public function getAge(){
return $this->age;
}
public function setAge($i){
$this->age = $i;
}
public function spawnChild()
{
return $this->server->api->entity->add($this->level, $this->class, $this->type, [
"x" => $this->x + lcg_value() * mt_rand(-1, 1),
"y" => $this->y,
"z" => $this->z + lcg_value() * mt_rand(-1, 1),
"IsBaby" => true,
"Age" => -24000,
]);
}
public function getMetadata(){
$d = parent::getMetadata();
$d[14]["value"] = $this->isBaby();
return $d;
}
public function createSaveData(){
$data = parent::createSaveData();
$data["IsBaby"] = $this->isBaby();
$data["Age"] = $this->getAge();
return $data;
}
public function isInLove(){
return $this->inLove > 0;
}
public function interactWith(Entity $e, $action){
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem();
if($this->isFood($slot->getID())){
$e->player->removeItem($slot->getID(), $slot->getMetadata(), 1);
$this->inLove = 600; //600 ticks, original mehod from mcpe
return true;
}
}
parent::interactWith($e, $action);
}
public function counterUpdate(){
parent::counterUpdate();
if($this->isInLove()){
--$this->inLove;
}
}
public function getDrops(){
if($this->isBaby()){
return [];
}
return parent::getDrops();
}
}

View file

@ -1,5 +0,0 @@
<?php
//Useless Interface
interface Attachable{
}

View file

@ -1,9 +0,0 @@
<?php
interface Breedable{
public function isFood($id); //original name
public function spawnChild();
public function isInLove();
}

View file

@ -1,57 +0,0 @@
<?php
/*
TODO:
move methods
*/
abstract class Creature extends Living{
const CLASS_TYPE = ENTITY_MOB;
public $inPanic;
public $ignited;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->inPanic = false; //force for now
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 1, "generic");
// $this->setName((isset($mobs[$this->type]) ? $mobs[$this->type]:$this->type));
$this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskRandomWalk());
$this->ai->addTask(new TaskLookAtPlayer());
$this->ai->addTask(new TaskSwimming());
}
public function createSaveData(){
$data = parent::createSaveData();
$data["State"] = @$this->getState();
return $data;
}
public function getSpeedModifer(){
return $this->speedModifer * ($this->inPanic ? 1.5 : 1.0);
}
public function getArmorValue(){
return 2;
}
public function spawn($player){
if(!($player instanceof Player)){
$player = $this->server->api->player->get($player);
}
if($player->eid === $this->eid or $this->closed !== false or ($player->level !== $this->level and $this->class !== ENTITY_PLAYER)){
return false;
}
$pk = new AddMobPacket;
$pk->eid = $this->eid;
$pk->type = $this->type;
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->yaw = $this->yaw;
$pk->pitch = $this->pitch;
$pk->metadata = $this->getMetadata();
$player->dataPacket($pk);
$pk = new SetEntityMotionPacket;
$pk->entities = [[$this->eid, $this->speedX, $this->speedY, $this->speedZ]];
$player->dataPacket($pk);
}
}

View file

@ -1,5 +0,0 @@
<?php
interface Damageable{
}

File diff suppressed because it is too large Load diff

View file

@ -1,5 +0,0 @@
<?php
//Useless Class(or not so usless =D?)
abstract class Hanging extends Entity implements Attachable{
const CLASS_TYPE = ENTITY_OBJECT;
}

View file

@ -1,5 +0,0 @@
<?php
class Human extends Creature{
const CLASS_TYPE = ENTITY_PLAYER;
}

View file

@ -1,57 +0,0 @@
<?php
abstract class Living extends Entity implements Damageable, Pathfindable{
public static $despawnMobs, $despawnTimer;
public $target, $ai;
public $pathFinder, $path = null, $currentIndex = 0, $currentNode, $pathFollower;
public function __construct(Level $level, $eid, $class, $type = 0, $data = array()){
$this->target = false;
$this->ai = new EntityAI($this);
$this->pathFinder = new TileNavigator(new MCBlockedProvider(), new MCDiagonalProvider(), new ManhattanHeuristic3D());
$this->pathFollower = new PathFollower($this);
parent::__construct($level, $eid, $class, $type, $data);
$this->canBeAttacked = true;
$this->hasGravity = true;
$this->hasKnockback = true;
if(self::$despawnMobs) $this->server->schedule(self::$despawnTimer, [$this, "close"]); //900*20
}
public function hasPath(){
return $this->path != null;
}
public function close(){
parent::close();
unset($this->pathFollower->entity);
unset($this->ai->entity);
unset($this->ai->mobController->entity);
unset($this->ai);
unset($this->parent);
}
public function updateEntityMovement(){
if(!$this->dead && Entity::$allowedAI && $this->idleTime <= 0) {
$this->ai->updateTasks();
}
$this->ai->mobController->rotateTick();
//$this->ai->mobController->movementTick();
/*if(self::$entityPushing){
$this->collideHandler();
}*/
if($this->onGround){
//if(!$this->hasPath() && $this->pathFinder instanceof ITileNavigator){
// $this->path = $this->pathFinder->navigate(new PathTileXYZ($this->x, $this->y, $this->z, $this->level), new PathTileXYZ($this->x + mt_rand(-10, 10), $this->y + mt_rand(-1, 1), $this->z + mt_rand(-10, 10), $this->level), 10);
//}
//$this->pathFollower->followPath();
}
}
public function sendMoveUpdate(){
if($this->counter % 3 != 0){
return;
}
parent::sendMoveUpdate();
}
}

View file

@ -1,15 +0,0 @@
<?php
class Monster extends Creature{
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->ai->addTask(new TaskAttackPlayer());
}
public function getAttackDamage(){
return 2;
}
public function attackEntity($entity){
$entity->harm($this->getAttackDamage(), $this->eid);
}
}

View file

@ -1,7 +0,0 @@
<?php
abstract class Neutral extends Creature
{
}

View file

@ -1,7 +0,0 @@
<?php
/*
Illegal features
*/
interface Pathfindable{
public function hasPath();
}

View file

@ -1,6 +0,0 @@
<?php
abstract class Projectile extends Entity{
const CLASS_TYPE = ENTITY_OBJECT;
}

View file

@ -1,5 +0,0 @@
<?php
interface Rideable{
public function canRide($e);
}

View file

@ -1,9 +0,0 @@
<?php
interface Tameable
{
public function isTamed();
public function getOwner();
}

View file

@ -1,5 +0,0 @@
<?php
abstract class Vehicle extends Entity implements Rideable{
const CLASS_TYPE = ENTITY_OBJECT;
}

View file

@ -1,80 +0,0 @@
<?php
class EntityAI
{
/**
* @var MobController
*/
public $mobController;
/**
* @var Living
*/
public $entity;
/**
* @var TaskBase[]
*/
protected $tasks;
public $lastTask;
public function __construct($entity){
$this->entity = $entity;
$this->tasks = [];
$this->mobController = new MobController($entity);
}
/**
* Add a task for entity
* @param TaskBase $task
*/
public function addTask(TaskBase $task){
$this->tasks[$task->__toString()] = $task;
}
public function removeTask($name){
if(isset($this->tasks[$name])){
unset($this->tasks[$name]);
return true;
}
return false;
}
/**
*
* @param mixed $id classname
* @return TaskBase | false
*/
public function getTask($id){
return isset($this->tasks[$id]) ? $this->tasks[$id] : false;
}
public function isStarted($id){
$task = @$this->getTask($id);
return $task instanceof TaskBase && $task->isStarted;
}
public function updateTasks(){
if(!isset($this->entity) or !($this->entity instanceof Entity)){
return;
}
foreach($this->tasks as $t){
if(!$t->isStarted && $t->canBeExecuted($this)){
$t->isStarted = true;
$t->onStart($this);
}
if($t->isStarted){
$t->onUpdate($this);
if($t->selfCounter <= 0){
$t->isStarted = false;
$t->onEnd($this);
}
}
}
}
public function __destruct(){
unset($this->entity);
}
}

View file

@ -1,96 +0,0 @@
<?php
class MobController
{
/**
* @var Entity
*/
public $entity;
public $finalYaw, $finalPitch, $finalHeadYaw;
public function __construct($e){
$this->entity = $e;
}
public function moveNonInstant($x, $y, $z){
if($x == 0 && $y == 0 && $z == 0){
return false;
}
$ox = ($x > 0 ? 1 : ($x < 0 ? -1 : 0));
$oy = ($y > 0 ? 1 : ($y < 0 ? -1 : 0));
$oz = ($z > 0 ? 1 : ($z < 0 ? -1 : 0));
$xf = $this->entity->x + ($this->entity->getSpeedModifer() * $ox * $this->entity->getSpeed());
$zf = $this->entity->z + ($this->entity->getSpeedModifer() * $oz * $this->entity->getSpeed());
if($this->entity->onGround){
$bs = [ //TODO simplify(somehow)
$this->entity->level->getBlockWithoutVector(ceil($xf), floor($this->entity->y), ceil($zf)),
$this->entity->level->getBlockWithoutVector(ceil($xf), floor($this->entity->y), $zf - ($oz < 0 ? 1 : 0)),
$this->entity->level->getBlockWithoutVector($xf - ($ox < 0 ? 1 : 0), floor($this->entity->y), $zf - ($oz < 0 ? 1 : 0)),
$this->entity->level->getBlockWithoutVector($xf - ($ox < 0 ? 1 : 0), floor($this->entity->y), ceil($zf)),
];
foreach($bs as $b){
if($b->isSolid){
if(!$b->getSide(1)->isSolid){
$oy = 1;
break;
}
}
}
}
$this->faceEntity($this->entity->add($ox, $oy, $oz));
if($this->entity->knockbackTime <= 0){
$this->entity->moveEntityWithOffset($ox, $oy, $oz);
}
return true;
}
public function rotateTick(){ //TODO handle more rotation
$w180 = Utils::wrapAngleTo180($this->finalHeadYaw - $this->entity->headYaw);
$w180min = min(abs($w180), 20)*Utils::getSign($w180);
$this->entity->headYaw = Utils::wrapAngleTo360($this->entity->headYaw + $w180min);
}
public function moveTo($x, $y, $z){
return $this->moveNonInstant($x - floor($this->entity->x), $y - floor($this->entity->y), $z - floor($this->entity->z));
}
public function faceEntity(Vector3 $v){
$d = $v->subtract($this->entity)->normalize();
$dx = $d->x;
$dz = $d->z;
$tan = $dz == 0 ? ($dx < 0 ? 180 : 0) : (90 - rad2deg(atan($dx / $dz)));
$thetaOffset = $dz < 0 ? 90 : 270;
$calcYaw = ($thetaOffset + $tan);
$this->finalHeadYaw = $this->entity->yaw = $calcYaw;
}
public function lookOffset($x, $y, $z, $pitch = true){
$tan = $z == 0 ? ($x < 0 ? 180 : 0) : (90 - rad2deg(atan($x / $z))); /*arctan(infinity) = pi/2 = (90deg) - 90 = 0*/
$thetaOffset = $z < 0 ? 90 : 270;
$calcYaw = $tan + $thetaOffset;
$this->entity->yaw = $this->finalHeadYaw = $calcYaw;
if($pitch){
$diff = sqrt($x * $x + $z * $z);
$calcPitch = $diff == 0 ? ($y < 0 ? -90 : 90) : rad2deg(atan($y / $diff));
$this->entity->pitch = $this->entity->type === MOB_CHICKEN ? -$calcPitch : $calcPitch;
}
$this->entity->server->query("UPDATE entities SET pitch = ".$this->entity->pitch.", yaw = ".$this->entity->yaw." WHERE EID = ".$this->entity->eid.";");
return true;
}
public function lookOn($x, $y = 0, $z = 0, $pitch = true){
if($x instanceof Vector3){
return $this->lookOn($x->x, $x->y + $x->getEyeHeight(), $x->z, $pitch);
}
return $this->lookOffset($x - $this->entity->x, ($this->entity->y + $this->entity->height) - $y, $z - $this->entity->z, $pitch);
}
public function __destruct(){
unset($this->entity);
}
}

View file

@ -1,27 +0,0 @@
<?php
class PathFollower{
/**
* @var Living
*/
public $entity;
public function __construct(Living $entity){
$this->entity = $entity;
}
public function followPath(){
if(!isset($entity) or $this->entity->path == null){
return;
}
if((is_array($this->entity->path) && count($this->entity->path) <= 0 || $this->entity->currentIndex >= count($this->entity->path))){
$this->entity->path = null;
$this->entity->currentIndex = 0;
$this->entity->currentNode = false;
}elseif(($this->entity->currentNode == false || $this->entity->ai->mobController->moveTo($this->entity->currentNode->x, $this->entity->currentNode->y, $this->entity->currentNode->z) === false)){
$this->entity->currentNode = $this->entity->path[$this->entity->currentIndex++];
}
}
}

View file

@ -1,63 +0,0 @@
<?php
/**
* A Tempt but for Monsters
*/
class TaskAttackPlayer extends TaskTempt{
public $attackTime = 0;
public function onStart(EntityAI $ai){
$this->selfCounter = 1;
}
public function onUpdate(EntityAI $ai){
if(!($this->target instanceof Entity)
|| ($ai->entity instanceof Spider && $ai->entity->level->isDay())
|| ($this->target instanceof Entity && !$this->target->isPlayer())
|| (Utils::distance_noroot($this->target, $ai->entity) > 256)
|| $this->target->level->getName() != $ai->entity->level->getName()){
$this->reset();
if($ai->entity instanceof Enderman){
$ai->entity->setAngry(false);
}
return;
}
$ai->mobController->moveTo($this->target->x, floor($ai->entity->y), $this->target->z);
$ai->mobController->lookOn($this->target);
$mult = $ai->entity instanceof Spider ? 1 : 2;
$radius = ($ai->entity->width * $mult)*($ai->entity->width * $mult);
if(Utils::distance_noroot($this->target, $ai->entity) <= $radius && $this->attackTime <= 0){
if($ai->entity instanceof Slime && $ai->entity->getSlimeSize() == 1){
$this->attackTime = 20;
}
else{
$ai->entity->attackEntity($this->target);
$this->attackTime = 20;
}
}
--$this->attackTime;
}
public function onEnd(EntityAI $ai){
parent::onEnd($ai);
if($ai->entity instanceof Enderman){
$ai->entity->setAngry(false);
}
}
public function canBeExecuted(EntityAI $ai){
$target = $this->findTarget($ai->entity, 16);
if(($ai->entity instanceof Spider && !$ai->entity->level->isDay())
|| $target instanceof Entity
&& $target->class === ENTITY_PLAYER
&& $target->isPlayer()){
$this->target = $target; //TODO get rid of it
$ai->entity->target = $target;
if($ai->entity instanceof Enderman){ //TODO find a better way
$ai->entity->setAngry(true);
}
return true;
}
return false;
}
}

View file

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

View file

@ -1,32 +0,0 @@
<?php
class TaskLookAround extends TaskBase
{
private $rotation;
public function onStart(EntityAI $ai)
{
$this->selfCounter = 1;
$this->rotation = mt_rand(-120, 120);
}
public function onEnd(EntityAI $ai)
{
$ai->entity->idleTime = mt_rand(20, 40);
}
public function canBeExecuted(EntityAI $ai)
{
return !$ai->entity->inPanic && !$ai->entity->isMoving() && lcg_value() < 0.02 && !$ai->isStarted("TaskLookAtPlayer") && !$ai->isStarted("TaskTempt") && !$ai->entity->hasPath(); /*Vanilla value*/
}
public function onUpdate(EntityAI $ai)
{
if($this->rotation === 0){
$this->selfCounter = 0;
}
$v = min(Utils::getSign($this->rotation) * 10, $this->rotation);
$ai->entity->headYaw += $v;
$this->rotation -= $v;
}
}

View file

@ -1,66 +0,0 @@
<?php
class TaskLookAtPlayer extends TaskBase{
public $target = false;
private $state, $yaw, $pitch;
public function canBeExecuted(EntityAI $ai){
return !$ai->entity->inPanic && lcg_value() < 0.02 && !$ai->entity->isMovingHorizontally() && !$ai->isStarted("TaskLookAround") && !$ai->isStarted("TaskTempt") && !$ai->entity->hasPath();
}
protected function findTarget($e, $r){
$svd = null;
$svdDist = -1;
foreach($e->level->players as $p){
$p = $p->entity;
if(Utils::distance_noroot($e, $p) > $r*$r){
continue;
}
if($svdDist === -1){
$svdDist = Utils::distance_noroot($e, $p);
$svd = $p;
continue;
}
if($svd != null && $svdDist === 0){
$svd = $p;
}
if(($cd = Utils::distance_noroot($e, $p)) < $svdDist){
$svdDist = $cd;
$svd = $p;
}
}
if($svd == null){
return null;
}
return $svd;
}
public function onStart(EntityAI $ai){
$this->target = $this->findTarget($ai->entity, 6); //TODO max distance for different mobs
if(!($this->target instanceof Entity) || !$this->target->isPlayer()){
$this->reset();
$this->onEnd($ai);
return;
}
$this->yaw = $ai->entity->yaw;
$this->pitch = $ai->entity->pitch;
$this->selfCounter = mt_rand(20, 60);
}
public function onUpdate(EntityAI $ai){
if(!($this->target instanceof Entity) || Utils::distance($ai->entity, $this->target) > 6 || $this->target->level->getName() != $ai->entity->level->getName()){ //TODO max distance for different mobs
$this->reset();
$this->onEnd($ai);
return;
}
$ai->mobController->lookOn($this->target);
$this->selfCounter--;
}
public function onEnd(EntityAI $ai){
unset($this->target);
$ai->entity->pitch = 0;
}
}

View file

@ -1,41 +0,0 @@
<?php
class TaskPanic extends TaskBase
{
protected $randX = 2, $randZ = 2;
public function onStart(EntityAI $ai)
{
$this->selfCounter = 60;
$this->regenerateRandXZ();
}
public function onEnd(EntityAI $ai)
{
$ai->entity->inPanic = false;
$this->reset();
}
public function regenerateRandXZ(){
$this->randX = (mt_rand(0, 1) ? -1 : 1) * 2;
$this->randZ = (mt_rand(0, 1) ? -1 : 1) * 2;
}
public function reset(){
$this->randX = $this->randZ = 2;
}
public function onUpdate(EntityAI $ai)
{
--$this->selfCounter;
if($this->selfCounter % 20 === 0) $this->regenerateRandXZ();
$ai->mobController->moveNonInstant($this->randX, 0, $this->randZ);
}
public function canBeExecuted(EntityAI $ai)
{
return $ai->entity instanceof Animal && $ai->entity->inPanic && $ai->entity->knockbackTime <= 0;
}
}

View file

@ -1,41 +0,0 @@
<?php
class TaskRandomWalk extends TaskBase
{
private $x, $z;
public function onStart(EntityAI $ai)
{
$this->x = mt_rand(-16, 16);
$this->z = mt_rand(-16, 16);
if($this->x === 0 && $this->z === 0){
$this->reset();
return false;
}
$this->selfCounter = floor(5 * Utils::distance($ai->entity, $ai->entity->add($this->x, 0, $this->z)));
}
public function onEnd(EntityAI $ai)
{
$this->x = $this->z = 0;
}
public function onUpdate(EntityAI $ai)
{
if(($ai->entity instanceof Creeper && $ai->entity->isIgnited()) || $ai->isStarted("TaskTempt")) {
$this->reset();
return false; //TODO Better way: block movement
}
--$this->selfCounter;
$ai->mobController->moveNonInstant($this->x, 0, $this->z);
}
public function canBeExecuted(EntityAI $ai)
{
if(($ai->entity instanceof Creeper && $ai->entity->isIgnited()) || $ai->entity->hasPath() || $ai->isStarted("TaskTempt")) {
return false;
}
return !$ai->entity->inPanic && !$ai->isStarted("TaskLookAround") && !$ai->isStarted("TaskLookAtPlayer") && mt_rand(0, 120) == 0;
}
}

View file

@ -1,34 +0,0 @@
<?php
class TaskSwimming extends TaskBase
{
public function onStart(EntityAI $ai)
{
$this->selfCounter = 1;
}
public function onEnd(EntityAI $ai)
{
}
public function onUpdate(EntityAI $ai)
{
if(!$ai->entity->inWater){
$this->reset();
}
if(lcg_value() < 0.8){ #1.5.2 method
$ai->entity->speedY = 0.42;
}
}
public function canBeExecuted(EntityAI $ai)
{
return $ai->entity->inWater;
}
}

View file

@ -1,74 +0,0 @@
<?php
class TaskTempt extends TaskBase
{
public $target = false;
public function onStart(EntityAI $ai)
{
$this->selfCounter = 1;
}
public function onEnd(EntityAI $ai)
{
unset($this->target);
unset($ai->entity->target);
$ai->entity->pitch = 0;
}
public function onUpdate(EntityAI $ai)
{
if(!($this->target instanceof Entity) || ($this->target instanceof Entity && !$this->target->isPlayer()) || (Utils::distance_noroot($this->target, $ai->entity) > 100) || !$ai->entity->isFood($this->target->player->getHeldItem()->getID()) || $this->target->level->getName() != $ai->entity->level->getName()){
$this->reset();
return;
}
$ai->mobController->moveTo($this->target->x, floor($ai->entity->y), $this->target->z);
$ai->mobController->lookOn($this->target);
}
public function canBeExecuted(EntityAI $ai)
{
if(!($ai->entity instanceof Breedable) || $ai->entity->inPanic){ //TODO Work with path
return false;
}
$target = $this->findTarget($ai->entity, 10);
if($target instanceof Entity && $target->class === ENTITY_PLAYER && $target->isPlayer() && $ai->entity->isFood($target->player->getHeldItem()->getID())){
$this->target = $target;
$ai->entity->target = $target;
return true;
}
return false;
}
protected function findTarget($e, $r){
$svd = null;
$svdDist = -1;
foreach($e->level->players as $p){
$p = $p->entity;
if(Utils::distance_noroot($e, $p) > $r*$r){
continue;
}
if($svdDist === -1){
$svdDist = Utils::distance_noroot($e, $p);
$svd = $p;
continue;
}
if($svd != null && $svdDist === 0){
$svd = $p;
}
if(($cd = Utils::distance_noroot($e, $p)) < $svdDist){
$svdDist = $cd;
$svd = $p;
}
}
if($svd == null){
return null;
}
return $svd;
}
}

View file

@ -1,41 +0,0 @@
<?php
class Chicken extends Animal{
const TYPE = MOB_CHICKEN;
public $timeUntilEgg;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->timeUntilEgg = mt_rand(0,6000) + 6000;
$this->setSize($this->isBaby() ? 0.2 : 0.4, $this->isBaby() ? 0.35 : 0.7);
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 4, "generic");
$this->setName('Chicken');
$this->setSpeed(0.25);
$this->update();
}
public function isFood($id){
return $id === PUMPKIN_SEEDS || $id === MELON_SEEDS || $id === BEETROOT_SEEDS || $id === WHEAT_SEEDS;
}
public function update(){
parent::update();
if($this->timeUntilEgg-- <= 0 && !$this->isBaby()){
$this->dropAnEgg();
$this->timeUntilEgg = mt_rand(0,6000) + 6000;
}
}
public function dropAnEgg(){
if($this->closed){
return;
}
ServerAPI::request()->api->entity->drop(new Position($this->x + 0.5, $this->y, $this->z + 0.5, $this->level), BlockAPI::getItem(EGG, 0, 1));
}
public function getDrops(){
return $this->isBaby() ? parent::getDrops() : [
[FEATHER, 0, mt_rand(0,2)],
[$this->fire > 0 ? COOKED_CHICKEN : RAW_CHICKEN, 0, 1]
];
}
}

View file

@ -1,37 +0,0 @@
<?php
class Cow extends Animal{
const TYPE = MOB_COW;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize($this->isBaby() ? 0.45 : 0.9 , $this->isBaby() ? 0.7 : 1.4);
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 10, "generic");
$this->setName("Cow");
$this->setSpeed(0.2);
$this->update();
}
public function isFood($id){
return $id === WHEAT;
}
public function interactWith(Entity $e, $action){
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem();
if($slot->getID() === BUCKET && $slot->getMetadata() === 0){
$e->player->removeItem($slot->getID(), $slot->getMetadata(), 1, true); //remove only 1 bucket
$e->player->addItem(BUCKET, 1, 1, true);
return true;
}
}
parent::interactWith($e, $action);
}
public function getDrops(){
return $this->isBaby() ? parent::getDrops() : [
[LEATHER, 0, mt_rand(0,2)],
[($this->fire > 0 ? STEAK : BEEF), 0, mt_rand(0, 3)]
];
}
}

View file

@ -1,25 +0,0 @@
<?php
require_once("Cow.php");
class Mooshroom extends Cow{
const TYPE = MOB_MOOSHROOM;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->setName("Mooshroom");
$this->update();
}
public function interactWith(Entity $e, $action){
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem();
if($slot->getID() === SHEARS){
//drop
$this->close();
$this->server->api->entity->summon($this, ENTITY_MOB, MOB_COW, $this->data);
return true;
}
}
parent::interactWith($e, $action);
}
}

View file

@ -1,72 +0,0 @@
<?php
class Pig extends Animal implements Rideable{
const TYPE = MOB_PIG;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize($this->isBaby() ? 0.45 : 0.9, $this->isBaby() ? 0.45 : 0.9);
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"]:10, "generic");
$this->server = ServerAPI::request();
$this->setName("Pig");
$this->setSpeed(0.25);
$this->update();
}
/**
* @return boolean
*/
public function isSaddled(){
return (boolean) $this->getState();
}
/**
* @param boolean $value
*/
public function setSaddled($value = null){
$this->setState($value === null ? !$this->getState() : $value);
}
public function canRide($e){
return $this->isSaddled() && !($this->linkedEntity instanceof Entity);
}
public function interactWith(Entity $e, $action)
{
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem();
if($this->canRide($e)){
$this->linkedEntity = $e;
$e->isRiding = true;
$this->linkEntity($e, SetEntityLinkPacket::TYPE_RIDE);
return true;
}
if($e->isRiding && $this->linkedEntity->eid = $e->eid){
$this->linkEntity($e, SetEntityLinkPacket::TYPE_REMOVE);
$e->isRiding = false;
$this->linkedEntity = 0;
return true;
}
if($slot->getID() === SADDLE){
if(!$this->isSaddled()){
$e->player->removeItem($slot->getID(), 0, 1);
$this->setSaddled(1);
}
return true; //avoid further interactions
}
}
return parent::interactWith($e, $action);
}
public function isFood($id){
return $id === POTATO || $id === CARROT || $id === BEETROOT;
}
public function getDrops(){
return $this->isBaby() ? parent::getDrops() : ($this->isSaddled() ? [
[($this->fire > 0 ? COOKED_PORKCHOP : RAW_PORKCHOP), 0, mt_rand(0,2)],
[SADDLE, 0, 1]
] : [
[($this->fire > 0 ? COOKED_PORKCHOP : RAW_PORKCHOP), 0, mt_rand(0,2)]
]);
}
}

View file

@ -1,128 +0,0 @@
<?php
class Sheep extends Animal{
public $color;
const TYPE = MOB_SHEEP;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize($this->isBaby() ? 0.45 : 0.9, $this->isBaby() ? 0.675 : 1.3);
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 8, "generic");
$this->setName("Sheep");
$this->data["Sheared"] = isset($this->data["Sheared"]) ? $this->data["Sheared"] : 0;
$this->data["Color"] = isset($this->data["Color"]) ? $this->data["Color"] : $this->sheepColor();
$this->setSpeed(0.25);
$this->update();
if($this->isSheared() and Entity::$updateOnTick){ //if ai enabled
$this->server->schedule(mt_rand(60, 400), [$this, "eatGrass"], null, true); //unknown time
}elseif($this->isBaby() and Entity::$updateOnTick){
$this->server->schedule(mt_rand(400, 1000), [$this, "eatGrass"], null, true); //unknown time
}
}
public function createSaveData(){
$data = parent::createSaveData();
$data["Color"] = @$this->data["Color"];
$data["Sheared"] = @$this->data["Sheared"];
return $data;
}
public function eatGrass(){
$downBlock = $this->level->getBlock(new Vector3($this->x, $this->y-1, $this->z));
if($downBlock->getID() !== GRASS){
//console("eww i don't wanna eat this $downBlock");
return false;
}
$pk = new EntityEventPacket;
$pk->eid = $this->eid;
$pk->event = EntityEventPacket::ENTITY_ANIM_10;
$this->server->api->player->broadcastPacket($this->level->players, $pk);
$this->server->schedule(38, [$this, "setSheared"], false);
$this->level->setBlock(new Position($this->x, $this->y-1, $this->z, $this->level), new DirtBlock());
}
public function setSheared($v = null){
$this->data["Sheared"] = $v === null ? !$this->isSheared() : $v;
$this->updateMetadata();
}
public function isSheared(){
return $this->data["Sheared"];
}
public function getColor(){
return $this->data["Color"]; //color === 16 -> color = 0, color === 17 -> color = 1 ...
}
public function switchColorMeta($meta){
return abs($meta - 15);
}
public function setColor($meta){
$this->data["Color"] = $meta;
}
public function getDrops(){
return ($this->isBaby() || $this->isSheared()) ? parent::getDrops() : [
[WOOL, $this->getColor(), 1]
];
}
public function isFood($id){
return $id === WHEAT;
}
public function interactWith(Entity $e, $action){
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem();
if($slot->getID() === SHEARS){
if(!$this->isSheared()){
if($e->player->gamemode != 1) $slot->useOn($this);
$this->setSheared(1);
$this->server->api->entity->drop($this, BlockAPI::getItem(WOOL, $this->getColor(), mt_rand(1, 3)));
//$this->server->schedule(20, [$this, "eatGrass"]);
if($slot->getMetadata() >= $slot->getMaxDurability()){
$e->player->removeItem($slot->getID(), $slot->getMetadata(), $slot->count, true);
}else{
$e->player->setSlot($e->player->slot, $slot);
}
}
return true;
}elseif($slot->getID() === DYE){
$this->setColor($this->switchColorMeta($slot->getMetadata()));
if(($e->player->gamemode & 0x01) === SURVIVAL){
$e->player->removeItem($slot->getID(), $slot->getMetadata(), 1, true);
}
}
}
return parent::interactWith($e, $action);
}
public function getMetadata(){
$d = parent::getMetadata();
if(!isset($this->data["Sheared"])){
$this->data["Sheared"] = 0;
}
$d[16]["value"] = ($this->data["Sheared"] << 4) | ($this->getColor() & 0x0F);
return $d;
}
public function sheepColor(){ //a method from 0.8.1
$c = mt_rand(0,100);
if($c <= 4){
return 0xF; //white
}
if($c <= 9){
return 0x7;
}
if($c <= 14){
return 0x8;
}
if($c <= 17){
return 0xC;
}
if(mt_rand(0, 500)){
return 0x0;
}
return 0x0;
}
}

View file

@ -1,50 +0,0 @@
<?php
class Wolf extends Animal implements Tameable
{
const TYPE = MOB_WOLF;
const WOLF_FLAGS = 14;
const WF_SITTING = 1;
const WF_ANGRY = 2;
const WF_INTERESTED = 3;
protected $interested = false;
protected $angry = false;
protected $sitting = false;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.6, 0.8);
parent::__construct($level, $eid, $class, $type, $data);
$this->setSpeed(0.3);
$this->setName("Wolf");
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 10, "generic");
}
public function getMetadata(){
$ret = parent::getMetadata();
$ret[self::WOLF_FLAGS] = ["type" => 0, "value" =>
(($this->angry) << self::WF_ANGRY) ^
(($this->interested) << self::WF_INTERESTED) ^
(($this->sitting) << self::WF_SITTING)
];//TODO toggles
return $ret;
}
public function isTamed()
{
return false;
}
public function getOwner()
{
return null;
}
public function isFood($id) //TODO
{
return false;
}
}

View file

@ -1,89 +0,0 @@
<?php
class Creeper extends Monster{
const TYPE = MOB_CREEPER;
const EXPL_TIME = 30;
public $timeUntilExplode;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.6, 1.7);
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 20, "generic");
$this->setName("Creeper");
$this->ignited = 0;
$this->setSpeed(0.25);
$this->update();
$this->timeUntilExplode = $this->isIgnited() ? self::EXPL_TIME : 0;
}
public function getAttackDamage(){
return 0; //TODO special attack
}
public function setIgnited($v = null){
$this->setState($v === null ? !$this->getState() : $v);
}
/**
* @return boolean
*/
public function isIgnited(){
return $this->getState() > 0;
}
public function interactWith(Entity $e, $action){
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$slot = $e->player->getHeldItem();
if($slot->getID() === FLINT_AND_STEEL && !$this->isIgnited()){
if($slot->useOn($this) && $slot->getMetadata() >= $slot->getMaxDurability()){
$e->player->removeItem($slot->getID(), $slot->getMetadata(), $slot->count, true);
}else{
$e->player->setSlot($e->player->slot, $slot);
}
$this->ignite();
return true;
}
}
return parent::interactWith($e, $action);
}
public function ignite(){
$this->setIgnited(1);
$this->timeUntilExplode = self::EXPL_TIME;
}
public function attackEntity($entity){
if(Utils::distance_noroot($entity, $this) <= 49 && !$this->isIgnited()){
$this->ignite();
}
}
public function update(){
if($this->isIgnited() && $this->target instanceof Entity && Utils::distance_noroot($this->target, $this) > 49){
$this->setIgnited(-1); //broken in vanilla too
$this->timeUntilExplode = 0;
}
if($this->timeUntilExplode === 1){
$this->explode();
}
if($this->timeUntilExplode >= 0){
--$this->timeUntilExplode;
}
parent::update();
}
public function explode()
{
if($this->closed || $this->dead){
return false;
}
$this->setIgnited(0);
$explosion = new Explosion($this, 3);
$this->close();
$explosion->explode();
}
public function getDrops(){
return [
[GUNPOWDER, 0, mt_rand(0,2)]
];
}
}

View file

@ -1,65 +0,0 @@
<?php
class Enderman extends Monster
{
const TYPE = MOB_ENDERMAN;
const DATA_BLOCKID = 16;
const DATA_BLOCKMETA = 17;
const DATA_ANGRY = 18;
public $forceTeleport;
protected $isAngry;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.6, 2.9);
parent::__construct($level, $eid, $class, $type, $data);
$this->setName("Enderman");
$this->setSpeed(0.3);
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 40, "generic");
}
public function getMetadata(){
$ret = parent::getMetadata();
$ret[self::DATA_ANGRY] = ["type" => 0, "value" => (int)$this->isAngry];
$ret[self::DATA_BLOCKID] = ["type" => 1, "value" => 0];
$ret[self::DATA_BLOCKMETA] = ["type" => 1, "value" => 0]; //TODO carry blocks
return $ret;
}
public function setAngry($t){
if($this->isAngry != $t){
$this->isAngry = $t;
$this->updateMetadata();
}
}
public function isAngry(){
return $this->isAngry;
}
public function harm($dmg, $cause = "generic", $force = false){
parent::harm($dmg, $cause, $force);
if($cause === "water"){
$this->randomTeleport();
}
if(is_numeric($cause) && $this->level->entityList[$cause]->isPlayer()){
$this->setAngry(true); //TODO better way to find is it angry or not
}
}
public function randomTeleport(){
$x = $this->x + ($this->random->nextFloat() - 0.5) * 64;
$z = $this->z + ($this->random->nextFloat() - 0.5) * 64;
for($y = 0; $y < 128; ++$y){
$b = $this->level->getBlockWithoutVector($x, $y, $z);
if($b instanceof Block && !$b->isTransparent){ //TODO hitbox check
$this->x = $x;
$this->y = $y+0.5;
$this->z = $z;
}
}
}
}

View file

@ -1,29 +0,0 @@
<?php
class PigZombie extends Monster{
const TYPE = MOB_PIGMAN;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.3, 1.95);
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 20, "generic");
$this->setName("Pigman");
$this->setSpeed(0.25);
$this->update();
}
public function getAttackDamage(){
return 5;
}
public function getDrops(){
return [
[COOKED_PORKCHOP, 0, mt_rand(0,2)],
[GOLD_INGOT, 0, mt_rand(0,1)]
];
}
public function harm($dmg, $cause = "generic", $force = false)
{
if($cause === "fire" || $cause === "lava" || $cause === "burning"){
return false;
}
return parent::harm($dmg, $cause, $force);
}
}

View file

@ -1,14 +0,0 @@
<?php
class SilverFish extends Monster
{
const TYPE = MOB_SILVERFISH;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.3, 0.7);
parent::__construct($level, $eid, $class, $type, $data);
$this->setSpeed(0.3);
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 8, "generic");
$this->setName("Silverfish");
}
}

View file

@ -1,49 +0,0 @@
<?php
class Skeleton extends Monster{
const TYPE = MOB_SKELETON;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.6, 1.99);
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 15, "generic");
$this->setName("Skeleton");
$this->ai->removeTask("TaskAttackPlayer");
$this->setSpeed(0.25);
$this->update();
}
public function getAttackDamage(){
return 0; //TODO special attack
}
public function updateBurning(){
if($this->fire > 0 or !$this->level->isDay()){
return false;
}
for($y = $this->y; $y < 129; $y++){
$block = $this->level->getBlockWithoutVector($this->x, $y, $this->z);
if($block->isSolid){
return false;
}
}
if($block->getID() === AIR){
$this->fire = 160; //Value from 0.8.1
$this->updateMetadata();
return true;
}else{
return false;
}
}
public function update(){
$this->updateBurning();
parent::update();
}
public function getDrops(){
return [
[ARROW, 0, mt_rand(0,2)],
[BONE, 0, mt_rand(0,2)]
];
}
}

View file

@ -1,58 +0,0 @@
<?php
class Slime extends Monster{
const TYPE = MOB_SLIME;
public $size;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->setName("Slime");
/* Health formula
* SlimeSize = Slime::getSlimeSize(this);
* return SlimeSize * SlimeSize;
*/
$this->setSlimeSize($data["Size"] ?? (1 << mt_rand(0, 2)));
}
public function getSlimeSize(){
return $this->size;
}
public function makeDead($cause){
$cnt = 2 + mt_rand(0, 2);
$s = $this->size;
if($s > 1){
for($i = 0; $i < $cnt; ++$i){
$xOff = (($cnt % 2) - 0.5) * $s / 4;
$zOff = (($cnt / 2) - 0.5) * $s / 4;
$e = $this->server->api->entity->add($this->level, $this->class, $this->type, [
"x" => $this->x + $xOff,
"y"=> $this->y + 1,
"z" => $this->z + $zOff,
"Size" => (int) ($s / 2)
]);
$this->server->api->entity->spawnToAll($e);
}
}
parent::makeDead($cause);
}
public function setSlimeSize($i){
$this->size = $i;
$this->setSize(0.6 * $i, 0.6 * $i);
$this->setHealth($i * $i);
}
public function createSaveData(){
$sd = parent::createSaveData();
$sd["Size"] = $this->size;
return $sd;
}
public function getMetadata(){
$ret = parent::getMetadata();
$ret[16]["value"] = $this->size;
return $ret;
}
}

View file

@ -1,18 +0,0 @@
<?php
class Spider extends Monster{
const TYPE = MOB_SPIDER;
function __construct(Level $level, $eid, $class, $type = 0, $data = array()){
$this->setSize(1.4, 0.9);
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 16, "generic");
$this->setName("Spider");
$this->setSpeed(0.3);
$this->update();
}
public function getDrops(){
return [
[STRING, 0, mt_rand(0,2)]
];
}
}

View file

@ -1,53 +0,0 @@
<?php
class Zombie extends Monster{
const TYPE = MOB_ZOMBIE;
function __construct(Level $level, $eid, $class, $type = 0, $data = array()){
$this->setSize(0.6, 1.85);
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 20, "generic");
$this->setName("Zombie");
$this->setSpeed(0.23);
$this->update();
}
public function getArmorValue(){
return 2;
}
public function updateBurning(){
if($this->fire > 0 or !$this->level->isDay()){
return false;
}
for($y = $this->y; $y < 129; $y++){
$block = $this->level->getBlockWithoutVector($this->x, $y, $this->z);
if($block->isSolid){
return false;
}
}
if($block->getID() === AIR){
$this->fire = 160; //Value from 0.8.1
$this->updateMetadata();
return true;
}else{
return false;
}
}
public function getAttackDamage(){
return 4; //TODO vanillafy(zombies might be able to hold items)
}
public function update(){
$this->updateBurning();
parent::update();
}
public function getDrops(){
return [
[CARROT, 0, Utils::chance(0.83) ? 1 : 0],
[POTATO, 0, Utils::chance(0.83) ? 1 : 0],
[FEATHER, 0, mt_rand(0,2)]
];
}
}

View file

@ -1,14 +0,0 @@
<?php
class Villager extends Neutral //TODO AI
{
const TYPE = MOB_VILLAGER;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.6, 1.8);
parent::__construct($level, $eid, $class, $type, $data);
$this->setSpeed(0.3);
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 10, "generic");
$this->setName("Villager");
}
}

View file

@ -1,66 +0,0 @@
<?php
class Minecart extends Vehicle{
const TYPE = OBJECT_MINECART;
private $moveVector = [];
const STATE_INITIAL = 0;
const STATE_ON_RAIL = 1;
const STATE_OFF_RAIL = 2;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->canBeAttacked = true;
$this->x = isset($this->data["TileX"]) ? $this->data["TileX"]:$this->x;
$this->y = isset($this->data["TileY"]) ? $this->data["TileY"]:$this->y;
$this->z = isset($this->data["TileZ"]) ? $this->data["TileZ"]:$this->z;
$this->setHealth(3, "generic");
//$this->setName((isset($objects[$this->type]) ? $objects[$this->type]:$this->type));
$this->width = 0.98;
$this->height = 0.7;
$this->update();
}
public function getDrops(){
return [
[MINECART, 0, 1]
];
}
public function spawn($player){
$pk = new AddEntityPacket;
$pk->eid = $this->eid;
$pk->type = $this->type;
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->yaw = $this->yaw;
$pk->pitch = $this->pitch;
$player->dataPacket($pk);
$pk = new SetEntityMotionPacket;
$pk->entities = [[$this->eid, $this->speedX, $this->speedY, $this->speedZ]];
$player->dataPacket($pk);
}
public function interactWith(Entity $e, $action){
if($action === InteractPacket::ACTION_HOLD && $e->isPlayer() && $this->canRide($e)){
$this->linkedEntity = $e;
$e->isRiding = true;
$this->linkEntity($e, SetEntityLinkPacket::TYPE_RIDE);
return true;
}
if($e->isPlayer() && $action === InteractPacket::ACTION_HOLD){
$this->linkEntity($e, SetEntityLinkPacket::TYPE_REMOVE);
$this->linkedEntity = 0;
$e->isRiding = false;
return true;
}
parent::interactWith($e, $action);
}
public function canRide($e)
{
return !($this->linkedEntity instanceof Entity) && !$e->isRiding;
}
}

View file

@ -1,40 +0,0 @@
<?php
class Painting extends Hanging{
const TYPE = OBJECT_PAINTING;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->x = isset($this->data["TileX"]) ? $this->data["TileX"]:$this->x;
$this->y = isset($this->data["TileY"]) ? $this->data["TileY"]:$this->y;
$this->z = isset($this->data["TileZ"]) ? $this->data["TileZ"]:$this->z;
$this->setHealth(1, "generic");
$this->canBeAttacked = true;
$this->width = 1;
$this->isStatic = true;
}
public function getDrops(){
return [
[PAINTING, 0, 1]
];
}
public function createSaveData(){
$data = parent::createSaveData();
$data["Motive"] = $this->data["Motive"];
return $data;
}
public function spawn($player){
$pk = new AddPaintingPacket;
$pk->eid = $this->eid;
$pk->x = (int) $this->x;
$pk->y = (int) $this->y;
$pk->z = (int) $this->z;
$pk->direction = $this->getDirection();
$pk->title = $this->data["Motive"];
$player->dataPacket($pk);
}
}

View file

@ -1,49 +0,0 @@
<?php
class PrimedTNT extends Entity{
const TYPE = OBJECT_PRIMEDTNT;
const CLASS_TYPE = ENTITY_OBJECT;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
if(!isset($this->data["fuse"])){
$this->data["fuse"] = 0;
}
$this->setHealth(10000000, "generic");
$this->server->schedule(5, [$this, "updateFuse"], [], true);
$this->update();
}
public function getMetadata(){
$d = parent::getMetadata();
$d[16]["value"] = (int) max(0, $this->data["fuse"] - (microtime(true) - $this->spawntime) * 20);
return $d;
}
public function updateFuse(){
if($this->closed === true){
return false;
}
if($this->type === OBJECT_PRIMEDTNT){
$this->updateMetadata();
if(((microtime(true) - $this->spawntime) * 20) >= $this->data["fuse"]){
$this->close();
$explosion = new Explosion($this, $this->data["power"]);
$explosion->explode();
}
}
}
public function spawn($player){
$pk = new AddEntityPacket;
$pk->eid = $this->eid;
$pk->type = $this->type;
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->did = 0;
$player->dataPacket($pk);
$pk = new SetEntityMotionPacket;
$pk->entities = [[$this->eid, $this->speedX, $this->speedY, $this->speedZ]];
$player->dataPacket($pk);
}
}

View file

@ -1,18 +0,0 @@
<?php
class TripodCamera extends Entity{
const TYPE = OBJECT_TRIPOD_CAMERA;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(PHP_INT_MAX, "generic");
}
public function interactWith(Entity $e, $action){
if($e->isPlayer() and $action === InteractPacket::ACTION_HOLD){
//todo
$this->server->schedule(40, [$this, "close"]);
}
parent::interactWith($e, $action);
}
}

View file

@ -1,61 +0,0 @@
<?php
class Arrow extends Projectile{
const TYPE = OBJECT_ARROW;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
//$this->server->schedule(1210, array($this, "update")); //Despawn
}
public function handleUpdate(){
$pk = new MoveEntityPacket_PosRot;
$pk->eid = $this->eid;
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->yaw = $this->yaw;
$pk->pitch = $this->pitch;
$this->server->api->player->broadcastPacket($this->level->players, $pk);
}
public function shoot($d, $d1, $d2, $f, $f1){ //original name from 0.8.1 IDA decompilation, var names are taken from b1.7.3
$f2 = sqrt($d * $d + $d1 * $d1 + $d2 * $d2);
$d /= $f2;
$d1 /= $f2;
$d2 /= $f2;
$d += $this->random->nextGaussian() * 0.0075 * $f1; //0.0074999998323619366 replaced with 0.0075
$d1 += $this->random->nextGaussian() * 0.0075 * $f1;
$d2 += $this->random->nextGaussian() * 0.0075 * $f1;
$d *= $f;
$d1 *= $f;
$d2 *= $f;
$this->speedX = $d;
$this->speedY = $d1;
$this->speedZ = $d2;
$f3 = sqrt($d * $d + $d2 * $d2);
$this->yaw = (atan2($d, $d2) * 180) / M_PI;
$this->pitch = (atan2($d1, $f3) * 180) / M_PI;
$this->update();
//TODO i guess? $ticksInGround = 0;
}
public function spawn($player){
//if($this->type === OBJECT_ARROW){
$pk = new AddEntityPacket;
$pk->eid = $this->eid;
$pk->type = $this->type;
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->did = 1;
$pk->speedX = $this->speedX;
$pk->speedY = $this->speedY;
$pk->speedZ = $this->speedZ;
$player->dataPacket($pk);
$pk = new SetEntityMotionPacket;
$pk->entities = [[$this->eid, $this->speedX, $this->speedY, $this->speedZ]];
$player->dataPacket($pk);
//}
}
}

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