DetourPathCorridor.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. //
  2. // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
  3. //
  4. // This software is provided 'as-is', without any express or implied
  5. // warranty. In no event will the authors be held liable for any damages
  6. // arising from the use of this software.
  7. // Permission is granted to anyone to use this software for any purpose,
  8. // including commercial applications, and to alter it and redistribute it
  9. // freely, subject to the following restrictions:
  10. // 1. The origin of this software must not be misrepresented; you must not
  11. // claim that you wrote the original software. If you use this software
  12. // in a product, an acknowledgment in the product documentation would be
  13. // appreciated but is not required.
  14. // 2. Altered source versions must be plainly marked as such, and must not be
  15. // misrepresented as being the original software.
  16. // 3. This notice may not be removed or altered from any source distribution.
  17. //
  18. #include <string.h>
  19. #include "DetourPathCorridor.h"
  20. #include "DetourNavMeshQuery.h"
  21. #include "DetourCommon.h"
  22. #include "DetourAssert.h"
  23. #include "DetourAlloc.h"
  24. int dtMergeCorridorStartMoved(dtPolyRef* path, const int npath, const int maxPath,
  25. const dtPolyRef* visited, const int nvisited)
  26. {
  27. int furthestPath = -1;
  28. int furthestVisited = -1;
  29. // Find furthest common polygon.
  30. for (int i = npath-1; i >= 0; --i)
  31. {
  32. bool found = false;
  33. for (int j = nvisited-1; j >= 0; --j)
  34. {
  35. if (path[i] == visited[j])
  36. {
  37. furthestPath = i;
  38. furthestVisited = j;
  39. found = true;
  40. }
  41. }
  42. if (found)
  43. break;
  44. }
  45. // If no intersection found just return current path.
  46. if (furthestPath == -1 || furthestVisited == -1)
  47. return npath;
  48. // Concatenate paths.
  49. // Adjust beginning of the buffer to include the visited.
  50. const int req = nvisited - furthestVisited;
  51. const int orig = dtMin(furthestPath+1, npath);
  52. int size = dtMax(0, npath-orig);
  53. if (req+size > maxPath)
  54. size = maxPath-req;
  55. if (size)
  56. memmove(path+req, path+orig, size*sizeof(dtPolyRef));
  57. // Store visited
  58. for (int i = 0; i < req; ++i)
  59. path[i] = visited[(nvisited-1)-i];
  60. return req+size;
  61. }
  62. int dtMergeCorridorEndMoved(dtPolyRef* path, const int npath, const int maxPath,
  63. const dtPolyRef* visited, const int nvisited)
  64. {
  65. int furthestPath = -1;
  66. int furthestVisited = -1;
  67. // Find furthest common polygon.
  68. for (int i = 0; i < npath; ++i)
  69. {
  70. bool found = false;
  71. for (int j = nvisited-1; j >= 0; --j)
  72. {
  73. if (path[i] == visited[j])
  74. {
  75. furthestPath = i;
  76. furthestVisited = j;
  77. found = true;
  78. }
  79. }
  80. if (found)
  81. break;
  82. }
  83. // If no intersection found just return current path.
  84. if (furthestPath == -1 || furthestVisited == -1)
  85. return npath;
  86. // Concatenate paths.
  87. const int ppos = furthestPath+1;
  88. const int vpos = furthestVisited+1;
  89. const int count = dtMin(nvisited-vpos, maxPath-ppos);
  90. dtAssert(ppos+count <= maxPath);
  91. if (count)
  92. memcpy(path+ppos, visited+vpos, sizeof(dtPolyRef)*count);
  93. return ppos+count;
  94. }
  95. int dtMergeCorridorStartShortcut(dtPolyRef* path, const int npath, const int maxPath,
  96. const dtPolyRef* visited, const int nvisited)
  97. {
  98. int furthestPath = -1;
  99. int furthestVisited = -1;
  100. // Find furthest common polygon.
  101. for (int i = npath-1; i >= 0; --i)
  102. {
  103. bool found = false;
  104. for (int j = nvisited-1; j >= 0; --j)
  105. {
  106. if (path[i] == visited[j])
  107. {
  108. furthestPath = i;
  109. furthestVisited = j;
  110. found = true;
  111. }
  112. }
  113. if (found)
  114. break;
  115. }
  116. // If no intersection found just return current path.
  117. if (furthestPath == -1 || furthestVisited == -1)
  118. return npath;
  119. // Concatenate paths.
  120. // Adjust beginning of the buffer to include the visited.
  121. const int req = furthestVisited;
  122. if (req <= 0)
  123. return npath;
  124. const int orig = furthestPath;
  125. int size = dtMax(0, npath-orig);
  126. if (req+size > maxPath)
  127. size = maxPath-req;
  128. if (size)
  129. memmove(path+req, path+orig, size*sizeof(dtPolyRef));
  130. // Store visited
  131. for (int i = 0; i < req; ++i)
  132. path[i] = visited[i];
  133. return req+size;
  134. }
  135. /**
  136. @class dtPathCorridor
  137. @par
  138. The corridor is loaded with a path, usually obtained from a #dtNavMeshQuery::findPath() query. The corridor
  139. is then used to plan local movement, with the corridor automatically updating as needed to deal with inaccurate
  140. agent locomotion.
  141. Example of a common use case:
  142. -# Construct the corridor object and call #init() to allocate its path buffer.
  143. -# Obtain a path from a #dtNavMeshQuery object.
  144. -# Use #reset() to set the agent's current position. (At the beginning of the path.)
  145. -# Use #setCorridor() to load the path and target.
  146. -# Use #findCorners() to plan movement. (This handles dynamic path straightening.)
  147. -# Use #movePosition() to feed agent movement back into the corridor. (The corridor will automatically adjust as needed.)
  148. -# If the target is moving, use #moveTargetPosition() to update the end of the corridor.
  149. (The corridor will automatically adjust as needed.)
  150. -# Repeat the previous 3 steps to continue to move the agent.
  151. The corridor position and target are always constrained to the navigation mesh.
  152. One of the difficulties in maintaining a path is that floating point errors, locomotion inaccuracies, and/or local
  153. steering can result in the agent crossing the boundary of the path corridor, temporarily invalidating the path.
  154. This class uses local mesh queries to detect and update the corridor as needed to handle these types of issues.
  155. The fact that local mesh queries are used to move the position and target locations results in two beahviors that
  156. need to be considered:
  157. Every time a move function is used there is a chance that the path will become non-optimial. Basically, the further
  158. the target is moved from its original location, and the further the position is moved outside the original corridor,
  159. the more likely the path will become non-optimal. This issue can be addressed by periodically running the
  160. #optimizePathTopology() and #optimizePathVisibility() methods.
  161. All local mesh queries have distance limitations. (Review the #dtNavMeshQuery methods for details.) So the most accurate
  162. use case is to move the position and target in small increments. If a large increment is used, then the corridor
  163. may not be able to accurately find the new location. Because of this limiation, if a position is moved in a large
  164. increment, then compare the desired and resulting polygon references. If the two do not match, then path replanning
  165. may be needed. E.g. If you move the target, check #getLastPoly() to see if it is the expected polygon.
  166. */
  167. dtPathCorridor::dtPathCorridor() :
  168. m_path(0),
  169. m_npath(0),
  170. m_maxPath(0)
  171. {
  172. }
  173. dtPathCorridor::~dtPathCorridor()
  174. {
  175. dtFree(m_path);
  176. }
  177. /// @par
  178. ///
  179. /// @warning Cannot be called more than once.
  180. bool dtPathCorridor::init(const int maxPath)
  181. {
  182. dtAssert(!m_path);
  183. m_path = (dtPolyRef*)dtAlloc(sizeof(dtPolyRef)*maxPath, DT_ALLOC_PERM);
  184. if (!m_path)
  185. return false;
  186. m_npath = 0;
  187. m_maxPath = maxPath;
  188. return true;
  189. }
  190. /// @par
  191. ///
  192. /// Essentially, the corridor is set of one polygon in size with the target
  193. /// equal to the position.
  194. void dtPathCorridor::reset(dtPolyRef ref, const float* pos)
  195. {
  196. dtAssert(m_path);
  197. dtVcopy(m_pos, pos);
  198. dtVcopy(m_target, pos);
  199. m_path[0] = ref;
  200. m_npath = 1;
  201. }
  202. /**
  203. @par
  204. This is the function used to plan local movement within the corridor. One or more corners can be
  205. detected in order to plan movement. It performs essentially the same function as #dtNavMeshQuery::findStraightPath.
  206. Due to internal optimizations, the maximum number of corners returned will be (@p maxCorners - 1)
  207. For example: If the buffers are sized to hold 10 corners, the function will never return more than 9 corners.
  208. So if 10 corners are needed, the buffers should be sized for 11 corners.
  209. If the target is within range, it will be the last corner and have a polygon reference id of zero.
  210. */
  211. int dtPathCorridor::findCorners(float* cornerVerts, unsigned char* cornerFlags,
  212. dtPolyRef* cornerPolys, const int maxCorners,
  213. dtNavMeshQuery* navquery, const dtQueryFilter* /*filter*/)
  214. {
  215. dtAssert(m_path);
  216. dtAssert(m_npath);
  217. static const float MIN_TARGET_DIST = 0.01f;
  218. int ncorners = 0;
  219. navquery->findStraightPath(m_pos, m_target, m_path, m_npath,
  220. cornerVerts, cornerFlags, cornerPolys, &ncorners, maxCorners);
  221. // Prune points in the beginning of the path which are too close.
  222. while (ncorners)
  223. {
  224. if ((cornerFlags[0] & DT_STRAIGHTPATH_OFFMESH_CONNECTION) ||
  225. dtVdist2DSqr(&cornerVerts[0], m_pos) > dtSqr(MIN_TARGET_DIST))
  226. break;
  227. ncorners--;
  228. if (ncorners)
  229. {
  230. memmove(cornerFlags, cornerFlags+1, sizeof(unsigned char)*ncorners);
  231. memmove(cornerPolys, cornerPolys+1, sizeof(dtPolyRef)*ncorners);
  232. memmove(cornerVerts, cornerVerts+3, sizeof(float)*3*ncorners);
  233. }
  234. }
  235. // Prune points after an off-mesh connection.
  236. for (int i = 0; i < ncorners; ++i)
  237. {
  238. if (cornerFlags[i] & DT_STRAIGHTPATH_OFFMESH_CONNECTION)
  239. {
  240. ncorners = i+1;
  241. break;
  242. }
  243. }
  244. return ncorners;
  245. }
  246. /**
  247. @par
  248. Inaccurate locomotion or dynamic obstacle avoidance can force the argent position significantly outside the
  249. original corridor. Over time this can result in the formation of a non-optimal corridor. Non-optimal paths can
  250. also form near the corners of tiles.
  251. This function uses an efficient local visibility search to try to optimize the corridor
  252. between the current position and @p next.
  253. The corridor will change only if @p next is visible from the current position and moving directly toward the point
  254. is better than following the existing path.
  255. The more inaccurate the agent movement, the more beneficial this function becomes. Simply adjust the frequency
  256. of the call to match the needs to the agent.
  257. This function is not suitable for long distance searches.
  258. */
  259. void dtPathCorridor::optimizePathVisibility(const float* next, const float pathOptimizationRange,
  260. dtNavMeshQuery* navquery, const dtQueryFilter* filter)
  261. {
  262. dtAssert(m_path);
  263. // Clamp the ray to max distance.
  264. float goal[3];
  265. dtVcopy(goal, next);
  266. float dist = dtVdist2D(m_pos, goal);
  267. // If too close to the goal, do not try to optimize.
  268. if (dist < 0.01f)
  269. return;
  270. // Overshoot a little. This helps to optimize open fields in tiled meshes.
  271. dist = dtMin(dist+0.01f, pathOptimizationRange);
  272. // Adjust ray length.
  273. float delta[3];
  274. dtVsub(delta, goal, m_pos);
  275. dtVmad(goal, m_pos, delta, pathOptimizationRange/dist);
  276. static const int MAX_RES = 32;
  277. dtPolyRef res[MAX_RES];
  278. float t, norm[3];
  279. int nres = 0;
  280. navquery->raycast(m_path[0], m_pos, goal, filter, &t, norm, res, &nres, MAX_RES);
  281. if (nres > 1 && t > 0.99f)
  282. {
  283. m_npath = dtMergeCorridorStartShortcut(m_path, m_npath, m_maxPath, res, nres);
  284. }
  285. }
  286. /**
  287. @par
  288. Inaccurate locomotion or dynamic obstacle avoidance can force the agent position significantly outside the
  289. original corridor. Over time this can result in the formation of a non-optimal corridor. This function will use a
  290. local area path search to try to re-optimize the corridor.
  291. The more inaccurate the agent movement, the more beneficial this function becomes. Simply adjust the frequency of
  292. the call to match the needs to the agent.
  293. */
  294. bool dtPathCorridor::optimizePathTopology(dtNavMeshQuery* navquery, const dtQueryFilter* filter)
  295. {
  296. dtAssert(navquery);
  297. dtAssert(filter);
  298. dtAssert(m_path);
  299. if (m_npath < 3)
  300. return false;
  301. static const int MAX_ITER = 32;
  302. static const int MAX_RES = 32;
  303. dtPolyRef res[MAX_RES];
  304. int nres = 0;
  305. navquery->initSlicedFindPath(m_path[0], m_path[m_npath-1], m_pos, m_target, filter);
  306. navquery->updateSlicedFindPath(MAX_ITER, 0);
  307. dtStatus status = navquery->finalizeSlicedFindPathPartial(m_path, m_npath, res, &nres, MAX_RES);
  308. if (dtStatusSucceed(status) && nres > 0)
  309. {
  310. m_npath = dtMergeCorridorStartShortcut(m_path, m_npath, m_maxPath, res, nres);
  311. return true;
  312. }
  313. return false;
  314. }
  315. bool dtPathCorridor::moveOverOffmeshConnection(dtPolyRef offMeshConRef, dtPolyRef* refs,
  316. float* startPos, float* endPos,
  317. dtNavMeshQuery* navquery)
  318. {
  319. dtAssert(navquery);
  320. dtAssert(m_path);
  321. dtAssert(m_npath);
  322. // Advance the path up to and over the off-mesh connection.
  323. dtPolyRef prevRef = 0, polyRef = m_path[0];
  324. int npos = 0;
  325. while (npos < m_npath && polyRef != offMeshConRef)
  326. {
  327. prevRef = polyRef;
  328. polyRef = m_path[npos];
  329. npos++;
  330. }
  331. if (npos == m_npath)
  332. {
  333. // Could not find offMeshConRef
  334. return false;
  335. }
  336. // Prune path
  337. for (int i = npos; i < m_npath; ++i)
  338. m_path[i-npos] = m_path[i];
  339. m_npath -= npos;
  340. refs[0] = prevRef;
  341. refs[1] = polyRef;
  342. const dtNavMesh* nav = navquery->getAttachedNavMesh();
  343. dtAssert(nav);
  344. dtStatus status = nav->getOffMeshConnectionPolyEndPoints(refs[0], refs[1], startPos, endPos);
  345. if (dtStatusSucceed(status))
  346. {
  347. dtVcopy(m_pos, endPos);
  348. return true;
  349. }
  350. return false;
  351. }
  352. /**
  353. @par
  354. Behavior:
  355. - The movement is constrained to the surface of the navigation mesh.
  356. - The corridor is automatically adjusted (shorted or lengthened) in order to remain valid.
  357. - The new position will be located in the adjusted corridor's first polygon.
  358. The expected use case is that the desired position will be 'near' the current corridor. What is considered 'near'
  359. depends on local polygon density, query search half extents, etc.
  360. The resulting position will differ from the desired position if the desired position is not on the navigation mesh,
  361. or it can't be reached using a local search.
  362. */
  363. bool dtPathCorridor::movePosition(const float* npos, dtNavMeshQuery* navquery, const dtQueryFilter* filter)
  364. {
  365. dtAssert(m_path);
  366. dtAssert(m_npath);
  367. // Move along navmesh and update new position.
  368. float result[3];
  369. static const int MAX_VISITED = 16;
  370. dtPolyRef visited[MAX_VISITED];
  371. int nvisited = 0;
  372. dtStatus status = navquery->moveAlongSurface(m_path[0], m_pos, npos, filter,
  373. result, visited, &nvisited, MAX_VISITED);
  374. if (dtStatusSucceed(status)) {
  375. m_npath = dtMergeCorridorStartMoved(m_path, m_npath, m_maxPath, visited, nvisited);
  376. // Adjust the position to stay on top of the navmesh.
  377. float h = m_pos[1];
  378. navquery->getPolyHeight(m_path[0], result, &h);
  379. result[1] = h;
  380. dtVcopy(m_pos, result);
  381. return true;
  382. }
  383. return false;
  384. }
  385. /**
  386. @par
  387. Behavior:
  388. - The movement is constrained to the surface of the navigation mesh.
  389. - The corridor is automatically adjusted (shorted or lengthened) in order to remain valid.
  390. - The new target will be located in the adjusted corridor's last polygon.
  391. The expected use case is that the desired target will be 'near' the current corridor. What is considered 'near' depends on local polygon density, query search half extents, etc.
  392. The resulting target will differ from the desired target if the desired target is not on the navigation mesh, or it can't be reached using a local search.
  393. */
  394. bool dtPathCorridor::moveTargetPosition(const float* npos, dtNavMeshQuery* navquery, const dtQueryFilter* filter)
  395. {
  396. dtAssert(m_path);
  397. dtAssert(m_npath);
  398. // Move along navmesh and update new position.
  399. float result[3];
  400. static const int MAX_VISITED = 16;
  401. dtPolyRef visited[MAX_VISITED];
  402. int nvisited = 0;
  403. dtStatus status = navquery->moveAlongSurface(m_path[m_npath-1], m_target, npos, filter,
  404. result, visited, &nvisited, MAX_VISITED);
  405. if (dtStatusSucceed(status))
  406. {
  407. m_npath = dtMergeCorridorEndMoved(m_path, m_npath, m_maxPath, visited, nvisited);
  408. // TODO: should we do that?
  409. // Adjust the position to stay on top of the navmesh.
  410. /* float h = m_target[1];
  411. navquery->getPolyHeight(m_path[m_npath-1], result, &h);
  412. result[1] = h;*/
  413. dtVcopy(m_target, result);
  414. return true;
  415. }
  416. return false;
  417. }
  418. /// @par
  419. ///
  420. /// The current corridor position is expected to be within the first polygon in the path. The target
  421. /// is expected to be in the last polygon.
  422. ///
  423. /// @warning The size of the path must not exceed the size of corridor's path buffer set during #init().
  424. void dtPathCorridor::setCorridor(const float* target, const dtPolyRef* path, const int npath)
  425. {
  426. dtAssert(m_path);
  427. dtAssert(npath > 0);
  428. dtAssert(npath < m_maxPath);
  429. dtVcopy(m_target, target);
  430. memcpy(m_path, path, sizeof(dtPolyRef)*npath);
  431. m_npath = npath;
  432. }
  433. bool dtPathCorridor::fixPathStart(dtPolyRef safeRef, const float* safePos)
  434. {
  435. dtAssert(m_path);
  436. dtVcopy(m_pos, safePos);
  437. if (m_npath < 3 && m_npath > 0)
  438. {
  439. m_path[2] = m_path[m_npath-1];
  440. m_path[0] = safeRef;
  441. m_path[1] = 0;
  442. m_npath = 3;
  443. }
  444. else
  445. {
  446. m_path[0] = safeRef;
  447. m_path[1] = 0;
  448. }
  449. return true;
  450. }
  451. bool dtPathCorridor::trimInvalidPath(dtPolyRef safeRef, const float* safePos,
  452. dtNavMeshQuery* navquery, const dtQueryFilter* filter)
  453. {
  454. dtAssert(navquery);
  455. dtAssert(filter);
  456. dtAssert(m_path);
  457. // Keep valid path as far as possible.
  458. int n = 0;
  459. while (n < m_npath && navquery->isValidPolyRef(m_path[n], filter)) {
  460. n++;
  461. }
  462. if (n == m_npath)
  463. {
  464. // All valid, no need to fix.
  465. return true;
  466. }
  467. else if (n == 0)
  468. {
  469. // The first polyref is bad, use current safe values.
  470. dtVcopy(m_pos, safePos);
  471. m_path[0] = safeRef;
  472. m_npath = 1;
  473. }
  474. else
  475. {
  476. // The path is partially usable.
  477. m_npath = n;
  478. }
  479. // Clamp target pos to last poly
  480. float tgt[3];
  481. dtVcopy(tgt, m_target);
  482. navquery->closestPointOnPolyBoundary(m_path[m_npath-1], tgt, m_target);
  483. return true;
  484. }
  485. /// @par
  486. ///
  487. /// The path can be invalidated if there are structural changes to the underlying navigation mesh, or the state of
  488. /// a polygon within the path changes resulting in it being filtered out. (E.g. An exclusion or inclusion flag changes.)
  489. bool dtPathCorridor::isValid(const int maxLookAhead, dtNavMeshQuery* navquery, const dtQueryFilter* filter)
  490. {
  491. // Check that all polygons still pass query filter.
  492. const int n = dtMin(m_npath, maxLookAhead);
  493. for (int i = 0; i < n; ++i)
  494. {
  495. if (!navquery->isValidPolyRef(m_path[i], filter))
  496. return false;
  497. }
  498. return true;
  499. }