Merge pull request #34 from gameherobrine2/newmovement

better movement
This commit is contained in:
GameHerobrine 2024-02-14 05:37:36 +03:00 • committed by GitHub
commit 7ad98fe444
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
55 changed files with 1321 additions and 794 deletions

View file

@ -162,6 +162,9 @@ class EntityAPI{
}else{
$this->entities[$eid] = new Entity($level, $eid, $class, $type, $data);
}
$cX = (int)$this->entities[$eid]->x >> 4;
$cZ = (int)$this->entities[$eid]->z >> 4;
$level->entityListPositioned["$cX $cZ"][$eid] = $eid;
$level->entityList[$eid] = &$this->entities[$eid];
$this->server->handle("entity.add", $this->entities[$eid]);
return $this->entities[$eid];
@ -182,6 +185,12 @@ class EntityAPI{
public function remove($eid){
if(isset($this->entities[$eid])){
$this->entities[$eid]->closed = true;
if($this->entities[$eid]->level instanceof Level){
$cX = (int)$this->entities[$eid]->x >> 4;
$cZ = (int)$this->entities[$eid]->z >> 4;
$index = "$cX $cZ";
unset($this->entities[$eid]->level->entityListPositioned[$index][$eid]);
}
if($this->entities[$eid]->isPlayer()){
$pk = new RemovePlayerPacket;
$pk->eid = $eid;
@ -195,22 +204,30 @@ class EntityAPI{
$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 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;
$minChunkX = ((int)($center->x - $radius)) >> 4;
$minChunkZ = ((int)($center->z - $radius)) >> 4;
$maxChunkX = ((int)($center->x + $radius)) >> 4;
$maxChunkZ = ((int)($center->z + $radius)) >> 4;
$ents = [];
//TODO also index by chunkY?
for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){
for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ){
$ind = "$chunkX $chunkZ";
foreach($center->level->entityListPositioned[$ind] ?? [] as $ind2 => $entid){
if(isset($this->entities[$entid]) && $this->entities[$entid] instanceof Entity && ($class === false || $this->entities[$entid]->class == $class)){
$ents[$entid] = $this->entities[$entid];
}else if(!isset($this->entities[$entid])){
ConsoleAPI::debug("Removing entity from level array at index $ind/$ind2: $entid");
unset($center->level->entityListPositioned[$ind][$ind2]);
}
}
}
}
return $entities;
return $ents;
}
public function heal($eid, $heal, $cause){

View file

@ -32,7 +32,7 @@ class PlayerAPI{
$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;");
//$this->server->preparedSQL->selectPlayersToHeal = $this->server->database->prepare("SELECT EID FROM entities WHERE class = " . ENTITY_PLAYER . " AND health < 20;");
}
public function registerCmd($cmd, $help = ""){
@ -43,7 +43,7 @@ class PlayerAPI{
switch($event){
case "server.regeneration":
if($this->server->difficulty === 0){
$result = $this->server->preparedSQL->selectPlayersToHeal->execute();
//$result = $this->server->preparedSQL->selectPlayersToHeal->execute();
if($result !== false){
while(($player = $result->fetchArray()) !== false){
if(($player = $this->server->api->entity->get($player["EID"])) !== false){
@ -365,6 +365,7 @@ class PlayerAPI{
"z" => $player->level->getSpawn()->z,
]);
}
$player->level->players[$CID] = $player;
$this->server->query("INSERT OR REPLACE INTO players (CID, ip, port, name) VALUES (" . $player->CID . ", '" . $player->ip . "', " . $player->port . ", '" . strtolower($player->username) . "');");
}
}
@ -434,16 +435,8 @@ class PlayerAPI{
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;
//safe_var_dump($level->players);
return $level->players;
}
return $this->server->clients;
@ -487,6 +480,7 @@ class PlayerAPI{
}
$this->server->query("DELETE FROM players WHERE name = '" . $player->username . "';");
$this->server->api->entity->remove($player->eid);
unset($player->level->players[$player->CID]);
if($player->entity instanceof Entity){
unset($player->entity->player);
//unset($player->entity);

View file

@ -2,7 +2,7 @@
class QueryAPI{
public static $NOT_FOUND_VALUE;
public static $NOT_FOUND_VALUE; //TODO just use null
private $queryData;
private $server;

View file

@ -143,11 +143,8 @@ class ServerAPI{
Entity::$allowedAI = $this->getProperty("enable-mob-ai", true);
//Load advanced properties
define("DEBUG", $this->getProperty("debug", 1));
define("ADVANCED_CACHE", $this->getProperty("enable-advanced-cache", false));
define("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");
if($this->getProperty("upnp-forwarding") == true){

View file

@ -110,8 +110,9 @@ class Player{
$this->blockUpdateQueue = new RakNetPacket(RakNetInfo::DATA_PACKET_0);
$this->blockUpdateQueue->data = [];
//$this->server->schedule(20 * 60, [$this, "clearQueue"], [], true);
$this->server->schedule(1, [$this, "handlePacketQueues"], [], true);
$this->server->schedule(20 * 60, [$this, "clearQueue"], [], true);
$this->evid[] = $this->server->event("server.close", [$this, "close"]);
console("[DEBUG] New Session started with " . $ip . ":" . $port . ". MTU " . $this->MTU . ", Client ID " . $this->clientID, true, true, 2);
}
@ -203,7 +204,13 @@ class Player{
}
$this->level->freeAllChunks($this);
unset($this->level->players[$this->CID]);
unset($this->level->entityListPositioned["{$this->entity->chunkX} {$this->entity->chunkZ}"][$this->eid]);
unset($this->level->entityList[$this->eid]);
$this->level = $pos->level;
$this->entity->level = $this->level;
$this->level->entityList[$this->entity->eid] = $this->entity;
$this->level->players[$this->CID] = $this;
$this->chunksLoaded = [];
$this->server->api->entity->spawnToAll($this->entity);
$this->server->api->entity->spawnAll($this);
@ -587,8 +594,6 @@ class Player{
}
public function sendInventorySlot($s){
$this->sendInventory();
return;
$s = (int) $s;
if(!isset($this->inventory[$s])){
$pk = new ContainerSetSlotPacket;
@ -747,7 +752,7 @@ class Player{
$pk->target = $data["entity"]->eid;
$this->dataPacket($pk);
if(($this->gamemode & 0x01) === 0x00){
$this->addItem($data["entity"]->type, $data["entity"]->meta, $data["entity"]->stack, false);
$this->addItem($data["entity"]->type, $data["entity"]->meta, $data["entity"]->stack, true);
}
switch($data["entity"]->type){
case WOOD:
@ -909,6 +914,15 @@ class Player{
}
if($m !== ""){
/*$pk = new LevelEventPacket();
$pk->evid = LevelEventPacket::EVENT_OPEN_DOOR_SOUND;
$pk->x = $this->entity->x;
$pk->y = $this->entity->y;
$pk->z = $this->entity->z;
$pk->data = 0;
$this->dataPacket($pk);*/
$pk = new MessagePacket;
$pk->source = ($author instanceof Player) ? $author->username : $author;
$pk->message = TextFormat::clean($m); //Colors not implemented :(
@ -1200,21 +1214,23 @@ class Player{
$moveSent = false;
$headSent = false;
if($e->speedX != 0 || $e->speedY != 0 || $e->speedZ != 0 || $e->speedY != $e->lastSpeedY || $e->speedX != $e->lastSpeedX || $e->speedZ != $e->lastSpeedZ){
$motion = new SetEntityMotionPacket();
$motion->eid = $e->eid;
$motion->speedX = $e->speedX;
$motion->speedY = $e->speedY;
$motion->speedZ = $e->speedZ;
$motion->encode();
$len += 1 + strlen($motion->buffer);
++$packets;
$motionSent = true;
if(!($e->speedY < 0 && $e->onGround)){
$motion = new SetEntityMotionPacket();
$motion->eid = $e->eid;
$motion->speedX = $e->speedX;
$motion->speedY = $e->speedY;
$motion->speedZ = $e->speedZ;
$motion->encode();
$len += 1 + strlen($motion->buffer);
++$packets;
$motionSent = true;
}
}
if($e->x != $e->lastX || $e->y != $e->lastY || $e->z != $e->lastZ || $e->yaw != $e->lastYaw || $e->pitch != $e->lastPitch){
$move = new MoveEntityPacket_PosRot();
$move->eid = $e->eid;
$move->x = $e->x;
$move->y = $e instanceof ItemEntity ? $e->boundingBox->maxY : $e->y; //TODO fix items getting into farmland in client side somehow else
$move->y = $e->y;
$move->z = $e->z;
$move->yaw = $e->yaw;
$move->pitch = $e->pitch;
@ -2325,6 +2341,7 @@ class Player{
$this->entity->linkedEntity->setPosition($this->entity);
$this->entity->linkedEntity->sendMoveUpdate();
//$this->entity->linkedEntity->moveFlying($packet->moveStrafe, $packet->moveForward, 1);
}
break;

View file

@ -89,10 +89,12 @@ class PocketMinecraftServer{
"16x16x16_chunk_sending" => false,
"experimental-mob-ai" => false,
"force-20-tps" => false,
"enable-mob-pushing" => Living::$entityPushing
]);
Player::$smallChunks = $this->extraprops->get("16x16x16_chunk_sending");
Living::$despawnMobs = $this->extraprops->get("despawn-mobs");
Living::$despawnTimer = $this->extraprops->get("mob-despawn-ticks");
Living::$entityPushing = $this->extraprops->get("enable-mob-pushing");
self::$FORCE_20_TPS = $this->extraprops->get("force-20-tps");
PocketMinecraftServer::$SAVE_PLAYER_DATA = $this->extraprops->get("save-player-data");
MobController::$ADVANCED = $this->extraprops->get("experimental-mob-ai");
@ -437,7 +439,6 @@ class PocketMinecraftServer{
}
$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);
}
@ -486,7 +487,7 @@ class PocketMinecraftServer{
} elseif($this->tick() > 0){
$lastLoop = 0;
} else{
++ $lastLoop;
++$lastLoop;
if($lastLoop < 16){
usleep(1);
} elseif($lastLoop < 128){
@ -620,7 +621,7 @@ class PocketMinecraftServer{
++$actionCount;
try{
$return = @call_user_func($this->schedule[$cid][0] ?? function(){}, $this->schedule[$cid][1], $this->schedule[$cid][2]); //somehow args can be null
}catch(Throwable $e){
}catch(TypeError $e){
$return = false;
}
}else{
@ -727,10 +728,8 @@ class PocketMinecraftServer{
$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["entities"] = count($this->api->entity->entities);
$info["players"] = count($this->clients);
$info["events"] = count($this->eventsID);
$info["handlers"] = $this->query("SELECT count(ID) as count FROM handlers;", true);
$info["handlers"] = $info["handlers"]["count"];

View file

@ -96,13 +96,9 @@ require_once(FILE_PATH . "/src/astarnavigator/TileNavigator.php");
require_once(FILE_PATH . "/src/entity/ai/tasks/TaskBase.php");
require_once(FILE_PATH. "/src/entity/ai/tasks/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");

View file

@ -12,9 +12,9 @@ abstract class Animal extends Creature implements Ageable, Breedable{
$this->setAge(-24000);
}
$this->ai->addTask(new TaskTempt());
$this->ai->addTask(new TaskPanic());
$this->ai->addTask(new TaskMate());
//$this->ai->addTask(new TaskTempt());
//$this->ai->addTask(new TaskPanic());
//$this->ai->addTask(new TaskMate());
}
public function harm($dmg, $cause = "generic", $force = false){

View file

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

View file

@ -11,10 +11,10 @@ abstract class Creature extends Living{
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 1, "generic");
$this->enableAutojump = true;
//$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());
//$this->ai->addTask(new TaskLookAround());
//$this->ai->addTask(new TaskRandomWalk());
//$this->ai->addTask(new TaskLookAtPlayer());
//$this->ai->addTask(new TaskSwimming());
}
public function createSaveData(){
@ -24,7 +24,7 @@ abstract class Creature extends Living{
}
public function getSpeedModifer(){
return $this->speedModifer * ($this->inPanic ? 1.5 : 1.0);
return 0.7; //$this->speedModifer; //should be 0.7?
}
public function getArmorValue(){
return 2;

View file

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

View file

@ -6,6 +6,7 @@ class Entity extends Position
const TYPE = - 1;
const CLASS_TYPE = - 1;
const MIN_POSSIBLE_SPEED = 1/8000; //anything below will send 0 to player
public $counter = 0;
public $fallDistance = 0;
public static $updateOnTick, $allowedAI;
@ -83,6 +84,20 @@ class Entity extends Position
public $stepHeight = 0.5;
public $enableAutojump = false;
public $yOffset = 0.0;
public $noClip = false;
public $chunkX = 0;
public $chunkZ = 0;
public $isCollidedHorizontally, $isCollidedVertically, $isCollided;
/**
* Amount of ticks you can be in fire until you start receiving damage
* @var integer
*/
public $fireResistance = 1;
public $inWeb;
public $inLava;
function __construct(Level $level, $eid, $class, $type = 0, $data = array())
{
$this->random = new Random();
@ -90,7 +105,7 @@ class Entity extends Position
$this->canBeAttacked = false;
$this->hasKnockback = false;
$this->level = $level;
$this->speedModifer = 0.7;
$this->speedModifer = 1;
$this->fallY = false;
$this->fallStart = false;
$this->server = ServerAPI::request();
@ -116,7 +131,6 @@ class Entity extends Position
$this->gravity = 0.08;
$this->state = $this->data["State"] = isset($this->data["State"]) ? $this->data["State"] : 0;
$this->tickCounter = 0;
$this->server->query("INSERT OR REPLACE INTO entities (EID, level, type, class, health, hasUpdate) VALUES (" . $this->eid . ", '" . $this->level->getName() . "', " . $this->type . ", " . $this->class . ", " . $this->health . ", 0);");
$this->x = isset($this->data["x"]) ? (float) $this->data["x"] : 0;
$this->y = isset($this->data["y"]) ? (float) $this->data["y"] : 0;
$this->z = isset($this->data["z"]) ? (float) $this->data["z"] : 0;
@ -148,6 +162,7 @@ class Entity extends Position
$this->hasKnockback = true;
$this->hasGravity = true;
$this->canBeAttacked = true;
$this->fireResistance = 20; //TODO fire resiatance for player
break;
case ENTITY_OBJECT:
$this->x = isset($this->data["TileX"]) ? $this->data["TileX"] : $this->x;
@ -183,6 +198,11 @@ class Entity extends Position
}
public function setInWeb(){
$this->inWeb = true;
$this->fallDistance = 0;
}
public function addVelocity($vX, $vY = 0, $vZ = 0)
{
if($vX instanceof Vector3){
@ -317,7 +337,24 @@ class Entity extends Position
$this->server->api->entity->drop($this, BlockAPI::getItem($drop[0] & 0xFFFF, $drop[1] & 0xFFFF, $drop[2] & 0xFF), true);
}
}
public function handleLavaMovement(){ //TODO maybe try merging with water?
$this->inLava = $this->level->isLavaInBB($this->boundingBox->expand(-0.1, -0.4, -0.1));
return $this->inLava;
}
public function handleWaterMovement(){
if($this->level->handleMaterialAcceleration($this->boundingBox->expand(0, -0.4, 0)->contract(0.001, 0.001, 0.001), 0, $this)){
$this->fallDistance = 0;
$this->inWater = true;
$this->fire = 0;
}else{
$this->inWater = false;
}
return $this->inWater;
}
public function environmentUpdate($time)
{
$hasUpdate = $this->class === ENTITY_MOB; // force true for mobs
@ -327,7 +364,7 @@ class Entity extends Position
if($this->class === ENTITY_PLAYER and ($this->player instanceof Player) and $this->player->spawned === true and $this->player->blocked !== true && ! $this->dead){
$myBB = $this->boundingBox->grow(1, 0.5, 1);
foreach($this->server->api->entity->getRadius($this, 2, ENTITY_ITEM) as $item){
if(!$item->closed && $item->spawntime > 0 && $item->delayBeforePickup == 0){
if(!$item->closed && $item->spawntime > 0 && $item->delayBeforePickup <= 0){
if($item->boundingBox->intersectsWith($myBB)){
if((($this->player->gamemode & 0x01) === 1 || $this->player->hasSpace($item->type, $item->meta, $item->stack) === true) && $this->server->api->dhandle("player.pickup", array(
"eid" => $this->player->eid,
@ -370,8 +407,11 @@ class Entity extends Position
$this->outOfWorld();
$hasUpdate = true;
}
if($this->fire > 0){
if(!$this->isPlayer()){
$this->handleWaterMovement();
}
if($this->fire > 0){ //TODO move somewhere
if(($this->fire % 20) === 0){
$this->harm(1, "burning");
}
@ -384,6 +424,13 @@ class Entity extends Position
}
}
if(!$this->isPlayer()) {
if($this->handleLavaMovement()){
//TODO this.setOnFireFromLava();
$this->fallDistance *= 0.5;
}
}
$startX = floor($this->boundingBox->minX);
$startY = floor($this->boundingBox->minY);
$startZ = floor($this->boundingBox->minZ);
@ -394,7 +441,7 @@ class Entity extends Position
if(!($this instanceof Painting) && !($this->isPlayer() && $this->player->isSleeping !== false)){ //TODO better way to fix
for($i = 0; $i < 8; ++$i){
$x = ((($i >> 0) % 2) - 0.5) * $this->width * 0.8;
$y= ((($i >> 1) % 2) - 0.5) * 0.1;
$y = ((($i >> 1) % 2) - 0.5) * 0.1;
$z = ((($i >> 2) % 2) - 0.5) * $this->width * 0.8;
$blockX = (int) ($this->x + $x);
@ -409,6 +456,8 @@ class Entity extends Position
}
}
//air damage
if($this->isPlayer() || $this instanceof Living){
$d = $this->y + $this->getEyeHeight();
@ -421,7 +470,7 @@ class Entity extends Position
$f = LiquidBlock::getPercentAir($this->level->level->getBlockDamage($x, $y, $z)) - 0.1111111;
$f1 = ($y + 1) - $f;
if($d < $f1){
$this->air -= 1*$tickDiff;
$this->air -= $tickDiff;
if($this->air <= -20){
$this->harm(2, "water");
$this->air = 0; //harm every 1 second
@ -487,9 +536,205 @@ class Entity extends Position
return $hasUpdate;
}
public function moveFlying($strafe, $forward, $speed){ //TODO rename?
$v4 = $strafe*$strafe + $forward*$forward;
if($v4 >= 0.0001){
$v4 = sqrt($v4);
if($v4 < 1) $v4 = 1;
$v4 = $speed / $v4;
$strafe *= $v4;
$forward *= $v4;
$v5 = sin($this->yaw * M_PI/180);
$v6 = cos($this->yaw * M_PI/180);
$this->speedX += $strafe*$v6 - $forward*$v5;
$this->speedZ += $forward*$v6 + $strafe*$v5;
}
}
public function updateEntityMovement(){}
public function doBlocksCollision(){
$minX = floor($this->boundingBox->minX + 0.001);
$minY = floor($this->boundingBox->minY + 0.001);
$minZ = floor($this->boundingBox->minZ + 0.001);
$maxX = floor($this->boundingBox->maxX - 0.001);
$maxY = floor($this->boundingBox->maxY - 0.001);
$maxZ = floor($this->boundingBox->maxZ - 0.001);
for($x = $minX; $x <= $maxX; ++$x){
for($y = $minY; $y <= $maxY; ++$y){
for($z = $minZ; $z <= $maxZ; ++$z){
$id = $this->level->level->getBlockID($x, $y, $z);
if($id > 0){
Block::$class[$id]::onEntityCollidedWithBlock($this->level, $x, $y, $z, $this);
}
}
}
}
}
public function move($dx, $dy, $dz){
$movX = $this->x;
$movY = $this->y;
$movZ = $this->z;
if($this->inWeb){
$this->inWeb = false;
$dx *= 0.25;
$dy *= 0.05;
$dz *= 0.25;
$this->speedX = $this->speedY = $this->speedZ = 0;
}
$savedDX = $dx;
$savedDY = $dy;
$savedDZ = $dz;
$oldBB = clone $this->boundingBox;
$aABB = $this->boundingBox->addCoord($dx, $dy, $dz);
$x0 = floor($aABB->minX);
$x1 = floor($aABB->maxX + 1);
$y0 = floor($aABB->minY);
$y1 = floor($aABB->maxY + 1);
$z0 = floor($aABB->minZ);
$z1 = floor($aABB->maxZ + 1);
for($x = $x0; $x < $x1; ++$x){
for($z = $z0; $z < $z1; ++$z){
for($y = $y0 - 1; $y < $y1; ++$y){
$b = $this->level->level->getBlockID($x, $y, $z);
if($b != 0){
$blockBounds = Block::$class[$b]::getCollisionBoundingBoxes($this->level, $x, $y, $z, $this);
foreach($blockBounds as $blockBound){
$dy = $blockBound->calculateYOffset($this->boundingBox, $dy);
$dx = $blockBound->calculateXOffset($this->boundingBox, $dx);
$dz = $blockBound->calculateZOffset($this->boundingBox, $dz);
}
}
}
}
}
$this->boundingBox->offset($dx, $dy, $dz);
$fallingFlag = $this->onGround || $savedDY != $dy && $savedDY < 0;
if($this->stepHeight > 0 && $fallingFlag && ($savedDX != $dx || $savedDZ != $dz)){
$cx = $dx;
$cy = $dy;
$cz = $dz;
$dx = $savedDX;
$dy = $this->stepHeight;
$dz = $savedDZ;
$aabb1 = clone $this->boundingBox;
$this->boundingBox->setBB($oldBB);
$aaBBs = $this->level->getCubes($this, $this->boundingBox->addCoord($dx, $dy, $dz));
foreach($aaBBs as $bb){ //TODO optimize
$dy = $bb->calculateYOffset($this->boundingBox, $dy);
}
$this->boundingBox->offset(0, $dy, 0);
foreach($aaBBs as $bb){
$dx = $bb->calculateXOffset($this->boundingBox, $dx);
}
$this->boundingBox->offset($dx, 0, 0);
foreach($aaBBs as $bb){
$dz = $bb->calculateZOffset($this->boundingBox, $dz);
}
$this->boundingBox->offset(0, 0, $dz);
$dy = -$this->stepHeight;
foreach($aaBBs as $bb){
$dy = $bb->calculateYOffset($this->boundingBox, $dy);
}
$this->boundingBox->offset(0, $dy, 0);
if ($cx*$cx + $cz*$cz >= $dx*$dx + $dz*$dz)
{
$dx = $cx;
$dy = $cy;
$dz = $cz;
$this->boundingBox->setBB($aabb1);
}
}
$this->x = ($this->boundingBox->minX + $this->boundingBox->maxX) / 2;
$this->y = $this->boundingBox->minY + $this->yOffset;
$this->z = ($this->boundingBox->minZ + $this->boundingBox->maxZ) / 2;
$this->isCollidedHorizontally = $savedDX != $dx || $savedDZ != $dz;
$this->isCollidedVertically = $savedDY != $dy;
$this->onGround = $savedDY != $dy && $savedDY < 0.0;
$this->isCollided = $this->isCollidedHorizontally || $this->isCollidedVertically;
$this->updateFallState($this->speedY);
if($savedDX != $dx) $this->speedX = 0;
if($savedDY != $dy) $this->speedY = 0;
if($savedDZ != $dz) $this->speedZ = 0;
//TODO more stuff -> onEntityWalking
$this->doBlocksCollision();
if($this->level->isBoundingBoxOnFire($this->boundingBox->contract(0.001, 0.001, 0.001))){
$this->harm(1, "fire");
if($this->inWater){
++$this->fire;
if($this->fire == 0) $this->fire = 8;
}
}else if($this->fire <= 0){
$this->fire = -$this->fireResistance;
}
if($this->inWater && $this->fire > 0){
$this->fire = -$this->fireResistance;
}
}
//in MCP it is called isOffsetPositionInLiquid, in 0.8 - isFree
public function isFree($offsetX, $offsetY, $offsetZ){
$offsetBB = $this->boundingBox->getOffsetBoundingBox($offsetX, $offsetY, $offsetZ);
$minX = floor($offsetBB->minX);
$minY = floor($offsetBB->minY);
$minZ = floor($offsetBB->minZ);
$maxX = floor($offsetBB->maxX + 1);
$maxY = floor($offsetBB->maxY + 1);
$maxZ = floor($offsetBB->maxZ + 1);
$hasLiquid = false;
$result = false;
for($x = $minX; $x < $maxX; ++$x){
for($z = $minZ; $z < $maxZ; ++$z){
for($y = $minY - 1; $y < $maxY; ++$y){
$v12 = $this->level->level->getBlockID($x, $y, $z);
if($y != ($minY - 1)) $hasLiquid |= StaticBlock::getIsLiquid($v12);
if($v12 != 0){
$result = true;
break 3;
}
}
}
}
if($result) return !$hasLiquid;
return false;
}
public function isInVoid(){
return $this->y < -1.6;
}
@ -513,178 +758,20 @@ class Entity extends Position
if($this->isStatic === false){
if(!$this->isPlayer()){
$this->updateLast();
$this->updatePosition(); //TODO shouldnt be called in Entity
$this->updateEntityMovement();
$update = false;
if($this->speedX > -self::MIN_POSSIBLE_SPEED && $this->speedX < self::MIN_POSSIBLE_SPEED){
$this->speedX = 0;
}
if($this->speedZ > -self::MIN_POSSIBLE_SPEED && $this->speedZ < self::MIN_POSSIBLE_SPEED){
$this->speedZ = 0;
}
if($this->speedY > -self::MIN_POSSIBLE_SPEED && $this->speedY < self::MIN_POSSIBLE_SPEED){
$this->speedY = 0;
}
$horizontalMultiplyFactor = 0.91;
if($this->onGround){
$horizontalMultiplyFactor = 0.54;
$b = $this->level->level->getBlockID(floor($this->x), floor($this->boundingBox->minY) - 1, floor($this->z));
if($b > 0){
$horizontalMultiplyFactor = StaticBlock::getSlipperiness($b) * 0.91;
}
}
if($this->inWater){
$this->speedX *= 0.8;
$this->speedY *= 0.8;
$this->speedZ *= 0.8;
}else{
$this->speedX *= $horizontalMultiplyFactor;
$this->speedY *= 0.98;
$this->speedZ *= $horizontalMultiplyFactor;
}
$savedSpeedY = $this->speedY;
$savedSpeedX = $this->speedX;
$savedSpeedZ = $this->speedZ;
$ultraMegaOldBB = clone $this->boundingBox;
$stepSuccess = false;
$beforeStepSpeedY = 0;
if($this->class === ENTITY_MOB || $this->class === ENTITY_ITEM || ($this->class === ENTITY_OBJECT && $this->type === OBJECT_PRIMEDTNT) || $this->class === ENTITY_FALLING){
$water = false;
if($this->hasGravity){
$this->speedY -= $this->inWater ? 0.02 : ($this->gravity);
}
$savedSpeedY = $this->speedY;
$aABB = $this->boundingBox->addCoord($this->speedX, $this->speedY, $this->speedZ);
$x0 = floor($aABB->minX);
$x1 = ceil($aABB->maxX);
$y0 = floor($aABB->minY);
$y1 = ceil($aABB->maxY);
$z0 = floor($aABB->minZ);
$z1 = ceil($aABB->maxZ);
for($x = $x0; $x <= $x1; ++$x){
for($y = $y0; $y <= $y1; ++$y){
for($z = $z0; $z <= $z1; ++$z){
$b = $this->level->level->getBlockID($x, $y, $z);
if(($b === WATER || $b === STILL_WATER)){
$water = $y == ($y1 - 1);
$this->fallDistance = 0;
}
if($b != 0){
$blockBounds = Block::$class[$b]::getCollisionBoundingBoxes($this->level, $x, $y, $z, $this);
foreach($blockBounds as $blockBound){
$this->speedY = $blockBound->calculateYOffset($this->boundingBox, $this->speedY);
$this->speedX = $blockBound->calculateXOffset($this->boundingBox, $this->speedX);
$this->speedZ = $blockBound->calculateZOffset($this->boundingBox, $this->speedZ);
}
}
}
}
}
$this->boundingBox->offset($this->speedX, $this->speedY, $this->speedZ);
$this->inWater = $water;
$fallingFlag = $this->onGround || $savedSpeedY != $this->speedY && $savedSpeedY < 0.0;
$beforeStepSpeedY = $this->speedY;
if($this->stepHeight > 0 && $fallingFlag && ($this->speedX != $savedSpeedX || $this->speedZ != $savedSpeedZ)){
$cx = $this->speedX;
$cy = $this->speedY;
$cz = $this->speedZ;
$this->speedX = $savedSpeedX;
$this->speedY = $this->stepHeight;
$this->speedZ = $savedSpeedZ;
$aabb = clone $this->boundingBox;
$this->boundingBox->setBB($ultraMegaOldBB);
$aaBBs = $this->level->getCubes($this, $this->boundingBox->addCoord($this->speedX, $this->speedY, $this->speedZ));
foreach($aaBBs as $bb){ //TODO optimize
$this->speedY = $bb->calculateYOffset($this->boundingBox, $this->speedY);
}
$this->boundingBox->offset(0, $this->speedY, 0);
foreach($aaBBs as $bb){
$this->speedX = $bb->calculateXOffset($this->boundingBox, $this->speedX);
}
$this->boundingBox->offset($this->speedX, 0, 0);
foreach($aaBBs as $bb){
$this->speedZ = $bb->calculateZOffset($this->boundingBox, $this->speedZ);
}
$this->boundingBox->offset(0, 0, $this->speedZ);
if ($cx*$cx + $cz*$cz >= $this->speedX*$this->speedX + $this->speedZ*$this->speedZ)
{
$this->speedX = $cx;
$this->speedY = $cy;
$this->speedZ = $cz;
$this->boundingBox->setBB($aabb);
}else{
$stepSuccess = true;
}
}
}
if($this->enableAutojump && $this instanceof Creature){
if(!$stepSuccess && $fallingFlag && ($this->speedX != $savedSpeedX || $this->speedZ != $savedSpeedZ)){
$this->ai->mobController->setJumping(true);
}else{
$this->ai->mobController->setJumping(false);
}
}
$support = $savedSpeedY != $this->speedY && $savedSpeedY < 0;
if($this->speedX != 0){
$this->x += $this->speedX;
$update = true;
}
if($this->speedZ != 0){
$this->z += $this->speedZ;
$update = true;
}
if($this->speedY != 0){
$ny = $this->y + $this->speedY;
if($stepSuccess) $this->speedY = $beforeStepSpeedY;
if($this->class === ENTITY_FALLING){
if($support){
$this->level->fastSetBlockUpdate($this->x, $this->y, $this->z, $this->data["Tile"], 0);
$this->close();
return;
}
$id = $this->level->level->getBlockID($this->x, $this->y, $this->z);
if($id > 0 && !StaticBlock::getIsSolid($id) && !StaticBlock::getIsLiquid($id)){
$this->server->api->entity->drop($this, BlockAPI::getItem($this->data["Tile"], 0, 1));
$this->close();
return;
}
}
$this->y = $ny;
$update = true;
}
$this->onGround = $support;
if($this->lastX != $this->x || $this->lastZ != $this->z || $this->lastY != $this->z){
$this->server->api->handle("entity.move", $this);
$update = true;
}elseif ($this->lastYaw != $this->yaw || $this->lastPitch != $this->pitch || $this->lastHeadYaw != $this->headYaw) {
$update = true;
}
if($update === true){
$hasUpdate = true;
$this->lastSpeedZ = $this->speedZ;
$this->lastSpeedY = $this->speedY;
$this->lastSpeedX = $this->speedX;
}
$this->updateFallState($this->speedY);
} elseif($this->player instanceof Player){
$prevGroundState = $this->onGround;
$this->onGround = false;
@ -808,10 +895,7 @@ class Entity extends Position
$this->server->api->player->broadcastPacket($players, $pk);
}
}
} else{
$this->updatePosition();
}
}
$this->lastUpdate = $now;
}
@ -991,26 +1075,6 @@ class Entity extends Position
$player->dataPacket($pk);
$this->player->sendArmor($player);
break;
case ENTITY_ITEM:
$pk = new AddItemEntityPacket();
$pk->eid = $this->eid;
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->yaw = $this->yaw;
$pk->pitch = $this->pitch;
$pk->roll = 0;
$pk->item = BlockAPI::getItem($this->type, $this->meta, $this->stack);
$pk->metadata = $this->getMetadata();
$player->dataPacket($pk);
$pk = new SetEntityMotionPacket();
$pk->eid = $this->eid;
$pk->speedX = $this->speedX;
$pk->speedY = $this->speedY;
$pk->speedZ = $this->speedZ;
$player->dataPacket($pk);
break;
case ENTITY_FALLING:
$pk = new AddEntityPacket();
$pk->eid = $this->eid;
@ -1075,7 +1139,6 @@ class Entity extends Position
public function setName($name)
{
$this->name = $name;
// $this->server->query("UPDATE entities SET name = '".str_replace("'", "", $this->name)."' WHERE EID = ".$this->eid.";"); is this neccessary for database?
}
public function look($pos2)
@ -1084,47 +1147,24 @@ class Entity extends Position
$angle = Utils::angle3D($pos2, $pos);
$this->yaw = $angle["yaw"];
$this->pitch = $angle["pitch"];
$this->server->query("UPDATE entities SET pitch = " . $this->pitch . ", yaw = " . $this->yaw . " WHERE EID = " . $this->eid . ";");
}
public function move(Vector3 $pos, $yaw = 0, $pitch = 0)
{
$this->x += $pos->x;
$this->y += $pos->y;
$this->z += $pos->z;
$this->yaw += $yaw;
$this->yaw %= 360;
$this->pitch += $pitch;
$this->pitch %= 90;
$this->server->query("UPDATE entities SET x = " . $this->x . ", y = " . $this->y . ", z = " . $this->z . ", pitch = " . $this->pitch . ", yaw = " . $this->yaw . " WHERE EID = " . $this->eid . ";");
$this->updateAABB();
}
public function updateAABB()
{
$this->boundingBox->setBounds(
$this->x - $this->radius, $this->y, $this->z - $this->radius,
$this->x + $this->radius, $this->y + $this->height, $this->z + $this->radius
$this->x - $this->radius, $this->y - $this->yOffset, $this->z - $this->radius,
$this->x + $this->radius, $this->y + $this->height - $this->yOffset, $this->z + $this->radius
);
}
public function updatePosition()
{
$this->server->query("UPDATE entities SET level = '" . $this->level->getName() . "', x = " . $this->x . ", y = " . $this->y . ", z = " . $this->z . ", pitch = " . $this->pitch . ", yaw = " . $this->yaw . " WHERE EID = " . $this->eid . ";");
$this->sendMoveUpdate();
$this->updateAABB();
}
public function setPosition(Vector3 $pos, $yaw = false, $pitch = false)
{
if($pos instanceof Position and $pos->level instanceof Level and $this->level !== $pos->level){
$this->level = $pos->level;
$this->server->preparedSQL->entity->setLevel->reset();
$this->server->preparedSQL->entity->setLevel->clear();
$this->server->preparedSQL->entity->setLevel->bindValue(":level", $this->level->getName(), SQLITE3_TEXT);
$this->server->preparedSQL->entity->setLevel->bindValue(":eid", $this->eid, SQLITE3_INTEGER);
$this->server->preparedSQL->entity->setLevel->execute();
}
$this->x = $pos->x;
$this->y = $pos->y;
$this->z = $pos->z;
@ -1134,15 +1174,6 @@ class Entity extends Position
if($pitch !== false){
$this->pitch = $pitch;
}
$this->server->preparedSQL->entity->setPosition->reset();
$this->server->preparedSQL->entity->setPosition->clear();
$this->server->preparedSQL->entity->setPosition->bindValue(":x", $this->x, SQLITE3_TEXT);
$this->server->preparedSQL->entity->setPosition->bindValue(":y", $this->y, SQLITE3_TEXT);
$this->server->preparedSQL->entity->setPosition->bindValue(":z", $this->z, SQLITE3_TEXT);
$this->server->preparedSQL->entity->setPosition->bindValue(":pitch", $this->pitch, SQLITE3_TEXT);
$this->server->preparedSQL->entity->setPosition->bindValue(":yaw", $this->yaw, SQLITE3_TEXT);
$this->server->preparedSQL->entity->setPosition->bindValue(":eid", $this->eid, SQLITE3_INTEGER);
$this->server->preparedSQL->entity->setPosition->execute();
}
public function inBlockNonVector($x, $y, $z, $radius = 0.8)
{
@ -1181,7 +1212,7 @@ class Entity extends Position
$this->speedMeasure = array(0, 0, 0, 0, 0, 0, 0);
}
public function getSpeed()
public function getSpeed() //TODO rename to getBaseSpeed
{
return $this->speed;
}
@ -1241,18 +1272,24 @@ class Entity extends Position
"Damage" => $this->meta,
"Count" => $this->stack,
];
$data["id"] = 64; //ty shoghicp
}
return $data;
}
public function updateLast()
{
$this->last[0] = $this->x;
$this->last[1] = $this->y;
$this->last[2] = $this->z;
$this->last[3] = $this->yaw;
$this->last[4] = $this->pitch;
$this->last[5] = microtime(true);
$this->lastX = $this->x;
$this->lastY = $this->y;
$this->lastZ = $this->z;
$this->lastYaw = $this->yaw;
$this->lastPitch = $this->pitch;
$this->lastTime = microtime(true);
$this->lastHeadYaw = $this->headYaw;
$this->lastSpeedZ = $this->speedZ;
$this->lastSpeedY = $this->speedY;
$this->lastSpeedX = $this->speedX;
}
public function getPosition($round = false)
@ -1265,7 +1302,7 @@ class Entity extends Position
if (! $this->canBeAttacked) {
return false;
}
$dmg = $this->applyArmor($dmg, $cause); //TODO HURTCAM
$dmg = $this->applyArmor($dmg, $cause);
$ret = $this->setHealth(max(- 128, $this->getHealth() - ((int) $dmg)), $cause, $force);
if ($ret != false && $this->hasKnockback && is_numeric($cause) && ($entity = $this->server->api->entity->get($cause)) != false) {
@ -1378,7 +1415,6 @@ class Entity extends Position
"cause" => $cause
)) !== false or $force === true){
$this->health = min(127, max(- 127, $health));
$this->server->query("UPDATE entities SET health = " . $this->health . " WHERE EID = " . $this->eid . ";");
if($harm === true){
$pk = new EntityEventPacket;
$pk->eid = $this->eid;

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,12 +1,19 @@
<?php
abstract class Living extends Entity implements Damageable, Pathfindable{
public static $despawnMobs, $despawnTimer, $entityPushing;
abstract class Living extends Entity implements Pathfindable{
public static $despawnMobs, $despawnTimer, $entityPushing = false;
public $moveStrafing, $moveForward;
public $target, $ai;
public $pathFinder, $path = null, $currentIndex = 0, $currentNode, $pathFollower;
public $ticksExisted = 0;
public $landMovementFactor = 0.1; //TODO may not be constant
public $jumpMovementFactor = 0.02; //TODO may not be constant
public $aiMoveSpeed;
public $renderYawOffset = 0.0; //used by head rotation, TODO better name
public $jumping, $jumpTicks;
public function __construct(Level $level, $eid, $class, $type = 0, $data = array()){
$this->target = false;
$this->ai = new EntityAI($this);
@ -24,6 +31,20 @@ abstract class Living extends Entity implements Damageable, Pathfindable{
$this->harm($dmg, "fall");
}
}
public function getAIMoveSpeed(){
return $this->aiMoveSpeed;
}
public function getVerticalFaceSpeed(){
return 40; //unused in 0.8 but may be useful in 0.9/0.10
}
public function setAIMoveSpeed($speed){
$this->aiMoveSpeed = $speed;
$this->moveForward = $speed;
}
public function hasPath(){
return $this->path != null;
}
@ -42,7 +63,23 @@ abstract class Living extends Entity implements Damageable, Pathfindable{
return true;
}
public function collideHandler(){
$rd = ceil($this->radius);
$minChunkX = ((int)($this->x - $rd)) >> 4;
$minChunkZ = ((int)($this->z - $rd)) >> 4;
$maxChunkX = ((int)($this->x + $rd)) >> 4;
$maxChunkZ = ((int)($this->z + $rd)) >> 4;
//TODO also index by chunkY?
for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){
for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ){
$ind = "$chunkX $chunkZ";
foreach($this->level->entityListPositioned[$ind] ?? [] as $entid){
if($this->level->entityList[$entid] instanceof Entity){
$this->applyCollision($this->level->entityList[$entid]);
}
}
}
}
}
public function applyCollision(Entity $collided){
@ -80,18 +117,148 @@ abstract class Living extends Entity implements Damageable, Pathfindable{
if(!$this->dead && Entity::$allowedAI && $this->idleTime <= 0) {
$this->ai->updateTasks();
}
$this->ai->mobController->rotateTick();
$this->ai->mobController->movementTick();
//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();
//}
/*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();
//not exactly here
if($this->jumping){
if(!$this->inWater){ //TODO also lava
if($this->onGround && $this->jumpTicks <= 0){
$this->jump();
$this->jumpTicks = 10;
}
}else{
$this->speedY += 0.04;
}
}else{
$this->jumpTicks = 0;
}
$this->ai->mobController->movementTick();
$this->ai->mobController->rotateTick();
$this->ai->mobController->jumpTick();
if(abs($this->speedX) < self::MIN_POSSIBLE_SPEED) $this->speedX = 0;
if(abs($this->speedZ) < self::MIN_POSSIBLE_SPEED) $this->speedZ = 0;
if(abs($this->speedY) < self::MIN_POSSIBLE_SPEED) $this->speedY = 0;
$this->moveStrafing *= 0.98;
$this->moveForward *= 0.98;
$savedLandFactor = $this->landMovementFactor;
$this->landMovementFactor *= $this->getSpeedModifer();
$this->moveEntityWithHeading($this->moveStrafing, $this->moveForward);
$this->landMovementFactor = $savedLandFactor;
if(self::$entityPushing){
$this->collideHandler();
}
//Yaw rotation in 1.5 is handled in a bit different place but hopefully this will work too
$this->ai->mobController->updateHeadYaw();
}
public function jump(){
$this->speedY = 0.42;
//TODO also set AirBorne?
}
public function counterUpdate(){
parent::counterUpdate();
if($this->jumpTicks > 0) --$this->jumpTicks;
}
public function moveEntityWithHeading($strafe, $forward){
if($this->inWater){ //also check is player, and can it fly or not
$prevPosY = $this->y;
$this->moveFlying($strafe, $forward, 0.04); //TODO speed: this.isAIEnabled() ? 0.04F : 0.02F
$this->move($this->speedX, $this->speedY, $this->speedZ);
$this->speedX *= 0.8;
$this->speedY *= 0.8;
$this->speedZ *= 0.8;
$this->speedY -= 0.02;
if($this->isCollidedHorizontally && $this->isFree($this->speedX, $this->speedY + 0.6 - $this->y + $prevPosY, $this->speedZ)){
$this->speedY = 0.3;
}
}else if($this->inLava){
$prevPosY = $this->y;
$this->moveFlying($strafe, $forward, 0.02);
$this->move($this->speedX, $this->speedY, $this->speedZ);
$this->speedX *= 0.5;
$this->speedY *= 0.5;
$this->speedZ *= 0.5;
$this->speedY -= 0.02;
if($this->isCollidedHorizontally && $this->isFree($this->speedX, $this->speedY + 0.6 - $this->y + $prevPosY, $this->speedZ)){
$this->speedY = 0.3;
}
}else{
$friction = 0.91;
if($this->onGround){
$friction = 0.546;
$blockAt = $this->level->level->getBlockID(floor($this->x), floor($this->boundingBox->minY) - 1, floor($this->z));
if($blockAt > 0) $friction = StaticBlock::getSlipperiness($blockAt) * 0.91;
}
$var8 = 0.16277136 / ($friction*$friction*$friction);
if($this->onGround){
//all mobs have ai enabled in nc for now
$var5 = $this->getAIMoveSpeed();
//TODO if AIEnabled
//{
//TODO $var5 = getAIMoveSpeed
//}
//else
//{
// $var5 = $this->landMovementFactor;
//}
//$var5 *= $var8;
}else{
$var5 = $this->jumpMovementFactor;
}
$this->moveFlying($strafe, $forward, $var5);
//1.5.2 recalculates friction, might be not neccessary
$friction = 0.91;
if($this->onGround){
$friction = 0.546;
$blockAt = $this->level->level->getBlockID(floor($this->x), floor($this->boundingBox->minY) - 1, floor($this->z));
if($blockAt > 0) $friction = StaticBlock::getSlipperiness($blockAt) * 0.91;
}
//TODO onLadder
$this->move($this->speedX, $this->speedY, $this->speedZ);
//TODO onLadder + isCollidedHorizonatlly => speedY = 0.2
$this->speedY -= 0.08; //gravity
$this->speedY *= 0.98;
$this->speedX *= $friction;
$this->speedZ *= $friction;
if($this->isCollidedHorizontally && $this->enableAutojump){
$this->ai->mobController->setJumping(true); //non vanilla
}
}
//TODO limbYaw - is it even needed?
}
public function sendMoveUpdate(){

View file

@ -2,7 +2,7 @@
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());
//$this->ai->addTask(new TaskAttackPlayer());
}
public function getAttackDamage(){

View file

@ -2,5 +2,4 @@
abstract class Projectile extends Entity{
const CLASS_TYPE = ENTITY_OBJECT;
}

View file

@ -11,14 +11,25 @@ class MobController
FIRE => true,
];
/**
* @var Entity
* @var Living
*/
public $entity;
public $finalYaw, $finalPitch, $finalHeadYaw;
public $headYaw;
public $someTicker = 0;
protected $jumping;
protected $jumpTimeout;
public $moveToX, $moveToY, $moveToZ;
public $speedMultiplier;
public $updateMove = false;
public $lookX, $lookY, $lookZ;
public $deltaLookYaw, $deltaLookPitch;
public $isLooking = false;
public function __construct($e){
$this->entity = $e;
@ -37,90 +48,154 @@ class MobController
public function isRotationCompleted(){
return $this->finalHeadYaw === $this->entity->headYaw;
}
public function moveNonInstant($x, $y, $z, $camera = true){
if($x == 0 && $y == 0 && $z == 0){
return false;
}
$ox = $x <=> 1;
$oy = $y <=> 1;
$oz = $z <=> 1;
$xf = $this->entity->x + ($this->entity->getSpeedModifer() * $ox * $this->entity->getSpeed());
$zf = $this->entity->z + ($this->entity->getSpeedModifer() * $oz * $this->entity->getSpeed());
$a = $b = $c = $d = 0;
if(self::$AUTOJUMP){
$oy = $this->entity->onGround && (
StaticBlock::getIsSolid(($a = $this->entity->level->level->getBlockID(ceil($xf), (int)($this->entity->y), ceil($zf)))) &&
!StaticBlock::getIsSolid($this->entity->level->level->getBlockID(ceil($xf), (int)($this->entity->y) + 1, ceil($zf)))
||
StaticBlock::getIsSolid(($b = $this->entity->level->level->getBlockID(ceil($xf), (int)($this->entity->y), $zf - ($oz < 0)))) &&
!StaticBlock::getIsSolid($this->entity->level->level->getBlockID(ceil($xf), (int)($this->entity->y) + 1, $zf - ($oz < 0)))
||
StaticBlock::getIsSolid(($c = $this->entity->level->level->getBlockID($xf - ($ox < 0), (int)($this->entity->y), $zf - ($oz < 0)))) &&
!StaticBlock::getIsSolid($this->entity->level->level->getBlockID($xf - ($ox < 0), (int)($this->entity->y) + 1, $zf - ($oz < 0)))
||
StaticBlock::getIsSolid(($d = $this->entity->level->level->getBlockID($xf - ($ox < 0), (int)($this->entity->y), ceil($zf)))) &&
!StaticBlock::getIsSolid($this->entity->level->level->getBlockID($xf - ($ox < 0), (int)($this->entity->y) + 1, ceil($zf)))
);
}
while(self::$ADVANCED){
if($this->isDangerous($a) || $this->isDangerous($b) || $this->isDangerous($c) || $this->isDangerous($d)){
return false;
}
$id1 = $this->entity->level->level->getBlockID($xf, $this->entity->y + $oy - 1, $zf);
if($this->isDangerous($id1)) return false;
if(!StaticBlock::getIsSolid($id1)){
$id2 = $this->entity->level->level->getBlockID($xf, $this->entity->y - 2, $zf);
$id3 = $this->entity->level->level->getBlockID($xf, $this->entity->y - 3, $zf);
$id4 = $this->entity->level->level->getBlockID($xf, $this->entity->y - 4, $zf);
$s2 = StaticBlock::getIsSolid($id2);
$s3 = StaticBlock::getIsSolid($id3);
$s4 = StaticBlock::getIsSolid($id4);
if($this->isDangerous($id2)) return false;
if($s2) break; //i cant goto label which wasnt declared before
if($this->isDangerous($id3)) return false;
if($s3) break;
if($this->isDangerous($id4)) return false;
if($s4) break;
if(!($this->entity instanceof Chicken)){
return false;
}
}
break;
}
if($camera) $this->faceEntity($ox, $oy, $oz);
if($this->entity->knockbackTime <= 0 && $this->isRotationCompleted()){
$this->entity->moveEntityWithOffset($ox, $oy, $oz);
}
return true;
public function setMovingTarget($x, $y, $z, $speed){
$this->moveToX = $x;
$this->moveToY = $y;
$this->moveToZ = $z;
$this->speedMultiplier = $speed;
$this->updateMove = true;
}
public function setMovingOffset($x, $y, $z, $speed){
$this->moveToX = $this->entity->x + ($x);
$this->moveToY = $this->entity->y + ($y);
$this->moveToZ = $this->entity->z + ($z);
$this->speedMultiplier = $speed;
$this->updateMove = true;
}
public function canJump(){
return $this->isJumping() && $this->jumpTimeout <= 0 && $this->entity->onGround;
}
public static function limitAngle2($old, $newA, $limit){
$v4 = Utils::wrapAngleTo180($old - $newA);
if($v4 < -$limit) $v4 = -$limit;
if($v4 >= $limit) $v4 = $limit;
return $old - $v4;
}
public static function limitAngle($old, $newA, $limit){
$v4 = Utils::wrapAngleTo180($newA - $old);
if($v4 > $limit) $v4 = $limit;
if($v4 < -$limit) $v4 = -$limit;
return $old + $v4;
}
public function jumpTick(){
$this->entity->jumping = $this->jumping;
$this->jumping = false;
}
public function movementTick(){
if($this->canJump()){
$this->jumpTimeout = 10;
$this->entity->speedY = 0.50;
$this->entity->moveForward = 0;
if($this->updateMove){
$this->updateMove = false;
$v1 = floor($this->entity->boundingBox->minY + 0.5);
$diffX = $this->moveToX - $this->entity->x;
$diffZ = $this->moveToZ - $this->entity->z;
$diffY = $this->moveToY - $v1;
$v8 = $diffX*$diffX + $diffY*$diffY + $diffZ*$diffZ;
if($v8 >= 2.500000277905201E-7){ //TODO convert notation
$v10 = (atan2($diffZ, $diffX) * 180 / M_PI) - 90;
$this->entity->yaw = self::limitAngle($this->entity->yaw, $v10, 30);
$this->entity->setAIMoveSpeed($this->speedMultiplier * $this->entity->getSpeed() * $this->entity->getSpeedModifer());
//TODO 0.8.1 doesnt seem to make 2 multiplications here
/*
* v15 = this->controlledEntity;
speedMultiplier = this->speedMultiplier;
v17 = v15->vtable->_virt_getBaseSpeed(v15);
Mob::setSpeed(v15, speedMultiplier * v17);
*/
if($diffY > 0 && $diffX*$diffX + $diffZ*$diffZ < 1) $this->setJumping(true);
}
}
//TODO handle jumps somewhere
//if($this->canJump()){
// $this->jumpTimeout = 10;
// $this->entity->speedY = 0.50;
//}
//if($this->jumpTimeout > 0) --$this->jumpTimeout;
}
public function updateHeadYaw(){
$diffX = $this->entity->x - $this->entity->lastX;
$diffZ = $this->entity->z - $this->entity->lastZ;
if(($diffX*$diffX + $diffZ*$diffZ) > 2.500000277905201E-7){ //TODO convert notation
$this->entity->renderYawOffset = $this->entity->yaw;
$this->entity->headYaw = self::limitAngle2($this->entity->renderYawOffset, $this->entity->headYaw, 75);
$this->headYaw = $this->entity->headYaw;
$this->someTicker = 0;
}else{
$v5 = 75;
if(abs($this->entity->headYaw - $this->headYaw) > 15){
$this->someTicker = 0;
$this->headYaw = $this->entity->headYaw;
}else{
++$this->someTicker;
if($this->someTicker > 10){
$v5 = max(1 - ($this->someTicker - 10) / 10, 0) * 75;
}
}
$this->entity->renderYawOffset = self::limitAngle2($this->entity->headYaw, $this->entity->renderYawOffset, $v5);
}
if($this->jumpTimeout > 0) --$this->jumpTimeout;
}
public function rotateTick(){ //TODO handle more rotation
$this->entity->lastHeadYaw = $this->entity->headYaw;
$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);
$this->entity->pitch = 0;
if($this->isLooking){
$this->isLooking = false;
$diffX = $this->lookX - $this->entity->x;
$diffY = $this->lookY - ($this->entity->y + $this->entity->getEyeHeight());
$diffZ = $this->lookZ - $this->entity->z;
$distance = sqrt($diffX*$diffX + $diffZ*$diffZ);
$v9 = (atan2($diffZ, $diffX)*180 / M_PI) - 90;
$v10 = -(atan2($diffY, $distance)*180 / M_PI);
$this->entity->pitch = self::limitAngle($this->entity->pitch, $v10, $this->deltaLookPitch);
$this->entity->headYaw = self::limitAngle($this->entity->headYaw, $v9, $this->deltaLookYaw);
}else{
$this->entity->headYaw = self::limitAngle($this->entity->headYaw, $this->entity->renderYawOffset, 10);
}
/* Some stuff for pathfinder - nc doesnt have it now
* float var11 = MathHelper.wrapAngleTo180_float(this.entity.rotationYawHead - this.entity.renderYawOffset);
if (!this.entity.getNavigator().noPath())
{
if (var11 < -75.0F)
{
this.entity.rotationYawHead = this.entity.renderYawOffset - 75.0F;
}
if (var11 > 75.0F)
{
this.entity.rotationYawHead = this.entity.renderYawOffset + 75.0F;
}
}
*/
//$this->entity->lastHeadYaw = $this->entity->headYaw;
//$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, $camera = true){
return $this->moveNonInstant($x - floor($this->entity->x), $y - floor($this->entity->y), $z - floor($this->entity->z), $camera);
public function setLookPosition($posX, $posY, $posZ, $lookYaw, $lookPitch){
$this->lookX = $posX;
$this->lookY = $posY;
$this->lookZ = $posZ;
$this->deltaLookYaw = $lookYaw;
$this->deltaLookPitch = $lookPitch;
$this->isLooking = true;
}
public function faceEntity($x, $y, $z){

View file

@ -13,13 +13,18 @@ class PathFollower{
public function followPath(){
if(!isset($this->entity) || !($this->entity instanceof Living)) return;
if(!$this->entity->hasPath()) return;
if($this->entity->path != null && (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->path != null && ($this->entity->currentNode == false || $this->entity->boundingBox->isXYZInside($this->entity->currentNode->x, $this->entity->currentNode->y, $this->entity->currentNode->z) || $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++];
if($this->entity->currentNode == null){
$this->entity->currentNode = $this->entity->path[$this->entity->currentIndex];
}
$this->entity->ai->mobController->setMovingTarget($this->entity->currentNode->x, $this->entity->currentNode->y, $this->entity->currentNode->z, 0.25);
console($this->entity->currentNode.":".$this->entity->boundingBox);
if($this->entity->boundingBox->isXYZInsideNS($this->entity->currentNode->x, $this->entity->currentNode->y, $this->entity->currentNode->z)){
++$this->entity->currentIndex;
console("next");
$this->entity->currentNode = null;
}
}

View file

@ -1,42 +1,111 @@
<?php
/**
* A Tempt but for Monsters
*/
class TaskAttackPlayer extends TaskTempt
class TaskAttackPlayer extends TaskBase
{
public $attackTime = 0;
public $speedMultiplier;
public $rangeSquared;
public $attackCounter;
public function __construct($speed, $range){
$this->speedMultiplier = $speed;
$this->rangeSquared = $range*$range;
}
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()){
if(!$this->isTargetValid($ai)){
$this->reset();
return;
return false;
}
$ai->mobController->setMovingTarget($ai->entity->target->x, $ai->entity->target->y, $ai->entity->target->z, $this->speedMultiplier);
$ai->mobController->setLookPosition($ai->entity->target->x, $ai->entity->target->y + 0.12, $ai->entity->target->z, 10, $ai->entity->getVerticalFaceSpeed());
$ai->mobController->moveTo($this->target->x - 0.5, floor($ai->entity->y), $this->target->z - 0.5, false);
$ai->mobController->lookOn($this->target);
--$this->attackCounter;
$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){
$ai->entity->attackEntity($this->target);
$this->attackTime = 20;
$v1 = $ai->entity->width * $ai->entity->width * $mult*$mult;
$e = $ai->entity;
$t = $e->target;
$xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z);
$dist = ($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff);
if($dist <= $v1){
if($this->attackCounter <= 0){
$this->attackCounter = 20;
$e->attackEntity($t);
}
}
--$this->attackTime;
}
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;
return true;
public function isTargetValid(EntityAI $ai){
$e = $ai->entity; //TODO sometimes it keeps being valid even after getting invalid (/gm 1 -> /gm 0 switch)
if($e->target instanceof Entity){
$t = $e->target;
$xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z);
return ($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff) <= $this->rangeSquared;
}
return false;
}
public function tryTargeting(EntityAI $ai){
$e = $ai->entity;
if($e->target instanceof Entity){
$t = $e->target;
$xDiff = ($t->x - $e->x);
$yDiff = ($t->y - $e->y);
$zDiff = ($t->z - $e->z);
if(($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff) <= $this->rangeSquared){
return true;
}
}
$bestTargetDistance = INF;
$closestTarget = null;
foreach($e->level->players as $p){
if($p->spawned){
$pt = $p->entity;
$xDiff = $pt->x - $e->x;
$yDiff = $pt->y - $e->y;
$zDiff = $pt->z - $e->z;
$d = ($xDiff*$xDiff + $yDiff*$yDiff + $zDiff*$zDiff);
if($d <= $this->rangeSquared){
if($bestTargetDistance >= $d){
$closestTarget = $pt;
$bestTargetDistance = $d;
}
}
}
}
if($closestTarget != null){
$e->target = $closestTarget; //TODO dont save entity object ?
return true;
}
return false;
}
public function canBeExecuted(EntityAI $ai)
{
return $this->tryTargeting($ai);
}
public function onEnd(EntityAI $ai)
{
}
}

View file

@ -1,89 +0,0 @@
<?php
class TaskDestroyServerPerformance extends TaskTempt
{
public $attackTime = 0;
public $server;
public function __construct(){
parent::__construct();
$this->server = ServerAPI::request();
}
public function onStart(EntityAI $ai)
{
$this->selfCounter = 1;
}
public function onUpdate(EntityAI $ai)
{
if(!($this->target instanceof Entity) || ($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();
return;
}
if(Utils::distance_noroot($this->target, $ai->entity) > 100){
$ai->mobController->moveTo($this->target->x, floor($ai->entity->y), $this->target->z, false);
}else{
}
$ai->mobController->lookOn($this->target);
if(--$this->attackTime <= 0){
$this->rangedAttack($ai->entity, $this->target);
$this->attackTime = 60;
}
}
/**
*
* @param Entity $selfEntity
* @param Entity $target
*/
public function rangedAttack($selfEntity, $target){
$d = [
"x" => $selfEntity->x,
"y" => $selfEntity->y + 1.6,
"z" => $selfEntity->z,
"yaw" => $selfEntity->yaw,
"pitch" => $selfEntity->pitch
];
/**
* @var Arrow $arrow
*/
$arrow = $this->server->api->entity->add($selfEntity->level, ENTITY_OBJECT, OBJECT_ARROW, $d);
$arrow->shotByEntity = true;
$arrow->shooterEID = $selfEntity->eid;
$posY = ($target->y + $target->getEyeHeight() - 0.1);
$diffX = $target->x - $selfEntity->x;
$diffY = ($target->boundingBox->minY + ($target->height / 3)) - $posY;
$diffZ = $target->z - $selfEntity->z;
$v12 = sqrt($diffX * $diffX + $diffZ * $diffZ);
if($v12 >= 1.0e-7){
$yaw = ((atan2($diffZ, $diffX) * 180) / M_PI) - 90;
$pitch = -((atan2($diffY, $v12) * 180) / M_PI);
$v16 = $diffX / $v12;
$v18 = $diffZ / $v12;
$arrow->x = $selfEntity->x + $v16;
$arrow->y = $posY;
$arrow->z = $selfEntity->z + $v18;
$arrow->yaw = $yaw;
$arrow->pitch = $pitch;
$arrow->updateAABB();
$v20 = $v12 * 0.2;
$arrow->shoot($diffX, $diffY + $v20, $diffZ, 1.6, 12);
$this->server->api->entity->spawnToAll($arrow);
}
}
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;
return true;
}
return false;
}
}

View file

@ -2,31 +2,29 @@
class TaskLookAround extends TaskBase
{
private $rotation;
public $lookOffsetX, $lookOffsetZ;
public function onStart(EntityAI $ai)
{
$this->selfCounter = 1;
$this->rotation = mt_rand(-120, 120);
$this->selfCounter = 20 + lcg_value();
$v = (M_PI * 2) * lcg_value();
$this->lookOffsetX = cos($v);
$this->lookOffsetZ = sin($v);
}
public function onEnd(EntityAI $ai)
{
$ai->entity->idleTime = mt_rand(20, 40);
//$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("TaskMate") && !$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;
--$this->selfCounter;
$ai->mobController->setLookPosition($ai->entity->x + $this->lookOffsetX, $ai->entity->y + $ai->entity->getEyeHeight(), $ai->entity->z + $this->lookOffsetZ, 10, $ai->entity->getVerticalFaceSpeed());
}
}

View file

@ -2,7 +2,11 @@
class TaskLookAtPlayer extends TaskBase{
public $target = false;
private $state, $yaw, $pitch;
public $distance;
public function __construct($distance){
$this->distance = $distance;
}
public function canBeExecuted(EntityAI $ai){
return !$ai->entity->inPanic && lcg_value() < 0.02 && !$ai->entity->isMovingHorizontally() && !$ai->isStarted("TaskMate") && !$ai->isStarted("TaskLookAround") && !$ai->isStarted("TaskTempt") && !$ai->isStarted("TaskPanic") && !$ai->entity->hasPath();
}
@ -37,14 +41,13 @@ class TaskLookAtPlayer extends TaskBase{
}
public function onStart(EntityAI $ai){
$this->target = $this->findTarget($ai->entity, 6); //TODO max distance for different mobs
$this->target = $this->findTarget($ai->entity, $this->distance);
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);
}
@ -54,6 +57,7 @@ class TaskLookAtPlayer extends TaskBase{
$this->onEnd($ai);
return;
}
$ai->mobController->setLookPosition($this->target->x, $this->target->y + $this->target->getEyeHeight(), $this->target->z, 10, $ai->entity->getVerticalFaceSpeed());
$ai->mobController->lookOn($this->target);
$this->selfCounter--;
}

View file

@ -1,72 +0,0 @@
<?php
class TaskMate extends \TaskBase
{
public $targetMateID;
public function onStart(EntityAI $ai)
{
$this->selfCounter = 60;
}
public function onEnd(EntityAI $ai)
{
$this->selfCounter = 0;
$this->targetMateID = null;
$ai->entity->pitch = 0;
}
public function onUpdate(EntityAI $ai)
{
$movTo = $ai->entity->level->entityList[$this->targetMateID] ?? false;
if(!($movTo instanceof Entity) || $movTo->dead || !$movTo->isInLove()){
$this->reset();
$this->onEnd($ai);
return;
}
$ai->mobController->moveTo($movTo->x, $movTo->y, $movTo->z, false);
$ai->mobController->lookOn($movTo);
--$this->selfCounter;
if($this->selfCounter <= 0 && $ai->entity->distanceSquared($movTo) < 9){
$this->createBaby($ai, $movTo);
}
}
public function createBaby(EntityAI $ai, Entity $entpar2){
/**
* @var Animal $baby
*/
$baby = $ai->entity->breed();
//this.theAnimal.setGrowingAge(6000); TODO growing age?
//this.targetMate.setGrowingAge(6000);
$ai->entity->resetInLove();
$entpar2->resetInLove();
$baby->setAge(-24000);
}
public function findMate(EntityAI $ai){
$distance = 8.0*8.0;
$minDist = $distance;; //TODO check bb intersection?
$matedEID = null;
foreach($ai->entity->level->entitiesInLove as $eid => $_){
$e = $ai->entity->level->entityList[$eid] ?? false;
if($e instanceof Entity){
$d = $ai->entity->distanceSquared($e);
if($ai->entity->canMate($e) && $d < $minDist){
$minDist = $d;
$matedEID = $e->eid;
}
}
}
return $matedEID;
}
public function canBeExecuted(EntityAI $ai)
{
return $ai->entity->isInLove() && ($this->targetMateID = $this->findMate($ai)) != null;
}
}

View file

@ -3,6 +3,12 @@
class TaskPanic extends TaskBase
{
protected $randX = 2, $randZ = 2;
public $speedMultiplier;
public function __construct($speedMultiplier){
$this->speedMultiplier = $speedMultiplier;
}
public function onStart(EntityAI $ai)
{
$this->selfCounter = 60;
@ -16,8 +22,8 @@ class TaskPanic extends TaskBase
}
public function regenerateRandXZ(){
$this->randX = (mt_rand(0, 1) ? -1 : 1) * 2;
$this->randZ = (mt_rand(0, 1) ? -1 : 1) * 2;
$this->randX = (mt_rand(0, 1) ? -1 : 1);
$this->randZ = (mt_rand(0, 1) ? -1 : 1);
}
public function reset(){
@ -28,7 +34,7 @@ class TaskPanic extends TaskBase
{
--$this->selfCounter;
if($this->selfCounter % 20 === 0) $this->regenerateRandXZ();
$ai->mobController->moveNonInstant($this->randX, 0, $this->randZ);
$ai->mobController->setMovingOffset($this->randX, 0, $this->randZ, $this->speedMultiplier);
}
public function canBeExecuted(EntityAI $ai)

View file

@ -3,15 +3,20 @@
class TaskRandomWalk extends TaskBase
{
private $x, $z;
public $speedMultiplier;
public function __construct($speedMultiplier){
$this->speedMultiplier = $speedMultiplier;
}
public function onStart(EntityAI $ai)
{
$this->x = mt_rand(-16, 16);
$this->z = mt_rand(-16, 16);
$this->x = mt_rand(-1, 1);
$this->z = mt_rand(-1, 1);
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)));
$this->selfCounter = mt_rand(80, 100);
}
public function onEnd(EntityAI $ai)
@ -26,7 +31,8 @@ class TaskRandomWalk extends TaskBase
return false; //TODO Better way: block movement
}
--$this->selfCounter;
$ai->mobController->moveNonInstant($this->x, 0, $this->z);
$ai->mobController->setMovingOffset($this->x, 0, $this->z, $this->speedMultiplier);
//TODO fix $ai->mobController->moveNonInstant($this->x, 0, $this->z);
}
public function canBeExecuted(EntityAI $ai)

View file

@ -14,22 +14,19 @@ class TaskSwimming extends TaskBase
public function onUpdate(EntityAI $ai)
{
if(!$ai->entity->inWater){
if(!$ai->entity->inWater && !$ai->entity->inLava){
$this->reset();
$ai->mobController->setJumping(false);
return;
}
if(lcg_value() < 0.8){ #1.5.2 method
$ai->mobController->setJumping(true);
}
}
public function canBeExecuted(EntityAI $ai)
{
return $ai->entity->inWater;
return $ai->entity->inWater || $ai->entity->inLava;
}
}

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 - 0.5, floor($ai->entity->y), $this->target->z - 0.5, false);
$ai->mobController->lookOn($this->target);
}
public function canBeExecuted(EntityAI $ai)
{
if(!($ai->entity instanceof Breedable) || $ai->entity->inPanic || $ai->isStarted("TaskMate")){
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

@ -10,19 +10,32 @@ class Chicken extends Animal{
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 4, "generic");
$this->setName('Chicken');
$this->setSpeed(0.25);
$this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAtPlayer(6));
$this->ai->addTask(new TaskPanic(1.5));
$this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming());
}
public function isFood($id){
return $id === PUMPKIN_SEEDS || $id === MELON_SEEDS || $id === BEETROOT_SEEDS || $id === WHEAT_SEEDS;
}
public function updateEntityMovement(){
parent::updateEntityMovement();
if(!$this->onGround && $this->speedY < 0) $this->speedY *= 0.6;
if($this->timeUntilEgg-- <= 0 && !$this->isBaby()){
$this->dropAnEgg();
$this->timeUntilEgg = mt_rand(0,6000) + 6000;
}
}
public function fall(){} //chickens have no fall dmg?
public function update($now){
parent::update($now);
if($this->timeUntilEgg-- <= 0 && !$this->isBaby()){
$this->dropAnEgg();
$this->timeUntilEgg = mt_rand(0,6000) + 6000;
}
}
public function dropAnEgg(){

View file

@ -8,6 +8,11 @@ class Cow extends Animal{
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 10, "generic");
$this->setName("Cow");
$this->setSpeed(0.2);
$this->ai->addTask(new TaskRandomWalk(0.8));
$this->ai->addTask(new TaskLookAtPlayer(6));
$this->ai->addTask(new TaskPanic(1.5));
$this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming());
}
public function isFood($id){

View file

@ -9,6 +9,12 @@ class Pig extends Animal implements Rideable{
$this->server = ServerAPI::request();
$this->setName("Pig");
$this->setSpeed(0.25);
$this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAtPlayer(6));
$this->ai->addTask(new TaskPanic(1.5));
$this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming());
}
/**
* @return boolean

View file

@ -12,7 +12,13 @@ class Sheep extends Animal{
$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->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAtPlayer(6));
$this->ai->addTask(new TaskPanic(1.5));
$this->ai->addTask(new TaskEatTileGoal());
$this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming());
}
public function createSaveData(){

View file

@ -11,6 +11,10 @@ class Creeper extends Monster{
$this->ignited = 0;
$this->setSpeed(0.25);
$this->timeUntilExplode = $this->isIgnited() ? self::EXPL_TIME : 0;
$this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming());
}
public function getAttackDamage(){

View file

@ -1,5 +1,5 @@
<?php
class PigZombie extends Monster{
class PigZombie extends Monster{ //TODO extends zombie
const TYPE = MOB_PIGMAN;
function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->setSize(0.3, 1.95);
@ -7,6 +7,11 @@ class PigZombie extends Monster{
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 12, "generic");
$this->setName("Pigman");
$this->setSpeed(0.25);
$this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskSwimming());
$this->ai->addTask(new TaskAttackPlayer(1.0, 16)); //TODO fix range?
}
public function getAttackDamage(){
return 5;

View file

@ -7,8 +7,12 @@ class Skeleton extends Monster{
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 10, "generic");
$this->setName("Skeleton");
$this->ai->removeTask("TaskAttackPlayer");
//$this->ai->addTask(new TaskDestroyServerPerformance());
$this->setSpeed(0.25);
//$this->ai->addTask(new TaskDestroyServerPerformance());
$this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming());
}
public function getAttackDamage(){
@ -16,7 +20,7 @@ class Skeleton extends Monster{
}
public function updateBurning(){
if($this->fire > 0 or !$this->level->isDay()){
if($this->fire > 0 or !$this->level->isDay() || $this->inWater){ //TODO fix burning in water
return false;
}

View file

@ -7,6 +7,10 @@ class Spider extends Monster{
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 8, "generic");
$this->setName("Spider");
$this->setSpeed(0.3);
$this->ai->addTask(new TaskRandomWalk(1.0)); //TODO this mob doesnt use newAI -> speed is not correct
$this->ai->addTask(new TaskLookAround()); //TODO this mob doesnt use newAI
$this->ai->addTask(new TaskSwimming());
$this->ai->addTask(new TaskAttackPlayer(1.0, 16)); //TODO fix range?
}
public function getDrops(){

View file

@ -7,6 +7,11 @@ class Zombie extends Monster{
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 12, "generic");
$this->setName("Zombie");
$this->setSpeed(0.23);
$this->ai->addTask(new TaskRandomWalk(1.0));
$this->ai->addTask(new TaskLookAround());
$this->ai->addTask(new TaskSwimming());
$this->ai->addTask(new TaskAttackPlayer(1.0, 16)); //TODO fix range?
}
public function getArmorValue(){
@ -14,7 +19,7 @@ class Zombie extends Monster{
}
public function updateBurning(){
if($this->fire > 0 or !$this->level->isDay()){
if($this->fire > 0 or !$this->level->isDay() || $this->inWater){ //TODO fix burning in water
return false;
}
@ -34,7 +39,7 @@ class Zombie extends Monster{
}
public function getAttackDamage(){
return 4; //TODO vanillafy(zombies might be able to hold items)
return 4;
}
public function update($now){

View file

@ -3,12 +3,53 @@
class FallingSand extends Entity{
const TYPE = FALLING_SAND;
const CLASS_TYPE = ENTITY_FALLING;
public $fallTime = 0;
public function __construct($level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(PHP_INT_MAX, "generic");
$this->height = 0.98;
$this->width = 0.98;
$this->yOffset = $this->height / 2;
$this->hasGravity = true;
$this->gravity = 0.04;
}
public function update($now){
if($this->closed) return;
if( $this->data["Tile"] == AIR) $this->close();
else {
$this->lastX = $this->x;
$this->lastY = $this->y;
$this->lastZ = $this->z;
++$this->fallTime;
$this->speedY -= 0.04;
$this->move($this->speedX, $this->speedY, $this->speedZ);
$this->speedX *= 0.98;
$this->speedY *= 0.98;
$this->speedZ *= 0.98;
$x = floor($this->x);
$y = floor($this->y);
$z = floor($this->z);
if($this->onGround){
$this->speedX *= 0.7;
$this->speedZ *= 0.7;
$this->speedY *= -0.5;
$this->close();
//TODO vanilla-like checking?
$this->level->fastSetBlockUpdate($x, $y, $z, $this->data["Tile"], 0); //TODO add metadata
}else if(($blockAt = $this->level->level->getBlockID($x, $y, $z)) != 0){
//TODO vanilla-like checking?
if(StaticBlock::getIsTransparent($blockAt) && !StaticBlock::getIsLiquid($blockAt)){
$this->close();
ServerAPI::request()->api->entity->drop($this, BlockAPI::getItem($this->data["Tile"], 0, 1)); //TODO add metadata
}
}
}
}
}

View file

@ -3,6 +3,7 @@
class ItemEntity extends Entity{
const TYPE = "itemSpecial";
const CLASS_TYPE = ENTITY_ITEM;
public static $searchRadiusX = 0.5, $searchRadiusY = 0.0, $searchRadiusZ = 0.5;
public $meta, $stack;
@ -10,6 +11,7 @@ class ItemEntity extends Entity{
{
parent::__construct($level, $eid, $class, $type, $data);
$this->setSize(0.25, 0.25);
$this->yOffset = $this->height / 2;
if(isset($data["item"]) and ($data["item"] instanceof Item)){
$this->meta = $this->data["item"]->getMetadata();
$this->stack = $this->data["item"]->count;
@ -23,4 +25,98 @@ class ItemEntity extends Entity{
$this->delayBeforePickup = 20;
$this->stepHeight = 0;
}
public function counterUpdate(){
parent::counterUpdate();
if($this->delayBeforePickup > 0) --$this->delayBeforePickup;
}
public function searchForOtherItemsNearby(){
$ents = $this->level->getEntitiesInAABBOfType($this->boundingBox->expand(self::$searchRadiusX, self::$searchRadiusY, self::$searchRadiusZ), ENTITY_ITEM);
foreach($ents as $e){
$this->tryCombining($e);
}
}
public function spawn($player)
{
$pk = new AddItemEntityPacket();
$pk->eid = $this->eid;
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->yaw = $this->yaw;
$pk->pitch = $this->pitch;
$pk->roll = 0;
$pk->item = BlockAPI::getItem($this->type, $this->meta, $this->stack);
$pk->metadata = $this->getMetadata();
$player->dataPacket($pk);
$pk = new SetEntityMotionPacket();
$pk->eid = $this->eid;
$pk->speedX = $this->speedX;
$pk->speedY = $this->speedY;
$pk->speedZ = $this->speedZ;
$player->dataPacket($pk);
}
public function tryCombining(Entity $another){
if($another->eid == $this->eid) return false;
if(!$another->closed && !$this->closed){
if($another->type == $this->type && $another->meta == $this->meta){
if(($another->stack + $this->stack) > 64) return false; //TODO dynamic stack size
$another->stack += $this->stack;
$another->age = min($this->age, $another->age);
$this->close();
//TODO respawn another entity?
}
}
}
public function updateEntityMovement(){
$this->speedY -= 0.04;
$this->noClip = false; //TODO pushOutofBlocks
$this->move($this->speedX, $this->speedY, $this->speedZ);
$var1 = (int)$this->x != (int)$this->lastX || (int)$this->y != (int)$this->lastY || (int)$this->z != (int)$this->lastZ;
if($var1 || $this->counter % 25 == 0){
$blockIDAt = $this->level->level->getBlockID(floor($this->x), floor($this->y), floor($this->z));
if($blockIDAt == LAVA || $blockIDAt == STILL_LAVA){
$this->speedY = 0.2;
$this->speedX = (lcg_value() - lcg_value()) * 0.2;
$this->speedZ = (lcg_value() - lcg_value()) * 0.2;
}
//$this->searchForOtherItemsNearby(); //not in vanilla 0.8.1, TODO reenable after fixing not correct count in inv
}
if($this->closed) return;
$friction = 0.98;
if($this->onGround){
$friction = 0.588;
$v3 = $this->level->level->getBlockID($this->x, floor($this->boundingBox->minY) - 1, $this->z);
if($v3 > 0) $friction = StaticBlock::getSlipperiness($v3);
}
$this->speedX *= $friction;
$this->speedY *= 0.98;
$this->speedZ *= $friction;
if($this->onGround) $this->speedY *= -0.5;
if(abs($this->speedX) < self::MIN_POSSIBLE_SPEED) $this->speedX = 0;
if(abs($this->speedZ) < self::MIN_POSSIBLE_SPEED) $this->speedZ = 0;
if(abs($this->speedY) < self::MIN_POSSIBLE_SPEED) $this->speedY = 0;
++$this->age;
//TODO despawn after age >= 6000 ?;
}
}

View file

@ -65,7 +65,7 @@ class Minecart extends Vehicle{
$this->setHealth(1, "generic"); //orig: 3
$this->width = 0.98;
$this->height = 0.7;
$this->update();
$this->yOffset = $this->height / 2;
}
public function getDrops(){

View file

@ -1,6 +1,7 @@
<?php
class Painting extends Hanging{
class Painting extends Entity{
const CLASS_TYPE = ENTITY_OBJECT;
const TYPE = OBJECT_PAINTING;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
parent::__construct($level, $eid, $class, $type, $data);

View file

@ -10,13 +10,15 @@ class PrimedTNT extends Entity{
}
$this->hasGravity = true;
$this->gravity = 0.04;
$this->setSize(0.98, 0.98);
$this->yOffset = $this->height / 2;
$this->setHealth(10000000, "generic");
$this->server->schedule(5, [$this, "updateFuse"], [], true);
//$this->server->schedule(5, [$this, "updateFuse"], [], true);
}
public function getMetadata(){
$d = parent::getMetadata();
$d[16]["value"] = (int) max(0, $this->data["fuse"] - (microtime(true) - $this->spawntime) * 20);
$d[16]["value"] = (int) $this->data["fuse"];
return $d;
}
public function createSaveData(){
@ -27,7 +29,40 @@ class PrimedTNT extends Entity{
return $data;
}
public function updateFuse(){
public function update($now){
if($this->closed) return;
$this->lastX = $this->x;
$this->lastY = $this->y;
$this->lastZ = $this->z;
$this->speedY -= 0.04;
$this->move($this->speedX, $this->speedY, $this->speedZ);
$this->speedX *- 0.98;
$this->speedY *= 0.98;
$this->speedZ *= 0.98;
if($this->onGround){
$this->speedX *= 0.6;
$this->speedZ *= 0.6;
$this->speedY *= -0.5;
}
$tickDiff = ($now - $this->lastUpdate) / 0.05;
$this->data["fuse"] -= $tickDiff;
$this->updateMetadata();
if($this->data["fuse"] <= 0){
$this->close();
$explosion = new Explosion($this, $this->data["power"]);
$explosion->explode();
}
$this->lastUpdate = $now;
}
/*public function updateFuse(){
if($this->closed === true){
return false;
}
@ -39,7 +74,7 @@ class PrimedTNT extends Entity{
$explosion->explode();
}
}
}
}*/
public function spawn($player){
$pk = new AddEntityPacket;

View file

@ -155,11 +155,29 @@ abstract class Block extends Position{
public $z = 0;
public $slipperiness;
public static $minX = 0, $minY = 0, $minZ = 0, $maxX = 1, $maxY = 1, $maxZ = 1;
public static function setBlockBounds($minX, $minY, $minZ, $maxX, $maxY, $maxZ){ //TODO call for some specific blocks
static::$minX = $minX;
static::$minY = $minY;
static::$minZ = $minZ;
static::$maxX = $maxX;
static::$maxY = $maxY;
static::$maxZ = $maxZ;
}
public static function getAABB(Level $level, $x, $y, $z){
return new AxisAlignedBB(static::$minX + $x, static::$minY + $y, static::$minZ + $z, static::$maxX + $x, static::$maxY + $y, static::$maxZ + $z);
}
public static function addVelocityToEntity(Level $level, $x, $y, $z, Entity $entity, Vector3 $velocityVector){}
public static function onRandomTick(Level $level, $x, $y, $z){}
public static function fallOn(Level $level, $x, $y, $z, Entity $entity, $fallDistance){}
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return [new AxisAlignedBB($x, $y, $z, $x, $y, $z)];
}
public static function onEntityCollidedWithBlock(Level $level, $x, $y, $z, Entity $entity){}
public function __construct($id, $meta = 0, $name = "Unknown"){
$this->id = (int) $id;
$this->meta = (int) $meta;

View file

@ -37,6 +37,33 @@ class StaticBlock
self::$boundingBoxes[$b->getID()] = $b->boundingBox;
self::$hardness[$b->getID()] = $b->getHardness();
}
Block::$class[BED_BLOCK]::setBlockBounds(0, 0, 0, 1, 0.5625, 1);
//Cake: has bounds based on world state
//Chest: has bounds based on world state
Block::$class[WHEAT_BLOCK]::setBlockBounds(0, 0, 0, 1, 0.25, 1);
Block::$class[CARROT_BLOCK]::setBlockBounds(0, 0, 0, 1, 0.25, 1);
Block::$class[POTATO_BLOCK]::setBlockBounds(0, 0, 0, 1, 0.25, 1);
Block::$class[BEETROOT_BLOCK]::setBlockBounds(0, 0, 0, 1, 0.25, 1); //i assume it extends class Crops
Block::$class[WHEAT_BLOCK]::setBlockBounds(0, 0, 0, 1, 0.25, 1);
Block::$class[DEAD_BUSH]::setBlockBounds(0.1, 0, 0.1, 0.9, 0.8, 0.9);
Block::$class[DOOR_BLOCK]::setBlockBounds(0, 0, 0, 1, 1, 1); //has bounds based on rotation
Block::$class[FARMLAND]::setBlockBounds(0, 0, 0, 1, 0.9375, 1);
//Fence: bounds on state
//Fence Gate: bounds on state
Block::$class[TALL_GRASS]::setBlockBounds(0.1, 0, 0.1, 0.9, 0.8, 0.9);
Block::$class[MELON_STEM]::setBlockBounds(0.5 - 0.125, 0, 0.5 - 0.125, 0.5 + 0.125, 0.25, 0.5 + 0.125);
Block::$class[PUMPKIN_STEM]::setBlockBounds(0.5 - 0.125, 0, 0.5 - 0.125, 0.5 + 0.125, 0.25, 0.5 + 0.125);
Block::$class[SAPLING]::setBlockBounds(0.1, 0, 0.1, 0.9, 0.8, 0.9);
Block::$class[BROWN_MUSHROOM]::setBlockBounds(0.3, 0, 0.3, 0.8, 0.4, 0.8);
Block::$class[SLAB]::setBlockBounds(0, 0, 0, 1, 0.5, 1);
//Ladder: based on rotation
//Glass Pane: based on state
RailBaseBlock::setBlockBounds(0, 0, 0, 1, 0.125, 1);
Block::$class[SUGARCANE_BLOCK]::setBlockBounds(0.5 - 0.375, 0, 0.5 - 0.375, 0.5 + 0.375, 1, 0.5 + 0.375);
Block::$class[SNOW_LAYER]::setBlockBounds(0, 0, 0, 1, 0.125, 1);
//Stairs: based on different factors
//Stone wall: based on state
}
public static function getBlock($id){
@ -47,6 +74,7 @@ class StaticBlock
return self::$hardness[$id] ?? StaticBlock::DEFAULT_HARDNESS;
}
//TODO: use static block min/max
public static function getBoundingBoxForBlockCoords($id, $x, $y, $z){
/**@var AxisAlignedBB $bb*/
$bb = self::$boundingBoxes[$id] ?? false;

View file

@ -18,5 +18,9 @@ class CobwebBlock extends FlowableBlock{
array(COBWEB, 0, 1),
];
}
}
}
public static function onEntityCollidedWithBlock(Level $level, $x, $y, $z, Entity $entity){
$entity->setInWeb();
}
}

View file

@ -6,16 +6,17 @@ class IceBlock extends TransparentBlock{
$this->hardness = 2.5;
$this->slipperiness = 0.98;
}
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return [new AxisAlignedBB($x, $y, $z, $x + 1, $y + 1, $z + 1)];
}
public function place(Item $item, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
$ret = $this->level->setBlock($this, $this, true, false, true);
$this->level->scheduleBlockUpdate(new Position($this, 0, 0, $this->level), Utils::getRandomUpdateTicks(), BLOCK_UPDATE_RANDOM);
return $ret;
}
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return [new AxisAlignedBB($x, $y, $z, $x+1, $y+1, $z+1)];
}
public function onBreak(Item $item, Player $player){
if(($player->gamemode & 0x01) === 0){
$this->level->setBlock($this, new WaterBlock(), true, false, true);

View file

@ -15,6 +15,11 @@ class LeavesBlock extends TransparentBlock{
$this->name = $names[$this->meta & 0x03];
$this->hardness = 1;
}
public static function getCollisionBoundingBoxes(Level $level, $x, $y, $z, Entity $entity){
return [new AxisAlignedBB($x, $y, $z, $x + 1, $y + 1, $z + 1)];
}
public static function createIndex($x, $y, $z){
return $x.".".$y.".".$z;
}

View file

@ -15,7 +15,7 @@ class MinecartItem extends Item{
"x" => $target->getX() + 0.5,
"y" => $target->getY() + 0.8,
"z" => $target->getZ() + 0.5,
];
];
$e = $server->api->entity->add($level, ENTITY_OBJECT, OBJECT_MINECART, $data);
$server->api->entity->spawnToAll($e);
if(($player->gamemode & 0x01) === 0x00){

View file

@ -13,7 +13,7 @@ class SpawnEggItem extends Item{
"x" => $block->x + 0.5,
"y" => $block->y,
"z" => $block->z + 0.5,
"IsBaby" => $ageable ? Utils::chance(5) ? 1 : 0 : 0
"IsBaby" => $ageable ? mt_rand(0, 5) == 0 ? 1 : 0 : 0
);
$e = ServerAPI::request()->api->entity->add($block->level, ENTITY_MOB, $this->meta, $data);
ServerAPI::request()->api->entity->spawnToAll($e);

View file

@ -188,7 +188,16 @@ class AxisAlignedBB{
public function intersectsWith(AxisAlignedBB $bb){
return $bb->maxX > $this->minX and $bb->minX < $this->maxX && $bb->maxZ > $this->minZ and $bb->minZ < $this->maxZ && $bb->maxY > $this->minY and $bb->minY < $this->maxY;
}
public function isXYZInsideNS($x, $y, $z){
if($x < $this->minX or $x > $this->maxX){
return false;
}
if($y < $this->minY or $y > $this->maxY){
return false;
}
return $z > $this->minZ and $z < $this->maxZ;
}
public function isXYZInside($x, $y, $z){
if($x <= $this->minX or $x >= $this->maxX){
return false;

View file

@ -1,6 +1,10 @@
<?php
class LevelEventPacket extends RakNetDataPacket{
const EVENT_OPEN_DOOR_SOUND = 1003;
const EVENT_ALL_PLAYERS_SLEEPING = 9800;
public $evid;
public $x;
public $y;

View file

@ -1,36 +0,0 @@
<?php
class Cache{
public static $cached = [];
public static function add($identifier, $blob, $minTTL = 30){
self::$cached[$identifier] = [$blob, microtime(true) + $minTTL, $minTTL];
}
public static function get($identifier){
if(isset(self::$cached[$identifier])){
self::$cached[$identifier][1] = microtime(true) + self::$cached[$identifier][2];
return self::$cached[$identifier][0];
}
return false;
}
public static function exists($identifier){
return isset(self::$cached[$identifier]);
}
public static function remove($identifier){
unset(self::$cached[$identifier]);
}
public static function cleanup(){
$time = microtime(true);
foreach(self::$cached as $index => $data){
if($data[1] < $time){
unset(self::$cached[$index]);
}
}
}
}

View file

@ -69,8 +69,11 @@ class Utils{
public static function wrapAngleTo180($angle)
{
$angle = fmod($angle+180, 360);
return $angle < 0 ? $angle + 360 : $angle - 180;
$angle = fmod($angle, 360);
if($angle >= 180) $angle -= 360;
if($angle < -180) $angle += 360;
return $angle;
}
public static function getSign($v){
return $v <=> 0;

View file

@ -11,14 +11,22 @@ class Level{
*/
public $entityList;
public $entityListPositioned = [];
public $entitiesInLove = [];
public $tiles, $blockUpdates, $nextSave, $players = [], $level, $mobSpawner, $totalMobsAmount = 0;
/**
* @var Player[]
*/
public $players = [];
public $tiles, $blockUpdates, $nextSave, $level, $mobSpawner, $totalMobsAmount = 0;
private $time, $startCheck, $startTime, $server, $name, $usedChunks, $changedBlocks, $changedCount, $stopTime;
public $randInt1, $randInt2;
public $queuedBlockUpdates = [];
public $forceDisableBlockQueue = false;
public static $randomUpdateBlocks = [
FIRE => true,
FARMLAND => true,
@ -75,6 +83,67 @@ class Level{
return true;
}
//TODO mayPlace
public function isLavaInBB($aabb){
$minX = floor($aabb->minX);
$maxX = floor($aabb->maxX + 1);
$minY = floor($aabb->minY);
$maxY = floor($aabb->maxY + 1);
$minZ = floor($aabb->minZ);
$maxZ = floor($aabb->maxZ + 1);
for($x = $minX; $x < $maxX; ++$x){
for($y = $minY; $y < $maxY; ++$y){
for($z = $minZ; $z < $maxZ; ++$z){
$blockId = $this->level->getBlockID($x, $y, $z);
if($blockId == LAVA || $blockId == STILL_LAVA) return true;
}
}
}
return false;
}
public function handleMaterialAcceleration(AxisAlignedBB $aabb, $materialType, Entity $entity){
$minX = floor($aabb->minX);
$maxX = ceil($aabb->maxX);
$minY = floor($aabb->minY);
$maxY = ceil($aabb->maxY);
$minZ = floor($aabb->minZ);
$maxZ = ceil($aabb->maxZ);
//1.5.2 checks that all chunks exist, not needed here i think
$appliedVelocity = false;
$velocityVec = new Vector3(0, 0, 0);
for($x = $minX; $x < $maxX; ++$x){
for($y = $minY; $y < $maxY; ++$y){
for($z = $minZ; $z < $maxZ; ++$z){
[$block, $meta] = $this->level->getBlock($x, $y, $z);
if(($materialType == 0 && ($block == WATER || $block == STILL_WATER)) || ($materialType == 1 && ($block == LAVA || $block == STILL_LAVA))){ //TODO better material system
$v16 = ($y + 1) - LiquidBlock::getPercentAir($meta);
if($maxY >= $v16){
$appliedVelocity = true;
Block::$class[$block]::addVelocityToEntity($this, $x, $y, $z, $entity, $velocityVec);
}
}
}
}
}
if($velocityVec->length() > 0){ //also checks is player flying
$velocityVec = $velocityVec->normalize(); //TODO do not use vec methods
$v18 = 0.014;
$entity->speedX += $velocityVec->x * $v18;
$entity->speedY += $velocityVec->y * $v18;
$entity->speedZ += $velocityVec->z * $v18;
}
return $appliedVelocity;
}
/**
* @param Entity $e
* @param AxisAlignedBB $aABB
@ -83,21 +152,15 @@ class Level{
public function getCubes(Entity $e, AxisAlignedBB $aABB) {
$aABBs = [];
$x0 = floor($aABB->minX);
$x1 = ceil($aABB->maxX);
$x1 = floor($aABB->maxX + 1);
$y0 = floor($aABB->minY);
$y1 = ceil($aABB->maxY);
$y1 = floor($aABB->maxY + 1);
$z0 = floor($aABB->minZ);
$z1 = ceil($aABB->maxZ);
$x0 = $x0 < 0 ? 0 : $x0;
$y0 = $y0 < 0 ? 0 : $y0;
$z0 = $z0 < 0 ? 0 : $z0;
$x1 = $x1 > 256 ? 256 : $x1;
$y1 = $y1 > 128 ? 128 : $y1;
$z1 = $z1 > 256 ? 256 : $z1;
$z1 = floor($aABB->maxZ + 1);
for($x = $x0; $x <= $x1; ++$x) {
for($y = $y0; $y <= $y1; ++$y) {
for($z = $z0; $z <= $z1; ++$z) {
for($x = $x0; $x < $x1; ++$x) {
for($z = $z0; $z < $z1; ++$z) {
for($y = $y0 - 1; $y < $y1; ++$y) {
$bid = $this->level->getBlockID($x, $y, $z);
if($bid > 0){
$blockBounds = Block::$class[$bid]::getCollisionBoundingBoxes($this, $x, $y, $z, $e); //StaticBlock::getBoundingBoxForBlockCoords($b, $x, $y, $z);
@ -291,9 +354,6 @@ class Level{
}
$block->position($pos);
$i = ($pos->x >> 4) . ":" . ($pos->y >> 4) . ":" . ($pos->z >> 4);
if(ADVANCED_CACHE == true){
Cache::remove("world:{$this->name}:" . ($pos->x >> 4) . ":" . ($pos->z >> 4));
}
if(!isset($this->changedBlocks[$i])){
$this->changedBlocks[$i] = [];
$this->changedCount[$i] = 0;
@ -321,7 +381,6 @@ class Level{
}
public function onTick(PocketMinecraftServer $server, $currentTime){
//$ents = $server->api->entity->getAll($this);
if(!$this->stopTime) ++$this->time;
for($cX = 0; $cX < 16; ++$cX){
for($cZ = 0; $cZ < 16; ++$cZ){
@ -343,11 +402,15 @@ class Level{
$this->totalMobsAmount = 0;
$post = [];
foreach($this->entityList as $k => $e){
if(!($e instanceof Entity)){
unset($this->entityList[$k]);
unset($this->server->entities[$k]);
//TODO try to remove from $entityListPositioned?
continue;
}
$curChunkX = (int)$e->x >> 4;
$curChunkZ = (int)$e->z >> 4;
if($e->class === ENTITY_MOB && !$e->isPlayer()){
++$this->totalMobsAmount;
}
@ -355,6 +418,32 @@ class Level{
$e->update($currentTime);
if(!$e->isPlayer()) $post[] = $k;
}
if($e instanceof Entity){
$newChunkX = (int)$e->x >> 4;
$newChunkZ = (int)$e->z >> 4;
if($e->chunkX != $newChunkX || $e->chunkZ != $newChunkZ){
$oldIndex = "{$e->chunkX} {$e->chunkZ}";
unset($this->entityListPositioned[$oldIndex][$e->eid]);
if($e->level == $this){
$e->chunkX = $newChunkX;
$e->chunkZ = $newChunkZ;
$newIndex = "$newChunkX $newChunkZ";
$this->entityListPositioned[$newIndex][$e->eid] = $e->eid;
}
}
if($e->level != $this && isset($this->entityListPositioned["$curChunkX $curChunkZ"])){
unset($this->entityListPositioned["$curChunkX $curChunkZ"][$e->eid]);
}else if($curChunkX != $newChunkX || $curChunkZ != $newChunkZ){
$index = "$curChunkX $curChunkZ"; //while creating index like $curChunkX << 32 | $curChunkZ is faster, placing it inside list is slow
$newIndex = "$newChunkX $newChunkZ";
unset($this->entityListPositioned[$index][$e->eid]);
$this->entityListPositioned[$newIndex][$e->eid] = $e->eid; //set to e->eid to avoid possible memory leaks
}
}else if(isset($this->entityListPositioned["$curChunkX $curChunkZ"])){
unset($this->entityListPositioned["$curChunkX $curChunkZ"][$k]);
}
}
$this->checkSleep();
@ -374,7 +463,7 @@ class Level{
}
$player->sendEntityMovementUpdateQueue();
foreach($this->queuedBlockUpdates as $update){
foreach($this->queuedBlockUpdates as $ind => $update){
$x = $update[0];
$y = $update[1];
$z = $update[2];
@ -389,8 +478,73 @@ class Level{
$this->queuedBlockUpdates = [];
}
public function isBoundingBoxOnFire(AxisAlignedBB $bb){
$minX = floor($bb->minX);
$maxX = floor($bb->maxX + 1);
$minY = floor($bb->minY);
$maxY = floor($bb->maxY + 1);
$minZ = floor($bb->minZ);
$maxZ = floor($bb->maxZ + 1);
for($x = $minX; $x < $maxX; ++$x){
for($y = $minY; $y < $maxY; ++$y){
for($z = $minZ; $z < $maxZ; ++$z){
$blockAt = $this->level->getBlockID($x, $y, $z);
if($blockAt == FIRE || $blockAt == STILL_LAVA || $blockAt == LAVA) return true;
}
}
}
return false;
}
public function getEntitiesInAABBOfType(AxisAlignedBB $bb, $class){
$minChunkX = ((int)($bb->minX)) >> 4;
$minChunkZ = ((int)($bb->minZ)) >> 4;
$maxChunkX = ((int)($bb->maxX)) >> 4;
$maxChunkZ = ((int)($bb->maxZ)) >> 4;
$ents = [];
for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){
for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ){
$ind = "$chunkX $chunkZ";
foreach($this->entityListPositioned[$ind] ?? [] as $ind2 => $entid){
if(isset($this->entityList[$entid]) && $this->entityList[$entid] instanceof Entity && $this->entityList[$entid]->class === $class && $this->entityList[$entid]->boundingBox->intersectsWith($bb)){
$ents[$entid] = $this->entityList[$entid];
}else if(!isset($this->entityList[$entid])){
ConsoleAPI::debug("Removing entity from level array at index $ind/$ind2: $entid");
unset($this->entityListPositioned[$ind][$ind2]);
}
}
}
}
return $ents;
}
public function getEntitiesInAABB(AxisAlignedBB $bb){
$minChunkX = ((int)($bb->minX)) >> 4;
$minChunkZ = ((int)($bb->minZ)) >> 4;
$maxChunkX = ((int)($bb->maxX)) >> 4;
$maxChunkZ = ((int)($bb->maxZ)) >> 4;
$ents = [];
//TODO also index by chunkY?
for($chunkX = $minChunkX; $chunkX <= $maxChunkX; ++$chunkX){
for($chunkZ = $minChunkZ; $chunkZ <= $maxChunkZ; ++$chunkZ){
$ind = "$chunkX $chunkZ";
foreach($this->entityListPositioned[$ind] ?? [] as $ind2 => $entid){
if(isset($this->entityList[$entid]) && $this->entityList[$entid] instanceof Entity && $this->entityList[$entid]->boundingBox->intersectsWith($bb)){
$ents[$entid] = $this->entityList[$entid];
}else if(!isset($this->entityList[$entid])){
ConsoleAPI::debug("Removing entity from level array at index $ind/$ind2: $entid");
unset($this->entityListPositioned[$ind][$ind2]);
}
}
}
}
return $ents;
}
public function addBlockToSendQueue($x, $y, $z, $id, $meta){
$this->queuedBlockUpdates["$x $y $z"] = [$x, $y, $z, $id, $meta];
if(!$this->forceDisableBlockQueue)
$this->queuedBlockUpdates["$x $y $z"] = [$x, $y, $z, $id, $meta];
}
public function setBlock(Vector3 $pos, Block $block, $update = true, $tiles = false, $direct = false){
@ -411,9 +565,6 @@ class Level{
$this->changedBlocks[$i] = [];
$this->changedCount[$i] = 0;
}
if(ADVANCED_CACHE == true){
Cache::remove("world:{$this->name}:" . ($pos->x >> 4) . ":" . ($pos->z >> 4));
}
$this->changedBlocks[$i][] = [$block->x, $block->y, $block->z, $block->id, $block->getMetadata()];
++$this->changedCount[$i];
}
@ -442,9 +593,6 @@ class Level{
return false;
}
$this->changedCount[$X . ":" . $Y . ":" . $Z] = 4096;
if(ADVANCED_CACHE == true){
Cache::remove("world:{$this->name}:$X:$Z");
}
return $this->level->setMiniChunk($X, $Z, $Y, $data);
}
@ -463,7 +611,6 @@ class Level{
if($force !== true and $this->isSpawnChunk($X, $Z)){
return false;
}
Cache::remove("world:{$this->name}:$X:$Z");
return $this->level->unloadChunk($X, $Z, $this->server->saveEnabled);
}
@ -471,13 +618,6 @@ class Level{
if(!isset($this->level)){
return false;
}
if(ADVANCED_CACHE == true and $Yndex == 0xff){
$identifier = "world:{$this->name}:$X:$Z";
if(($cache = Cache::get($identifier)) !== false){
return $cache;
}
}
$raw = [];
for($Y = 0; $Y < 8; ++$Y){
@ -494,9 +634,6 @@ class Level{
$ordered .= substr($mini, $j << 5, 24); //16 + 8
}
}
if(ADVANCED_CACHE == true and $Yndex == 0xff){
Cache::add($identifier, $ordered, 60);
}
return $ordered;
}

View file

@ -29,6 +29,7 @@ class WorldGenerator{
}
public function generate(){
$this->level->forceDisableBlockQueue = true;
$this->generator->init($this->level, $this->random);
for($Z = 0; $Z < $this->width; ++$Z){
for($X = 0; $X < $this->width; ++$X){
@ -49,6 +50,7 @@ class WorldGenerator{
$this->level->setSpawn($this->generator->getSpawn());
$this->level->save(true, true);
$this->level->forceDisableBlockQueue = false;
}
public function close(){