RecastContour.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. //
  2. // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
  3. //
  4. // This software is provided 'as-is', without any express or implied
  5. // warranty. In no event will the authors be held liable for any damages
  6. // arising from the use of this software.
  7. // Permission is granted to anyone to use this software for any purpose,
  8. // including commercial applications, and to alter it and redistribute it
  9. // freely, subject to the following restrictions:
  10. // 1. The origin of this software must not be misrepresented; you must not
  11. // claim that you wrote the original software. If you use this software
  12. // in a product, an acknowledgment in the product documentation would be
  13. // appreciated but is not required.
  14. // 2. Altered source versions must be plainly marked as such, and must not be
  15. // misrepresented as being the original software.
  16. // 3. This notice may not be removed or altered from any source distribution.
  17. //
  18. #include <math.h>
  19. #include <string.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include "Recast.h"
  23. #include "RecastAlloc.h"
  24. #include "RecastAssert.h"
  25. static int getCornerHeight(int x, int y, int i, int dir,
  26. const rcCompactHeightfield& chf,
  27. bool& isBorderVertex)
  28. {
  29. const rcCompactSpan& s = chf.spans[i];
  30. int ch = (int)s.y;
  31. int dirp = (dir+1) & 0x3;
  32. unsigned int regs[4] = {0,0,0,0};
  33. // Combine region and area codes in order to prevent
  34. // border vertices which are in between two areas to be removed.
  35. regs[0] = chf.spans[i].reg | (chf.areas[i] << 16);
  36. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  37. {
  38. const int ax = x + rcGetDirOffsetX(dir);
  39. const int ay = y + rcGetDirOffsetY(dir);
  40. const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
  41. const rcCompactSpan& as = chf.spans[ai];
  42. ch = rcMax(ch, (int)as.y);
  43. regs[1] = chf.spans[ai].reg | (chf.areas[ai] << 16);
  44. if (rcGetCon(as, dirp) != RC_NOT_CONNECTED)
  45. {
  46. const int ax2 = ax + rcGetDirOffsetX(dirp);
  47. const int ay2 = ay + rcGetDirOffsetY(dirp);
  48. const int ai2 = (int)chf.cells[ax2+ay2*chf.width].index + rcGetCon(as, dirp);
  49. const rcCompactSpan& as2 = chf.spans[ai2];
  50. ch = rcMax(ch, (int)as2.y);
  51. regs[2] = chf.spans[ai2].reg | (chf.areas[ai2] << 16);
  52. }
  53. }
  54. if (rcGetCon(s, dirp) != RC_NOT_CONNECTED)
  55. {
  56. const int ax = x + rcGetDirOffsetX(dirp);
  57. const int ay = y + rcGetDirOffsetY(dirp);
  58. const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dirp);
  59. const rcCompactSpan& as = chf.spans[ai];
  60. ch = rcMax(ch, (int)as.y);
  61. regs[3] = chf.spans[ai].reg | (chf.areas[ai] << 16);
  62. if (rcGetCon(as, dir) != RC_NOT_CONNECTED)
  63. {
  64. const int ax2 = ax + rcGetDirOffsetX(dir);
  65. const int ay2 = ay + rcGetDirOffsetY(dir);
  66. const int ai2 = (int)chf.cells[ax2+ay2*chf.width].index + rcGetCon(as, dir);
  67. const rcCompactSpan& as2 = chf.spans[ai2];
  68. ch = rcMax(ch, (int)as2.y);
  69. regs[2] = chf.spans[ai2].reg | (chf.areas[ai2] << 16);
  70. }
  71. }
  72. // Check if the vertex is special edge vertex, these vertices will be removed later.
  73. for (int j = 0; j < 4; ++j)
  74. {
  75. const int a = j;
  76. const int b = (j+1) & 0x3;
  77. const int c = (j+2) & 0x3;
  78. const int d = (j+3) & 0x3;
  79. // The vertex is a border vertex there are two same exterior cells in a row,
  80. // followed by two interior cells and none of the regions are out of bounds.
  81. const bool twoSameExts = (regs[a] & regs[b] & RC_BORDER_REG) != 0 && regs[a] == regs[b];
  82. const bool twoInts = ((regs[c] | regs[d]) & RC_BORDER_REG) == 0;
  83. const bool intsSameArea = (regs[c]>>16) == (regs[d]>>16);
  84. const bool noZeros = regs[a] != 0 && regs[b] != 0 && regs[c] != 0 && regs[d] != 0;
  85. if (twoSameExts && twoInts && intsSameArea && noZeros)
  86. {
  87. isBorderVertex = true;
  88. break;
  89. }
  90. }
  91. return ch;
  92. }
  93. static void walkContour(int x, int y, int i,
  94. const rcCompactHeightfield& chf,
  95. unsigned char* flags, rcIntArray& points)
  96. {
  97. // Choose the first non-connected edge
  98. unsigned char dir = 0;
  99. while ((flags[i] & (1 << dir)) == 0)
  100. dir++;
  101. unsigned char startDir = dir;
  102. int starti = i;
  103. const unsigned char area = chf.areas[i];
  104. int iter = 0;
  105. while (++iter < 40000)
  106. {
  107. if (flags[i] & (1 << dir))
  108. {
  109. // Choose the edge corner
  110. bool isBorderVertex = false;
  111. bool isAreaBorder = false;
  112. int px = x;
  113. int py = getCornerHeight(x, y, i, dir, chf, isBorderVertex);
  114. int pz = y;
  115. switch(dir)
  116. {
  117. case 0: pz++; break;
  118. case 1: px++; pz++; break;
  119. case 2: px++; break;
  120. }
  121. int r = 0;
  122. const rcCompactSpan& s = chf.spans[i];
  123. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  124. {
  125. const int ax = x + rcGetDirOffsetX(dir);
  126. const int ay = y + rcGetDirOffsetY(dir);
  127. const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
  128. r = (int)chf.spans[ai].reg;
  129. if (area != chf.areas[ai])
  130. isAreaBorder = true;
  131. }
  132. if (isBorderVertex)
  133. r |= RC_BORDER_VERTEX;
  134. if (isAreaBorder)
  135. r |= RC_AREA_BORDER;
  136. points.push(px);
  137. points.push(py);
  138. points.push(pz);
  139. points.push(r);
  140. flags[i] &= ~(1 << dir); // Remove visited edges
  141. dir = (dir+1) & 0x3; // Rotate CW
  142. }
  143. else
  144. {
  145. int ni = -1;
  146. const int nx = x + rcGetDirOffsetX(dir);
  147. const int ny = y + rcGetDirOffsetY(dir);
  148. const rcCompactSpan& s = chf.spans[i];
  149. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  150. {
  151. const rcCompactCell& nc = chf.cells[nx+ny*chf.width];
  152. ni = (int)nc.index + rcGetCon(s, dir);
  153. }
  154. if (ni == -1)
  155. {
  156. // Should not happen.
  157. return;
  158. }
  159. x = nx;
  160. y = ny;
  161. i = ni;
  162. dir = (dir+3) & 0x3; // Rotate CCW
  163. }
  164. if (starti == i && startDir == dir)
  165. {
  166. break;
  167. }
  168. }
  169. }
  170. static float distancePtSeg(const int x, const int z,
  171. const int px, const int pz,
  172. const int qx, const int qz)
  173. {
  174. float pqx = (float)(qx - px);
  175. float pqz = (float)(qz - pz);
  176. float dx = (float)(x - px);
  177. float dz = (float)(z - pz);
  178. float d = pqx*pqx + pqz*pqz;
  179. float t = pqx*dx + pqz*dz;
  180. if (d > 0)
  181. t /= d;
  182. if (t < 0)
  183. t = 0;
  184. else if (t > 1)
  185. t = 1;
  186. dx = px + t*pqx - x;
  187. dz = pz + t*pqz - z;
  188. return dx*dx + dz*dz;
  189. }
  190. static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
  191. const float maxError, const int maxEdgeLen, const int buildFlags)
  192. {
  193. // Add initial points.
  194. bool hasConnections = false;
  195. for (int i = 0; i < points.size(); i += 4)
  196. {
  197. if ((points[i+3] & RC_CONTOUR_REG_MASK) != 0)
  198. {
  199. hasConnections = true;
  200. break;
  201. }
  202. }
  203. if (hasConnections)
  204. {
  205. // The contour has some portals to other regions.
  206. // Add a new point to every location where the region changes.
  207. for (int i = 0, ni = points.size()/4; i < ni; ++i)
  208. {
  209. int ii = (i+1) % ni;
  210. const bool differentRegs = (points[i*4+3] & RC_CONTOUR_REG_MASK) != (points[ii*4+3] & RC_CONTOUR_REG_MASK);
  211. const bool areaBorders = (points[i*4+3] & RC_AREA_BORDER) != (points[ii*4+3] & RC_AREA_BORDER);
  212. if (differentRegs || areaBorders)
  213. {
  214. simplified.push(points[i*4+0]);
  215. simplified.push(points[i*4+1]);
  216. simplified.push(points[i*4+2]);
  217. simplified.push(i);
  218. }
  219. }
  220. }
  221. if (simplified.size() == 0)
  222. {
  223. // If there is no connections at all,
  224. // create some initial points for the simplification process.
  225. // Find lower-left and upper-right vertices of the contour.
  226. int llx = points[0];
  227. int lly = points[1];
  228. int llz = points[2];
  229. int lli = 0;
  230. int urx = points[0];
  231. int ury = points[1];
  232. int urz = points[2];
  233. int uri = 0;
  234. for (int i = 0; i < points.size(); i += 4)
  235. {
  236. int x = points[i+0];
  237. int y = points[i+1];
  238. int z = points[i+2];
  239. if (x < llx || (x == llx && z < llz))
  240. {
  241. llx = x;
  242. lly = y;
  243. llz = z;
  244. lli = i/4;
  245. }
  246. if (x > urx || (x == urx && z > urz))
  247. {
  248. urx = x;
  249. ury = y;
  250. urz = z;
  251. uri = i/4;
  252. }
  253. }
  254. simplified.push(llx);
  255. simplified.push(lly);
  256. simplified.push(llz);
  257. simplified.push(lli);
  258. simplified.push(urx);
  259. simplified.push(ury);
  260. simplified.push(urz);
  261. simplified.push(uri);
  262. }
  263. // Add points until all raw points are within
  264. // error tolerance to the simplified shape.
  265. const int pn = points.size()/4;
  266. for (int i = 0; i < simplified.size()/4; )
  267. {
  268. int ii = (i+1) % (simplified.size()/4);
  269. int ax = simplified[i*4+0];
  270. int az = simplified[i*4+2];
  271. int ai = simplified[i*4+3];
  272. int bx = simplified[ii*4+0];
  273. int bz = simplified[ii*4+2];
  274. int bi = simplified[ii*4+3];
  275. // Find maximum deviation from the segment.
  276. float maxd = 0;
  277. int maxi = -1;
  278. int ci, cinc, endi;
  279. // Traverse the segment in lexilogical order so that the
  280. // max deviation is calculated similarly when traversing
  281. // opposite segments.
  282. if (bx > ax || (bx == ax && bz > az))
  283. {
  284. cinc = 1;
  285. ci = (ai+cinc) % pn;
  286. endi = bi;
  287. }
  288. else
  289. {
  290. cinc = pn-1;
  291. ci = (bi+cinc) % pn;
  292. endi = ai;
  293. rcSwap(ax, bx);
  294. rcSwap(az, bz);
  295. }
  296. // Tessellate only outer edges or edges between areas.
  297. if ((points[ci*4+3] & RC_CONTOUR_REG_MASK) == 0 ||
  298. (points[ci*4+3] & RC_AREA_BORDER))
  299. {
  300. while (ci != endi)
  301. {
  302. float d = distancePtSeg(points[ci*4+0], points[ci*4+2], ax, az, bx, bz);
  303. if (d > maxd)
  304. {
  305. maxd = d;
  306. maxi = ci;
  307. }
  308. ci = (ci+cinc) % pn;
  309. }
  310. }
  311. // If the max deviation is larger than accepted error,
  312. // add new point, else continue to next segment.
  313. if (maxi != -1 && maxd > (maxError*maxError))
  314. {
  315. // Add space for the new point.
  316. simplified.resize(simplified.size()+4);
  317. const int n = simplified.size()/4;
  318. for (int j = n-1; j > i; --j)
  319. {
  320. simplified[j*4+0] = simplified[(j-1)*4+0];
  321. simplified[j*4+1] = simplified[(j-1)*4+1];
  322. simplified[j*4+2] = simplified[(j-1)*4+2];
  323. simplified[j*4+3] = simplified[(j-1)*4+3];
  324. }
  325. // Add the point.
  326. simplified[(i+1)*4+0] = points[maxi*4+0];
  327. simplified[(i+1)*4+1] = points[maxi*4+1];
  328. simplified[(i+1)*4+2] = points[maxi*4+2];
  329. simplified[(i+1)*4+3] = maxi;
  330. }
  331. else
  332. {
  333. ++i;
  334. }
  335. }
  336. // Split too long edges.
  337. if (maxEdgeLen > 0 && (buildFlags & (RC_CONTOUR_TESS_WALL_EDGES|RC_CONTOUR_TESS_AREA_EDGES)) != 0)
  338. {
  339. for (int i = 0; i < simplified.size()/4; )
  340. {
  341. const int ii = (i+1) % (simplified.size()/4);
  342. const int ax = simplified[i*4+0];
  343. const int az = simplified[i*4+2];
  344. const int ai = simplified[i*4+3];
  345. const int bx = simplified[ii*4+0];
  346. const int bz = simplified[ii*4+2];
  347. const int bi = simplified[ii*4+3];
  348. // Find maximum deviation from the segment.
  349. int maxi = -1;
  350. int ci = (ai+1) % pn;
  351. // Tessellate only outer edges or edges between areas.
  352. bool tess = false;
  353. // Wall edges.
  354. if ((buildFlags & RC_CONTOUR_TESS_WALL_EDGES) && (points[ci*4+3] & RC_CONTOUR_REG_MASK) == 0)
  355. tess = true;
  356. // Edges between areas.
  357. if ((buildFlags & RC_CONTOUR_TESS_AREA_EDGES) && (points[ci*4+3] & RC_AREA_BORDER))
  358. tess = true;
  359. if (tess)
  360. {
  361. int dx = bx - ax;
  362. int dz = bz - az;
  363. if (dx*dx + dz*dz > maxEdgeLen*maxEdgeLen)
  364. {
  365. // Round based on the segments in lexilogical order so that the
  366. // max tesselation is consistent regardles in which direction
  367. // segments are traversed.
  368. const int n = bi < ai ? (bi+pn - ai) : (bi - ai);
  369. if (n > 1)
  370. {
  371. if (bx > ax || (bx == ax && bz > az))
  372. maxi = (ai + n/2) % pn;
  373. else
  374. maxi = (ai + (n+1)/2) % pn;
  375. }
  376. }
  377. }
  378. // If the max deviation is larger than accepted error,
  379. // add new point, else continue to next segment.
  380. if (maxi != -1)
  381. {
  382. // Add space for the new point.
  383. simplified.resize(simplified.size()+4);
  384. const int n = simplified.size()/4;
  385. for (int j = n-1; j > i; --j)
  386. {
  387. simplified[j*4+0] = simplified[(j-1)*4+0];
  388. simplified[j*4+1] = simplified[(j-1)*4+1];
  389. simplified[j*4+2] = simplified[(j-1)*4+2];
  390. simplified[j*4+3] = simplified[(j-1)*4+3];
  391. }
  392. // Add the point.
  393. simplified[(i+1)*4+0] = points[maxi*4+0];
  394. simplified[(i+1)*4+1] = points[maxi*4+1];
  395. simplified[(i+1)*4+2] = points[maxi*4+2];
  396. simplified[(i+1)*4+3] = maxi;
  397. }
  398. else
  399. {
  400. ++i;
  401. }
  402. }
  403. }
  404. for (int i = 0; i < simplified.size()/4; ++i)
  405. {
  406. // The edge vertex flag is take from the current raw point,
  407. // and the neighbour region is take from the next raw point.
  408. const int ai = (simplified[i*4+3]+1) % pn;
  409. const int bi = simplified[i*4+3];
  410. simplified[i*4+3] = (points[ai*4+3] & (RC_CONTOUR_REG_MASK|RC_AREA_BORDER)) | (points[bi*4+3] & RC_BORDER_VERTEX);
  411. }
  412. }
  413. static int calcAreaOfPolygon2D(const int* verts, const int nverts)
  414. {
  415. int area = 0;
  416. for (int i = 0, j = nverts-1; i < nverts; j=i++)
  417. {
  418. const int* vi = &verts[i*4];
  419. const int* vj = &verts[j*4];
  420. area += vi[0] * vj[2] - vj[0] * vi[2];
  421. }
  422. return (area+1) / 2;
  423. }
  424. // TODO: these are the same as in RecastMesh.cpp, consider using the same.
  425. // Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
  426. inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
  427. inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
  428. inline int area2(const int* a, const int* b, const int* c)
  429. {
  430. return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]);
  431. }
  432. // Exclusive or: true iff exactly one argument is true.
  433. // The arguments are negated to ensure that they are 0/1
  434. // values. Then the bitwise Xor operator may apply.
  435. // (This idea is due to Michael Baldwin.)
  436. inline bool xorb(bool x, bool y)
  437. {
  438. return !x ^ !y;
  439. }
  440. // Returns true iff c is strictly to the left of the directed
  441. // line through a to b.
  442. inline bool left(const int* a, const int* b, const int* c)
  443. {
  444. return area2(a, b, c) < 0;
  445. }
  446. inline bool leftOn(const int* a, const int* b, const int* c)
  447. {
  448. return area2(a, b, c) <= 0;
  449. }
  450. inline bool collinear(const int* a, const int* b, const int* c)
  451. {
  452. return area2(a, b, c) == 0;
  453. }
  454. // Returns true iff ab properly intersects cd: they share
  455. // a point interior to both segments. The properness of the
  456. // intersection is ensured by using strict leftness.
  457. static bool intersectProp(const int* a, const int* b, const int* c, const int* d)
  458. {
  459. // Eliminate improper cases.
  460. if (collinear(a,b,c) || collinear(a,b,d) ||
  461. collinear(c,d,a) || collinear(c,d,b))
  462. return false;
  463. return xorb(left(a,b,c), left(a,b,d)) && xorb(left(c,d,a), left(c,d,b));
  464. }
  465. // Returns T iff (a,b,c) are collinear and point c lies
  466. // on the closed segement ab.
  467. static bool between(const int* a, const int* b, const int* c)
  468. {
  469. if (!collinear(a, b, c))
  470. return false;
  471. // If ab not vertical, check betweenness on x; else on y.
  472. if (a[0] != b[0])
  473. return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0]));
  474. else
  475. return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2]));
  476. }
  477. // Returns true iff segments ab and cd intersect, properly or improperly.
  478. static bool intersect(const int* a, const int* b, const int* c, const int* d)
  479. {
  480. if (intersectProp(a, b, c, d))
  481. return true;
  482. else if (between(a, b, c) || between(a, b, d) ||
  483. between(c, d, a) || between(c, d, b))
  484. return true;
  485. else
  486. return false;
  487. }
  488. static bool vequal(const int* a, const int* b)
  489. {
  490. return a[0] == b[0] && a[2] == b[2];
  491. }
  492. static bool intersectSegContour(const int* d0, const int* d1, int i, int n, const int* verts)
  493. {
  494. // For each edge (k,k+1) of P
  495. for (int k = 0; k < n; k++)
  496. {
  497. int k1 = next(k, n);
  498. // Skip edges incident to i.
  499. if (i == k || i == k1)
  500. continue;
  501. const int* p0 = &verts[k * 4];
  502. const int* p1 = &verts[k1 * 4];
  503. if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
  504. continue;
  505. if (intersect(d0, d1, p0, p1))
  506. return true;
  507. }
  508. return false;
  509. }
  510. static bool inCone(int i, int n, const int* verts, const int* pj)
  511. {
  512. const int* pi = &verts[i * 4];
  513. const int* pi1 = &verts[next(i, n) * 4];
  514. const int* pin1 = &verts[prev(i, n) * 4];
  515. // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
  516. if (leftOn(pin1, pi, pi1))
  517. return left(pi, pj, pin1) && left(pj, pi, pi1);
  518. // Assume (i-1,i,i+1) not collinear.
  519. // else P[i] is reflex.
  520. return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
  521. }
  522. static void removeDegenerateSegments(rcIntArray& simplified)
  523. {
  524. // Remove adjacent vertices which are equal on xz-plane,
  525. // or else the triangulator will get confused.
  526. int npts = simplified.size()/4;
  527. for (int i = 0; i < npts; ++i)
  528. {
  529. int ni = next(i, npts);
  530. if (vequal(&simplified[i*4], &simplified[ni*4]))
  531. {
  532. // Degenerate segment, remove.
  533. for (int j = i; j < simplified.size()/4-1; ++j)
  534. {
  535. simplified[j*4+0] = simplified[(j+1)*4+0];
  536. simplified[j*4+1] = simplified[(j+1)*4+1];
  537. simplified[j*4+2] = simplified[(j+1)*4+2];
  538. simplified[j*4+3] = simplified[(j+1)*4+3];
  539. }
  540. simplified.resize(simplified.size()-4);
  541. npts--;
  542. }
  543. }
  544. }
  545. static bool mergeContours(rcContour& ca, rcContour& cb, int ia, int ib)
  546. {
  547. const int maxVerts = ca.nverts + cb.nverts + 2;
  548. int* verts = (int*)rcAlloc(sizeof(int)*maxVerts*4, RC_ALLOC_PERM);
  549. if (!verts)
  550. return false;
  551. int nv = 0;
  552. // Copy contour A.
  553. for (int i = 0; i <= ca.nverts; ++i)
  554. {
  555. int* dst = &verts[nv*4];
  556. const int* src = &ca.verts[((ia+i)%ca.nverts)*4];
  557. dst[0] = src[0];
  558. dst[1] = src[1];
  559. dst[2] = src[2];
  560. dst[3] = src[3];
  561. nv++;
  562. }
  563. // Copy contour B
  564. for (int i = 0; i <= cb.nverts; ++i)
  565. {
  566. int* dst = &verts[nv*4];
  567. const int* src = &cb.verts[((ib+i)%cb.nverts)*4];
  568. dst[0] = src[0];
  569. dst[1] = src[1];
  570. dst[2] = src[2];
  571. dst[3] = src[3];
  572. nv++;
  573. }
  574. rcFree(ca.verts);
  575. ca.verts = verts;
  576. ca.nverts = nv;
  577. rcFree(cb.verts);
  578. cb.verts = 0;
  579. cb.nverts = 0;
  580. return true;
  581. }
  582. struct rcContourHole
  583. {
  584. rcContour* contour;
  585. int minx, minz, leftmost;
  586. };
  587. struct rcContourRegion
  588. {
  589. rcContour* outline;
  590. rcContourHole* holes;
  591. int nholes;
  592. };
  593. struct rcPotentialDiagonal
  594. {
  595. int vert;
  596. int dist;
  597. };
  598. // Finds the lowest leftmost vertex of a contour.
  599. static void findLeftMostVertex(rcContour* contour, int* minx, int* minz, int* leftmost)
  600. {
  601. *minx = contour->verts[0];
  602. *minz = contour->verts[2];
  603. *leftmost = 0;
  604. for (int i = 1; i < contour->nverts; i++)
  605. {
  606. const int x = contour->verts[i*4+0];
  607. const int z = contour->verts[i*4+2];
  608. if (x < *minx || (x == *minx && z < *minz))
  609. {
  610. *minx = x;
  611. *minz = z;
  612. *leftmost = i;
  613. }
  614. }
  615. }
  616. static int compareHoles(const void* va, const void* vb)
  617. {
  618. const rcContourHole* a = (const rcContourHole*)va;
  619. const rcContourHole* b = (const rcContourHole*)vb;
  620. if (a->minx == b->minx)
  621. {
  622. if (a->minz < b->minz)
  623. return -1;
  624. if (a->minz > b->minz)
  625. return 1;
  626. }
  627. else
  628. {
  629. if (a->minx < b->minx)
  630. return -1;
  631. if (a->minx > b->minx)
  632. return 1;
  633. }
  634. return 0;
  635. }
  636. static int compareDiagDist(const void* va, const void* vb)
  637. {
  638. const rcPotentialDiagonal* a = (const rcPotentialDiagonal*)va;
  639. const rcPotentialDiagonal* b = (const rcPotentialDiagonal*)vb;
  640. if (a->dist < b->dist)
  641. return -1;
  642. if (a->dist > b->dist)
  643. return 1;
  644. return 0;
  645. }
  646. static void mergeRegionHoles(rcContext* ctx, rcContourRegion& region)
  647. {
  648. // Sort holes from left to right.
  649. for (int i = 0; i < region.nholes; i++)
  650. findLeftMostVertex(region.holes[i].contour, &region.holes[i].minx, &region.holes[i].minz, &region.holes[i].leftmost);
  651. qsort(region.holes, region.nholes, sizeof(rcContourHole), compareHoles);
  652. int maxVerts = region.outline->nverts;
  653. for (int i = 0; i < region.nholes; i++)
  654. maxVerts += region.holes[i].contour->nverts;
  655. rcScopedDelete<rcPotentialDiagonal> diags((rcPotentialDiagonal*)rcAlloc(sizeof(rcPotentialDiagonal)*maxVerts, RC_ALLOC_TEMP));
  656. if (!diags)
  657. {
  658. ctx->log(RC_LOG_WARNING, "mergeRegionHoles: Failed to allocated diags %d.", maxVerts);
  659. return;
  660. }
  661. rcContour* outline = region.outline;
  662. // Merge holes into the outline one by one.
  663. for (int i = 0; i < region.nholes; i++)
  664. {
  665. rcContour* hole = region.holes[i].contour;
  666. int index = -1;
  667. int bestVertex = region.holes[i].leftmost;
  668. for (int iter = 0; iter < hole->nverts; iter++)
  669. {
  670. // Find potential diagonals.
  671. // The 'best' vertex must be in the cone described by 3 cosequtive vertices of the outline.
  672. // ..o j-1
  673. // |
  674. // | * best
  675. // |
  676. // j o-----o j+1
  677. // :
  678. int ndiags = 0;
  679. const int* corner = &hole->verts[bestVertex*4];
  680. for (int j = 0; j < outline->nverts; j++)
  681. {
  682. if (inCone(j, outline->nverts, outline->verts, corner))
  683. {
  684. int dx = outline->verts[j*4+0] - corner[0];
  685. int dz = outline->verts[j*4+2] - corner[2];
  686. diags[ndiags].vert = j;
  687. diags[ndiags].dist = dx*dx + dz*dz;
  688. ndiags++;
  689. }
  690. }
  691. // Sort potential diagonals by distance, we want to make the connection as short as possible.
  692. qsort(diags, ndiags, sizeof(rcPotentialDiagonal), compareDiagDist);
  693. // Find a diagonal that is not intersecting the outline not the remaining holes.
  694. index = -1;
  695. for (int j = 0; j < ndiags; j++)
  696. {
  697. const int* pt = &outline->verts[diags[j].vert*4];
  698. bool intersect = intersectSegContour(pt, corner, diags[i].vert, outline->nverts, outline->verts);
  699. for (int k = i; k < region.nholes && !intersect; k++)
  700. intersect |= intersectSegContour(pt, corner, -1, region.holes[k].contour->nverts, region.holes[k].contour->verts);
  701. if (!intersect)
  702. {
  703. index = diags[j].vert;
  704. break;
  705. }
  706. }
  707. // If found non-intersecting diagonal, stop looking.
  708. if (index != -1)
  709. break;
  710. // All the potential diagonals for the current vertex were intersecting, try next vertex.
  711. bestVertex = (bestVertex + 1) % hole->nverts;
  712. }
  713. if (index == -1)
  714. {
  715. ctx->log(RC_LOG_WARNING, "mergeHoles: Failed to find merge points for %p and %p.", region.outline, hole);
  716. continue;
  717. }
  718. if (!mergeContours(*region.outline, *hole, index, bestVertex))
  719. {
  720. ctx->log(RC_LOG_WARNING, "mergeHoles: Failed to merge contours %p and %p.", region.outline, hole);
  721. continue;
  722. }
  723. }
  724. }
  725. /// @par
  726. ///
  727. /// The raw contours will match the region outlines exactly. The @p maxError and @p maxEdgeLen
  728. /// parameters control how closely the simplified contours will match the raw contours.
  729. ///
  730. /// Simplified contours are generated such that the vertices for portals between areas match up.
  731. /// (They are considered mandatory vertices.)
  732. ///
  733. /// Setting @p maxEdgeLength to zero will disabled the edge length feature.
  734. ///
  735. /// See the #rcConfig documentation for more information on the configuration parameters.
  736. ///
  737. /// @see rcAllocContourSet, rcCompactHeightfield, rcContourSet, rcConfig
  738. bool rcBuildContours(rcContext* ctx, const rcCompactHeightfield& chf,
  739. const float maxError, const int maxEdgeLen,
  740. rcContourSet& cset, const int buildFlags)
  741. {
  742. rcAssert(ctx);
  743. const int w = chf.width;
  744. const int h = chf.height;
  745. const int borderSize = chf.borderSize;
  746. rcScopedTimer timer(ctx, RC_TIMER_BUILD_CONTOURS);
  747. rcVcopy(cset.bmin, chf.bmin);
  748. rcVcopy(cset.bmax, chf.bmax);
  749. if (borderSize > 0)
  750. {
  751. // If the heightfield was build with bordersize, remove the offset.
  752. const float pad = borderSize*chf.cs;
  753. cset.bmin[0] += pad;
  754. cset.bmin[2] += pad;
  755. cset.bmax[0] -= pad;
  756. cset.bmax[2] -= pad;
  757. }
  758. cset.cs = chf.cs;
  759. cset.ch = chf.ch;
  760. cset.width = chf.width - chf.borderSize*2;
  761. cset.height = chf.height - chf.borderSize*2;
  762. cset.borderSize = chf.borderSize;
  763. cset.maxError = maxError;
  764. int maxContours = rcMax((int)chf.maxRegions, 8);
  765. cset.conts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM);
  766. if (!cset.conts)
  767. return false;
  768. cset.nconts = 0;
  769. rcScopedDelete<unsigned char> flags((unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP));
  770. if (!flags)
  771. {
  772. ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'flags' (%d).", chf.spanCount);
  773. return false;
  774. }
  775. ctx->startTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
  776. // Mark boundaries.
  777. for (int y = 0; y < h; ++y)
  778. {
  779. for (int x = 0; x < w; ++x)
  780. {
  781. const rcCompactCell& c = chf.cells[x+y*w];
  782. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  783. {
  784. unsigned char res = 0;
  785. const rcCompactSpan& s = chf.spans[i];
  786. if (!chf.spans[i].reg || (chf.spans[i].reg & RC_BORDER_REG))
  787. {
  788. flags[i] = 0;
  789. continue;
  790. }
  791. for (int dir = 0; dir < 4; ++dir)
  792. {
  793. unsigned short r = 0;
  794. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  795. {
  796. const int ax = x + rcGetDirOffsetX(dir);
  797. const int ay = y + rcGetDirOffsetY(dir);
  798. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
  799. r = chf.spans[ai].reg;
  800. }
  801. if (r == chf.spans[i].reg)
  802. res |= (1 << dir);
  803. }
  804. flags[i] = res ^ 0xf; // Inverse, mark non connected edges.
  805. }
  806. }
  807. }
  808. ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
  809. rcIntArray verts(256);
  810. rcIntArray simplified(64);
  811. for (int y = 0; y < h; ++y)
  812. {
  813. for (int x = 0; x < w; ++x)
  814. {
  815. const rcCompactCell& c = chf.cells[x+y*w];
  816. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  817. {
  818. if (flags[i] == 0 || flags[i] == 0xf)
  819. {
  820. flags[i] = 0;
  821. continue;
  822. }
  823. const unsigned short reg = chf.spans[i].reg;
  824. if (!reg || (reg & RC_BORDER_REG))
  825. continue;
  826. const unsigned char area = chf.areas[i];
  827. verts.clear();
  828. simplified.clear();
  829. ctx->startTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
  830. walkContour(x, y, i, chf, flags, verts);
  831. ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
  832. ctx->startTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY);
  833. simplifyContour(verts, simplified, maxError, maxEdgeLen, buildFlags);
  834. removeDegenerateSegments(simplified);
  835. ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY);
  836. // Store region->contour remap info.
  837. // Create contour.
  838. if (simplified.size()/4 >= 3)
  839. {
  840. if (cset.nconts >= maxContours)
  841. {
  842. // Allocate more contours.
  843. // This happens when a region has holes.
  844. const int oldMax = maxContours;
  845. maxContours *= 2;
  846. rcContour* newConts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM);
  847. for (int j = 0; j < cset.nconts; ++j)
  848. {
  849. newConts[j] = cset.conts[j];
  850. // Reset source pointers to prevent data deletion.
  851. cset.conts[j].verts = 0;
  852. cset.conts[j].rverts = 0;
  853. }
  854. rcFree(cset.conts);
  855. cset.conts = newConts;
  856. ctx->log(RC_LOG_WARNING, "rcBuildContours: Expanding max contours from %d to %d.", oldMax, maxContours);
  857. }
  858. rcContour* cont = &cset.conts[cset.nconts++];
  859. cont->nverts = simplified.size()/4;
  860. cont->verts = (int*)rcAlloc(sizeof(int)*cont->nverts*4, RC_ALLOC_PERM);
  861. if (!cont->verts)
  862. {
  863. ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'verts' (%d).", cont->nverts);
  864. return false;
  865. }
  866. memcpy(cont->verts, &simplified[0], sizeof(int)*cont->nverts*4);
  867. if (borderSize > 0)
  868. {
  869. // If the heightfield was build with bordersize, remove the offset.
  870. for (int j = 0; j < cont->nverts; ++j)
  871. {
  872. int* v = &cont->verts[j*4];
  873. v[0] -= borderSize;
  874. v[2] -= borderSize;
  875. }
  876. }
  877. cont->nrverts = verts.size()/4;
  878. cont->rverts = (int*)rcAlloc(sizeof(int)*cont->nrverts*4, RC_ALLOC_PERM);
  879. if (!cont->rverts)
  880. {
  881. ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'rverts' (%d).", cont->nrverts);
  882. return false;
  883. }
  884. memcpy(cont->rverts, &verts[0], sizeof(int)*cont->nrverts*4);
  885. if (borderSize > 0)
  886. {
  887. // If the heightfield was build with bordersize, remove the offset.
  888. for (int j = 0; j < cont->nrverts; ++j)
  889. {
  890. int* v = &cont->rverts[j*4];
  891. v[0] -= borderSize;
  892. v[2] -= borderSize;
  893. }
  894. }
  895. cont->reg = reg;
  896. cont->area = area;
  897. }
  898. }
  899. }
  900. }
  901. // Merge holes if needed.
  902. if (cset.nconts > 0)
  903. {
  904. // Calculate winding of all polygons.
  905. rcScopedDelete<signed char> winding((signed char*)rcAlloc(sizeof(signed char)*cset.nconts, RC_ALLOC_TEMP));
  906. if (!winding)
  907. {
  908. ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'hole' (%d).", cset.nconts);
  909. return false;
  910. }
  911. int nholes = 0;
  912. for (int i = 0; i < cset.nconts; ++i)
  913. {
  914. rcContour& cont = cset.conts[i];
  915. // If the contour is wound backwards, it is a hole.
  916. winding[i] = calcAreaOfPolygon2D(cont.verts, cont.nverts) < 0 ? -1 : 1;
  917. if (winding[i] < 0)
  918. nholes++;
  919. }
  920. if (nholes > 0)
  921. {
  922. // Collect outline contour and holes contours per region.
  923. // We assume that there is one outline and multiple holes.
  924. const int nregions = chf.maxRegions+1;
  925. rcScopedDelete<rcContourRegion> regions((rcContourRegion*)rcAlloc(sizeof(rcContourRegion)*nregions, RC_ALLOC_TEMP));
  926. if (!regions)
  927. {
  928. ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'regions' (%d).", nregions);
  929. return false;
  930. }
  931. memset(regions, 0, sizeof(rcContourRegion)*nregions);
  932. rcScopedDelete<rcContourHole> holes((rcContourHole*)rcAlloc(sizeof(rcContourHole)*cset.nconts, RC_ALLOC_TEMP));
  933. if (!holes)
  934. {
  935. ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'holes' (%d).", cset.nconts);
  936. return false;
  937. }
  938. memset(holes, 0, sizeof(rcContourHole)*cset.nconts);
  939. for (int i = 0; i < cset.nconts; ++i)
  940. {
  941. rcContour& cont = cset.conts[i];
  942. // Positively would contours are outlines, negative holes.
  943. if (winding[i] > 0)
  944. {
  945. if (regions[cont.reg].outline)
  946. ctx->log(RC_LOG_ERROR, "rcBuildContours: Multiple outlines for region %d.", cont.reg);
  947. regions[cont.reg].outline = &cont;
  948. }
  949. else
  950. {
  951. regions[cont.reg].nholes++;
  952. }
  953. }
  954. int index = 0;
  955. for (int i = 0; i < nregions; i++)
  956. {
  957. if (regions[i].nholes > 0)
  958. {
  959. regions[i].holes = &holes[index];
  960. index += regions[i].nholes;
  961. regions[i].nholes = 0;
  962. }
  963. }
  964. for (int i = 0; i < cset.nconts; ++i)
  965. {
  966. rcContour& cont = cset.conts[i];
  967. rcContourRegion& reg = regions[cont.reg];
  968. if (winding[i] < 0)
  969. reg.holes[reg.nholes++].contour = &cont;
  970. }
  971. // Finally merge each regions holes into the outline.
  972. for (int i = 0; i < nregions; i++)
  973. {
  974. rcContourRegion& reg = regions[i];
  975. if (!reg.nholes) continue;
  976. if (reg.outline)
  977. {
  978. mergeRegionHoles(ctx, reg);
  979. }
  980. else
  981. {
  982. // The region does not have an outline.
  983. // This can happen if the contour becaomes selfoverlapping because of
  984. // too aggressive simplification settings.
  985. ctx->log(RC_LOG_ERROR, "rcBuildContours: Bad outline for region %d, contour simplification is likely too aggressive.", i);
  986. }
  987. }
  988. }
  989. }
  990. return true;
  991. }