changed pathfinder(hopefully one last time)

This commit is contained in:
GameHerobrine 2022-12-26 02:16:24 +03:00
parent 8c12e0de26
commit e11c40f645
28 changed files with 401 additions and 416 deletions

View file

@ -0,0 +1,40 @@
<?php
class ArrayList{
public $arr = [];
public function add(IElement $e){
$this->arr[$e->__toString()] = $e;
return $this;
}
public function addAll($es){
foreach($es as $e){
$this->add($this->add($e));
}
}
public function getFirst(){
return array_values($this->arr)[0];
}
public function remove(IElement $e){
unset($this->arr[$e->__toString()]);
return $this;
}
public function __isset($e){
return isset($this->arr[$e->__toString()]);
}
public function has(IElement $e){
return isset($this->arr[$e->__toString()]);
}
public function sortWith($func){
return uasort($this->arr, $func);
}
public function countElements(){
return count($this->arr);
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,84 @@
<?php
class TileNavigator implements ITileNavigator
{
private $blockedProvider, $neighborProvider, $distanceAlgorithm, $heuristicAlgorithm;
public function __construct(IBlockedProvider $blockedProvider, INeighborProvider $neighborProvider, IDistanceAlgorithm $distanceAlgorithm, IDistanceAlgorithm $heuristicAlgorithm){
$this->blockedProvider = $blockedProvider;
$this->neighborProvider = $neighborProvider;
$this->distanceAlgorithm = $distanceAlgorithm;
$this->heuristicAlgorithm = $heuristicAlgorithm;
}
public function reconstructPath($path, $current){
$totalPath = [$current];
while (array_key_exists((string)$current, $path))
{
$current = $path[(string)$current];
$totalPath[] = $current;
}
$totalPath = array_reverse($totalPath);
unset($totalPath[0]);
return array_values($totalPath);
}
public function navigate(PathTile $from, PathTile $to)
{
$closed = new ArrayList();
$open = new ArrayList();
$open->add($from);
$path = []; //new Dictionary<Tile, Tile>();
$gScore = []; //new Dictionary<Tile, double>();
$gScore[(string) $from] = 0;
/**
* @var array[Tile] $fScore
*/
$fScore = [];//new Dictionary<Tile, double>();
$fScore[(string) $from] = $this->heuristicAlgorithm->calculate($from, $to);
if($this->blockedProvider->isBlocked($to)){
return null;
}
while($open->countElements() > 0)
{
//sleep(1);
$open->sortWith(function($k, $k1) use ($fScore){
return $fScore[(string)$k] === $fScore[(string)$k1] ? 0 : ($fScore[(string)$k] > $fScore[(string)$k1] ? 1 : -1);
});
$current = $open->getFirst();
if ($current->equals($to)){
return $this->reconstructPath($path, $current);
}
$open->remove($current);
$closed->add($current);
foreach($this->neighborProvider->getNeighbors($current) as $neighbor)
{
if ($closed->has($neighbor) || $this->blockedProvider->isBlocked($neighbor))
{
continue;
}
$tentativeG = $gScore[(string) $current] + $this->distanceAlgorithm->calculate($current, $neighbor);
if (!$open->has($neighbor))
{
$open->add($neighbor);
}
else if ($tentativeG >= $gScore[(string) $neighbor])
{
continue;
}
$path[(string) $neighbor] = $current;
$gScore[(string) $neighbor] = $tentativeG;
$fScore[(string) $neighbor] = $gScore[(string) $neighbor] + $this->heuristicAlgorithm->calculate($neighbor, $to);
}
}
return null;
}
}

View file

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

View file

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

View file

@ -0,0 +1,12 @@
<?php
class ManhattanHeuristicAlgorithm implements IDistanceAlgorithm
{
public function calculate(PathTile $from, PathTile $to)
{
return abs($from->x - $to->x) + abs($from->y - $to->y);
}
}

View file

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

View file

@ -0,0 +1,11 @@
<?php
class PythagorasAlgorithm implements IDistanceAlgorithm
{
public function calculate(PathTile $from, PathTile $to)
{
return sqrt(pow($to->x - $from->x, 2) + pow($to->y - $from->y, 2));
}
}

View file

@ -0,0 +1,17 @@
<?php
class DiagonalNeighborProvider implements INeighborProvider
{
private static $neighbors = array([ 0, -1 ], [ 1, 0 ], [ 0, 1 ], [ -1, 0 ], [ -1, -1 ], [ 1, -1 ], [ 1, 1 ], [ -1, 1 ]);
public function getNeighbors(PathTile $tile)
{
$result = [];
foreach(self::$neighbors as $offset){
$t = clone $tile;
$result[] = $t->addOffset($offset);
}
return $result;
}
}

View file

@ -0,0 +1,10 @@
<?php
class EmptyBlockedProvider implements IBlockedProvider
{
public function isBlocked(PathTile $tile)
{
return false;
}
}

View file

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

View file

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

View file

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

View file

@ -0,0 +1,22 @@
<?php
class MCDiagonalProvider implements INeighborProvider
{
private static $neighbors = array([ 0, 0, -1 ], [ 1, 0, 0 ], [ 0, 0, 1 ], [ -1, 0, 0 ], [ -1, 0, -1 ], [ 1, 0, -1 ], [ 1, 0, 1 ], [ -1, 0, 1 ]);
public function getNeighbors(PathTile $tile)
{
if($tile instanceof PathTileXYZ){
$result = [];
foreach(self::$neighbors as $offset){
$t = clone $tile;
$result[] = $t->addOffset($offset);
}
return $result;
}
return [];
}
}

View file

@ -77,8 +77,24 @@ require_once(FILE_PATH . "/src/math/Vector3.php");
require_once(FILE_PATH . "/src/world/Position.php");
require_once(FILE_PATH . "/src/pmf/PMF.php");
require_once(FILE_PATH . "/src/utils/pathfinder/astar/Node.php");
require_once(FILE_PATH . "/src/utils/pathfinder/astar/AStar.php");
require_once(FILE_PATH . "/src/astarnavigator/IElement.php");
require_once(FILE_PATH . "/src/astarnavigator/PHPUtils.php");
require_once(FILE_PATH . "/src/astarnavigator/PathTile.php");
require_once(FILE_PATH . "/src/astarnavigator/ArrayList.php");
require_once(FILE_PATH . "/src/astarnavigator/algorithms/IDistanceAlgorithm.php");
require_once(FILE_PATH . "/src/astarnavigator/algorithms/PythagorasAlgorithm.php");
require_once(FILE_PATH . "/src/astarnavigator/algorithms/ManhattanHeuristicAlgorithm.php");
require_once(FILE_PATH . "/src/astarnavigator/providers/INeighborProvider.php");
require_once(FILE_PATH . "/src/astarnavigator/providers/DiagonalNeighborProvider.php");
require_once(FILE_PATH . "/src/astarnavigator/providers/IBlockedProvider.php");
require_once(FILE_PATH . "/src/astarnavigator/providers/EmptyBlockedProvider.php");
require_once(FILE_PATH . "/src/astarnavigator/ITileNavigator.php");
require_once(FILE_PATH . "/src/astarnavigator/TileNavigator.php");
require_once(FILE_PATH . "/src/entity/ai/tasks/TaskBase.php");

View file

@ -6,10 +6,13 @@ move methods
abstract class Creature extends Living{
const CLASS_TYPE = ENTITY_MOB;
public $pathFinder, $path = null, $currentIndex = 0, $currentNode;
public $inPanic;
public function __construct(Level $level, $eid, $class, $type = 0, $data = []){
$this->inPanic = false; //force for now
$this->pathFinder = new TileNavigator(new MCBlockedProvider(), new MCDiagonalProvider(), new Pythagoras3D(), new ManhattanHeuristic3D());
parent::__construct($level, $eid, $class, $type, $data);
$this->setHealth(isset($this->data["Health"]) ? $this->data["Health"] : 1, "generic");
//$this->setName((isset($mobs[$this->type]) ? $mobs[$this->type]:$this->type));
@ -18,11 +21,24 @@ abstract class Creature extends Living{
$this->ai->addTask(new TaskRandomWalk());
$this->ai->addTask(new TaskLookAtPlayer());
}
}
public function update(){
/*if($this->path === null && $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(-7, 7), $this->y, $this->z + mt_rand(-7, 7), $this->level));
}
if(is_array($this->path) && count($this->path) <= 0 || $this->currentIndex >= count($this->path)){
$this->path = null;
$this->currentIndex = 0;
$this->currentNode = false;
}elseif($this->currentNode == false || $this->ai->mobController->moveTo($this->currentNode->x, $this->currentNode->y, $this->currentNode->z) === false){
console("this");
$this->currentNode = $this->path[$this->currentIndex++];
}*/
/*if($this->path === false || count($this->path) <= 0){
$this->path = $this->pathFinder->findPath(MinecraftNode::fromArray([$this->x, $this->y, $this->z]), new MinecraftNode($this->x + mt_rand(-7, 7), $this->y, $this->z + mt_rand(-7, 7)));
}
$state = $this->pathNavigator->followPath($this->path);
if($state === PathNavigator::PATH_COMPLETED){

View file

@ -1,14 +1,10 @@
<?php
abstract class Living extends Entity implements Damageable{
public $pathFinder, $pathFound, $path, $pathNavigator, $target, $ai;
public $target, $ai;
public function __construct(Level $level, $eid, $class, $type = 0, $data = array()){
$this->pathFinder = new AStar($this);
$this->pathFound = false;
$this->target = false;
$this->path = null;
$this->ai = new EntityAI($this);
$this->pathNavigator = new PathNavigator($this);
parent::__construct($level, $eid, $class, $type, $data);
$this->canBeAttacked = true;
$this->hasGravity = true;

View file

@ -12,9 +12,10 @@ class MobController
}
public function moveNonInstant($x, $y, $z){
if($x === $this->entity->x && $y === $this->entity->y && $z === $this->entity->z){
if($x == 0 && $y == 0 && $z == 0){
return false; //failed
}
$ox = ($x > 0 ? 1 : ($x < 0 ? -1 : 0));
$oy = ($y > 0 ? 1 : ($y < 0 ? -1 : 0));
$oz = ($z > 0 ? 1 : ($z < 0 ? -1 : 0));
@ -27,6 +28,10 @@ class MobController
return true;
}
public function moveTo($x, $y, $z){
return $this->moveNonInstant($x - floor($this->entity->x), $y - floor($this->entity->y), $z - floor($this->entity->z));
}
public function faceEntity(Vector3 $v){
$d = $v->subtract($this->entity)->normalize();
$dx = $d->x;

View file

@ -440,7 +440,6 @@ class PMFLevel extends PMF{
$b = ord($this->chunks[$index][$Y][(int) ($aY + ($aX << 5) + ($aZ << 9))]);
$m = ord($this->chunks[$index][$Y][(int) (($aY >> 1) + 16 + ($aX << 5) + ($aZ << 9))]);
}else{
console(get_class($this->chunks[$index][$Y]));
$b = 0;
$m = 0;
}

View file

@ -1,102 +0,0 @@
<?php
class MinecraftNode extends Node
{
public $nodes = null;
/**
* {@inheritDoc}
* @see Node::__toString()
*/
public function __construct($x, $y, $z){
parent::__construct($x, $y, $z);
}
public static function fromArray($arr){
return new MinecraftNode($arr[0], $arr[1], $arr[2]);
}
public function __toString()
{
return "MinecraftNode({$this->x}, {$this->y}, {$this->z})";
}
public function add($x = 0, $y = 0, $z = 0){
return new MinecraftNode($x+$this->x, $y+$this->y, $z+$this->z);
}
/**
* {@inheritDoc}
* @see Node::getOwnCost()
*/
public function getOwnCost()
{
return 1;
}
public function getParentAndCleanSelf(){
try{
return $this->parent;
}finally{
$this->parent = null;
$this->nodes = null;
}
}
public function generateAdjNodes(AStar $pf)
{
$this->nodes = [];
for($x = -1; $x <= 1; $x++){
for($z = -1; $z <= 1; $z++){
$node = new MinecraftNode($x + $this->x, $this->y, $z + $this->z);
if(!$node->canMoveHere($pf)){
//console("[DEBUG] Obstacle at $node");
continue;
}
$this->nodes[] = $node;
}
}
}
/**
* {@inheritDoc}
* @see Node::getAdjacentNodes()
*/
public function getAdjacentNodes(AStar $pf)
{
if($this->nodes === null){
$this->generateAdjNodes($pf);
}
return $this->nodes;
}
/**
* {@inheritDoc}
* @see Node::equals()
*/
public function equals(Node $node)
{
return $node->x === $this->x && $this->z === $node->z;
}
/**
* {@inheritDoc}
* @see Node::getHCost()
*/
public function getHCost(Node $target)
{
return abs($target->x - $this->x) + abs($target->z - $this->z);
}
/**
* {@inheritDoc}
* @see Node::canMoveHere()
*/
public function canMoveHere(AStar $pf)
{
return !$pf->entity->level->getBlockWithoutVector($this->x, $this->y, $this->z)->isSolid;
}
}

View file

@ -1,167 +0,0 @@
<?php
/*
MIT License
Copyright (c) 2014 Peter Petermann
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* Class AStar
*
*/
class AStar
{
/**
* @var Node[]
*/
protected $open = [];
/**
* @var string[]
*/
protected $closed = [];
/**
* @var Entity
*/
public $entity;
public function __construct(&$entity){
$this->entity = $entity;
}
/**
* find a path from Node $start to Node $end
* @param Node $start
* @param Node $end
* @param number $maxOffset
* @return array|Node[]
*/
public function findPath(Node $start, Node $end)
{
// no path if there is no need for moving
if ($start->equals($end)) {
//console("[DEBUG] $start equals $end, route is empty");
return [];
}
if(!$end->canMoveHere($this)){
//console("[DEBUG] $end is not accessible, path will not be found");
return false;
}
$maxOffsetX = abs($start->x - $end->x);
$maxOffsetZ = abs($start->z - $end->z);
$this->addToOpen($start);
$foundTarget = false;
while (!$foundTarget && count($this->open) > 0) {
//console("[DEBUG] sorting open nodes by cost. Node count:" . count($this->open));
uasort(
$this->open,
function (Node $a, Node $b) use ($end) {
return $a->getFCost($end) - $b->getFCost($end);
}
);
/** @var Node $current */
$current = $this->open[array_keys($this->open)[0]];
unset($this->open[array_keys($this->open)[0]]);
//console("[DEBUG] current node selected: " . $current);
if ((string)$current == (string)$end) {
$foundTarget = $current;
//console("[DEBUG] current node is target node, exiting loop");
continue;
}
$adjacent = $current->getAdjacentNodes($this);
foreach ($adjacent as $node) {
if (in_array((string)$node, $this->closed)) {
//console("[DEBUG] skipping adjacent: $node as it was already processed");
continue;
}
$node->setParent($current);
$this->addToOpen($node);
}
$this->addToClosed($current);
}
// we failed to find a route
if (!$foundTarget && count($this->open) == 0) {
//console("[DEBUG] no open nodes left, and no target found.");
return false;
}
//console("[DEBUG] found route!");
/** @var Node $foundTarget */
try{
return $this->createRouteList($foundTarget);
}finally{ //removing all elements from them
$this->closed = [];
$this->open = [];
}
}
/**
* @param Node $node
*/
protected function addToOpen(Node $node)
{
if (
isset($this->open[(string)$node])
&& $this->open[(string)$node]->getGCost() < $node->getGCost()
) {
//console("[DEBUG] skipping add, $node is already known and gcost <= new path");
return;
}
//console("[DEBUG] adding new open node: $node");
$this->open[(string)$node] = $node;
}
/**
* @param Node $node
*/
protected function addToClosed(Node $node)
{
//console("[DEBUG] adding $node to closed");
$this->closed[] = (string)$node;
}
/**
* @param Node $foundTarget
* @return Node[]
*/
protected function createRouteList(Node $foundTarget)
{
$route = [];
$route[] = $foundTarget;
while ($foundTarget = $foundTarget->getParentAndCleanSelf()) {
$route[] = $foundTarget;
}
$route = array_reverse($route);
return $route;
}
}

View file

@ -1,136 +0,0 @@
<?php
/*
MIT License
Copyright (c) 2014 Peter Petermann
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
abstract class Node extends Vector3
{
/**
* @var Node|bool
*/
protected $parent = false;
/**
* @var int|float
*/
protected $gCost;
/**
* @param Node $parent
*/
public function setParent(Node $parent)
{
$this->parent = $parent;
}
/**
* @return Node|bool
*/
public function getParent()
{
return $this->parent;
}
public function getParentAndCleanSelf(){
try{
return $this->parent;
}finally{
$this->parent = null;
}
}
/**
* @return int|float
*/
public function getGCost()
{
if(is_null($this->gCost)) {
$this->gCost =
$this->parent ? $this->parent->getGCost() + $this->getOwnCost() : $this->getOwnCost();
}
return $this->gCost;
}
/**
* @param Node $target
* @return float|int
*/
public function getFCost(Node $target)
{
return $this->getGCost() + $this->getHCost($target);
}
/**
* @return int|float
*/
abstract public function getOwnCost();
/**
* @param Node $target
* @return int|float
*/
abstract public function getHCost(Node $target);
/**
* @param AStar $pf
* @return Node[]
*/
abstract public function getAdjacentNodes(AStar $pf);
/**
* @param Node $compareTo
* @return bool
*/
abstract public function equals(Node $compareTo);
/**
* Check can this point be used
* @param AStar $pf
* @return bool
*/
abstract public function canMoveHere(AStar $pf);
/**
* should return a unique string for this
*
* @return string
*/
public function __toString(){
return parent::__toString();
}
/**
* this method should allow a node
* to get the data from the target node getHostCost requires for its heuristic (if needed)
*
* @return array
*/
public function getDataForH()
{
return [];
}
}

View file

@ -20,6 +20,7 @@ class MobSpawner{
}
public function handle(){
return false;
if($this->countEntities() > self::MOB_LIMIT || count($this->level->players) <= 0){
return false; //not spawning
}

View file

@ -3,7 +3,7 @@ TITLE NostalgiaCore server software for Minecraft: Pocket Edition
cd /d %~dp0
if exist bin\php\php.exe (
if exist bin\mintty.exe (
start "" bin\mintty.exe -o Columns=88 -o Rows=32 -o AllowBlinking=0 -o FontQuality=3 -o CursorType=0 -o CursorBlinks=1 -h error -t "NostalgiaCore" -i bin/pocketmine.ico -w max bin\php\php.exe -d enable_dl=On PocketMine-MP.php --enable-ansi %*
start "" bin\mintty.exe -o Columns=88 -o Rows=32 -o AllowBlinking=0 -o FontQuality=3 -o CursorType=0 -o CursorBlinks=1 -h error -t "NostalgiaCore" -i bin/pocketmine.ico -w max bin\php8test\php.exe -d enable_dl=On PocketMine-MP.php --enable-ansi %*
) else (
bin\php\php.exe -d enable_dl=On PocketMine-MP.php %*
)