DetourNavMesh.cpp 42 KB

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