RecastContour.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  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. #define _USE_MATH_DEFINES
  19. #include <math.h>
  20. #include <string.h>
  21. #include <stdio.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. 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 pqy = (float)(qy - py);
  176. float pqz = (float)(qz - pz);
  177. float dx = (float)(x - px);
  178. float dy = (float)(y - py);
  179. float dz = (float)(z - pz);
  180. float d = pqx*pqx + pqy*pqy + pqz*pqz;
  181. float t = pqx*dx + pqy*dy + pqz*dz;
  182. if (d > 0)
  183. t /= d;
  184. if (t < 0)
  185. t = 0;
  186. else if (t > 1)
  187. t = 1;
  188. dx = px + t*pqx - x;
  189. dy = py + t*pqy - y;
  190. dz = pz + t*pqz - z;
  191. return dx*dx + dy*dy + dz*dz;*/
  192. float pqx = (float)(qx - px);
  193. float pqz = (float)(qz - pz);
  194. float dx = (float)(x - px);
  195. float dz = (float)(z - pz);
  196. float d = pqx*pqx + pqz*pqz;
  197. float t = pqx*dx + pqz*dz;
  198. if (d > 0)
  199. t /= d;
  200. if (t < 0)
  201. t = 0;
  202. else if (t > 1)
  203. t = 1;
  204. dx = px + t*pqx - x;
  205. dz = pz + t*pqz - z;
  206. return dx*dx + dz*dz;
  207. }
  208. static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
  209. const float maxError, const int maxEdgeLen, const int buildFlags)
  210. {
  211. // Add initial points.
  212. bool hasConnections = false;
  213. for (int i = 0; i < points.size(); i += 4)
  214. {
  215. if ((points[i+3] & RC_CONTOUR_REG_MASK) != 0)
  216. {
  217. hasConnections = true;
  218. break;
  219. }
  220. }
  221. if (hasConnections)
  222. {
  223. // The contour has some portals to other regions.
  224. // Add a new point to every location where the region changes.
  225. for (int i = 0, ni = points.size()/4; i < ni; ++i)
  226. {
  227. int ii = (i+1) % ni;
  228. const bool differentRegs = (points[i*4+3] & RC_CONTOUR_REG_MASK) != (points[ii*4+3] & RC_CONTOUR_REG_MASK);
  229. const bool areaBorders = (points[i*4+3] & RC_AREA_BORDER) != (points[ii*4+3] & RC_AREA_BORDER);
  230. if (differentRegs || areaBorders)
  231. {
  232. simplified.push(points[i*4+0]);
  233. simplified.push(points[i*4+1]);
  234. simplified.push(points[i*4+2]);
  235. simplified.push(i);
  236. }
  237. }
  238. }
  239. if (simplified.size() == 0)
  240. {
  241. // If there is no connections at all,
  242. // create some initial points for the simplification process.
  243. // Find lower-left and upper-right vertices of the contour.
  244. int llx = points[0];
  245. int lly = points[1];
  246. int llz = points[2];
  247. int lli = 0;
  248. int urx = points[0];
  249. int ury = points[1];
  250. int urz = points[2];
  251. int uri = 0;
  252. for (int i = 0; i < points.size(); i += 4)
  253. {
  254. int x = points[i+0];
  255. int y = points[i+1];
  256. int z = points[i+2];
  257. if (x < llx || (x == llx && z < llz))
  258. {
  259. llx = x;
  260. lly = y;
  261. llz = z;
  262. lli = i/4;
  263. }
  264. if (x > urx || (x == urx && z > urz))
  265. {
  266. urx = x;
  267. ury = y;
  268. urz = z;
  269. uri = i/4;
  270. }
  271. }
  272. simplified.push(llx);
  273. simplified.push(lly);
  274. simplified.push(llz);
  275. simplified.push(lli);
  276. simplified.push(urx);
  277. simplified.push(ury);
  278. simplified.push(urz);
  279. simplified.push(uri);
  280. }
  281. // Add points until all raw points are within
  282. // error tolerance to the simplified shape.
  283. const int pn = points.size()/4;
  284. for (int i = 0; i < simplified.size()/4; )
  285. {
  286. int ii = (i+1) % (simplified.size()/4);
  287. const int ax = simplified[i*4+0];
  288. const int az = simplified[i*4+2];
  289. const int ai = simplified[i*4+3];
  290. const int bx = simplified[ii*4+0];
  291. const int bz = simplified[ii*4+2];
  292. const int bi = simplified[ii*4+3];
  293. // Find maximum deviation from the segment.
  294. float maxd = 0;
  295. int maxi = -1;
  296. int ci, cinc, endi;
  297. // Traverse the segment in lexilogical order so that the
  298. // max deviation is calculated similarly when traversing
  299. // opposite segments.
  300. if (bx > ax || (bx == ax && bz > az))
  301. {
  302. cinc = 1;
  303. ci = (ai+cinc) % pn;
  304. endi = bi;
  305. }
  306. else
  307. {
  308. cinc = pn-1;
  309. ci = (bi+cinc) % pn;
  310. endi = ai;
  311. }
  312. // Tessellate only outer edges or edges between areas.
  313. if ((points[ci*4+3] & RC_CONTOUR_REG_MASK) == 0 ||
  314. (points[ci*4+3] & RC_AREA_BORDER))
  315. {
  316. while (ci != endi)
  317. {
  318. float d = distancePtSeg(points[ci*4+0], points[ci*4+2], ax, az, bx, bz);
  319. if (d > maxd)
  320. {
  321. maxd = d;
  322. maxi = ci;
  323. }
  324. ci = (ci+cinc) % pn;
  325. }
  326. }
  327. // If the max deviation is larger than accepted error,
  328. // add new point, else continue to next segment.
  329. if (maxi != -1 && maxd > (maxError*maxError))
  330. {
  331. // Add space for the new point.
  332. simplified.resize(simplified.size()+4);
  333. const int n = simplified.size()/4;
  334. for (int j = n-1; j > i; --j)
  335. {
  336. simplified[j*4+0] = simplified[(j-1)*4+0];
  337. simplified[j*4+1] = simplified[(j-1)*4+1];
  338. simplified[j*4+2] = simplified[(j-1)*4+2];
  339. simplified[j*4+3] = simplified[(j-1)*4+3];
  340. }
  341. // Add the point.
  342. simplified[(i+1)*4+0] = points[maxi*4+0];
  343. simplified[(i+1)*4+1] = points[maxi*4+1];
  344. simplified[(i+1)*4+2] = points[maxi*4+2];
  345. simplified[(i+1)*4+3] = maxi;
  346. }
  347. else
  348. {
  349. ++i;
  350. }
  351. }
  352. // Split too long edges.
  353. if (maxEdgeLen > 0 && (buildFlags & (RC_CONTOUR_TESS_WALL_EDGES|RC_CONTOUR_TESS_AREA_EDGES)) != 0)
  354. {
  355. for (int i = 0; i < simplified.size()/4; )
  356. {
  357. const int ii = (i+1) % (simplified.size()/4);
  358. const int ax = simplified[i*4+0];
  359. const int az = simplified[i*4+2];
  360. const int ai = simplified[i*4+3];
  361. const int bx = simplified[ii*4+0];
  362. const int bz = simplified[ii*4+2];
  363. const int bi = simplified[ii*4+3];
  364. // Find maximum deviation from the segment.
  365. int maxi = -1;
  366. int ci = (ai+1) % pn;
  367. // Tessellate only outer edges or edges between areas.
  368. bool tess = false;
  369. // Wall edges.
  370. if ((buildFlags & RC_CONTOUR_TESS_WALL_EDGES) && (points[ci*4+3] & RC_CONTOUR_REG_MASK) == 0)
  371. tess = true;
  372. // Edges between areas.
  373. if ((buildFlags & RC_CONTOUR_TESS_AREA_EDGES) && (points[ci*4+3] & RC_AREA_BORDER))
  374. tess = true;
  375. if (tess)
  376. {
  377. int dx = bx - ax;
  378. int dz = bz - az;
  379. if (dx*dx + dz*dz > maxEdgeLen*maxEdgeLen)
  380. {
  381. // Round based on the segments in lexilogical order so that the
  382. // max tesselation is consistent regardles in which direction
  383. // segments are traversed.
  384. const int n = bi < ai ? (bi+pn - ai) : (bi - ai);
  385. if (n > 1)
  386. {
  387. if (bx > ax || (bx == ax && bz > az))
  388. maxi = (ai + n/2) % pn;
  389. else
  390. maxi = (ai + (n+1)/2) % pn;
  391. }
  392. }
  393. }
  394. // If the max deviation is larger than accepted error,
  395. // add new point, else continue to next segment.
  396. if (maxi != -1)
  397. {
  398. // Add space for the new point.
  399. simplified.resize(simplified.size()+4);
  400. const int n = simplified.size()/4;
  401. for (int j = n-1; j > i; --j)
  402. {
  403. simplified[j*4+0] = simplified[(j-1)*4+0];
  404. simplified[j*4+1] = simplified[(j-1)*4+1];
  405. simplified[j*4+2] = simplified[(j-1)*4+2];
  406. simplified[j*4+3] = simplified[(j-1)*4+3];
  407. }
  408. // Add the point.
  409. simplified[(i+1)*4+0] = points[maxi*4+0];
  410. simplified[(i+1)*4+1] = points[maxi*4+1];
  411. simplified[(i+1)*4+2] = points[maxi*4+2];
  412. simplified[(i+1)*4+3] = maxi;
  413. }
  414. else
  415. {
  416. ++i;
  417. }
  418. }
  419. }
  420. for (int i = 0; i < simplified.size()/4; ++i)
  421. {
  422. // The edge vertex flag is take from the current raw point,
  423. // and the neighbour region is take from the next raw point.
  424. const int ai = (simplified[i*4+3]+1) % pn;
  425. const int bi = simplified[i*4+3];
  426. simplified[i*4+3] = (points[ai*4+3] & (RC_CONTOUR_REG_MASK|RC_AREA_BORDER)) | (points[bi*4+3] & RC_BORDER_VERTEX);
  427. }
  428. }
  429. static void removeDegenerateSegments(rcIntArray& simplified)
  430. {
  431. // Remove adjacent vertices which are equal on xz-plane,
  432. // or else the triangulator will get confused.
  433. for (int i = 0; i < simplified.size()/4; ++i)
  434. {
  435. int ni = i+1;
  436. if (ni >= (simplified.size()/4))
  437. ni = 0;
  438. if (simplified[i*4+0] == simplified[ni*4+0] &&
  439. simplified[i*4+2] == simplified[ni*4+2])
  440. {
  441. // Degenerate segment, remove.
  442. for (int j = i; j < simplified.size()/4-1; ++j)
  443. {
  444. simplified[j*4+0] = simplified[(j+1)*4+0];
  445. simplified[j*4+1] = simplified[(j+1)*4+1];
  446. simplified[j*4+2] = simplified[(j+1)*4+2];
  447. simplified[j*4+3] = simplified[(j+1)*4+3];
  448. }
  449. simplified.resize(simplified.size()-4);
  450. }
  451. }
  452. }
  453. static int calcAreaOfPolygon2D(const int* verts, const int nverts)
  454. {
  455. int area = 0;
  456. for (int i = 0, j = nverts-1; i < nverts; j=i++)
  457. {
  458. const int* vi = &verts[i*4];
  459. const int* vj = &verts[j*4];
  460. area += vi[0] * vj[2] - vj[0] * vi[2];
  461. }
  462. return (area+1) / 2;
  463. }
  464. inline bool ileft(const int* a, const int* b, const int* c)
  465. {
  466. return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]) <= 0;
  467. }
  468. static void getClosestIndices(const int* vertsa, const int nvertsa,
  469. const int* vertsb, const int nvertsb,
  470. int& ia, int& ib)
  471. {
  472. int closestDist = 0xfffffff;
  473. ia = -1, ib = -1;
  474. for (int i = 0; i < nvertsa; ++i)
  475. {
  476. const int in = (i+1) % nvertsa;
  477. const int ip = (i+nvertsa-1) % nvertsa;
  478. const int* va = &vertsa[i*4];
  479. const int* van = &vertsa[in*4];
  480. const int* vap = &vertsa[ip*4];
  481. for (int j = 0; j < nvertsb; ++j)
  482. {
  483. const int* vb = &vertsb[j*4];
  484. // vb must be "infront" of va.
  485. if (ileft(vap,va,vb) && ileft(va,van,vb))
  486. {
  487. const int dx = vb[0] - va[0];
  488. const int dz = vb[2] - va[2];
  489. const int d = dx*dx + dz*dz;
  490. if (d < closestDist)
  491. {
  492. ia = i;
  493. ib = j;
  494. closestDist = d;
  495. }
  496. }
  497. }
  498. }
  499. }
  500. static bool mergeContours(rcContour& ca, rcContour& cb, int ia, int ib)
  501. {
  502. const int maxVerts = ca.nverts + cb.nverts + 2;
  503. int* verts = (int*)rcAlloc(sizeof(int)*maxVerts*4, RC_ALLOC_PERM);
  504. if (!verts)
  505. return false;
  506. int nv = 0;
  507. // Copy contour A.
  508. for (int i = 0; i <= ca.nverts; ++i)
  509. {
  510. int* dst = &verts[nv*4];
  511. const int* src = &ca.verts[((ia+i)%ca.nverts)*4];
  512. dst[0] = src[0];
  513. dst[1] = src[1];
  514. dst[2] = src[2];
  515. dst[3] = src[3];
  516. nv++;
  517. }
  518. // Copy contour B
  519. for (int i = 0; i <= cb.nverts; ++i)
  520. {
  521. int* dst = &verts[nv*4];
  522. const int* src = &cb.verts[((ib+i)%cb.nverts)*4];
  523. dst[0] = src[0];
  524. dst[1] = src[1];
  525. dst[2] = src[2];
  526. dst[3] = src[3];
  527. nv++;
  528. }
  529. rcFree(ca.verts);
  530. ca.verts = verts;
  531. ca.nverts = nv;
  532. rcFree(cb.verts);
  533. cb.verts = 0;
  534. cb.nverts = 0;
  535. return true;
  536. }
  537. /// @par
  538. ///
  539. /// The raw contours will match the region outlines exactly. The @p maxError and @p maxEdgeLen
  540. /// parameters control how closely the simplified contours will match the raw contours.
  541. ///
  542. /// Simplified contours are generated such that the vertices for portals between areas match up.
  543. /// (They are considered mandatory vertices.)
  544. ///
  545. /// Setting @p maxEdgeLength to zero will disabled the edge length feature.
  546. ///
  547. /// See the #rcConfig documentation for more information on the configuration parameters.
  548. ///
  549. /// @see rcAllocContourSet, rcCompactHeightfield, rcContourSet, rcConfig
  550. bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
  551. const float maxError, const int maxEdgeLen,
  552. rcContourSet& cset, const int buildFlags)
  553. {
  554. rcAssert(ctx);
  555. const int w = chf.width;
  556. const int h = chf.height;
  557. const int borderSize = chf.borderSize;
  558. ctx->startTimer(RC_TIMER_BUILD_CONTOURS);
  559. rcVcopy(cset.bmin, chf.bmin);
  560. rcVcopy(cset.bmax, chf.bmax);
  561. if (borderSize > 0)
  562. {
  563. // If the heightfield was build with bordersize, remove the offset.
  564. const float pad = borderSize*chf.cs;
  565. cset.bmin[0] += pad;
  566. cset.bmin[2] += pad;
  567. cset.bmax[0] -= pad;
  568. cset.bmax[2] -= pad;
  569. }
  570. cset.cs = chf.cs;
  571. cset.ch = chf.ch;
  572. cset.width = chf.width - chf.borderSize*2;
  573. cset.height = chf.height - chf.borderSize*2;
  574. cset.borderSize = chf.borderSize;
  575. int maxContours = rcMax((int)chf.maxRegions, 8);
  576. cset.conts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM);
  577. if (!cset.conts)
  578. return false;
  579. cset.nconts = 0;
  580. rcScopedDelete<unsigned char> flags = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
  581. if (!flags)
  582. {
  583. ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'flags' (%d).", chf.spanCount);
  584. return false;
  585. }
  586. ctx->startTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
  587. // Mark boundaries.
  588. for (int y = 0; y < h; ++y)
  589. {
  590. for (int x = 0; x < w; ++x)
  591. {
  592. const rcCompactCell& c = chf.cells[x+y*w];
  593. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  594. {
  595. unsigned char res = 0;
  596. const rcCompactSpan& s = chf.spans[i];
  597. if (!chf.spans[i].reg || (chf.spans[i].reg & RC_BORDER_REG))
  598. {
  599. flags[i] = 0;
  600. continue;
  601. }
  602. for (int dir = 0; dir < 4; ++dir)
  603. {
  604. unsigned short r = 0;
  605. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  606. {
  607. const int ax = x + rcGetDirOffsetX(dir);
  608. const int ay = y + rcGetDirOffsetY(dir);
  609. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
  610. r = chf.spans[ai].reg;
  611. }
  612. if (r == chf.spans[i].reg)
  613. res |= (1 << dir);
  614. }
  615. flags[i] = res ^ 0xf; // Inverse, mark non connected edges.
  616. }
  617. }
  618. }
  619. ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
  620. rcIntArray verts(256);
  621. rcIntArray simplified(64);
  622. for (int y = 0; y < h; ++y)
  623. {
  624. for (int x = 0; x < w; ++x)
  625. {
  626. const rcCompactCell& c = chf.cells[x+y*w];
  627. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  628. {
  629. if (flags[i] == 0 || flags[i] == 0xf)
  630. {
  631. flags[i] = 0;
  632. continue;
  633. }
  634. const unsigned short reg = chf.spans[i].reg;
  635. if (!reg || (reg & RC_BORDER_REG))
  636. continue;
  637. const unsigned char area = chf.areas[i];
  638. verts.resize(0);
  639. simplified.resize(0);
  640. ctx->startTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
  641. walkContour(x, y, i, chf, flags, verts);
  642. ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
  643. ctx->startTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY);
  644. simplifyContour(verts, simplified, maxError, maxEdgeLen, buildFlags);
  645. removeDegenerateSegments(simplified);
  646. ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY);
  647. // Store region->contour remap info.
  648. // Create contour.
  649. if (simplified.size()/4 >= 3)
  650. {
  651. if (cset.nconts >= maxContours)
  652. {
  653. // Allocate more contours.
  654. // This can happen when there are tiny holes in the heightfield.
  655. const int oldMax = maxContours;
  656. maxContours *= 2;
  657. rcContour* newConts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM);
  658. for (int j = 0; j < cset.nconts; ++j)
  659. {
  660. newConts[j] = cset.conts[j];
  661. // Reset source pointers to prevent data deletion.
  662. cset.conts[j].verts = 0;
  663. cset.conts[j].rverts = 0;
  664. }
  665. rcFree(cset.conts);
  666. cset.conts = newConts;
  667. ctx->log(RC_LOG_WARNING, "rcBuildContours: Expanding max contours from %d to %d.", oldMax, maxContours);
  668. }
  669. rcContour* cont = &cset.conts[cset.nconts++];
  670. cont->nverts = simplified.size()/4;
  671. cont->verts = (int*)rcAlloc(sizeof(int)*cont->nverts*4, RC_ALLOC_PERM);
  672. if (!cont->verts)
  673. {
  674. ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'verts' (%d).", cont->nverts);
  675. return false;
  676. }
  677. memcpy(cont->verts, &simplified[0], sizeof(int)*cont->nverts*4);
  678. if (borderSize > 0)
  679. {
  680. // If the heightfield was build with bordersize, remove the offset.
  681. for (int j = 0; j < cont->nverts; ++j)
  682. {
  683. int* v = &cont->verts[j*4];
  684. v[0] -= borderSize;
  685. v[2] -= borderSize;
  686. }
  687. }
  688. cont->nrverts = verts.size()/4;
  689. cont->rverts = (int*)rcAlloc(sizeof(int)*cont->nrverts*4, RC_ALLOC_PERM);
  690. if (!cont->rverts)
  691. {
  692. ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'rverts' (%d).", cont->nrverts);
  693. return false;
  694. }
  695. memcpy(cont->rverts, &verts[0], sizeof(int)*cont->nrverts*4);
  696. if (borderSize > 0)
  697. {
  698. // If the heightfield was build with bordersize, remove the offset.
  699. for (int j = 0; j < cont->nrverts; ++j)
  700. {
  701. int* v = &cont->rverts[j*4];
  702. v[0] -= borderSize;
  703. v[2] -= borderSize;
  704. }
  705. }
  706. /* cont->cx = cont->cy = cont->cz = 0;
  707. for (int i = 0; i < cont->nverts; ++i)
  708. {
  709. cont->cx += cont->verts[i*4+0];
  710. cont->cy += cont->verts[i*4+1];
  711. cont->cz += cont->verts[i*4+2];
  712. }
  713. cont->cx /= cont->nverts;
  714. cont->cy /= cont->nverts;
  715. cont->cz /= cont->nverts;*/
  716. cont->reg = reg;
  717. cont->area = area;
  718. }
  719. }
  720. }
  721. }
  722. // Check and merge droppings.
  723. // Sometimes the previous algorithms can fail and create several contours
  724. // per area. This pass will try to merge the holes into the main region.
  725. for (int i = 0; i < cset.nconts; ++i)
  726. {
  727. rcContour& cont = cset.conts[i];
  728. // Check if the contour is would backwards.
  729. if (calcAreaOfPolygon2D(cont.verts, cont.nverts) < 0)
  730. {
  731. // Find another contour which has the same region ID.
  732. int mergeIdx = -1;
  733. for (int j = 0; j < cset.nconts; ++j)
  734. {
  735. if (i == j) continue;
  736. if (cset.conts[j].nverts && cset.conts[j].reg == cont.reg)
  737. {
  738. // Make sure the polygon is correctly oriented.
  739. if (calcAreaOfPolygon2D(cset.conts[j].verts, cset.conts[j].nverts))
  740. {
  741. mergeIdx = j;
  742. break;
  743. }
  744. }
  745. }
  746. if (mergeIdx == -1)
  747. {
  748. ctx->log(RC_LOG_WARNING, "rcBuildContours: Could not find merge target for bad contour %d.", i);
  749. }
  750. else
  751. {
  752. rcContour& mcont = cset.conts[mergeIdx];
  753. // Merge by closest points.
  754. int ia = 0, ib = 0;
  755. getClosestIndices(mcont.verts, mcont.nverts, cont.verts, cont.nverts, ia, ib);
  756. if (ia == -1 || ib == -1)
  757. {
  758. ctx->log(RC_LOG_WARNING, "rcBuildContours: Failed to find merge points for %d and %d.", i, mergeIdx);
  759. continue;
  760. }
  761. if (!mergeContours(mcont, cont, ia, ib))
  762. {
  763. ctx->log(RC_LOG_WARNING, "rcBuildContours: Failed to merge contours %d and %d.", i, mergeIdx);
  764. continue;
  765. }
  766. }
  767. }
  768. }
  769. ctx->stopTimer(RC_TIMER_BUILD_CONTOURS);
  770. return true;
  771. }