3 Copyright (C) 2013 sapier, sapier at gmx dot net
4 Copyright (C) 2016 est31, <MTest31@outlook.com>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 /******************************************************************************/
23 /******************************************************************************/
25 #include "pathfinder.h"
26 #include "serverenvironment.h"
30 //#define PATHFINDER_DEBUG
31 //#define PATHFINDER_CALC_TIME
33 #ifdef PATHFINDER_DEBUG
36 #ifdef PATHFINDER_DEBUG
39 #ifdef PATHFINDER_CALC_TIME
43 /******************************************************************************/
44 /* Typedefs and macros */
45 /******************************************************************************/
47 #define LVL "(" << level << ")" <<
49 #ifdef PATHFINDER_DEBUG
50 #define DEBUG_OUT(a) std::cout << a
51 #define INFO_TARGET std::cout
52 #define VERBOSE_TARGET std::cout
53 #define ERROR_TARGET std::cout
55 #define DEBUG_OUT(a) while(0)
56 #define INFO_TARGET infostream << "Pathfinder: "
57 #define VERBOSE_TARGET verbosestream << "Pathfinder: "
58 #define ERROR_TARGET warningstream << "Pathfinder: "
61 #define PATHFINDER_MAX_WAYPOINTS 700
63 /******************************************************************************/
64 /* Class definitions */
65 /******************************************************************************/
68 /** representation of cost in specific direction */
72 /** default constructor */
75 /** copy constructor */
76 PathCost(const PathCost &b);
78 /** assignment operator */
79 PathCost &operator= (const PathCost &b);
81 bool valid = false; /**< movement is possible */
82 int value = 0; /**< cost of movement */
83 int y_change = 0; /**< change of y position of movement */
84 bool updated = false; /**< this cost has ben calculated */
89 /** representation of a mapnode to be used for pathfinding */
93 /** default constructor */
94 PathGridnode() = default;
96 /** copy constructor */
97 PathGridnode(const PathGridnode &b);
100 * assignment operator
101 * @param b node to copy
103 PathGridnode &operator= (const PathGridnode &b);
106 * read cost in a specific direction
107 * @param dir direction of cost to fetch
109 PathCost getCost(v3s16 dir);
112 * set cost value for movement
113 * @param dir direction to set cost for
116 void setCost(v3s16 dir, const PathCost &cost);
118 bool valid = false; /**< node is on surface */
119 bool target = false; /**< node is target position */
120 bool source = false; /**< node is stating position */
121 int totalcost = -1; /**< cost to move here from starting point */
122 int estimated_cost = -1; /**< totalcost + heuristic cost to end */
123 v3s16 sourcedir; /**< origin of movement for current cost */
124 v3s16 pos; /**< real position of node */
125 PathCost directions[4]; /**< cost in different directions */
126 bool is_closed = false; /**< for A* search: if true, is in closed list */
127 bool is_open = false; /**< for A* search: if true, is in open list */
130 bool is_element = false; /**< node is element of path detected */
131 char type = 'u'; /**< Type of pathfinding node.
134 * s = surface (walkable node)
135 * - = non-walkable node (e.g. air) above surface
136 * g = other non-walkable node
141 class PathfinderCompareHeuristic;
143 /** Abstract class to manage the map data */
144 class GridNodeContainer {
146 virtual PathGridnode &access(v3s16 p)=0;
147 virtual ~GridNodeContainer() = default;
152 void initNode(v3s16 ipos, PathGridnode *p_node);
155 class ArrayGridNodeContainer : public GridNodeContainer {
157 virtual ~ArrayGridNodeContainer() = default;
159 ArrayGridNodeContainer(Pathfinder *pathf, v3s16 dimensions);
160 virtual PathGridnode &access(v3s16 p);
166 std::vector<PathGridnode> m_nodes_array;
169 class MapGridNodeContainer : public GridNodeContainer {
171 virtual ~MapGridNodeContainer() = default;
173 MapGridNodeContainer(Pathfinder *pathf);
174 virtual PathGridnode &access(v3s16 p);
176 std::map<v3s16, PathGridnode> m_nodes;
179 /** class doing pathfinding */
184 * default constructor
186 Pathfinder() = default;
191 * path evaluation function
192 * @param env environment to look for path
193 * @param source origin of path
194 * @param destination end position of path
195 * @param searchdistance maximum number of nodes to look in each direction
196 * @param max_jump maximum number of blocks a path may jump up
197 * @param max_drop maximum number of blocks a path may drop
198 * @param algo Algorithm to use for finding a path
200 std::vector<v3s16> getPath(ServerEnvironment *env,
203 unsigned int searchdistance,
204 unsigned int max_jump,
205 unsigned int max_drop,
209 /* helper functions */
212 * transform index pos to mappos
213 * @param ipos a index position
214 * @return map position
216 v3s16 getRealPos(v3s16 ipos);
219 * transform mappos to index pos
220 * @param pos a real pos
221 * @return index position
223 v3s16 getIndexPos(v3s16 pos);
226 * get gridnode at a specific index position
227 * @param ipos index position
228 * @return gridnode for index
230 PathGridnode &getIndexElement(v3s16 ipos);
233 * Get gridnode at a specific index position
234 * @return gridnode for index
236 PathGridnode &getIdxElem(s16 x, s16 y, s16 z);
239 * invert a 3D position (change sign of coordinates)
240 * @param pos 3D position
243 v3s16 invert(v3s16 pos);
246 * check if a index is within current search area
247 * @param index position to validate
250 bool isValidIndex(v3s16 index);
253 /* algorithm functions */
256 * calculate 2D Manhattan distance to target
257 * @param pos position to calc distance
258 * @return integer distance
260 int getXZManhattanDist(v3s16 pos);
263 * calculate cost of movement
264 * @param pos real world position to start movement
265 * @param dir direction to move to
266 * @return cost information
268 PathCost calcCost(v3s16 pos, v3s16 dir);
271 * recursive update whole search areas total cost information
272 * @param ipos position to check next
273 * @param srcdir positionc checked last time
274 * @param total_cost cost of moving to ipos
275 * @param level current recursion depth
276 * @return true/false path to destination has been found
278 bool updateAllCosts(v3s16 ipos, v3s16 srcdir, int current_cost, int level);
281 * try to find a path to destination using a heuristic function
282 * to estimate distance to target (A* search algorithm)
283 * @param isource start position (index pos)
284 * @param idestination end position (index pos)
285 * @return true/false path to destination has been found
287 bool updateCostHeuristic(v3s16 isource, v3s16 idestination);
290 * build a vector containing all nodes from destination to source;
291 * to be called after the node costs have been processed
292 * @param path vector to add nodes to
293 * @param ipos initial pos to check (index pos)
294 * @return true/false path has been fully built
296 bool buildPath(std::vector<v3s16> &path, v3s16 ipos);
299 * go downwards from a position until some barrier
301 * @param pos position from which to go downwards
302 * @param max_down maximum distance to go downwards
303 * @return new position after movement; if too far down,
306 v3s16 walkDownwards(v3s16 pos, unsigned int max_down);
309 int m_max_index_x = 0; /**< max index of search area in x direction */
310 int m_max_index_y = 0; /**< max index of search area in y direction */
311 int m_max_index_z = 0; /**< max index of search area in z direction */
314 int m_searchdistance = 0; /**< max distance to search in each direction */
315 int m_maxdrop = 0; /**< maximum number of blocks a path may drop */
316 int m_maxjump = 0; /**< maximum number of blocks a path may jump */
317 int m_min_target_distance = 0; /**< current smalest path to target */
319 bool m_prefetch = true; /**< prefetch cost data */
321 v3s16 m_start; /**< source position */
322 v3s16 m_destination; /**< destination position */
324 core::aabbox3d<s16> m_limits; /**< position limits in real map coordinates */
326 /** contains all map data already collected and analyzed.
327 Access it via the getIndexElement/getIdxElem methods. */
328 friend class GridNodeContainer;
329 GridNodeContainer *m_nodes_container = nullptr;
331 ServerEnvironment *m_env = 0; /**< minetest environment pointer */
333 friend class PathfinderCompareHeuristic;
335 #ifdef PATHFINDER_DEBUG
338 * print collected cost information
343 * print collected cost information in a specific direction
344 * @param dir direction to print
346 void printCost(PathDirections dir);
349 * print type of node as evaluated
354 * print pathlenght for all nodes in search area
360 * @param path path to show
362 void printPath(std::vector<v3s16> path);
365 * print y direction for all movements
370 * print y direction for moving in a specific direction
371 * @param dir direction to show data
373 void printYdir(PathDirections dir);
376 * helper function to translate a direction to speaking text
377 * @param dir direction to translate
378 * @return textual name of direction
380 std::string dirToName(PathDirections dir);
384 /** Helper class for the open list priority queue in the A* pathfinder
385 * to sort the pathfinder nodes by cost.
387 class PathfinderCompareHeuristic
390 Pathfinder *myPathfinder;
392 PathfinderCompareHeuristic(Pathfinder *pf)
396 bool operator() (v3s16 pos1, v3s16 pos2) {
397 v3s16 ipos1 = myPathfinder->getIndexPos(pos1);
398 v3s16 ipos2 = myPathfinder->getIndexPos(pos2);
399 PathGridnode &g_pos1 = myPathfinder->getIndexElement(ipos1);
400 PathGridnode &g_pos2 = myPathfinder->getIndexElement(ipos2);
405 return g_pos1.estimated_cost > g_pos2.estimated_cost;
409 /******************************************************************************/
411 /******************************************************************************/
413 std::vector<v3s16> get_path(ServerEnvironment* env,
416 unsigned int searchdistance,
417 unsigned int max_jump,
418 unsigned int max_drop,
421 Pathfinder searchclass;
423 return searchclass.getPath(env,
425 searchdistance, max_jump, max_drop, algo);
428 /******************************************************************************/
429 PathCost::PathCost(const PathCost &b)
432 y_change = b.y_change;
437 /******************************************************************************/
438 PathCost &PathCost::operator= (const PathCost &b)
441 y_change = b.y_change;
448 /******************************************************************************/
449 PathGridnode::PathGridnode(const PathGridnode &b)
453 totalcost(b.totalcost),
454 sourcedir(b.sourcedir),
456 is_element(b.is_element),
460 directions[DIR_XP] = b.directions[DIR_XP];
461 directions[DIR_XM] = b.directions[DIR_XM];
462 directions[DIR_ZP] = b.directions[DIR_ZP];
463 directions[DIR_ZM] = b.directions[DIR_ZM];
466 /******************************************************************************/
467 PathGridnode &PathGridnode::operator= (const PathGridnode &b)
472 is_element = b.is_element;
473 totalcost = b.totalcost;
474 sourcedir = b.sourcedir;
478 directions[DIR_XP] = b.directions[DIR_XP];
479 directions[DIR_XM] = b.directions[DIR_XM];
480 directions[DIR_ZP] = b.directions[DIR_ZP];
481 directions[DIR_ZM] = b.directions[DIR_ZM];
486 /******************************************************************************/
487 PathCost PathGridnode::getCost(v3s16 dir)
490 return directions[DIR_XP];
493 return directions[DIR_XM];
496 return directions[DIR_ZP];
499 return directions[DIR_ZM];
505 /******************************************************************************/
506 void PathGridnode::setCost(v3s16 dir, const PathCost &cost)
509 directions[DIR_XP] = cost;
512 directions[DIR_XM] = cost;
515 directions[DIR_ZP] = cost;
518 directions[DIR_ZM] = cost;
522 void GridNodeContainer::initNode(v3s16 ipos, PathGridnode *p_node)
524 const NodeDefManager *ndef = m_pathf->m_env->getGameDef()->ndef();
525 PathGridnode &elem = *p_node;
527 v3s16 realpos = m_pathf->getRealPos(ipos);
529 MapNode current = m_pathf->m_env->getMap().getNode(realpos);
530 MapNode below = m_pathf->m_env->getMap().getNode(realpos + v3s16(0, -1, 0));
533 if ((current.param0 == CONTENT_IGNORE) ||
534 (below.param0 == CONTENT_IGNORE)) {
535 DEBUG_OUT("Pathfinder: " << PP(realpos) <<
536 " current or below is invalid element" << std::endl);
537 if (current.param0 == CONTENT_IGNORE) {
539 DEBUG_OUT(PP(ipos) << ": " << 'i' << std::endl);
544 //don't add anything if it isn't an air node
545 if (ndef->get(current).walkable || !ndef->get(below).walkable) {
546 DEBUG_OUT("Pathfinder: " << PP(realpos)
547 << " not on surface" << std::endl);
548 if (ndef->get(current).walkable) {
550 DEBUG_OUT(PP(ipos) << ": " << 's' << std::endl);
553 DEBUG_OUT(PP(ipos) << ": " << '-' << std::endl);
561 DEBUG_OUT(PP(ipos) << ": " << 'a' << std::endl);
563 if (m_pathf->m_prefetch) {
564 elem.directions[DIR_XP] = m_pathf->calcCost(realpos, v3s16( 1, 0, 0));
565 elem.directions[DIR_XM] = m_pathf->calcCost(realpos, v3s16(-1, 0, 0));
566 elem.directions[DIR_ZP] = m_pathf->calcCost(realpos, v3s16( 0, 0, 1));
567 elem.directions[DIR_ZM] = m_pathf->calcCost(realpos, v3s16( 0, 0,-1));
571 ArrayGridNodeContainer::ArrayGridNodeContainer(Pathfinder *pathf, v3s16 dimensions) :
572 m_x_stride(dimensions.Y * dimensions.Z),
573 m_y_stride(dimensions.Z)
577 m_nodes_array.resize(dimensions.X * dimensions.Y * dimensions.Z);
578 INFO_TARGET << "Pathfinder ArrayGridNodeContainer constructor." << std::endl;
579 for (int x = 0; x < dimensions.X; x++) {
580 for (int y = 0; y < dimensions.Y; y++) {
581 for (int z= 0; z < dimensions.Z; z++) {
583 initNode(ipos, &access(ipos));
589 PathGridnode &ArrayGridNodeContainer::access(v3s16 p)
591 return m_nodes_array[p.X * m_x_stride + p.Y * m_y_stride + p.Z];
594 MapGridNodeContainer::MapGridNodeContainer(Pathfinder *pathf)
599 PathGridnode &MapGridNodeContainer::access(v3s16 p)
601 std::map<v3s16, PathGridnode>::iterator it = m_nodes.find(p);
602 if (it != m_nodes.end()) {
605 PathGridnode &n = m_nodes[p];
612 /******************************************************************************/
613 std::vector<v3s16> Pathfinder::getPath(ServerEnvironment *env,
616 unsigned int searchdistance,
617 unsigned int max_jump,
618 unsigned int max_drop,
621 #ifdef PATHFINDER_CALC_TIME
623 clock_gettime(CLOCK_REALTIME, &ts);
625 std::vector<v3s16> retval;
629 ERROR_TARGET << "Missing environment pointer" << std::endl;
634 m_searchdistance = searchdistance;
636 m_maxjump = max_jump;
637 m_maxdrop = max_drop;
639 m_destination = destination;
640 m_min_target_distance = -1;
643 if (algo == PA_PLAIN_NP) {
647 //calculate boundaries within we're allowed to search
648 int min_x = MYMIN(source.X, destination.X);
649 int max_x = MYMAX(source.X, destination.X);
651 int min_y = MYMIN(source.Y, destination.Y);
652 int max_y = MYMAX(source.Y, destination.Y);
654 int min_z = MYMIN(source.Z, destination.Z);
655 int max_z = MYMAX(source.Z, destination.Z);
657 m_limits.MinEdge.X = min_x - searchdistance;
658 m_limits.MinEdge.Y = min_y - searchdistance;
659 m_limits.MinEdge.Z = min_z - searchdistance;
661 m_limits.MaxEdge.X = max_x + searchdistance;
662 m_limits.MaxEdge.Y = max_y + searchdistance;
663 m_limits.MaxEdge.Z = max_z + searchdistance;
665 v3s16 diff = m_limits.MaxEdge - m_limits.MinEdge;
667 m_max_index_x = diff.X;
668 m_max_index_y = diff.Y;
669 m_max_index_z = diff.Z;
671 delete m_nodes_container;
672 if (diff.getLength() > 5) {
673 m_nodes_container = new MapGridNodeContainer(this);
675 m_nodes_container = new ArrayGridNodeContainer(this, diff);
677 #ifdef PATHFINDER_DEBUG
683 //fail if source or destination is walkable
684 const NodeDefManager *ndef = m_env->getGameDef()->ndef();
685 MapNode node_at_pos = m_env->getMap().getNode(destination);
686 if (ndef->get(node_at_pos).walkable) {
687 VERBOSE_TARGET << "Destination is walkable. " <<
688 "Pos: " << PP(destination) << std::endl;
691 node_at_pos = m_env->getMap().getNode(source);
692 if (ndef->get(node_at_pos).walkable) {
693 VERBOSE_TARGET << "Source is walkable. " <<
694 "Pos: " << PP(source) << std::endl;
698 //If source pos is hovering above air, drop
699 //to the first walkable node (up to m_maxdrop).
700 //All algorithms expect the source pos to be *directly* above
702 v3s16 true_source = v3s16(source);
703 source = walkDownwards(source, m_maxdrop);
705 //If destination pos is hovering above air, go downwards
706 //to the first walkable node (up to m_maxjump).
707 //This means a hovering destination pos could be reached
708 //by a final upwards jump.
709 v3s16 true_destination = v3s16(destination);
710 destination = walkDownwards(destination, m_maxjump);
712 //validate and mark start and end pos
714 v3s16 StartIndex = getIndexPos(source);
715 v3s16 EndIndex = getIndexPos(destination);
717 PathGridnode &startpos = getIndexElement(StartIndex);
718 PathGridnode &endpos = getIndexElement(EndIndex);
720 if (!startpos.valid) {
721 VERBOSE_TARGET << "Invalid startpos " <<
722 "Index: " << PP(StartIndex) <<
723 "Realpos: " << PP(getRealPos(StartIndex)) << std::endl;
727 VERBOSE_TARGET << "Invalid stoppos " <<
728 "Index: " << PP(EndIndex) <<
729 "Realpos: " << PP(getRealPos(EndIndex)) << std::endl;
733 endpos.target = true;
734 startpos.source = true;
735 startpos.totalcost = 0;
737 bool update_cost_retval = false;
739 //calculate node costs
742 update_cost_retval = updateAllCosts(StartIndex, v3s16(0, 0, 0), 0, 0);
746 update_cost_retval = updateCostHeuristic(StartIndex, EndIndex);
749 ERROR_TARGET << "Missing PathAlgorithm" << std::endl;
753 if (update_cost_retval) {
755 #ifdef PATHFINDER_DEBUG
756 std::cout << "Path to target found!" << std::endl;
761 std::vector<v3s16> index_path;
762 buildPath(index_path, EndIndex);
763 //Now we have a path of index positions,
764 //and it's in reverse.
765 //The "true" start or end position might be missing
766 //since those have been given special treatment.
768 #ifdef PATHFINDER_DEBUG
769 std::cout << "Index path:" << std::endl;
770 printPath(index_path);
772 //from here we'll make the final changes to the path
773 std::vector<v3s16> full_path;
775 //calculate required size
776 int full_path_size = index_path.size();
777 if (source != true_source) {
780 if (destination != true_destination) {
783 full_path.reserve(full_path_size);
785 //manually add true_source to start of path, if needed
786 if (source != true_source) {
787 full_path.push_back(true_source);
789 //convert all index positions to "normal" positions and insert
790 //them into full_path in reverse
791 std::vector<v3s16>::reverse_iterator rit = index_path.rbegin();
792 for (; rit != index_path.rend(); ++rit) {
793 full_path.push_back(getIndexElement(*rit).pos);
795 //manually add true_destination to end of path, if needed
796 if (destination != true_destination) {
797 full_path.push_back(true_destination);
800 //Done! We now have a complete path of normal positions.
803 #ifdef PATHFINDER_DEBUG
804 std::cout << "Full path:" << std::endl;
805 printPath(full_path);
807 #ifdef PATHFINDER_CALC_TIME
809 clock_gettime(CLOCK_REALTIME, &ts2);
811 int ms = (ts2.tv_nsec - ts.tv_nsec)/(1000*1000);
812 int us = ((ts2.tv_nsec - ts.tv_nsec) - (ms*1000*1000))/1000;
813 int ns = ((ts2.tv_nsec - ts.tv_nsec) - ( (ms*1000*1000) + (us*1000)));
816 std::cout << "Calculating path took: " << (ts2.tv_sec - ts.tv_sec) <<
817 "s " << ms << "ms " << us << "us " << ns << "ns " << std::endl;
822 #ifdef PATHFINDER_DEBUG
825 INFO_TARGET << "No path found" << std::endl;
833 Pathfinder::~Pathfinder()
835 delete m_nodes_container;
837 /******************************************************************************/
838 v3s16 Pathfinder::getRealPos(v3s16 ipos)
840 return m_limits.MinEdge + ipos;
843 /******************************************************************************/
844 PathCost Pathfinder::calcCost(v3s16 pos, v3s16 dir)
846 const NodeDefManager *ndef = m_env->getGameDef()->ndef();
849 retval.updated = true;
851 v3s16 pos2 = pos + dir;
854 if (!m_limits.isPointInside(pos2)) {
855 DEBUG_OUT("Pathfinder: " << PP(pos2) <<
856 " no cost -> out of limits" << std::endl);
860 MapNode node_at_pos2 = m_env->getMap().getNode(pos2);
862 //did we get information about node?
863 if (node_at_pos2.param0 == CONTENT_IGNORE ) {
864 VERBOSE_TARGET << "Pathfinder: (1) area at pos: "
865 << PP(pos2) << " not loaded";
869 if (!ndef->get(node_at_pos2).walkable) {
870 MapNode node_below_pos2 =
871 m_env->getMap().getNode(pos2 + v3s16(0, -1, 0));
873 //did we get information about node?
874 if (node_below_pos2.param0 == CONTENT_IGNORE ) {
875 VERBOSE_TARGET << "Pathfinder: (2) area at pos: "
876 << PP((pos2 + v3s16(0, -1, 0))) << " not loaded";
880 //test if the same-height neighbor is suitable
881 if (ndef->get(node_below_pos2).walkable) {
886 DEBUG_OUT("Pathfinder: "<< PP(pos)
887 << " cost same height found" << std::endl);
890 //test if we can fall a couple of nodes (m_maxdrop)
891 v3s16 testpos = pos2 + v3s16(0, -1, 0);
892 MapNode node_at_pos = m_env->getMap().getNode(testpos);
894 while ((node_at_pos.param0 != CONTENT_IGNORE) &&
895 (!ndef->get(node_at_pos).walkable) &&
896 (testpos.Y > m_limits.MinEdge.Y)) {
897 testpos += v3s16(0, -1, 0);
898 node_at_pos = m_env->getMap().getNode(testpos);
901 //did we find surface?
902 if ((testpos.Y >= m_limits.MinEdge.Y) &&
903 (node_at_pos.param0 != CONTENT_IGNORE) &&
904 (ndef->get(node_at_pos).walkable)) {
905 if ((pos2.Y - testpos.Y - 1) <= m_maxdrop) {
909 //difference of y-pos +1 (target node is ABOVE solid node)
910 retval.y_change = ((testpos.Y - pos2.Y) +1);
911 DEBUG_OUT("Pathfinder cost below height found" << std::endl);
914 INFO_TARGET << "Pathfinder:"
915 " distance to surface below too big: "
916 << (testpos.Y - pos2.Y) << " max: " << m_maxdrop
921 DEBUG_OUT("Pathfinder: no surface below found" << std::endl);
926 //test if we can jump upwards (m_maxjump)
928 v3s16 targetpos = pos2; // position for jump target
929 v3s16 jumppos = pos; // position for checking if jumping space is free
930 MapNode node_target = m_env->getMap().getNode(targetpos);
931 MapNode node_jump = m_env->getMap().getNode(jumppos);
932 bool headbanger = false; // true if anything blocks jumppath
934 while ((node_target.param0 != CONTENT_IGNORE) &&
935 (ndef->get(node_target).walkable) &&
936 (targetpos.Y < m_limits.MaxEdge.Y)) {
937 //if the jump would hit any solid node, discard
938 if ((node_jump.param0 == CONTENT_IGNORE) ||
939 (ndef->get(node_jump).walkable)) {
943 targetpos += v3s16(0, 1, 0);
944 jumppos += v3s16(0, 1, 0);
945 node_target = m_env->getMap().getNode(targetpos);
946 node_jump = m_env->getMap().getNode(jumppos);
949 //check headbanger one last time
950 if ((node_jump.param0 == CONTENT_IGNORE) ||
951 (ndef->get(node_jump).walkable)) {
955 //did we find surface without banging our head?
956 if ((!headbanger) && (targetpos.Y <= m_limits.MaxEdge.Y) &&
957 (!ndef->get(node_target).walkable)) {
959 if (targetpos.Y - pos2.Y <= m_maxjump) {
963 retval.y_change = (targetpos.Y - pos2.Y);
964 DEBUG_OUT("Pathfinder cost above found" << std::endl);
967 DEBUG_OUT("Pathfinder: distance to surface above too big: "
968 << (targetpos.Y - pos2.Y) << " max: " << m_maxjump
973 DEBUG_OUT("Pathfinder: no surface above found" << std::endl);
979 /******************************************************************************/
980 v3s16 Pathfinder::getIndexPos(v3s16 pos)
982 return pos - m_limits.MinEdge;
985 /******************************************************************************/
986 PathGridnode &Pathfinder::getIndexElement(v3s16 ipos)
988 return m_nodes_container->access(ipos);
991 /******************************************************************************/
992 inline PathGridnode &Pathfinder::getIdxElem(s16 x, s16 y, s16 z)
994 return m_nodes_container->access(v3s16(x,y,z));
997 /******************************************************************************/
998 bool Pathfinder::isValidIndex(v3s16 index)
1000 if ( (index.X < m_max_index_x) &&
1001 (index.Y < m_max_index_y) &&
1002 (index.Z < m_max_index_z) &&
1011 /******************************************************************************/
1012 v3s16 Pathfinder::invert(v3s16 pos)
1023 /******************************************************************************/
1024 bool Pathfinder::updateAllCosts(v3s16 ipos,
1029 PathGridnode &g_pos = getIndexElement(ipos);
1030 g_pos.totalcost = current_cost;
1031 g_pos.sourcedir = srcdir;
1035 //check if target has been found
1037 m_min_target_distance = current_cost;
1038 DEBUG_OUT(LVL " Pathfinder: target found!" << std::endl);
1042 bool retval = false;
1044 // the 4 cardinal directions
1045 const static v3s16 directions[4] = {
1052 for (v3s16 direction : directions) {
1053 if (direction != srcdir) {
1054 PathCost cost = g_pos.getCost(direction);
1057 direction.Y = cost.y_change;
1059 v3s16 ipos2 = ipos + direction;
1061 if (!isValidIndex(ipos2)) {
1062 DEBUG_OUT(LVL " Pathfinder: " << PP(ipos2) <<
1063 " out of range, max=" << PP(m_limits.MaxEdge) << std::endl);
1067 PathGridnode &g_pos2 = getIndexElement(ipos2);
1069 if (!g_pos2.valid) {
1070 VERBOSE_TARGET << LVL "Pathfinder: no data for new position: "
1071 << PP(ipos2) << std::endl;
1075 assert(cost.value > 0);
1077 int new_cost = current_cost + cost.value;
1079 // check if there already is a smaller path
1080 if ((m_min_target_distance > 0) &&
1081 (m_min_target_distance < new_cost)) {
1085 if ((g_pos2.totalcost < 0) ||
1086 (g_pos2.totalcost > new_cost)) {
1087 DEBUG_OUT(LVL "Pathfinder: updating path at: "<<
1088 PP(ipos2) << " from: " << g_pos2.totalcost << " to "<<
1089 new_cost << std::endl);
1090 if (updateAllCosts(ipos2, invert(direction),
1096 DEBUG_OUT(LVL "Pathfinder:"
1097 " already found shorter path to: "
1098 << PP(ipos2) << std::endl);
1102 DEBUG_OUT(LVL "Pathfinder:"
1103 " not moving to invalid direction: "
1104 << PP(directions[i]) << std::endl);
1111 /******************************************************************************/
1112 int Pathfinder::getXZManhattanDist(v3s16 pos)
1114 int min_x = MYMIN(pos.X, m_destination.X);
1115 int max_x = MYMAX(pos.X, m_destination.X);
1116 int min_z = MYMIN(pos.Z, m_destination.Z);
1117 int max_z = MYMAX(pos.Z, m_destination.Z);
1119 return (max_x - min_x) + (max_z - min_z);
1124 /******************************************************************************/
1125 bool Pathfinder::updateCostHeuristic(v3s16 isource, v3s16 idestination)
1127 // A* search algorithm.
1129 // The open list contains the pathfinder nodes that still need to be
1130 // checked. The priority queue sorts the pathfinder nodes by
1131 // estimated cost, with lowest cost on the top.
1132 std::priority_queue<v3s16, std::vector<v3s16>, PathfinderCompareHeuristic>
1133 openList(PathfinderCompareHeuristic(this));
1135 v3s16 source = getRealPos(isource);
1136 v3s16 destination = getRealPos(idestination);
1139 openList.push(source);
1141 // the 4 cardinal directions
1142 const static v3s16 directions[4] = {
1150 PathGridnode& s_pos = getIndexElement(isource);
1151 s_pos.source = true;
1152 s_pos.totalcost = 0;
1154 // estimated cost from start to finish
1155 int cur_manhattan = getXZManhattanDist(destination);
1156 s_pos.estimated_cost = cur_manhattan;
1158 while (!openList.empty()) {
1159 // Pick node with lowest total cost estimate.
1160 // The "cheapest" node is always on top.
1161 current_pos = openList.top();
1163 v3s16 ipos = getIndexPos(current_pos);
1165 // check if node is inside searchdistance and valid
1166 if (!isValidIndex(ipos)) {
1167 DEBUG_OUT(LVL " Pathfinder: " << PP(current_pos) <<
1168 " out of search distance, max=" << PP(m_limits.MaxEdge) << std::endl);
1172 PathGridnode& g_pos = getIndexElement(ipos);
1173 g_pos.is_closed = true;
1174 g_pos.is_open = false;
1179 if (current_pos == destination) {
1180 // destination found, terminate
1181 g_pos.target = true;
1185 // for this node, check the 4 cardinal directions
1186 for (v3s16 direction_flat : directions) {
1187 int current_totalcost = g_pos.totalcost;
1189 // get cost from current node to currently checked direction
1190 PathCost cost = g_pos.getCost(direction_flat);
1191 if (!cost.updated) {
1192 cost = calcCost(current_pos, direction_flat);
1193 g_pos.setCost(direction_flat, cost);
1195 // update Y component of direction if neighbor requires jump or fall
1196 v3s16 direction_3d = v3s16(direction_flat);
1197 direction_3d.Y = cost.y_change;
1199 // get position of true neighbor
1200 v3s16 neighbor = current_pos + direction_3d;
1201 v3s16 ineighbor = getIndexPos(neighbor);
1202 PathGridnode &n_pos = getIndexElement(ineighbor);
1204 if (cost.valid && !n_pos.is_closed && !n_pos.is_open) {
1205 // heuristic function; estimate cost from neighbor to destination
1206 cur_manhattan = getXZManhattanDist(neighbor);
1208 // add neighbor to open list
1209 n_pos.sourcedir = invert(direction_3d);
1210 n_pos.totalcost = current_totalcost + cost.value;
1211 n_pos.estimated_cost = current_totalcost + cost.value + cur_manhattan;
1212 n_pos.is_open = true;
1213 openList.push(neighbor);
1217 // no path found; all possible nodes within searchdistance have been exhausted
1221 /******************************************************************************/
1222 bool Pathfinder::buildPath(std::vector<v3s16> &path, v3s16 ipos)
1224 // The cost calculation should have set a source direction for all relevant nodes.
1225 // To build the path, we go backwards from the destination until we reach the start.
1226 for(u32 waypoints = 1; waypoints++; ) {
1227 if (waypoints > PATHFINDER_MAX_WAYPOINTS) {
1228 ERROR_TARGET << "Pathfinder: buildPath: path is too long (too many waypoints), aborting" << std::endl;
1231 // Insert node into path
1232 PathGridnode &g_pos = getIndexElement(ipos);
1234 ERROR_TARGET << "Pathfinder: buildPath: invalid next pos detected, aborting" << std::endl;
1238 g_pos.is_element = true;
1239 path.push_back(ipos);
1241 // start node found, terminate
1244 // go to the node from which the pathfinder came
1245 ipos += g_pos.sourcedir;
1248 ERROR_TARGET << "Pathfinder: buildPath: no source node found" << std::endl;
1252 /******************************************************************************/
1253 v3s16 Pathfinder::walkDownwards(v3s16 pos, unsigned int max_down) {
1256 v3s16 testpos = v3s16(pos);
1257 MapNode node_at_pos = m_env->getMap().getNode(testpos);
1258 const NodeDefManager *ndef = m_env->getGameDef()->ndef();
1259 unsigned int down = 0;
1260 while ((node_at_pos.param0 != CONTENT_IGNORE) &&
1261 (!ndef->get(node_at_pos).walkable) &&
1262 (testpos.Y > m_limits.MinEdge.Y) &&
1263 (down <= max_down)) {
1264 testpos += v3s16(0, -1, 0);
1266 node_at_pos = m_env->getMap().getNode(testpos);
1268 //did we find surface?
1269 if ((testpos.Y >= m_limits.MinEdge.Y) &&
1270 (node_at_pos.param0 != CONTENT_IGNORE) &&
1271 (ndef->get(node_at_pos).walkable)) {
1274 } else if ((down - 1) <= max_down) {
1275 //difference of y-pos +1 (target node is ABOVE solid node)
1276 testpos += v3s16(0, 1, 0);
1280 VERBOSE_TARGET << "Pos too far above ground: " <<
1281 "Index: " << PP(getIndexPos(pos)) <<
1282 "Realpos: " << PP(getRealPos(getIndexPos(pos))) << std::endl;
1285 DEBUG_OUT("Pathfinder: no surface found below pos" << std::endl);
1290 #ifdef PATHFINDER_DEBUG
1292 /******************************************************************************/
1293 void Pathfinder::printCost()
1301 /******************************************************************************/
1302 void Pathfinder::printYdir()
1310 /******************************************************************************/
1311 void Pathfinder::printCost(PathDirections dir)
1313 std::cout << "Cost in direction: " << dirToName(dir) << std::endl;
1314 std::cout << std::setfill('-') << std::setw(80) << "-" << std::endl;
1315 std::cout << std::setfill(' ');
1316 for (int y = 0; y < m_max_index_y; y++) {
1318 std::cout << "Level: " << y << std::endl;
1320 std::cout << std::setw(4) << " " << " ";
1321 for (int x = 0; x < m_max_index_x; x++) {
1322 std::cout << std::setw(4) << x;
1324 std::cout << std::endl;
1326 for (int z = 0; z < m_max_index_z; z++) {
1327 std::cout << std::setw(4) << z <<": ";
1328 for (int x = 0; x < m_max_index_x; x++) {
1329 if (getIdxElem(x, y, z).directions[dir].valid)
1330 std::cout << std::setw(4)
1331 << getIdxElem(x, y, z).directions[dir].value;
1333 std::cout << std::setw(4) << "-";
1335 std::cout << std::endl;
1337 std::cout << std::endl;
1341 /******************************************************************************/
1342 void Pathfinder::printYdir(PathDirections dir)
1344 std::cout << "Height difference in direction: " << dirToName(dir) << std::endl;
1345 std::cout << std::setfill('-') << std::setw(80) << "-" << std::endl;
1346 std::cout << std::setfill(' ');
1347 for (int y = 0; y < m_max_index_y; y++) {
1349 std::cout << "Level: " << y << std::endl;
1351 std::cout << std::setw(4) << " " << " ";
1352 for (int x = 0; x < m_max_index_x; x++) {
1353 std::cout << std::setw(4) << x;
1355 std::cout << std::endl;
1357 for (int z = 0; z < m_max_index_z; z++) {
1358 std::cout << std::setw(4) << z <<": ";
1359 for (int x = 0; x < m_max_index_x; x++) {
1360 if (getIdxElem(x, y, z).directions[dir].valid)
1361 std::cout << std::setw(4)
1362 << getIdxElem(x, y, z).directions[dir].y_change;
1364 std::cout << std::setw(4) << "-";
1366 std::cout << std::endl;
1368 std::cout << std::endl;
1372 /******************************************************************************/
1373 void Pathfinder::printType()
1375 std::cout << "Type of node:" << std::endl;
1376 std::cout << std::setfill('-') << std::setw(80) << "-" << std::endl;
1377 std::cout << std::setfill(' ');
1378 for (int y = 0; y < m_max_index_y; y++) {
1380 std::cout << "Level: " << y << std::endl;
1382 std::cout << std::setw(3) << " " << " ";
1383 for (int x = 0; x < m_max_index_x; x++) {
1384 std::cout << std::setw(3) << x;
1386 std::cout << std::endl;
1388 for (int z = 0; z < m_max_index_z; z++) {
1389 std::cout << std::setw(3) << z <<": ";
1390 for (int x = 0; x < m_max_index_x; x++) {
1391 char toshow = getIdxElem(x, y, z).type;
1392 std::cout << std::setw(3) << toshow;
1394 std::cout << std::endl;
1396 std::cout << std::endl;
1398 std::cout << std::endl;
1401 /******************************************************************************/
1402 void Pathfinder::printPathLen()
1404 std::cout << "Pathlen:" << std::endl;
1405 std::cout << std::setfill('-') << std::setw(80) << "-" << std::endl;
1406 std::cout << std::setfill(' ');
1407 for (int y = 0; y < m_max_index_y; y++) {
1409 std::cout << "Level: " << y << std::endl;
1411 std::cout << std::setw(3) << " " << " ";
1412 for (int x = 0; x < m_max_index_x; x++) {
1413 std::cout << std::setw(3) << x;
1415 std::cout << std::endl;
1417 for (int z = 0; z < m_max_index_z; z++) {
1418 std::cout << std::setw(3) << z <<": ";
1419 for (int x = 0; x < m_max_index_x; x++) {
1420 std::cout << std::setw(3) << getIdxElem(x, y, z).totalcost;
1422 std::cout << std::endl;
1424 std::cout << std::endl;
1426 std::cout << std::endl;
1429 /******************************************************************************/
1430 std::string Pathfinder::dirToName(PathDirections dir)
1450 /******************************************************************************/
1451 void Pathfinder::printPath(std::vector<v3s16> path)
1453 unsigned int current = 0;
1454 for (std::vector<v3s16>::iterator i = path.begin();
1455 i != path.end(); ++i) {
1456 std::cout << std::setw(3) << current << ":" << PP((*i)) << std::endl;