DetourNavMesh.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. //
  2. // Copyright (c) 2009-2010 Mikko Mononen [email protected]
  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 <math.h>
  19. #include <float.h>
  20. #include <string.h>
  21. #include <stdio.h>
  22. #include "DetourNavMesh.h"
  23. #include "DetourNode.h"
  24. #include "DetourCommon.h"
  25. #include "DetourAlloc.h"
  26. #include "DetourAssert.h"
  27. #include <new>
  28. inline bool overlapSlabs(const float* amin, const float* amax,
  29. const float* bmin, const float* bmax,
  30. const float px, const float py)
  31. {
  32. // Check for horizontal overlap.
  33. // The segment is shrunken a little so that slabs which touch
  34. // at end points are not connected.
  35. const float minx = dtMax(amin[0]+px,bmin[0]+px);
  36. const float maxx = dtMin(amax[0]-px,bmax[0]-px);
  37. if (minx > maxx)
  38. return false;
  39. // Check vertical overlap.
  40. const float ad = (amax[1]-amin[1]) / (amax[0]-amin[0]);
  41. const float ak = amin[1] - ad*amin[0];
  42. const float bd = (bmax[1]-bmin[1]) / (bmax[0]-bmin[0]);
  43. const float bk = bmin[1] - bd*bmin[0];
  44. const float aminy = ad*minx + ak;
  45. const float amaxy = ad*maxx + ak;
  46. const float bminy = bd*minx + bk;
  47. const float bmaxy = bd*maxx + bk;
  48. const float dmin = bminy - aminy;
  49. const float dmax = bmaxy - amaxy;
  50. // Crossing segments always overlap.
  51. if (dmin*dmax < 0)
  52. return true;
  53. // Check for overlap at endpoints.
  54. const float thr = dtSqr(py*2);
  55. if (dmin*dmin <= thr || dmax*dmax <= thr)
  56. return true;
  57. return false;
  58. }
  59. static float getSlabCoord(const float* va, const int side)
  60. {
  61. if (side == 0 || side == 4)
  62. return va[0];
  63. else if (side == 2 || side == 6)
  64. return va[2];
  65. return 0;
  66. }
  67. static void calcSlabEndPoints(const float* va, const float* vb, float* bmin, float* bmax, const int side)
  68. {
  69. if (side == 0 || side == 4)
  70. {
  71. if (va[2] < vb[2])
  72. {
  73. bmin[0] = va[2];
  74. bmin[1] = va[1];
  75. bmax[0] = vb[2];
  76. bmax[1] = vb[1];
  77. }
  78. else
  79. {
  80. bmin[0] = vb[2];
  81. bmin[1] = vb[1];
  82. bmax[0] = va[2];
  83. bmax[1] = va[1];
  84. }
  85. }
  86. else if (side == 2 || side == 6)
  87. {
  88. if (va[0] < vb[0])
  89. {
  90. bmin[0] = va[0];
  91. bmin[1] = va[1];
  92. bmax[0] = vb[0];
  93. bmax[1] = vb[1];
  94. }
  95. else
  96. {
  97. bmin[0] = vb[0];
  98. bmin[1] = vb[1];
  99. bmax[0] = va[0];
  100. bmax[1] = va[1];
  101. }
  102. }
  103. }
  104. inline int computeTileHash(int x, int y, const int mask)
  105. {
  106. const unsigned int h1 = 0x8da6b343; // Large multiplicative constants;
  107. const unsigned int h2 = 0xd8163841; // here arbitrarily chosen primes
  108. unsigned int n = h1 * x + h2 * y;
  109. return (int)(n & mask);
  110. }
  111. inline unsigned int allocLink(dtMeshTile* tile)
  112. {
  113. if (tile->linksFreeList == DT_NULL_LINK)
  114. return DT_NULL_LINK;
  115. unsigned int link = tile->linksFreeList;
  116. tile->linksFreeList = tile->links[link].next;
  117. return link;
  118. }
  119. inline void freeLink(dtMeshTile* tile, unsigned int link)
  120. {
  121. tile->links[link].next = tile->linksFreeList;
  122. tile->linksFreeList = link;
  123. }
  124. dtNavMesh* dtAllocNavMesh()
  125. {
  126. void* mem = dtAlloc(sizeof(dtNavMesh), DT_ALLOC_PERM);
  127. if (!mem) return 0;
  128. return new(mem) dtNavMesh;
  129. }
  130. /// @par
  131. ///
  132. /// This function will only free the memory for tiles with the #DT_TILE_FREE_DATA
  133. /// flag set.
  134. void dtFreeNavMesh(dtNavMesh* navmesh)
  135. {
  136. if (!navmesh) return;
  137. navmesh->~dtNavMesh();
  138. dtFree(navmesh);
  139. }
  140. //////////////////////////////////////////////////////////////////////////////////////////
  141. /**
  142. @class dtNavMesh
  143. The navigation mesh consists of one or more tiles defining three primary types of structural data:
  144. A polygon mesh which defines most of the navigation graph. (See rcPolyMesh for its structure.)
  145. A detail mesh used for determining surface height on the polygon mesh. (See rcPolyMeshDetail for its structure.)
  146. Off-mesh connections, which define custom point-to-point edges within the navigation graph.
  147. The general build process is as follows:
  148. -# Create rcPolyMesh and rcPolyMeshDetail data using the Recast build pipeline.
  149. -# Optionally, create off-mesh connection data.
  150. -# Combine the source data into a dtNavMeshCreateParams structure.
  151. -# Create a tile data array using dtCreateNavMeshData().
  152. -# Allocate at dtNavMesh object and initialize it. (For single tile navigation meshes,
  153. the tile data is loaded during this step.)
  154. -# For multi-tile navigation meshes, load the tile data using dtNavMesh::addTile().
  155. Notes:
  156. - This class is usually used in conjunction with the dtNavMeshQuery class for pathfinding.
  157. - Technically, all navigation meshes are tiled. A 'solo' mesh is simply a navigation mesh initialized
  158. to have only a single tile.
  159. - This class does not implement any asynchronous methods. So the ::dtStatus result of all methods will
  160. always contain either a success or failure flag.
  161. @see dtNavMeshQuery, dtCreateNavMeshData, dtNavMeshCreateParams, #dtAllocNavMesh, #dtFreeNavMesh
  162. */
  163. dtNavMesh::dtNavMesh() :
  164. m_tileWidth(0),
  165. m_tileHeight(0),
  166. m_maxTiles(0),
  167. m_tileLutSize(0),
  168. m_tileLutMask(0),
  169. m_posLookup(0),
  170. m_nextFree(0),
  171. m_tiles(0),
  172. m_saltBits(0),
  173. m_tileBits(0),
  174. m_polyBits(0)
  175. {
  176. memset(&m_params, 0, sizeof(dtNavMeshParams));
  177. m_orig[0] = 0;
  178. m_orig[1] = 0;
  179. m_orig[2] = 0;
  180. }
  181. dtNavMesh::~dtNavMesh()
  182. {
  183. for (int i = 0; i < m_maxTiles; ++i)
  184. {
  185. if (m_tiles[i].flags & DT_TILE_FREE_DATA)
  186. {
  187. dtFree(m_tiles[i].data);
  188. m_tiles[i].data = 0;
  189. m_tiles[i].dataSize = 0;
  190. }
  191. }
  192. dtFree(m_posLookup);
  193. dtFree(m_tiles);
  194. }
  195. dtStatus dtNavMesh::init(const dtNavMeshParams* params)
  196. {
  197. memcpy(&m_params, params, sizeof(dtNavMeshParams));
  198. dtVcopy(m_orig, params->orig);
  199. m_tileWidth = params->tileWidth;
  200. m_tileHeight = params->tileHeight;
  201. // Init tiles
  202. m_maxTiles = params->maxTiles;
  203. m_tileLutSize = dtNextPow2(params->maxTiles/4);
  204. if (!m_tileLutSize) m_tileLutSize = 1;
  205. m_tileLutMask = m_tileLutSize-1;
  206. m_tiles = (dtMeshTile*)dtAlloc(sizeof(dtMeshTile)*m_maxTiles, DT_ALLOC_PERM);
  207. if (!m_tiles)
  208. return DT_FAILURE | DT_OUT_OF_MEMORY;
  209. m_posLookup = (dtMeshTile**)dtAlloc(sizeof(dtMeshTile*)*m_tileLutSize, DT_ALLOC_PERM);
  210. if (!m_posLookup)
  211. return DT_FAILURE | DT_OUT_OF_MEMORY;
  212. memset(m_tiles, 0, sizeof(dtMeshTile)*m_maxTiles);
  213. memset(m_posLookup, 0, sizeof(dtMeshTile*)*m_tileLutSize);
  214. m_nextFree = 0;
  215. for (int i = m_maxTiles-1; i >= 0; --i)
  216. {
  217. m_tiles[i].salt = 1;
  218. m_tiles[i].next = m_nextFree;
  219. m_nextFree = &m_tiles[i];
  220. }
  221. // Init ID generator values.
  222. m_tileBits = dtIlog2(dtNextPow2((unsigned int)params->maxTiles));
  223. m_polyBits = dtIlog2(dtNextPow2((unsigned int)params->maxPolys));
  224. // Only allow 31 salt bits, since the salt mask is calculated using 32bit uint and it will overflow.
  225. m_saltBits = dtMin((unsigned int)31, 32 - m_tileBits - m_polyBits);
  226. if (m_saltBits < 10)
  227. return DT_FAILURE | DT_INVALID_PARAM;
  228. return DT_SUCCESS;
  229. }
  230. dtStatus dtNavMesh::init(unsigned char* data, const int dataSize, const int flags)
  231. {
  232. // Make sure the data is in right format.
  233. dtMeshHeader* header = (dtMeshHeader*)data;
  234. if (header->magic != DT_NAVMESH_MAGIC)
  235. return DT_FAILURE | DT_WRONG_MAGIC;
  236. if (header->version != DT_NAVMESH_VERSION)
  237. return DT_FAILURE | DT_WRONG_VERSION;
  238. dtNavMeshParams params;
  239. dtVcopy(params.orig, header->bmin);
  240. params.tileWidth = header->bmax[0] - header->bmin[0];
  241. params.tileHeight = header->bmax[2] - header->bmin[2];
  242. params.maxTiles = 1;
  243. params.maxPolys = header->polyCount;
  244. dtStatus status = init(&params);
  245. if (dtStatusFailed(status))
  246. return status;
  247. return addTile(data, dataSize, flags, 0, 0);
  248. }
  249. /// @par
  250. ///
  251. /// @note The parameters are created automatically when the single tile
  252. /// initialization is performed.
  253. const dtNavMeshParams* dtNavMesh::getParams() const
  254. {
  255. return &m_params;
  256. }
  257. //////////////////////////////////////////////////////////////////////////////////////////
  258. int dtNavMesh::findConnectingPolys(const float* va, const float* vb,
  259. const dtMeshTile* tile, int side,
  260. dtPolyRef* con, float* conarea, int maxcon) const
  261. {
  262. if (!tile) return 0;
  263. float amin[2], amax[2];
  264. calcSlabEndPoints(va,vb, amin,amax, side);
  265. const float apos = getSlabCoord(va, side);
  266. // Remove links pointing to 'side' and compact the links array.
  267. float bmin[2], bmax[2];
  268. unsigned short m = DT_EXT_LINK | (unsigned short)side;
  269. int n = 0;
  270. dtPolyRef base = getPolyRefBase(tile);
  271. for (int i = 0; i < tile->header->polyCount; ++i)
  272. {
  273. dtPoly* poly = &tile->polys[i];
  274. const int nv = poly->vertCount;
  275. for (int j = 0; j < nv; ++j)
  276. {
  277. // Skip edges which do not point to the right side.
  278. if (poly->neis[j] != m) continue;
  279. const float* vc = &tile->verts[poly->verts[j]*3];
  280. const float* vd = &tile->verts[poly->verts[(j+1) % nv]*3];
  281. const float bpos = getSlabCoord(vc, side);
  282. // Segments are not close enough.
  283. if (dtAbs(apos-bpos) > 0.01f)
  284. continue;
  285. // Check if the segments touch.
  286. calcSlabEndPoints(vc,vd, bmin,bmax, side);
  287. if (!overlapSlabs(amin,amax, bmin,bmax, 0.01f, tile->header->walkableClimb)) continue;
  288. // Add return value.
  289. if (n < maxcon)
  290. {
  291. conarea[n*2+0] = dtMax(amin[0], bmin[0]);
  292. conarea[n*2+1] = dtMin(amax[0], bmax[0]);
  293. con[n] = base | (dtPolyRef)i;
  294. n++;
  295. }
  296. break;
  297. }
  298. }
  299. return n;
  300. }
  301. void dtNavMesh::unconnectExtLinks(dtMeshTile* tile, dtMeshTile* target)
  302. {
  303. if (!tile || !target) return;
  304. const unsigned int targetNum = decodePolyIdTile(getTileRef(target));
  305. for (int i = 0; i < tile->header->polyCount; ++i)
  306. {
  307. dtPoly* poly = &tile->polys[i];
  308. unsigned int j = poly->firstLink;
  309. unsigned int pj = DT_NULL_LINK;
  310. while (j != DT_NULL_LINK)
  311. {
  312. if (tile->links[j].side != 0xff &&
  313. decodePolyIdTile(tile->links[j].ref) == targetNum)
  314. {
  315. // Revove link.
  316. unsigned int nj = tile->links[j].next;
  317. if (pj == DT_NULL_LINK)
  318. poly->firstLink = nj;
  319. else
  320. tile->links[pj].next = nj;
  321. freeLink(tile, j);
  322. j = nj;
  323. }
  324. else
  325. {
  326. // Advance
  327. pj = j;
  328. j = tile->links[j].next;
  329. }
  330. }
  331. }
  332. }
  333. void dtNavMesh::connectExtLinks(dtMeshTile* tile, dtMeshTile* target, int side)
  334. {
  335. if (!tile) return;
  336. // Connect border links.
  337. for (int i = 0; i < tile->header->polyCount; ++i)
  338. {
  339. dtPoly* poly = &tile->polys[i];
  340. // Create new links.
  341. // unsigned short m = DT_EXT_LINK | (unsigned short)side;
  342. const int nv = poly->vertCount;
  343. for (int j = 0; j < nv; ++j)
  344. {
  345. // Skip non-portal edges.
  346. if ((poly->neis[j] & DT_EXT_LINK) == 0)
  347. continue;
  348. const int dir = (int)(poly->neis[j] & 0xff);
  349. if (side != -1 && dir != side)
  350. continue;
  351. // Create new links
  352. const float* va = &tile->verts[poly->verts[j]*3];
  353. const float* vb = &tile->verts[poly->verts[(j+1) % nv]*3];
  354. dtPolyRef nei[4];
  355. float neia[4*2];
  356. int nnei = findConnectingPolys(va,vb, target, dtOppositeTile(dir), nei,neia,4);
  357. for (int k = 0; k < nnei; ++k)
  358. {
  359. unsigned int idx = allocLink(tile);
  360. if (idx != DT_NULL_LINK)
  361. {
  362. dtLink* link = &tile->links[idx];
  363. link->ref = nei[k];
  364. link->edge = (unsigned char)j;
  365. link->side = (unsigned char)dir;
  366. link->next = poly->firstLink;
  367. poly->firstLink = idx;
  368. // Compress portal limits to a byte value.
  369. if (dir == 0 || dir == 4)
  370. {
  371. float tmin = (neia[k*2+0]-va[2]) / (vb[2]-va[2]);
  372. float tmax = (neia[k*2+1]-va[2]) / (vb[2]-va[2]);
  373. if (tmin > tmax)
  374. dtSwap(tmin,tmax);
  375. link->bmin = (unsigned char)(dtClamp(tmin, 0.0f, 1.0f)*255.0f);
  376. link->bmax = (unsigned char)(dtClamp(tmax, 0.0f, 1.0f)*255.0f);
  377. }
  378. else if (dir == 2 || dir == 6)
  379. {
  380. float tmin = (neia[k*2+0]-va[0]) / (vb[0]-va[0]);
  381. float tmax = (neia[k*2+1]-va[0]) / (vb[0]-va[0]);
  382. if (tmin > tmax)
  383. dtSwap(tmin,tmax);
  384. link->bmin = (unsigned char)(dtClamp(tmin, 0.0f, 1.0f)*255.0f);
  385. link->bmax = (unsigned char)(dtClamp(tmax, 0.0f, 1.0f)*255.0f);
  386. }
  387. }
  388. }
  389. }
  390. }
  391. }
  392. void dtNavMesh::connectExtOffMeshLinks(dtMeshTile* tile, dtMeshTile* target, int side)
  393. {
  394. if (!tile) return;
  395. // Connect off-mesh links.
  396. // We are interested on links which land from target tile to this tile.
  397. const unsigned char oppositeSide = (side == -1) ? 0xff : (unsigned char)dtOppositeTile(side);
  398. for (int i = 0; i < target->header->offMeshConCount; ++i)
  399. {
  400. dtOffMeshConnection* targetCon = &target->offMeshCons[i];
  401. if (targetCon->side != oppositeSide)
  402. continue;
  403. dtPoly* targetPoly = &target->polys[targetCon->poly];
  404. // Skip off-mesh connections which start location could not be connected at all.
  405. if (targetPoly->firstLink == DT_NULL_LINK)
  406. continue;
  407. const float ext[3] = { targetCon->rad, target->header->walkableClimb, targetCon->rad };
  408. // Find polygon to connect to.
  409. const float* p = &targetCon->pos[3];
  410. float nearestPt[3];
  411. dtPolyRef ref = findNearestPolyInTile(tile, p, ext, nearestPt);
  412. if (!ref)
  413. continue;
  414. // findNearestPoly may return too optimistic results, further check to make sure.
  415. if (dtSqr(nearestPt[0]-p[0])+dtSqr(nearestPt[2]-p[2]) > dtSqr(targetCon->rad))
  416. continue;
  417. // Make sure the location is on current mesh.
  418. float* v = &target->verts[targetPoly->verts[1]*3];
  419. dtVcopy(v, nearestPt);
  420. // Link off-mesh connection to target poly.
  421. unsigned int idx = allocLink(target);
  422. if (idx != DT_NULL_LINK)
  423. {
  424. dtLink* link = &target->links[idx];
  425. link->ref = ref;
  426. link->edge = (unsigned char)1;
  427. link->side = oppositeSide;
  428. link->bmin = link->bmax = 0;
  429. // Add to linked list.
  430. link->next = targetPoly->firstLink;
  431. targetPoly->firstLink = idx;
  432. }
  433. // Link target poly to off-mesh connection.
  434. if (targetCon->flags & DT_OFFMESH_CON_BIDIR)
  435. {
  436. unsigned int tidx = allocLink(tile);
  437. if (tidx != DT_NULL_LINK)
  438. {
  439. const unsigned short landPolyIdx = (unsigned short)decodePolyIdPoly(ref);
  440. dtPoly* landPoly = &tile->polys[landPolyIdx];
  441. dtLink* link = &tile->links[tidx];
  442. link->ref = getPolyRefBase(target) | (dtPolyRef)(targetCon->poly);
  443. link->edge = 0xff;
  444. link->side = (unsigned char)(side == -1 ? 0xff : side);
  445. link->bmin = link->bmax = 0;
  446. // Add to linked list.
  447. link->next = landPoly->firstLink;
  448. landPoly->firstLink = tidx;
  449. }
  450. }
  451. }
  452. }
  453. void dtNavMesh::connectIntLinks(dtMeshTile* tile)
  454. {
  455. if (!tile) return;
  456. dtPolyRef base = getPolyRefBase(tile);
  457. for (int i = 0; i < tile->header->polyCount; ++i)
  458. {
  459. dtPoly* poly = &tile->polys[i];
  460. poly->firstLink = DT_NULL_LINK;
  461. if (poly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
  462. continue;
  463. // Build edge links backwards so that the links will be
  464. // in the linked list from lowest index to highest.
  465. for (int j = poly->vertCount-1; j >= 0; --j)
  466. {
  467. // Skip hard and non-internal edges.
  468. if (poly->neis[j] == 0 || (poly->neis[j] & DT_EXT_LINK)) continue;
  469. unsigned int idx = allocLink(tile);
  470. if (idx != DT_NULL_LINK)
  471. {
  472. dtLink* link = &tile->links[idx];
  473. link->ref = base | (dtPolyRef)(poly->neis[j]-1);
  474. link->edge = (unsigned char)j;
  475. link->side = 0xff;
  476. link->bmin = link->bmax = 0;
  477. // Add to linked list.
  478. link->next = poly->firstLink;
  479. poly->firstLink = idx;
  480. }
  481. }
  482. }
  483. }
  484. void dtNavMesh::baseOffMeshLinks(dtMeshTile* tile)
  485. {
  486. if (!tile) return;
  487. dtPolyRef base = getPolyRefBase(tile);
  488. // Base off-mesh connection start points.
  489. for (int i = 0; i < tile->header->offMeshConCount; ++i)
  490. {
  491. dtOffMeshConnection* con = &tile->offMeshCons[i];
  492. dtPoly* poly = &tile->polys[con->poly];
  493. const float ext[3] = { con->rad, tile->header->walkableClimb, con->rad };
  494. // Find polygon to connect to.
  495. const float* p = &con->pos[0]; // First vertex
  496. float nearestPt[3];
  497. dtPolyRef ref = findNearestPolyInTile(tile, p, ext, nearestPt);
  498. if (!ref) continue;
  499. // findNearestPoly may return too optimistic results, further check to make sure.
  500. if (dtSqr(nearestPt[0]-p[0])+dtSqr(nearestPt[2]-p[2]) > dtSqr(con->rad))
  501. continue;
  502. // Make sure the location is on current mesh.
  503. float* v = &tile->verts[poly->verts[0]*3];
  504. dtVcopy(v, nearestPt);
  505. // Link off-mesh connection to target poly.
  506. unsigned int idx = allocLink(tile);
  507. if (idx != DT_NULL_LINK)
  508. {
  509. dtLink* link = &tile->links[idx];
  510. link->ref = ref;
  511. link->edge = (unsigned char)0;
  512. link->side = 0xff;
  513. link->bmin = link->bmax = 0;
  514. // Add to linked list.
  515. link->next = poly->firstLink;
  516. poly->firstLink = idx;
  517. }
  518. // Start end-point is always connect back to off-mesh connection.
  519. unsigned int tidx = allocLink(tile);
  520. if (tidx != DT_NULL_LINK)
  521. {
  522. const unsigned short landPolyIdx = (unsigned short)decodePolyIdPoly(ref);
  523. dtPoly* landPoly = &tile->polys[landPolyIdx];
  524. dtLink* link = &tile->links[tidx];
  525. link->ref = base | (dtPolyRef)(con->poly);
  526. link->edge = 0xff;
  527. link->side = 0xff;
  528. link->bmin = link->bmax = 0;
  529. // Add to linked list.
  530. link->next = landPoly->firstLink;
  531. landPoly->firstLink = tidx;
  532. }
  533. }
  534. }
  535. void dtNavMesh::closestPointOnPolyInTile(const dtMeshTile* tile, unsigned int ip,
  536. const float* pos, float* closest) const
  537. {
  538. const dtPoly* poly = &tile->polys[ip];
  539. // Off-mesh connections don't have detail polygons.
  540. if (poly->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
  541. {
  542. const float* v0 = &tile->verts[poly->verts[0]*3];
  543. const float* v1 = &tile->verts[poly->verts[1]*3];
  544. const float d0 = dtVdist(pos, v0);
  545. const float d1 = dtVdist(pos, v1);
  546. const float u = d0 / (d0+d1);
  547. dtVlerp(closest, v0, v1, u);
  548. return;
  549. }
  550. const dtPolyDetail* pd = &tile->detailMeshes[ip];
  551. // Clamp point to be inside the polygon.
  552. float verts[DT_VERTS_PER_POLYGON*3];
  553. float edged[DT_VERTS_PER_POLYGON];
  554. float edget[DT_VERTS_PER_POLYGON];
  555. const int nv = poly->vertCount;
  556. for (int i = 0; i < nv; ++i)
  557. dtVcopy(&verts[i*3], &tile->verts[poly->verts[i]*3]);
  558. dtVcopy(closest, pos);
  559. if (!dtDistancePtPolyEdgesSqr(pos, verts, nv, edged, edget))
  560. {
  561. // Point is outside the polygon, dtClamp to nearest edge.
  562. float dmin = FLT_MAX;
  563. int imin = -1;
  564. for (int i = 0; i < nv; ++i)
  565. {
  566. if (edged[i] < dmin)
  567. {
  568. dmin = edged[i];
  569. imin = i;
  570. }
  571. }
  572. const float* va = &verts[imin*3];
  573. const float* vb = &verts[((imin+1)%nv)*3];
  574. dtVlerp(closest, va, vb, edget[imin]);
  575. }
  576. // Find height at the location.
  577. for (int j = 0; j < pd->triCount; ++j)
  578. {
  579. const unsigned char* t = &tile->detailTris[(pd->triBase+j)*4];
  580. const float* v[3];
  581. for (int k = 0; k < 3; ++k)
  582. {
  583. if (t[k] < poly->vertCount)
  584. v[k] = &tile->verts[poly->verts[t[k]]*3];
  585. else
  586. v[k] = &tile->detailVerts[(pd->vertBase+(t[k]-poly->vertCount))*3];
  587. }
  588. float h;
  589. if (dtClosestHeightPointTriangle(pos, v[0], v[1], v[2], h))
  590. {
  591. closest[1] = h;
  592. break;
  593. }
  594. }
  595. }
  596. dtPolyRef dtNavMesh::findNearestPolyInTile(const dtMeshTile* tile,
  597. const float* center, const float* extents,
  598. float* nearestPt) const
  599. {
  600. float bmin[3], bmax[3];
  601. dtVsub(bmin, center, extents);
  602. dtVadd(bmax, center, extents);
  603. // Get nearby polygons from proximity grid.
  604. dtPolyRef polys[128];
  605. int polyCount = queryPolygonsInTile(tile, bmin, bmax, polys, 128);
  606. // Find nearest polygon amongst the nearby polygons.
  607. dtPolyRef nearest = 0;
  608. float nearestDistanceSqr = FLT_MAX;
  609. for (int i = 0; i < polyCount; ++i)
  610. {
  611. dtPolyRef ref = polys[i];
  612. float closestPtPoly[3];
  613. closestPointOnPolyInTile(tile, decodePolyIdPoly(ref), center, closestPtPoly);
  614. float d = dtVdistSqr(center, closestPtPoly);
  615. if (d < nearestDistanceSqr)
  616. {
  617. if (nearestPt)
  618. dtVcopy(nearestPt, closestPtPoly);
  619. nearestDistanceSqr = d;
  620. nearest = ref;
  621. }
  622. }
  623. return nearest;
  624. }
  625. int dtNavMesh::queryPolygonsInTile(const dtMeshTile* tile, const float* qmin, const float* qmax,
  626. dtPolyRef* polys, const int maxPolys) const
  627. {
  628. if (tile->bvTree)
  629. {
  630. const dtBVNode* node = &tile->bvTree[0];
  631. const dtBVNode* end = &tile->bvTree[tile->header->bvNodeCount];
  632. const float* tbmin = tile->header->bmin;
  633. const float* tbmax = tile->header->bmax;
  634. const float qfac = tile->header->bvQuantFactor;
  635. // Calculate quantized box
  636. unsigned short bmin[3], bmax[3];
  637. // dtClamp query box to world box.
  638. float minx = dtClamp(qmin[0], tbmin[0], tbmax[0]) - tbmin[0];
  639. float miny = dtClamp(qmin[1], tbmin[1], tbmax[1]) - tbmin[1];
  640. float minz = dtClamp(qmin[2], tbmin[2], tbmax[2]) - tbmin[2];
  641. float maxx = dtClamp(qmax[0], tbmin[0], tbmax[0]) - tbmin[0];
  642. float maxy = dtClamp(qmax[1], tbmin[1], tbmax[1]) - tbmin[1];
  643. float maxz = dtClamp(qmax[2], tbmin[2], tbmax[2]) - tbmin[2];
  644. // Quantize
  645. bmin[0] = (unsigned short)(qfac * minx) & 0xfffe;
  646. bmin[1] = (unsigned short)(qfac * miny) & 0xfffe;
  647. bmin[2] = (unsigned short)(qfac * minz) & 0xfffe;
  648. bmax[0] = (unsigned short)(qfac * maxx + 1) | 1;
  649. bmax[1] = (unsigned short)(qfac * maxy + 1) | 1;
  650. bmax[2] = (unsigned short)(qfac * maxz + 1) | 1;
  651. // Traverse tree
  652. dtPolyRef base = getPolyRefBase(tile);
  653. int n = 0;
  654. while (node < end)
  655. {
  656. const bool overlap = dtOverlapQuantBounds(bmin, bmax, node->bmin, node->bmax);
  657. const bool isLeafNode = node->i >= 0;
  658. if (isLeafNode && overlap)
  659. {
  660. if (n < maxPolys)
  661. polys[n++] = base | (dtPolyRef)node->i;
  662. }
  663. if (overlap || isLeafNode)
  664. node++;
  665. else
  666. {
  667. const int escapeIndex = -node->i;
  668. node += escapeIndex;
  669. }
  670. }
  671. return n;
  672. }
  673. else
  674. {
  675. float bmin[3], bmax[3];
  676. int n = 0;
  677. dtPolyRef base = getPolyRefBase(tile);
  678. for (int i = 0; i < tile->header->polyCount; ++i)
  679. {
  680. dtPoly* p = &tile->polys[i];
  681. // Do not return off-mesh connection polygons.
  682. if (p->getType() == DT_POLYTYPE_OFFMESH_CONNECTION)
  683. continue;
  684. // Calc polygon bounds.
  685. const float* v = &tile->verts[p->verts[0]*3];
  686. dtVcopy(bmin, v);
  687. dtVcopy(bmax, v);
  688. for (int j = 1; j < p->vertCount; ++j)
  689. {
  690. v = &tile->verts[p->verts[j]*3];
  691. dtVmin(bmin, v);
  692. dtVmax(bmax, v);
  693. }
  694. if (dtOverlapBounds(qmin,qmax, bmin,bmax))
  695. {
  696. if (n < maxPolys)
  697. polys[n++] = base | (dtPolyRef)i;
  698. }
  699. }
  700. return n;
  701. }
  702. }
  703. /// @par
  704. ///
  705. /// The add operation will fail if the data is in the wrong format, the allocated tile
  706. /// space is full, or there is a tile already at the specified reference.
  707. ///
  708. /// The lastRef parameter is used to restore a tile with the same tile
  709. /// reference it had previously used. In this case the #dtPolyRef's for the
  710. /// tile will be restored to the same values they were before the tile was
  711. /// removed.
  712. ///
  713. /// @see dtCreateNavMeshData, #removeTile
  714. dtStatus dtNavMesh::addTile(unsigned char* data, int dataSize, int flags,
  715. dtTileRef lastRef, dtTileRef* result)
  716. {
  717. // Make sure the data is in right format.
  718. dtMeshHeader* header = (dtMeshHeader*)data;
  719. if (header->magic != DT_NAVMESH_MAGIC)
  720. return DT_FAILURE | DT_WRONG_MAGIC;
  721. if (header->version != DT_NAVMESH_VERSION)
  722. return DT_FAILURE | DT_WRONG_VERSION;
  723. // Make sure the location is free.
  724. if (getTileAt(header->x, header->y, header->layer))
  725. return DT_FAILURE;
  726. // Allocate a tile.
  727. dtMeshTile* tile = 0;
  728. if (!lastRef)
  729. {
  730. if (m_nextFree)
  731. {
  732. tile = m_nextFree;
  733. m_nextFree = tile->next;
  734. tile->next = 0;
  735. }
  736. }
  737. else
  738. {
  739. // Try to relocate the tile to specific index with same salt.
  740. int tileIndex = (int)decodePolyIdTile((dtPolyRef)lastRef);
  741. if (tileIndex >= m_maxTiles)
  742. return DT_FAILURE | DT_OUT_OF_MEMORY;
  743. // Try to find the specific tile id from the free list.
  744. dtMeshTile* target = &m_tiles[tileIndex];
  745. dtMeshTile* prev = 0;
  746. tile = m_nextFree;
  747. while (tile && tile != target)
  748. {
  749. prev = tile;
  750. tile = tile->next;
  751. }
  752. // Could not find the correct location.
  753. if (tile != target)
  754. return DT_FAILURE | DT_OUT_OF_MEMORY;
  755. // Remove from freelist
  756. if (!prev)
  757. m_nextFree = tile->next;
  758. else
  759. prev->next = tile->next;
  760. // Restore salt.
  761. tile->salt = decodePolyIdSalt((dtPolyRef)lastRef);
  762. }
  763. // Make sure we could allocate a tile.
  764. if (!tile)
  765. return DT_FAILURE | DT_OUT_OF_MEMORY;
  766. // Insert tile into the position lut.
  767. int h = computeTileHash(header->x, header->y, m_tileLutMask);
  768. tile->next = m_posLookup[h];
  769. m_posLookup[h] = tile;
  770. // Patch header pointers.
  771. const int headerSize = dtAlign4(sizeof(dtMeshHeader));
  772. const int vertsSize = dtAlign4(sizeof(float)*3*header->vertCount);
  773. const int polysSize = dtAlign4(sizeof(dtPoly)*header->polyCount);
  774. const int linksSize = dtAlign4(sizeof(dtLink)*(header->maxLinkCount));
  775. const int detailMeshesSize = dtAlign4(sizeof(dtPolyDetail)*header->detailMeshCount);
  776. const int detailVertsSize = dtAlign4(sizeof(float)*3*header->detailVertCount);
  777. const int detailTrisSize = dtAlign4(sizeof(unsigned char)*4*header->detailTriCount);
  778. const int bvtreeSize = dtAlign4(sizeof(dtBVNode)*header->bvNodeCount);
  779. const int offMeshLinksSize = dtAlign4(sizeof(dtOffMeshConnection)*header->offMeshConCount);
  780. unsigned char* d = data + headerSize;
  781. tile->verts = (float*)d; d += vertsSize;
  782. tile->polys = (dtPoly*)d; d += polysSize;
  783. tile->links = (dtLink*)d; d += linksSize;
  784. tile->detailMeshes = (dtPolyDetail*)d; d += detailMeshesSize;
  785. tile->detailVerts = (float*)d; d += detailVertsSize;
  786. tile->detailTris = (unsigned char*)d; d += detailTrisSize;
  787. tile->bvTree = (dtBVNode*)d; d += bvtreeSize;
  788. tile->offMeshCons = (dtOffMeshConnection*)d; d += offMeshLinksSize;
  789. // If there are no items in the bvtree, reset the tree pointer.
  790. if (!bvtreeSize)
  791. tile->bvTree = 0;
  792. // Build links freelist
  793. tile->linksFreeList = 0;
  794. tile->links[header->maxLinkCount-1].next = DT_NULL_LINK;
  795. for (int i = 0; i < header->maxLinkCount-1; ++i)
  796. tile->links[i].next = i+1;
  797. // Init tile.
  798. tile->header = header;
  799. tile->data = data;
  800. tile->dataSize = dataSize;
  801. tile->flags = flags;
  802. connectIntLinks(tile);
  803. baseOffMeshLinks(tile);
  804. // Create connections with neighbour tiles.
  805. static const int MAX_NEIS = 32;
  806. dtMeshTile* neis[MAX_NEIS];
  807. int nneis;
  808. // Connect with layers in current tile.
  809. nneis = getTilesAt(header->x, header->y, neis, MAX_NEIS);
  810. for (int j = 0; j < nneis; ++j)
  811. {
  812. if (neis[j] != tile)
  813. {
  814. connectExtLinks(tile, neis[j], -1);
  815. connectExtLinks(neis[j], tile, -1);
  816. }
  817. connectExtOffMeshLinks(tile, neis[j], -1);
  818. connectExtOffMeshLinks(neis[j], tile, -1);
  819. }
  820. // Connect with neighbour tiles.
  821. for (int i = 0; i < 8; ++i)
  822. {
  823. nneis = getNeighbourTilesAt(header->x, header->y, i, neis, MAX_NEIS);
  824. for (int j = 0; j < nneis; ++j)
  825. {
  826. connectExtLinks(tile, neis[j], i);
  827. connectExtLinks(neis[j], tile, dtOppositeTile(i));
  828. connectExtOffMeshLinks(tile, neis[j], i);
  829. connectExtOffMeshLinks(neis[j], tile, dtOppositeTile(i));
  830. }
  831. }
  832. if (result)
  833. *result = getTileRef(tile);
  834. return DT_SUCCESS;
  835. }
  836. const dtMeshTile* dtNavMesh::getTileAt(const int x, const int y, const int layer) const
  837. {
  838. // Find tile based on hash.
  839. int h = computeTileHash(x,y,m_tileLutMask);
  840. dtMeshTile* tile = m_posLookup[h];
  841. while (tile)
  842. {
  843. if (tile->header &&
  844. tile->header->x == x &&
  845. tile->header->y == y &&
  846. tile->header->layer == layer)
  847. {
  848. return tile;
  849. }
  850. tile = tile->next;
  851. }
  852. return 0;
  853. }
  854. int dtNavMesh::getNeighbourTilesAt(const int x, const int y, const int side, dtMeshTile** tiles, const int maxTiles) const
  855. {
  856. int nx = x, ny = y;
  857. switch (side)
  858. {
  859. case 0: nx++; break;
  860. case 1: nx++; ny++; break;
  861. case 2: ny++; break;
  862. case 3: nx--; ny++; break;
  863. case 4: nx--; break;
  864. case 5: nx--; ny--; break;
  865. case 6: ny--; break;
  866. case 7: nx++; ny--; break;
  867. };
  868. return getTilesAt(nx, ny, tiles, maxTiles);
  869. }
  870. int dtNavMesh::getTilesAt(const int x, const int y, dtMeshTile** tiles, const int maxTiles) const
  871. {
  872. int n = 0;
  873. // Find tile based on hash.
  874. int h = computeTileHash(x,y,m_tileLutMask);
  875. dtMeshTile* tile = m_posLookup[h];
  876. while (tile)
  877. {
  878. if (tile->header &&
  879. tile->header->x == x &&
  880. tile->header->y == y)
  881. {
  882. if (n < maxTiles)
  883. tiles[n++] = tile;
  884. }
  885. tile = tile->next;
  886. }
  887. return n;
  888. }
  889. /// @par
  890. ///
  891. /// This function will not fail if the tiles array is too small to hold the
  892. /// entire result set. It will simply fill the array to capacity.
  893. int dtNavMesh::getTilesAt(const int x, const int y, dtMeshTile const** tiles, const int maxTiles) const
  894. {
  895. int n = 0;
  896. // Find tile based on hash.
  897. int h = computeTileHash(x,y,m_tileLutMask);
  898. dtMeshTile* tile = m_posLookup[h];
  899. while (tile)
  900. {
  901. if (tile->header &&
  902. tile->header->x == x &&
  903. tile->header->y == y)
  904. {
  905. if (n < maxTiles)
  906. tiles[n++] = tile;
  907. }
  908. tile = tile->next;
  909. }
  910. return n;
  911. }
  912. dtTileRef dtNavMesh::getTileRefAt(const int x, const int y, const int layer) const
  913. {
  914. // Find tile based on hash.
  915. int h = computeTileHash(x,y,m_tileLutMask);
  916. dtMeshTile* tile = m_posLookup[h];
  917. while (tile)
  918. {
  919. if (tile->header &&
  920. tile->header->x == x &&
  921. tile->header->y == y &&
  922. tile->header->layer == layer)
  923. {
  924. return getTileRef(tile);
  925. }
  926. tile = tile->next;
  927. }
  928. return 0;
  929. }
  930. const dtMeshTile* dtNavMesh::getTileByRef(dtTileRef ref) const
  931. {
  932. if (!ref)
  933. return 0;
  934. unsigned int tileIndex = decodePolyIdTile((dtPolyRef)ref);
  935. unsigned int tileSalt = decodePolyIdSalt((dtPolyRef)ref);
  936. if ((int)tileIndex >= m_maxTiles)
  937. return 0;
  938. const dtMeshTile* tile = &m_tiles[tileIndex];
  939. if (tile->salt != tileSalt)
  940. return 0;
  941. return tile;
  942. }
  943. int dtNavMesh::getMaxTiles() const
  944. {
  945. return m_maxTiles;
  946. }
  947. dtMeshTile* dtNavMesh::getTile(int i)
  948. {
  949. return &m_tiles[i];
  950. }
  951. const dtMeshTile* dtNavMesh::getTile(int i) const
  952. {
  953. return &m_tiles[i];
  954. }
  955. void dtNavMesh::calcTileLoc(const float* pos, int* tx, int* ty) const
  956. {
  957. *tx = (int)floorf((pos[0]-m_orig[0]) / m_tileWidth);
  958. *ty = (int)floorf((pos[2]-m_orig[2]) / m_tileHeight);
  959. }
  960. dtStatus dtNavMesh::getTileAndPolyByRef(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const
  961. {
  962. if (!ref) return DT_FAILURE;
  963. unsigned int salt, it, ip;
  964. decodePolyId(ref, salt, it, ip);
  965. if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
  966. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
  967. if (ip >= (unsigned int)m_tiles[it].header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
  968. *tile = &m_tiles[it];
  969. *poly = &m_tiles[it].polys[ip];
  970. return DT_SUCCESS;
  971. }
  972. /// @par
  973. ///
  974. /// @warning Only use this function if it is known that the provided polygon
  975. /// reference is valid. This function is faster than #getTileAndPolyByRef, but
  976. /// it does not validate the reference.
  977. void dtNavMesh::getTileAndPolyByRefUnsafe(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const
  978. {
  979. unsigned int salt, it, ip;
  980. decodePolyId(ref, salt, it, ip);
  981. *tile = &m_tiles[it];
  982. *poly = &m_tiles[it].polys[ip];
  983. }
  984. bool dtNavMesh::isValidPolyRef(dtPolyRef ref) const
  985. {
  986. if (!ref) return false;
  987. unsigned int salt, it, ip;
  988. decodePolyId(ref, salt, it, ip);
  989. if (it >= (unsigned int)m_maxTiles) return false;
  990. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return false;
  991. if (ip >= (unsigned int)m_tiles[it].header->polyCount) return false;
  992. return true;
  993. }
  994. /// @par
  995. ///
  996. /// This function returns the data for the tile so that, if desired,
  997. /// it can be added back to the navigation mesh at a later point.
  998. ///
  999. /// @see #addTile
  1000. dtStatus dtNavMesh::removeTile(dtTileRef ref, unsigned char** data, int* dataSize)
  1001. {
  1002. if (!ref)
  1003. return DT_FAILURE | DT_INVALID_PARAM;
  1004. unsigned int tileIndex = decodePolyIdTile((dtPolyRef)ref);
  1005. unsigned int tileSalt = decodePolyIdSalt((dtPolyRef)ref);
  1006. if ((int)tileIndex >= m_maxTiles)
  1007. return DT_FAILURE | DT_INVALID_PARAM;
  1008. dtMeshTile* tile = &m_tiles[tileIndex];
  1009. if (tile->salt != tileSalt)
  1010. return DT_FAILURE | DT_INVALID_PARAM;
  1011. // Remove tile from hash lookup.
  1012. int h = computeTileHash(tile->header->x,tile->header->y,m_tileLutMask);
  1013. dtMeshTile* prev = 0;
  1014. dtMeshTile* cur = m_posLookup[h];
  1015. while (cur)
  1016. {
  1017. if (cur == tile)
  1018. {
  1019. if (prev)
  1020. prev->next = cur->next;
  1021. else
  1022. m_posLookup[h] = cur->next;
  1023. break;
  1024. }
  1025. prev = cur;
  1026. cur = cur->next;
  1027. }
  1028. // Remove connections to neighbour tiles.
  1029. // Create connections with neighbour tiles.
  1030. static const int MAX_NEIS = 32;
  1031. dtMeshTile* neis[MAX_NEIS];
  1032. int nneis;
  1033. // Connect with layers in current tile.
  1034. nneis = getTilesAt(tile->header->x, tile->header->y, neis, MAX_NEIS);
  1035. for (int j = 0; j < nneis; ++j)
  1036. {
  1037. if (neis[j] == tile) continue;
  1038. unconnectExtLinks(neis[j], tile);
  1039. }
  1040. // Connect with neighbour tiles.
  1041. for (int i = 0; i < 8; ++i)
  1042. {
  1043. nneis = getNeighbourTilesAt(tile->header->x, tile->header->y, i, neis, MAX_NEIS);
  1044. for (int j = 0; j < nneis; ++j)
  1045. unconnectExtLinks(neis[j], tile);
  1046. }
  1047. // Reset tile.
  1048. if (tile->flags & DT_TILE_FREE_DATA)
  1049. {
  1050. // Owns data
  1051. dtFree(tile->data);
  1052. tile->data = 0;
  1053. tile->dataSize = 0;
  1054. if (data) *data = 0;
  1055. if (dataSize) *dataSize = 0;
  1056. }
  1057. else
  1058. {
  1059. if (data) *data = tile->data;
  1060. if (dataSize) *dataSize = tile->dataSize;
  1061. }
  1062. tile->header = 0;
  1063. tile->flags = 0;
  1064. tile->linksFreeList = 0;
  1065. tile->polys = 0;
  1066. tile->verts = 0;
  1067. tile->links = 0;
  1068. tile->detailMeshes = 0;
  1069. tile->detailVerts = 0;
  1070. tile->detailTris = 0;
  1071. tile->bvTree = 0;
  1072. tile->offMeshCons = 0;
  1073. // Update salt, salt should never be zero.
  1074. tile->salt = (tile->salt+1) & ((1<<m_saltBits)-1);
  1075. if (tile->salt == 0)
  1076. tile->salt++;
  1077. // Add to free list.
  1078. tile->next = m_nextFree;
  1079. m_nextFree = tile;
  1080. return DT_SUCCESS;
  1081. }
  1082. dtTileRef dtNavMesh::getTileRef(const dtMeshTile* tile) const
  1083. {
  1084. if (!tile) return 0;
  1085. const unsigned int it = (unsigned int)(tile - m_tiles);
  1086. return (dtTileRef)encodePolyId(tile->salt, it, 0);
  1087. }
  1088. /// @par
  1089. ///
  1090. /// Example use case:
  1091. /// @code
  1092. ///
  1093. /// const dtPolyRef base = navmesh->getPolyRefBase(tile);
  1094. /// for (int i = 0; i < tile->header->polyCount; ++i)
  1095. /// {
  1096. /// const dtPoly* p = &tile->polys[i];
  1097. /// const dtPolyRef ref = base | (dtPolyRef)i;
  1098. ///
  1099. /// // Use the reference to access the polygon data.
  1100. /// }
  1101. /// @endcode
  1102. dtPolyRef dtNavMesh::getPolyRefBase(const dtMeshTile* tile) const
  1103. {
  1104. if (!tile) return 0;
  1105. const unsigned int it = (unsigned int)(tile - m_tiles);
  1106. return encodePolyId(tile->salt, it, 0);
  1107. }
  1108. struct dtTileState
  1109. {
  1110. int magic; // Magic number, used to identify the data.
  1111. int version; // Data version number.
  1112. dtTileRef ref; // Tile ref at the time of storing the data.
  1113. };
  1114. struct dtPolyState
  1115. {
  1116. unsigned short flags; // Flags (see dtPolyFlags).
  1117. unsigned char area; // Area ID of the polygon.
  1118. };
  1119. /// @see #storeTileState
  1120. int dtNavMesh::getTileStateSize(const dtMeshTile* tile) const
  1121. {
  1122. if (!tile) return 0;
  1123. const int headerSize = dtAlign4(sizeof(dtTileState));
  1124. const int polyStateSize = dtAlign4(sizeof(dtPolyState) * tile->header->polyCount);
  1125. return headerSize + polyStateSize;
  1126. }
  1127. /// @par
  1128. ///
  1129. /// Tile state includes non-structural data such as polygon flags, area ids, etc.
  1130. /// @note The state data is only valid until the tile reference changes.
  1131. /// @see #getTileStateSize, #restoreTileState
  1132. dtStatus dtNavMesh::storeTileState(const dtMeshTile* tile, unsigned char* data, const int maxDataSize) const
  1133. {
  1134. // Make sure there is enough space to store the state.
  1135. const int sizeReq = getTileStateSize(tile);
  1136. if (maxDataSize < sizeReq)
  1137. return DT_FAILURE | DT_BUFFER_TOO_SMALL;
  1138. dtTileState* tileState = (dtTileState*)data; data += dtAlign4(sizeof(dtTileState));
  1139. dtPolyState* polyStates = (dtPolyState*)data; data += dtAlign4(sizeof(dtPolyState) * tile->header->polyCount);
  1140. // Store tile state.
  1141. tileState->magic = DT_NAVMESH_STATE_MAGIC;
  1142. tileState->version = DT_NAVMESH_STATE_VERSION;
  1143. tileState->ref = getTileRef(tile);
  1144. // Store per poly state.
  1145. for (int i = 0; i < tile->header->polyCount; ++i)
  1146. {
  1147. const dtPoly* p = &tile->polys[i];
  1148. dtPolyState* s = &polyStates[i];
  1149. s->flags = p->flags;
  1150. s->area = p->getArea();
  1151. }
  1152. return DT_SUCCESS;
  1153. }
  1154. /// @par
  1155. ///
  1156. /// Tile state includes non-structural data such as polygon flags, area ids, etc.
  1157. /// @note This function does not impact the tile's #dtTileRef and #dtPolyRef's.
  1158. /// @see #storeTileState
  1159. dtStatus dtNavMesh::restoreTileState(dtMeshTile* tile, const unsigned char* data, const int maxDataSize)
  1160. {
  1161. // Make sure there is enough space to store the state.
  1162. const int sizeReq = getTileStateSize(tile);
  1163. if (maxDataSize < sizeReq)
  1164. return DT_FAILURE | DT_INVALID_PARAM;
  1165. const dtTileState* tileState = (const dtTileState*)data; data += dtAlign4(sizeof(dtTileState));
  1166. const dtPolyState* polyStates = (const dtPolyState*)data; data += dtAlign4(sizeof(dtPolyState) * tile->header->polyCount);
  1167. // Check that the restore is possible.
  1168. if (tileState->magic != DT_NAVMESH_STATE_MAGIC)
  1169. return DT_FAILURE | DT_WRONG_MAGIC;
  1170. if (tileState->version != DT_NAVMESH_STATE_VERSION)
  1171. return DT_FAILURE | DT_WRONG_VERSION;
  1172. if (tileState->ref != getTileRef(tile))
  1173. return DT_FAILURE | DT_INVALID_PARAM;
  1174. // Restore per poly state.
  1175. for (int i = 0; i < tile->header->polyCount; ++i)
  1176. {
  1177. dtPoly* p = &tile->polys[i];
  1178. const dtPolyState* s = &polyStates[i];
  1179. p->flags = s->flags;
  1180. p->setArea(s->area);
  1181. }
  1182. return DT_SUCCESS;
  1183. }
  1184. /// @par
  1185. ///
  1186. /// Off-mesh connections are stored in the navigation mesh as special 2-vertex
  1187. /// polygons with a single edge. At least one of the vertices is expected to be
  1188. /// inside a normal polygon. So an off-mesh connection is "entered" from a
  1189. /// normal polygon at one of its endpoints. This is the polygon identified by
  1190. /// the prevRef parameter.
  1191. dtStatus dtNavMesh::getOffMeshConnectionPolyEndPoints(dtPolyRef prevRef, dtPolyRef polyRef, float* startPos, float* endPos) const
  1192. {
  1193. unsigned int salt, it, ip;
  1194. if (!polyRef)
  1195. return DT_FAILURE;
  1196. // Get current polygon
  1197. decodePolyId(polyRef, salt, it, ip);
  1198. if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
  1199. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
  1200. const dtMeshTile* tile = &m_tiles[it];
  1201. if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
  1202. const dtPoly* poly = &tile->polys[ip];
  1203. // Make sure that the current poly is indeed off-mesh link.
  1204. if (poly->getType() != DT_POLYTYPE_OFFMESH_CONNECTION)
  1205. return DT_FAILURE;
  1206. // Figure out which way to hand out the vertices.
  1207. int idx0 = 0, idx1 = 1;
  1208. // Find link that points to first vertex.
  1209. for (unsigned int i = poly->firstLink; i != DT_NULL_LINK; i = tile->links[i].next)
  1210. {
  1211. if (tile->links[i].edge == 0)
  1212. {
  1213. if (tile->links[i].ref != prevRef)
  1214. {
  1215. idx0 = 1;
  1216. idx1 = 0;
  1217. }
  1218. break;
  1219. }
  1220. }
  1221. dtVcopy(startPos, &tile->verts[poly->verts[idx0]*3]);
  1222. dtVcopy(endPos, &tile->verts[poly->verts[idx1]*3]);
  1223. return DT_SUCCESS;
  1224. }
  1225. const dtOffMeshConnection* dtNavMesh::getOffMeshConnectionByRef(dtPolyRef ref) const
  1226. {
  1227. unsigned int salt, it, ip;
  1228. if (!ref)
  1229. return 0;
  1230. // Get current polygon
  1231. decodePolyId(ref, salt, it, ip);
  1232. if (it >= (unsigned int)m_maxTiles) return 0;
  1233. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return 0;
  1234. const dtMeshTile* tile = &m_tiles[it];
  1235. if (ip >= (unsigned int)tile->header->polyCount) return 0;
  1236. const dtPoly* poly = &tile->polys[ip];
  1237. // Make sure that the current poly is indeed off-mesh link.
  1238. if (poly->getType() != DT_POLYTYPE_OFFMESH_CONNECTION)
  1239. return 0;
  1240. const unsigned int idx = ip - tile->header->offMeshBase;
  1241. dtAssert(idx < (unsigned int)tile->header->offMeshConCount);
  1242. return &tile->offMeshCons[idx];
  1243. }
  1244. dtStatus dtNavMesh::setPolyFlags(dtPolyRef ref, unsigned short flags)
  1245. {
  1246. if (!ref) return DT_FAILURE;
  1247. unsigned int salt, it, ip;
  1248. decodePolyId(ref, salt, it, ip);
  1249. if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
  1250. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
  1251. dtMeshTile* tile = &m_tiles[it];
  1252. if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
  1253. dtPoly* poly = &tile->polys[ip];
  1254. // Change flags.
  1255. poly->flags = flags;
  1256. return DT_SUCCESS;
  1257. }
  1258. dtStatus dtNavMesh::getPolyFlags(dtPolyRef ref, unsigned short* resultFlags) const
  1259. {
  1260. if (!ref) return DT_FAILURE;
  1261. unsigned int salt, it, ip;
  1262. decodePolyId(ref, salt, it, ip);
  1263. if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
  1264. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
  1265. const dtMeshTile* tile = &m_tiles[it];
  1266. if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
  1267. const dtPoly* poly = &tile->polys[ip];
  1268. *resultFlags = poly->flags;
  1269. return DT_SUCCESS;
  1270. }
  1271. dtStatus dtNavMesh::setPolyArea(dtPolyRef ref, unsigned char area)
  1272. {
  1273. if (!ref) return DT_FAILURE;
  1274. unsigned int salt, it, ip;
  1275. decodePolyId(ref, salt, it, ip);
  1276. if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
  1277. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
  1278. dtMeshTile* tile = &m_tiles[it];
  1279. if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
  1280. dtPoly* poly = &tile->polys[ip];
  1281. poly->setArea(area);
  1282. return DT_SUCCESS;
  1283. }
  1284. dtStatus dtNavMesh::getPolyArea(dtPolyRef ref, unsigned char* resultArea) const
  1285. {
  1286. if (!ref) return DT_FAILURE;
  1287. unsigned int salt, it, ip;
  1288. decodePolyId(ref, salt, it, ip);
  1289. if (it >= (unsigned int)m_maxTiles) return DT_FAILURE | DT_INVALID_PARAM;
  1290. if (m_tiles[it].salt != salt || m_tiles[it].header == 0) return DT_FAILURE | DT_INVALID_PARAM;
  1291. const dtMeshTile* tile = &m_tiles[it];
  1292. if (ip >= (unsigned int)tile->header->polyCount) return DT_FAILURE | DT_INVALID_PARAM;
  1293. const dtPoly* poly = &tile->polys[ip];
  1294. *resultArea = poly->getArea();
  1295. return DT_SUCCESS;
  1296. }