pathfinder.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  1. /*
  2. Minetest
  3. Copyright (C) 2013 sapier, sapier at gmx dot net
  4. Copyright (C) 2016 est31, <MTest31@outlook.com>
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU Lesser General Public License as published by
  7. the Free Software Foundation; either version 2.1 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public License along
  14. with this program; if not, write to the Free Software Foundation, Inc.,
  15. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. */
  17. /******************************************************************************/
  18. /* Includes */
  19. /******************************************************************************/
  20. #include "pathfinder.h"
  21. #include "serverenvironment.h"
  22. #include "server.h"
  23. #include "nodedef.h"
  24. //#define PATHFINDER_DEBUG
  25. //#define PATHFINDER_CALC_TIME
  26. #ifdef PATHFINDER_DEBUG
  27. #include <string>
  28. #endif
  29. #ifdef PATHFINDER_DEBUG
  30. #include <iomanip>
  31. #endif
  32. #ifdef PATHFINDER_CALC_TIME
  33. #include <sys/time.h>
  34. #endif
  35. /******************************************************************************/
  36. /* Typedefs and macros */
  37. /******************************************************************************/
  38. #define LVL "(" << level << ")" <<
  39. #ifdef PATHFINDER_DEBUG
  40. #define DEBUG_OUT(a) std::cout << a
  41. #define INFO_TARGET std::cout
  42. #define VERBOSE_TARGET std::cout
  43. #define ERROR_TARGET std::cout
  44. #else
  45. #define DEBUG_OUT(a) while(0)
  46. #define INFO_TARGET infostream << "Pathfinder: "
  47. #define VERBOSE_TARGET verbosestream << "Pathfinder: "
  48. #define ERROR_TARGET warningstream << "Pathfinder: "
  49. #endif
  50. /******************************************************************************/
  51. /* Class definitions */
  52. /******************************************************************************/
  53. /** representation of cost in specific direction */
  54. class PathCost {
  55. public:
  56. /** default constructor */
  57. PathCost() = default;
  58. /** copy constructor */
  59. PathCost(const PathCost &b);
  60. /** assignment operator */
  61. PathCost &operator= (const PathCost &b);
  62. bool valid = false; /**< movement is possible */
  63. int value = 0; /**< cost of movement */
  64. int direction = 0; /**< y-direction of movement */
  65. bool updated = false; /**< this cost has ben calculated */
  66. };
  67. /** representation of a mapnode to be used for pathfinding */
  68. class PathGridnode {
  69. public:
  70. /** default constructor */
  71. PathGridnode() = default;
  72. /** copy constructor */
  73. PathGridnode(const PathGridnode &b);
  74. /**
  75. * assignment operator
  76. * @param b node to copy
  77. */
  78. PathGridnode &operator= (const PathGridnode &b);
  79. /**
  80. * read cost in a specific direction
  81. * @param dir direction of cost to fetch
  82. */
  83. PathCost getCost(v3s16 dir);
  84. /**
  85. * set cost value for movement
  86. * @param dir direction to set cost for
  87. * @cost cost to set
  88. */
  89. void setCost(v3s16 dir, const PathCost &cost);
  90. bool valid = false; /**< node is on surface */
  91. bool target = false; /**< node is target position */
  92. bool source = false; /**< node is stating position */
  93. int totalcost = -1; /**< cost to move here from starting point */
  94. v3s16 sourcedir; /**< origin of movement for current cost */
  95. v3s16 pos; /**< real position of node */
  96. PathCost directions[4]; /**< cost in different directions */
  97. /* debug values */
  98. bool is_element = false; /**< node is element of path detected */
  99. char type = 'u'; /**< type of node */
  100. };
  101. class Pathfinder;
  102. /** Abstract class to manage the map data */
  103. class GridNodeContainer {
  104. public:
  105. virtual PathGridnode &access(v3s16 p)=0;
  106. virtual ~GridNodeContainer() = default;
  107. protected:
  108. Pathfinder *m_pathf;
  109. void initNode(v3s16 ipos, PathGridnode *p_node);
  110. };
  111. class ArrayGridNodeContainer : public GridNodeContainer {
  112. public:
  113. virtual ~ArrayGridNodeContainer() = default;
  114. ArrayGridNodeContainer(Pathfinder *pathf, v3s16 dimensions);
  115. virtual PathGridnode &access(v3s16 p);
  116. private:
  117. v3s16 m_dimensions;
  118. int m_x_stride;
  119. int m_y_stride;
  120. std::vector<PathGridnode> m_nodes_array;
  121. };
  122. class MapGridNodeContainer : public GridNodeContainer {
  123. public:
  124. virtual ~MapGridNodeContainer() = default;
  125. MapGridNodeContainer(Pathfinder *pathf);
  126. virtual PathGridnode &access(v3s16 p);
  127. private:
  128. std::map<v3s16, PathGridnode> m_nodes;
  129. };
  130. /** class doing pathfinding */
  131. class Pathfinder {
  132. public:
  133. /**
  134. * default constructor
  135. */
  136. Pathfinder() = default;
  137. ~Pathfinder();
  138. /**
  139. * path evaluation function
  140. * @param env environment to look for path
  141. * @param source origin of path
  142. * @param destination end position of path
  143. * @param searchdistance maximum number of nodes to look in each direction
  144. * @param max_jump maximum number of blocks a path may jump up
  145. * @param max_drop maximum number of blocks a path may drop
  146. * @param algo Algorithm to use for finding a path
  147. */
  148. std::vector<v3s16> getPath(ServerEnvironment *env,
  149. v3s16 source,
  150. v3s16 destination,
  151. unsigned int searchdistance,
  152. unsigned int max_jump,
  153. unsigned int max_drop,
  154. PathAlgorithm algo);
  155. private:
  156. /* helper functions */
  157. /**
  158. * transform index pos to mappos
  159. * @param ipos a index position
  160. * @return map position
  161. */
  162. v3s16 getRealPos(v3s16 ipos);
  163. /**
  164. * transform mappos to index pos
  165. * @param pos a real pos
  166. * @return index position
  167. */
  168. v3s16 getIndexPos(v3s16 pos);
  169. /**
  170. * get gridnode at a specific index position
  171. * @param ipos index position
  172. * @return gridnode for index
  173. */
  174. PathGridnode &getIndexElement(v3s16 ipos);
  175. /**
  176. * Get gridnode at a specific index position
  177. * @return gridnode for index
  178. */
  179. PathGridnode &getIdxElem(s16 x, s16 y, s16 z);
  180. /**
  181. * invert a 3d position
  182. * @param pos 3d position
  183. * @return pos *-1
  184. */
  185. v3s16 invert(v3s16 pos);
  186. /**
  187. * check if a index is within current search area
  188. * @param index position to validate
  189. * @return true/false
  190. */
  191. bool isValidIndex(v3s16 index);
  192. /**
  193. * translate position to float position
  194. * @param pos integer position
  195. * @return float position
  196. */
  197. v3f tov3f(v3s16 pos);
  198. /* algorithm functions */
  199. /**
  200. * calculate 2d manahttan distance to target on the xz plane
  201. * @param pos position to calc distance
  202. * @return integer distance
  203. */
  204. int getXZManhattanDist(v3s16 pos);
  205. /**
  206. * get best direction based uppon heuristics
  207. * @param directions list of unchecked directions
  208. * @param g_pos mapnode to start from
  209. * @return direction to check
  210. */
  211. v3s16 getDirHeuristic(std::vector<v3s16> &directions, PathGridnode &g_pos);
  212. /**
  213. * build internal data representation of search area
  214. * @return true/false if costmap creation was successfull
  215. */
  216. bool buildCostmap();
  217. /**
  218. * calculate cost of movement
  219. * @param pos real world position to start movement
  220. * @param dir direction to move to
  221. * @return cost information
  222. */
  223. PathCost calcCost(v3s16 pos, v3s16 dir);
  224. /**
  225. * recursive update whole search areas total cost information
  226. * @param ipos position to check next
  227. * @param srcdir positionc checked last time
  228. * @param total_cost cost of moving to ipos
  229. * @param level current recursion depth
  230. * @return true/false path to destination has been found
  231. */
  232. bool updateAllCosts(v3s16 ipos, v3s16 srcdir, int current_cost, int level);
  233. /**
  234. * recursive try to find a patrh to destionation
  235. * @param ipos position to check next
  236. * @param srcdir positionc checked last time
  237. * @param total_cost cost of moving to ipos
  238. * @param level current recursion depth
  239. * @return true/false path to destination has been found
  240. */
  241. bool updateCostHeuristic(v3s16 ipos, v3s16 srcdir, int current_cost, int level);
  242. /**
  243. * recursive build a vector containing all nodes from source to destination
  244. * @param path vector to add nodes to
  245. * @param pos pos to check next
  246. * @param level recursion depth
  247. */
  248. void buildPath(std::vector<v3s16> &path, v3s16 pos, int level);
  249. /* variables */
  250. int m_max_index_x = 0; /**< max index of search area in x direction */
  251. int m_max_index_y = 0; /**< max index of search area in y direction */
  252. int m_max_index_z = 0; /**< max index of search area in z direction */
  253. int m_searchdistance = 0; /**< max distance to search in each direction */
  254. int m_maxdrop = 0; /**< maximum number of blocks a path may drop */
  255. int m_maxjump = 0; /**< maximum number of blocks a path may jump */
  256. int m_min_target_distance = 0; /**< current smalest path to target */
  257. bool m_prefetch = true; /**< prefetch cost data */
  258. v3s16 m_start; /**< source position */
  259. v3s16 m_destination; /**< destination position */
  260. core::aabbox3d<s16> m_limits; /**< position limits in real map coordinates */
  261. /** contains all map data already collected and analyzed.
  262. Access it via the getIndexElement/getIdxElem methods. */
  263. friend class GridNodeContainer;
  264. GridNodeContainer *m_nodes_container = nullptr;
  265. ServerEnvironment *m_env = 0; /**< minetest environment pointer */
  266. #ifdef PATHFINDER_DEBUG
  267. /**
  268. * print collected cost information
  269. */
  270. void printCost();
  271. /**
  272. * print collected cost information in a specific direction
  273. * @param dir direction to print
  274. */
  275. void printCost(PathDirections dir);
  276. /**
  277. * print type of node as evaluated
  278. */
  279. void printType();
  280. /**
  281. * print pathlenght for all nodes in search area
  282. */
  283. void printPathLen();
  284. /**
  285. * print a path
  286. * @param path path to show
  287. */
  288. void printPath(std::vector<v3s16> path);
  289. /**
  290. * print y direction for all movements
  291. */
  292. void printYdir();
  293. /**
  294. * print y direction for moving in a specific direction
  295. * @param dir direction to show data
  296. */
  297. void printYdir(PathDirections dir);
  298. /**
  299. * helper function to translate a direction to speaking text
  300. * @param dir direction to translate
  301. * @return textual name of direction
  302. */
  303. std::string dirToName(PathDirections dir);
  304. #endif
  305. };
  306. /******************************************************************************/
  307. /* implementation */
  308. /******************************************************************************/
  309. std::vector<v3s16> get_path(ServerEnvironment* env,
  310. v3s16 source,
  311. v3s16 destination,
  312. unsigned int searchdistance,
  313. unsigned int max_jump,
  314. unsigned int max_drop,
  315. PathAlgorithm algo)
  316. {
  317. Pathfinder searchclass;
  318. return searchclass.getPath(env,
  319. source, destination,
  320. searchdistance, max_jump, max_drop, algo);
  321. }
  322. /******************************************************************************/
  323. PathCost::PathCost(const PathCost &b)
  324. {
  325. valid = b.valid;
  326. direction = b.direction;
  327. value = b.value;
  328. updated = b.updated;
  329. }
  330. /******************************************************************************/
  331. PathCost &PathCost::operator= (const PathCost &b)
  332. {
  333. valid = b.valid;
  334. direction = b.direction;
  335. value = b.value;
  336. updated = b.updated;
  337. return *this;
  338. }
  339. /******************************************************************************/
  340. PathGridnode::PathGridnode(const PathGridnode &b)
  341. : valid(b.valid),
  342. target(b.target),
  343. source(b.source),
  344. totalcost(b.totalcost),
  345. sourcedir(b.sourcedir),
  346. pos(b.pos),
  347. is_element(b.is_element),
  348. type(b.type)
  349. {
  350. directions[DIR_XP] = b.directions[DIR_XP];
  351. directions[DIR_XM] = b.directions[DIR_XM];
  352. directions[DIR_ZP] = b.directions[DIR_ZP];
  353. directions[DIR_ZM] = b.directions[DIR_ZM];
  354. }
  355. /******************************************************************************/
  356. PathGridnode &PathGridnode::operator= (const PathGridnode &b)
  357. {
  358. valid = b.valid;
  359. target = b.target;
  360. source = b.source;
  361. is_element = b.is_element;
  362. totalcost = b.totalcost;
  363. sourcedir = b.sourcedir;
  364. pos = b.pos;
  365. type = b.type;
  366. directions[DIR_XP] = b.directions[DIR_XP];
  367. directions[DIR_XM] = b.directions[DIR_XM];
  368. directions[DIR_ZP] = b.directions[DIR_ZP];
  369. directions[DIR_ZM] = b.directions[DIR_ZM];
  370. return *this;
  371. }
  372. /******************************************************************************/
  373. PathCost PathGridnode::getCost(v3s16 dir)
  374. {
  375. if (dir.X > 0) {
  376. return directions[DIR_XP];
  377. }
  378. if (dir.X < 0) {
  379. return directions[DIR_XM];
  380. }
  381. if (dir.Z > 0) {
  382. return directions[DIR_ZP];
  383. }
  384. if (dir.Z < 0) {
  385. return directions[DIR_ZM];
  386. }
  387. PathCost retval;
  388. return retval;
  389. }
  390. /******************************************************************************/
  391. void PathGridnode::setCost(v3s16 dir, const PathCost &cost)
  392. {
  393. if (dir.X > 0) {
  394. directions[DIR_XP] = cost;
  395. }
  396. if (dir.X < 0) {
  397. directions[DIR_XM] = cost;
  398. }
  399. if (dir.Z > 0) {
  400. directions[DIR_ZP] = cost;
  401. }
  402. if (dir.Z < 0) {
  403. directions[DIR_ZM] = cost;
  404. }
  405. }
  406. void GridNodeContainer::initNode(v3s16 ipos, PathGridnode *p_node)
  407. {
  408. const NodeDefManager *ndef = m_pathf->m_env->getGameDef()->ndef();
  409. PathGridnode &elem = *p_node;
  410. v3s16 realpos = m_pathf->getRealPos(ipos);
  411. MapNode current = m_pathf->m_env->getMap().getNode(realpos);
  412. MapNode below = m_pathf->m_env->getMap().getNode(realpos + v3s16(0, -1, 0));
  413. if ((current.param0 == CONTENT_IGNORE) ||
  414. (below.param0 == CONTENT_IGNORE)) {
  415. DEBUG_OUT("Pathfinder: " << PP(realpos) <<
  416. " current or below is invalid element" << std::endl);
  417. if (current.param0 == CONTENT_IGNORE) {
  418. elem.type = 'i';
  419. DEBUG_OUT(PP(ipos) << ": " << 'i' << std::endl);
  420. }
  421. return;
  422. }
  423. //don't add anything if it isn't an air node
  424. if (ndef->get(current).walkable || !ndef->get(below).walkable) {
  425. DEBUG_OUT("Pathfinder: " << PP(realpos)
  426. << " not on surface" << std::endl);
  427. if (ndef->get(current).walkable) {
  428. elem.type = 's';
  429. DEBUG_OUT(PP(ipos) << ": " << 's' << std::endl);
  430. } else {
  431. elem.type = '-';
  432. DEBUG_OUT(PP(ipos) << ": " << '-' << std::endl);
  433. }
  434. return;
  435. }
  436. elem.valid = true;
  437. elem.pos = realpos;
  438. elem.type = 'g';
  439. DEBUG_OUT(PP(ipos) << ": " << 'a' << std::endl);
  440. if (m_pathf->m_prefetch) {
  441. elem.directions[DIR_XP] = m_pathf->calcCost(realpos, v3s16( 1, 0, 0));
  442. elem.directions[DIR_XM] = m_pathf->calcCost(realpos, v3s16(-1, 0, 0));
  443. elem.directions[DIR_ZP] = m_pathf->calcCost(realpos, v3s16( 0, 0, 1));
  444. elem.directions[DIR_ZM] = m_pathf->calcCost(realpos, v3s16( 0, 0,-1));
  445. }
  446. }
  447. ArrayGridNodeContainer::ArrayGridNodeContainer(Pathfinder *pathf, v3s16 dimensions) :
  448. m_x_stride(dimensions.Y * dimensions.Z),
  449. m_y_stride(dimensions.Z)
  450. {
  451. m_pathf = pathf;
  452. m_nodes_array.resize(dimensions.X * dimensions.Y * dimensions.Z);
  453. INFO_TARGET << "Pathfinder ArrayGridNodeContainer constructor." << std::endl;
  454. for (int x = 0; x < dimensions.X; x++) {
  455. for (int y = 0; y < dimensions.Y; y++) {
  456. for (int z= 0; z < dimensions.Z; z++) {
  457. v3s16 ipos(x, y, z);
  458. initNode(ipos, &access(ipos));
  459. }
  460. }
  461. }
  462. }
  463. PathGridnode &ArrayGridNodeContainer::access(v3s16 p)
  464. {
  465. return m_nodes_array[p.X * m_x_stride + p.Y * m_y_stride + p.Z];
  466. }
  467. MapGridNodeContainer::MapGridNodeContainer(Pathfinder *pathf)
  468. {
  469. m_pathf = pathf;
  470. }
  471. PathGridnode &MapGridNodeContainer::access(v3s16 p)
  472. {
  473. std::map<v3s16, PathGridnode>::iterator it = m_nodes.find(p);
  474. if (it != m_nodes.end()) {
  475. return it->second;
  476. }
  477. PathGridnode &n = m_nodes[p];
  478. initNode(p, &n);
  479. return n;
  480. }
  481. /******************************************************************************/
  482. std::vector<v3s16> Pathfinder::getPath(ServerEnvironment *env,
  483. v3s16 source,
  484. v3s16 destination,
  485. unsigned int searchdistance,
  486. unsigned int max_jump,
  487. unsigned int max_drop,
  488. PathAlgorithm algo)
  489. {
  490. #ifdef PATHFINDER_CALC_TIME
  491. timespec ts;
  492. clock_gettime(CLOCK_REALTIME, &ts);
  493. #endif
  494. std::vector<v3s16> retval;
  495. //check parameters
  496. if (env == 0) {
  497. ERROR_TARGET << "missing environment pointer" << std::endl;
  498. return retval;
  499. }
  500. m_searchdistance = searchdistance;
  501. m_env = env;
  502. m_maxjump = max_jump;
  503. m_maxdrop = max_drop;
  504. m_start = source;
  505. m_destination = destination;
  506. m_min_target_distance = -1;
  507. m_prefetch = true;
  508. if (algo == PA_PLAIN_NP) {
  509. m_prefetch = false;
  510. }
  511. int min_x = MYMIN(source.X, destination.X);
  512. int max_x = MYMAX(source.X, destination.X);
  513. int min_y = MYMIN(source.Y, destination.Y);
  514. int max_y = MYMAX(source.Y, destination.Y);
  515. int min_z = MYMIN(source.Z, destination.Z);
  516. int max_z = MYMAX(source.Z, destination.Z);
  517. m_limits.MinEdge.X = min_x - searchdistance;
  518. m_limits.MinEdge.Y = min_y - searchdistance;
  519. m_limits.MinEdge.Z = min_z - searchdistance;
  520. m_limits.MaxEdge.X = max_x + searchdistance;
  521. m_limits.MaxEdge.Y = max_y + searchdistance;
  522. m_limits.MaxEdge.Z = max_z + searchdistance;
  523. v3s16 diff = m_limits.MaxEdge - m_limits.MinEdge;
  524. m_max_index_x = diff.X;
  525. m_max_index_y = diff.Y;
  526. m_max_index_z = diff.Z;
  527. delete m_nodes_container;
  528. if (diff.getLength() > 5) {
  529. m_nodes_container = new MapGridNodeContainer(this);
  530. } else {
  531. m_nodes_container = new ArrayGridNodeContainer(this, diff);
  532. }
  533. #ifdef PATHFINDER_DEBUG
  534. printType();
  535. printCost();
  536. printYdir();
  537. #endif
  538. //validate and mark start and end pos
  539. v3s16 StartIndex = getIndexPos(source);
  540. v3s16 EndIndex = getIndexPos(destination);
  541. PathGridnode &startpos = getIndexElement(StartIndex);
  542. PathGridnode &endpos = getIndexElement(EndIndex);
  543. if (!startpos.valid) {
  544. VERBOSE_TARGET << "invalid startpos" <<
  545. "Index: " << PP(StartIndex) <<
  546. "Realpos: " << PP(getRealPos(StartIndex)) << std::endl;
  547. return retval;
  548. }
  549. if (!endpos.valid) {
  550. VERBOSE_TARGET << "invalid stoppos" <<
  551. "Index: " << PP(EndIndex) <<
  552. "Realpos: " << PP(getRealPos(EndIndex)) << std::endl;
  553. return retval;
  554. }
  555. endpos.target = true;
  556. startpos.source = true;
  557. startpos.totalcost = 0;
  558. bool update_cost_retval = false;
  559. switch (algo) {
  560. case PA_DIJKSTRA:
  561. update_cost_retval = updateAllCosts(StartIndex, v3s16(0, 0, 0), 0, 0);
  562. break;
  563. case PA_PLAIN_NP:
  564. case PA_PLAIN:
  565. update_cost_retval = updateCostHeuristic(StartIndex, v3s16(0, 0, 0), 0, 0);
  566. break;
  567. default:
  568. ERROR_TARGET << "missing PathAlgorithm"<< std::endl;
  569. break;
  570. }
  571. if (update_cost_retval) {
  572. #ifdef PATHFINDER_DEBUG
  573. std::cout << "Path to target found!" << std::endl;
  574. printPathLen();
  575. #endif
  576. //find path
  577. std::vector<v3s16> path;
  578. buildPath(path, EndIndex, 0);
  579. #ifdef PATHFINDER_DEBUG
  580. std::cout << "Full index path:" << std::endl;
  581. printPath(path);
  582. #endif
  583. //finalize path
  584. std::vector<v3s16> full_path;
  585. full_path.reserve(path.size());
  586. for (const v3s16 &i : path) {
  587. full_path.push_back(getIndexElement(i).pos);
  588. }
  589. #ifdef PATHFINDER_DEBUG
  590. std::cout << "full path:" << std::endl;
  591. printPath(full_path);
  592. #endif
  593. #ifdef PATHFINDER_CALC_TIME
  594. timespec ts2;
  595. clock_gettime(CLOCK_REALTIME, &ts2);
  596. int ms = (ts2.tv_nsec - ts.tv_nsec)/(1000*1000);
  597. int us = ((ts2.tv_nsec - ts.tv_nsec) - (ms*1000*1000))/1000;
  598. int ns = ((ts2.tv_nsec - ts.tv_nsec) - ( (ms*1000*1000) + (us*1000)));
  599. std::cout << "Calculating path took: " << (ts2.tv_sec - ts.tv_sec) <<
  600. "s " << ms << "ms " << us << "us " << ns << "ns " << std::endl;
  601. #endif
  602. return full_path;
  603. }
  604. else {
  605. #ifdef PATHFINDER_DEBUG
  606. printPathLen();
  607. #endif
  608. ERROR_TARGET << "failed to update cost map"<< std::endl;
  609. }
  610. //return
  611. return retval;
  612. }
  613. Pathfinder::~Pathfinder()
  614. {
  615. delete m_nodes_container;
  616. }
  617. /******************************************************************************/
  618. v3s16 Pathfinder::getRealPos(v3s16 ipos)
  619. {
  620. return m_limits.MinEdge + ipos;
  621. }
  622. /******************************************************************************/
  623. PathCost Pathfinder::calcCost(v3s16 pos, v3s16 dir)
  624. {
  625. const NodeDefManager *ndef = m_env->getGameDef()->ndef();
  626. PathCost retval;
  627. retval.updated = true;
  628. v3s16 pos2 = pos + dir;
  629. //check limits
  630. if (!m_limits.isPointInside(pos2)) {
  631. DEBUG_OUT("Pathfinder: " << PP(pos2) <<
  632. " no cost -> out of limits" << std::endl);
  633. return retval;
  634. }
  635. MapNode node_at_pos2 = m_env->getMap().getNode(pos2);
  636. //did we get information about node?
  637. if (node_at_pos2.param0 == CONTENT_IGNORE ) {
  638. VERBOSE_TARGET << "Pathfinder: (1) area at pos: "
  639. << PP(pos2) << " not loaded";
  640. return retval;
  641. }
  642. if (!ndef->get(node_at_pos2).walkable) {
  643. MapNode node_below_pos2 =
  644. m_env->getMap().getNode(pos2 + v3s16(0, -1, 0));
  645. //did we get information about node?
  646. if (node_below_pos2.param0 == CONTENT_IGNORE ) {
  647. VERBOSE_TARGET << "Pathfinder: (2) area at pos: "
  648. << PP((pos2 + v3s16(0, -1, 0))) << " not loaded";
  649. return retval;
  650. }
  651. if (ndef->get(node_below_pos2).walkable) {
  652. retval.valid = true;
  653. retval.value = 1;
  654. retval.direction = 0;
  655. DEBUG_OUT("Pathfinder: "<< PP(pos)
  656. << " cost same height found" << std::endl);
  657. }
  658. else {
  659. v3s16 testpos = pos2 - v3s16(0, -1, 0);
  660. MapNode node_at_pos = m_env->getMap().getNode(testpos);
  661. while ((node_at_pos.param0 != CONTENT_IGNORE) &&
  662. (!ndef->get(node_at_pos).walkable) &&
  663. (testpos.Y > m_limits.MinEdge.Y)) {
  664. testpos += v3s16(0, -1, 0);
  665. node_at_pos = m_env->getMap().getNode(testpos);
  666. }
  667. //did we find surface?
  668. if ((testpos.Y >= m_limits.MinEdge.Y) &&
  669. (node_at_pos.param0 != CONTENT_IGNORE) &&
  670. (ndef->get(node_at_pos).walkable)) {
  671. if ((pos2.Y - testpos.Y - 1) <= m_maxdrop) {
  672. retval.valid = true;
  673. retval.value = 2;
  674. //difference of y-pos +1 (target node is ABOVE solid node)
  675. retval.direction = ((testpos.Y - pos2.Y) +1);
  676. DEBUG_OUT("Pathfinder cost below height found" << std::endl);
  677. }
  678. else {
  679. INFO_TARGET << "Pathfinder:"
  680. " distance to surface below to big: "
  681. << (testpos.Y - pos2.Y) << " max: " << m_maxdrop
  682. << std::endl;
  683. }
  684. }
  685. else {
  686. DEBUG_OUT("Pathfinder: no surface below found" << std::endl);
  687. }
  688. }
  689. }
  690. else {
  691. v3s16 testpos = pos2;
  692. MapNode node_at_pos = m_env->getMap().getNode(testpos);
  693. while ((node_at_pos.param0 != CONTENT_IGNORE) &&
  694. (ndef->get(node_at_pos).walkable) &&
  695. (testpos.Y < m_limits.MaxEdge.Y)) {
  696. testpos += v3s16(0, 1, 0);
  697. node_at_pos = m_env->getMap().getNode(testpos);
  698. }
  699. //did we find surface?
  700. if ((testpos.Y <= m_limits.MaxEdge.Y) &&
  701. (!ndef->get(node_at_pos).walkable)) {
  702. if (testpos.Y - pos2.Y <= m_maxjump) {
  703. retval.valid = true;
  704. retval.value = 2;
  705. retval.direction = (testpos.Y - pos2.Y);
  706. DEBUG_OUT("Pathfinder cost above found" << std::endl);
  707. }
  708. else {
  709. DEBUG_OUT("Pathfinder: distance to surface above to big: "
  710. << (testpos.Y - pos2.Y) << " max: " << m_maxjump
  711. << std::endl);
  712. }
  713. }
  714. else {
  715. DEBUG_OUT("Pathfinder: no surface above found" << std::endl);
  716. }
  717. }
  718. return retval;
  719. }
  720. /******************************************************************************/
  721. v3s16 Pathfinder::getIndexPos(v3s16 pos)
  722. {
  723. return pos - m_limits.MinEdge;
  724. }
  725. /******************************************************************************/
  726. PathGridnode &Pathfinder::getIndexElement(v3s16 ipos)
  727. {
  728. return m_nodes_container->access(ipos);
  729. }
  730. /******************************************************************************/
  731. inline PathGridnode &Pathfinder::getIdxElem(s16 x, s16 y, s16 z)
  732. {
  733. return m_nodes_container->access(v3s16(x,y,z));
  734. }
  735. /******************************************************************************/
  736. bool Pathfinder::isValidIndex(v3s16 index)
  737. {
  738. if ( (index.X < m_max_index_x) &&
  739. (index.Y < m_max_index_y) &&
  740. (index.Z < m_max_index_z) &&
  741. (index.X >= 0) &&
  742. (index.Y >= 0) &&
  743. (index.Z >= 0))
  744. return true;
  745. return false;
  746. }
  747. /******************************************************************************/
  748. v3s16 Pathfinder::invert(v3s16 pos)
  749. {
  750. v3s16 retval = pos;
  751. retval.X *=-1;
  752. retval.Y *=-1;
  753. retval.Z *=-1;
  754. return retval;
  755. }
  756. /******************************************************************************/
  757. bool Pathfinder::updateAllCosts(v3s16 ipos,
  758. v3s16 srcdir,
  759. int current_cost,
  760. int level)
  761. {
  762. PathGridnode &g_pos = getIndexElement(ipos);
  763. g_pos.totalcost = current_cost;
  764. g_pos.sourcedir = srcdir;
  765. level ++;
  766. //check if target has been found
  767. if (g_pos.target) {
  768. m_min_target_distance = current_cost;
  769. DEBUG_OUT(LVL " Pathfinder: target found!" << std::endl);
  770. return true;
  771. }
  772. bool retval = false;
  773. std::vector<v3s16> directions;
  774. directions.emplace_back(1,0, 0);
  775. directions.emplace_back(-1,0, 0);
  776. directions.emplace_back(0,0, 1);
  777. directions.emplace_back(0,0,-1);
  778. for (v3s16 &direction : directions) {
  779. if (direction != srcdir) {
  780. PathCost cost = g_pos.getCost(direction);
  781. if (cost.valid) {
  782. direction.Y = cost.direction;
  783. v3s16 ipos2 = ipos + direction;
  784. if (!isValidIndex(ipos2)) {
  785. DEBUG_OUT(LVL " Pathfinder: " << PP(ipos2) <<
  786. " out of range, max=" << PP(m_limits.MaxEdge) << std::endl);
  787. continue;
  788. }
  789. PathGridnode &g_pos2 = getIndexElement(ipos2);
  790. if (!g_pos2.valid) {
  791. VERBOSE_TARGET << LVL "Pathfinder: no data for new position: "
  792. << PP(ipos2) << std::endl;
  793. continue;
  794. }
  795. assert(cost.value > 0);
  796. int new_cost = current_cost + cost.value;
  797. // check if there already is a smaller path
  798. if ((m_min_target_distance > 0) &&
  799. (m_min_target_distance < new_cost)) {
  800. return false;
  801. }
  802. if ((g_pos2.totalcost < 0) ||
  803. (g_pos2.totalcost > new_cost)) {
  804. DEBUG_OUT(LVL "Pathfinder: updating path at: "<<
  805. PP(ipos2) << " from: " << g_pos2.totalcost << " to "<<
  806. new_cost << std::endl);
  807. if (updateAllCosts(ipos2, invert(direction),
  808. new_cost, level)) {
  809. retval = true;
  810. }
  811. }
  812. else {
  813. DEBUG_OUT(LVL "Pathfinder:"
  814. " already found shorter path to: "
  815. << PP(ipos2) << std::endl);
  816. }
  817. }
  818. else {
  819. DEBUG_OUT(LVL "Pathfinder:"
  820. " not moving to invalid direction: "
  821. << PP(directions[i]) << std::endl);
  822. }
  823. }
  824. }
  825. return retval;
  826. }
  827. /******************************************************************************/
  828. int Pathfinder::getXZManhattanDist(v3s16 pos)
  829. {
  830. int min_x = MYMIN(pos.X, m_destination.X);
  831. int max_x = MYMAX(pos.X, m_destination.X);
  832. int min_z = MYMIN(pos.Z, m_destination.Z);
  833. int max_z = MYMAX(pos.Z, m_destination.Z);
  834. return (max_x - min_x) + (max_z - min_z);
  835. }
  836. /******************************************************************************/
  837. v3s16 Pathfinder::getDirHeuristic(std::vector<v3s16> &directions, PathGridnode &g_pos)
  838. {
  839. int minscore = -1;
  840. v3s16 retdir = v3s16(0, 0, 0);
  841. v3s16 srcpos = g_pos.pos;
  842. DEBUG_OUT("Pathfinder: remaining dirs at beginning:"
  843. << directions.size() << std::endl);
  844. for (v3s16 &direction : directions) {
  845. v3s16 pos1 = v3s16(srcpos.X + direction.X, 0, srcpos.Z+ direction.Z);
  846. int cur_manhattan = getXZManhattanDist(pos1);
  847. PathCost cost = g_pos.getCost(direction);
  848. if (!cost.updated) {
  849. cost = calcCost(g_pos.pos, direction);
  850. g_pos.setCost(direction, cost);
  851. }
  852. if (cost.valid) {
  853. int score = cost.value + cur_manhattan;
  854. if ((minscore < 0)|| (score < minscore)) {
  855. minscore = score;
  856. retdir = direction;
  857. }
  858. }
  859. }
  860. if (retdir != v3s16(0, 0, 0)) {
  861. for (std::vector<v3s16>::iterator iter = directions.begin();
  862. iter != directions.end();
  863. ++iter) {
  864. if(*iter == retdir) {
  865. DEBUG_OUT("Pathfinder: removing return direction" << std::endl);
  866. directions.erase(iter);
  867. break;
  868. }
  869. }
  870. }
  871. else {
  872. DEBUG_OUT("Pathfinder: didn't find any valid direction clearing"
  873. << std::endl);
  874. directions.clear();
  875. }
  876. DEBUG_OUT("Pathfinder: remaining dirs at end:" << directions.size()
  877. << std::endl);
  878. return retdir;
  879. }
  880. /******************************************************************************/
  881. bool Pathfinder::updateCostHeuristic( v3s16 ipos,
  882. v3s16 srcdir,
  883. int current_cost,
  884. int level)
  885. {
  886. PathGridnode &g_pos = getIndexElement(ipos);
  887. g_pos.totalcost = current_cost;
  888. g_pos.sourcedir = srcdir;
  889. level ++;
  890. //check if target has been found
  891. if (g_pos.target) {
  892. m_min_target_distance = current_cost;
  893. DEBUG_OUT(LVL " Pathfinder: target found!" << std::endl);
  894. return true;
  895. }
  896. bool retval = false;
  897. std::vector<v3s16> directions;
  898. directions.emplace_back(1, 0, 0);
  899. directions.emplace_back(-1, 0, 0);
  900. directions.emplace_back(0, 0, 1);
  901. directions.emplace_back(0, 0, -1);
  902. v3s16 direction = getDirHeuristic(directions, g_pos);
  903. while (direction != v3s16(0, 0, 0) && (!retval)) {
  904. if (direction != srcdir) {
  905. PathCost cost = g_pos.getCost(direction);
  906. if (cost.valid) {
  907. direction.Y = cost.direction;
  908. v3s16 ipos2 = ipos + direction;
  909. if (!isValidIndex(ipos2)) {
  910. DEBUG_OUT(LVL " Pathfinder: " << PP(ipos2) <<
  911. " out of range, max=" << PP(m_limits.MaxEdge) << std::endl);
  912. direction = getDirHeuristic(directions, g_pos);
  913. continue;
  914. }
  915. PathGridnode &g_pos2 = getIndexElement(ipos2);
  916. if (!g_pos2.valid) {
  917. VERBOSE_TARGET << LVL "Pathfinder: no data for new position: "
  918. << PP(ipos2) << std::endl;
  919. direction = getDirHeuristic(directions, g_pos);
  920. continue;
  921. }
  922. assert(cost.value > 0);
  923. int new_cost = current_cost + cost.value;
  924. // check if there already is a smaller path
  925. if ((m_min_target_distance > 0) &&
  926. (m_min_target_distance < new_cost)) {
  927. DEBUG_OUT(LVL "Pathfinder:"
  928. " already longer than best already found path "
  929. << PP(ipos2) << std::endl);
  930. return false;
  931. }
  932. if ((g_pos2.totalcost < 0) ||
  933. (g_pos2.totalcost > new_cost)) {
  934. DEBUG_OUT(LVL "Pathfinder: updating path at: "<<
  935. PP(ipos2) << " from: " << g_pos2.totalcost << " to "<<
  936. new_cost << " srcdir=" <<
  937. PP(invert(direction))<< std::endl);
  938. if (updateCostHeuristic(ipos2, invert(direction),
  939. new_cost, level)) {
  940. retval = true;
  941. }
  942. }
  943. else {
  944. DEBUG_OUT(LVL "Pathfinder:"
  945. " already found shorter path to: "
  946. << PP(ipos2) << std::endl);
  947. }
  948. }
  949. else {
  950. DEBUG_OUT(LVL "Pathfinder:"
  951. " not moving to invalid direction: "
  952. << PP(direction) << std::endl);
  953. }
  954. }
  955. else {
  956. DEBUG_OUT(LVL "Pathfinder:"
  957. " skipping srcdir: "
  958. << PP(direction) << std::endl);
  959. }
  960. direction = getDirHeuristic(directions, g_pos);
  961. }
  962. return retval;
  963. }
  964. /******************************************************************************/
  965. void Pathfinder::buildPath(std::vector<v3s16> &path, v3s16 pos, int level)
  966. {
  967. level ++;
  968. if (level > 700) {
  969. ERROR_TARGET
  970. << LVL "Pathfinder: path is too long aborting" << std::endl;
  971. return;
  972. }
  973. PathGridnode &g_pos = getIndexElement(pos);
  974. if (!g_pos.valid) {
  975. ERROR_TARGET
  976. << LVL "Pathfinder: invalid next pos detected aborting" << std::endl;
  977. return;
  978. }
  979. g_pos.is_element = true;
  980. //check if source reached
  981. if (g_pos.source) {
  982. path.push_back(pos);
  983. return;
  984. }
  985. buildPath(path, pos + g_pos.sourcedir, level);
  986. path.push_back(pos);
  987. }
  988. /******************************************************************************/
  989. v3f Pathfinder::tov3f(v3s16 pos)
  990. {
  991. return v3f(BS * pos.X, BS * pos.Y, BS * pos.Z);
  992. }
  993. #ifdef PATHFINDER_DEBUG
  994. /******************************************************************************/
  995. void Pathfinder::printCost()
  996. {
  997. printCost(DIR_XP);
  998. printCost(DIR_XM);
  999. printCost(DIR_ZP);
  1000. printCost(DIR_ZM);
  1001. }
  1002. /******************************************************************************/
  1003. void Pathfinder::printYdir()
  1004. {
  1005. printYdir(DIR_XP);
  1006. printYdir(DIR_XM);
  1007. printYdir(DIR_ZP);
  1008. printYdir(DIR_ZM);
  1009. }
  1010. /******************************************************************************/
  1011. void Pathfinder::printCost(PathDirections dir)
  1012. {
  1013. std::cout << "Cost in direction: " << dirToName(dir) << std::endl;
  1014. std::cout << std::setfill('-') << std::setw(80) << "-" << std::endl;
  1015. std::cout << std::setfill(' ');
  1016. for (int y = 0; y < m_max_index_y; y++) {
  1017. std::cout << "Level: " << y << std::endl;
  1018. std::cout << std::setw(4) << " " << " ";
  1019. for (int x = 0; x < m_max_index_x; x++) {
  1020. std::cout << std::setw(4) << x;
  1021. }
  1022. std::cout << std::endl;
  1023. for (int z = 0; z < m_max_index_z; z++) {
  1024. std::cout << std::setw(4) << z <<": ";
  1025. for (int x = 0; x < m_max_index_x; x++) {
  1026. if (getIdxElem(x, y, z).directions[dir].valid)
  1027. std::cout << std::setw(4)
  1028. << getIdxElem(x, y, z).directions[dir].value;
  1029. else
  1030. std::cout << std::setw(4) << "-";
  1031. }
  1032. std::cout << std::endl;
  1033. }
  1034. std::cout << std::endl;
  1035. }
  1036. }
  1037. /******************************************************************************/
  1038. void Pathfinder::printYdir(PathDirections dir)
  1039. {
  1040. std::cout << "Height difference in direction: " << dirToName(dir) << std::endl;
  1041. std::cout << std::setfill('-') << std::setw(80) << "-" << std::endl;
  1042. std::cout << std::setfill(' ');
  1043. for (int y = 0; y < m_max_index_y; y++) {
  1044. std::cout << "Level: " << y << std::endl;
  1045. std::cout << std::setw(4) << " " << " ";
  1046. for (int x = 0; x < m_max_index_x; x++) {
  1047. std::cout << std::setw(4) << x;
  1048. }
  1049. std::cout << std::endl;
  1050. for (int z = 0; z < m_max_index_z; z++) {
  1051. std::cout << std::setw(4) << z <<": ";
  1052. for (int x = 0; x < m_max_index_x; x++) {
  1053. if (getIdxElem(x, y, z).directions[dir].valid)
  1054. std::cout << std::setw(4)
  1055. << getIdxElem(x, y, z).directions[dir].direction;
  1056. else
  1057. std::cout << std::setw(4) << "-";
  1058. }
  1059. std::cout << std::endl;
  1060. }
  1061. std::cout << std::endl;
  1062. }
  1063. }
  1064. /******************************************************************************/
  1065. void Pathfinder::printType()
  1066. {
  1067. std::cout << "Type of node:" << std::endl;
  1068. std::cout << std::setfill('-') << std::setw(80) << "-" << std::endl;
  1069. std::cout << std::setfill(' ');
  1070. for (int y = 0; y < m_max_index_y; y++) {
  1071. std::cout << "Level: " << y << std::endl;
  1072. std::cout << std::setw(3) << " " << " ";
  1073. for (int x = 0; x < m_max_index_x; x++) {
  1074. std::cout << std::setw(3) << x;
  1075. }
  1076. std::cout << std::endl;
  1077. for (int z = 0; z < m_max_index_z; z++) {
  1078. std::cout << std::setw(3) << z <<": ";
  1079. for (int x = 0; x < m_max_index_x; x++) {
  1080. char toshow = getIdxElem(x, y, z).type;
  1081. std::cout << std::setw(3) << toshow;
  1082. }
  1083. std::cout << std::endl;
  1084. }
  1085. std::cout << std::endl;
  1086. }
  1087. std::cout << std::endl;
  1088. }
  1089. /******************************************************************************/
  1090. void Pathfinder::printPathLen()
  1091. {
  1092. std::cout << "Pathlen:" << std::endl;
  1093. std::cout << std::setfill('-') << std::setw(80) << "-" << std::endl;
  1094. std::cout << std::setfill(' ');
  1095. for (int y = 0; y < m_max_index_y; y++) {
  1096. std::cout << "Level: " << y << std::endl;
  1097. std::cout << std::setw(3) << " " << " ";
  1098. for (int x = 0; x < m_max_index_x; x++) {
  1099. std::cout << std::setw(3) << x;
  1100. }
  1101. std::cout << std::endl;
  1102. for (int z = 0; z < m_max_index_z; z++) {
  1103. std::cout << std::setw(3) << z <<": ";
  1104. for (int x = 0; x < m_max_index_x; x++) {
  1105. std::cout << std::setw(3) << getIdxElem(x, y, z).totalcost;
  1106. }
  1107. std::cout << std::endl;
  1108. }
  1109. std::cout << std::endl;
  1110. }
  1111. std::cout << std::endl;
  1112. }
  1113. /******************************************************************************/
  1114. std::string Pathfinder::dirToName(PathDirections dir)
  1115. {
  1116. switch (dir) {
  1117. case DIR_XP:
  1118. return "XP";
  1119. break;
  1120. case DIR_XM:
  1121. return "XM";
  1122. break;
  1123. case DIR_ZP:
  1124. return "ZP";
  1125. break;
  1126. case DIR_ZM:
  1127. return "ZM";
  1128. break;
  1129. default:
  1130. return "UKN";
  1131. }
  1132. }
  1133. /******************************************************************************/
  1134. void Pathfinder::printPath(std::vector<v3s16> path)
  1135. {
  1136. unsigned int current = 0;
  1137. for (std::vector<v3s16>::iterator i = path.begin();
  1138. i != path.end(); ++i) {
  1139. std::cout << std::setw(3) << current << ":" << PP((*i)) << std::endl;
  1140. current++;
  1141. }
  1142. }
  1143. #endif