RecastRegion.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812
  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 <float.h>
  19. #include <math.h>
  20. #include <string.h>
  21. #include <stdlib.h>
  22. #include <stdio.h>
  23. #include "Recast.h"
  24. #include "RecastAlloc.h"
  25. #include "RecastAssert.h"
  26. namespace
  27. {
  28. struct LevelStackEntry
  29. {
  30. LevelStackEntry(int x_, int y_, int index_) : x(x_), y(y_), index(index_) {}
  31. int x;
  32. int y;
  33. int index;
  34. };
  35. } // namespace
  36. static void calculateDistanceField(rcCompactHeightfield& chf, unsigned short* src, unsigned short& maxDist)
  37. {
  38. const int w = chf.width;
  39. const int h = chf.height;
  40. // Init distance and points.
  41. for (int i = 0; i < chf.spanCount; ++i)
  42. src[i] = 0xffff;
  43. // Mark boundary cells.
  44. for (int y = 0; y < h; ++y)
  45. {
  46. for (int x = 0; x < w; ++x)
  47. {
  48. const rcCompactCell& c = chf.cells[x+y*w];
  49. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  50. {
  51. const rcCompactSpan& s = chf.spans[i];
  52. const unsigned char area = chf.areas[i];
  53. int nc = 0;
  54. for (int dir = 0; dir < 4; ++dir)
  55. {
  56. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  57. {
  58. const int ax = x + rcGetDirOffsetX(dir);
  59. const int ay = y + rcGetDirOffsetY(dir);
  60. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
  61. if (area == chf.areas[ai])
  62. nc++;
  63. }
  64. }
  65. if (nc != 4)
  66. src[i] = 0;
  67. }
  68. }
  69. }
  70. // Pass 1
  71. for (int y = 0; y < h; ++y)
  72. {
  73. for (int x = 0; x < w; ++x)
  74. {
  75. const rcCompactCell& c = chf.cells[x+y*w];
  76. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  77. {
  78. const rcCompactSpan& s = chf.spans[i];
  79. if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
  80. {
  81. // (-1,0)
  82. const int ax = x + rcGetDirOffsetX(0);
  83. const int ay = y + rcGetDirOffsetY(0);
  84. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0);
  85. const rcCompactSpan& as = chf.spans[ai];
  86. if (src[ai]+2 < src[i])
  87. src[i] = src[ai]+2;
  88. // (-1,-1)
  89. if (rcGetCon(as, 3) != RC_NOT_CONNECTED)
  90. {
  91. const int aax = ax + rcGetDirOffsetX(3);
  92. const int aay = ay + rcGetDirOffsetY(3);
  93. const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 3);
  94. if (src[aai]+3 < src[i])
  95. src[i] = src[aai]+3;
  96. }
  97. }
  98. if (rcGetCon(s, 3) != RC_NOT_CONNECTED)
  99. {
  100. // (0,-1)
  101. const int ax = x + rcGetDirOffsetX(3);
  102. const int ay = y + rcGetDirOffsetY(3);
  103. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3);
  104. const rcCompactSpan& as = chf.spans[ai];
  105. if (src[ai]+2 < src[i])
  106. src[i] = src[ai]+2;
  107. // (1,-1)
  108. if (rcGetCon(as, 2) != RC_NOT_CONNECTED)
  109. {
  110. const int aax = ax + rcGetDirOffsetX(2);
  111. const int aay = ay + rcGetDirOffsetY(2);
  112. const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 2);
  113. if (src[aai]+3 < src[i])
  114. src[i] = src[aai]+3;
  115. }
  116. }
  117. }
  118. }
  119. }
  120. // Pass 2
  121. for (int y = h-1; y >= 0; --y)
  122. {
  123. for (int x = w-1; x >= 0; --x)
  124. {
  125. const rcCompactCell& c = chf.cells[x+y*w];
  126. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  127. {
  128. const rcCompactSpan& s = chf.spans[i];
  129. if (rcGetCon(s, 2) != RC_NOT_CONNECTED)
  130. {
  131. // (1,0)
  132. const int ax = x + rcGetDirOffsetX(2);
  133. const int ay = y + rcGetDirOffsetY(2);
  134. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 2);
  135. const rcCompactSpan& as = chf.spans[ai];
  136. if (src[ai]+2 < src[i])
  137. src[i] = src[ai]+2;
  138. // (1,1)
  139. if (rcGetCon(as, 1) != RC_NOT_CONNECTED)
  140. {
  141. const int aax = ax + rcGetDirOffsetX(1);
  142. const int aay = ay + rcGetDirOffsetY(1);
  143. const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 1);
  144. if (src[aai]+3 < src[i])
  145. src[i] = src[aai]+3;
  146. }
  147. }
  148. if (rcGetCon(s, 1) != RC_NOT_CONNECTED)
  149. {
  150. // (0,1)
  151. const int ax = x + rcGetDirOffsetX(1);
  152. const int ay = y + rcGetDirOffsetY(1);
  153. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 1);
  154. const rcCompactSpan& as = chf.spans[ai];
  155. if (src[ai]+2 < src[i])
  156. src[i] = src[ai]+2;
  157. // (-1,1)
  158. if (rcGetCon(as, 0) != RC_NOT_CONNECTED)
  159. {
  160. const int aax = ax + rcGetDirOffsetX(0);
  161. const int aay = ay + rcGetDirOffsetY(0);
  162. const int aai = (int)chf.cells[aax+aay*w].index + rcGetCon(as, 0);
  163. if (src[aai]+3 < src[i])
  164. src[i] = src[aai]+3;
  165. }
  166. }
  167. }
  168. }
  169. }
  170. maxDist = 0;
  171. for (int i = 0; i < chf.spanCount; ++i)
  172. maxDist = rcMax(src[i], maxDist);
  173. }
  174. static unsigned short* boxBlur(rcCompactHeightfield& chf, int thr,
  175. unsigned short* src, unsigned short* dst)
  176. {
  177. const int w = chf.width;
  178. const int h = chf.height;
  179. thr *= 2;
  180. for (int y = 0; y < h; ++y)
  181. {
  182. for (int x = 0; x < w; ++x)
  183. {
  184. const rcCompactCell& c = chf.cells[x+y*w];
  185. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  186. {
  187. const rcCompactSpan& s = chf.spans[i];
  188. const unsigned short cd = src[i];
  189. if (cd <= thr)
  190. {
  191. dst[i] = cd;
  192. continue;
  193. }
  194. int d = (int)cd;
  195. for (int dir = 0; dir < 4; ++dir)
  196. {
  197. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  198. {
  199. const int ax = x + rcGetDirOffsetX(dir);
  200. const int ay = y + rcGetDirOffsetY(dir);
  201. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
  202. d += (int)src[ai];
  203. const rcCompactSpan& as = chf.spans[ai];
  204. const int dir2 = (dir+1) & 0x3;
  205. if (rcGetCon(as, dir2) != RC_NOT_CONNECTED)
  206. {
  207. const int ax2 = ax + rcGetDirOffsetX(dir2);
  208. const int ay2 = ay + rcGetDirOffsetY(dir2);
  209. const int ai2 = (int)chf.cells[ax2+ay2*w].index + rcGetCon(as, dir2);
  210. d += (int)src[ai2];
  211. }
  212. else
  213. {
  214. d += cd;
  215. }
  216. }
  217. else
  218. {
  219. d += cd*2;
  220. }
  221. }
  222. dst[i] = (unsigned short)((d+5)/9);
  223. }
  224. }
  225. }
  226. return dst;
  227. }
  228. static bool floodRegion(int x, int y, int i,
  229. unsigned short level, unsigned short r,
  230. rcCompactHeightfield& chf,
  231. unsigned short* srcReg, unsigned short* srcDist,
  232. rcTempVector<LevelStackEntry>& stack)
  233. {
  234. const int w = chf.width;
  235. const unsigned char area = chf.areas[i];
  236. // Flood fill mark region.
  237. stack.clear();
  238. stack.push_back(LevelStackEntry(x, y, i));
  239. srcReg[i] = r;
  240. srcDist[i] = 0;
  241. unsigned short lev = level >= 2 ? level-2 : 0;
  242. int count = 0;
  243. while (stack.size() > 0)
  244. {
  245. LevelStackEntry& back = stack.back();
  246. int cx = back.x;
  247. int cy = back.y;
  248. int ci = back.index;
  249. stack.pop_back();
  250. const rcCompactSpan& cs = chf.spans[ci];
  251. // Check if any of the neighbours already have a valid region set.
  252. unsigned short ar = 0;
  253. for (int dir = 0; dir < 4; ++dir)
  254. {
  255. // 8 connected
  256. if (rcGetCon(cs, dir) != RC_NOT_CONNECTED)
  257. {
  258. const int ax = cx + rcGetDirOffsetX(dir);
  259. const int ay = cy + rcGetDirOffsetY(dir);
  260. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(cs, dir);
  261. if (chf.areas[ai] != area)
  262. continue;
  263. unsigned short nr = srcReg[ai];
  264. if (nr & RC_BORDER_REG) // Do not take borders into account.
  265. continue;
  266. if (nr != 0 && nr != r)
  267. {
  268. ar = nr;
  269. break;
  270. }
  271. const rcCompactSpan& as = chf.spans[ai];
  272. const int dir2 = (dir+1) & 0x3;
  273. if (rcGetCon(as, dir2) != RC_NOT_CONNECTED)
  274. {
  275. const int ax2 = ax + rcGetDirOffsetX(dir2);
  276. const int ay2 = ay + rcGetDirOffsetY(dir2);
  277. const int ai2 = (int)chf.cells[ax2+ay2*w].index + rcGetCon(as, dir2);
  278. if (chf.areas[ai2] != area)
  279. continue;
  280. unsigned short nr2 = srcReg[ai2];
  281. if (nr2 != 0 && nr2 != r)
  282. {
  283. ar = nr2;
  284. break;
  285. }
  286. }
  287. }
  288. }
  289. if (ar != 0)
  290. {
  291. srcReg[ci] = 0;
  292. continue;
  293. }
  294. count++;
  295. // Expand neighbours.
  296. for (int dir = 0; dir < 4; ++dir)
  297. {
  298. if (rcGetCon(cs, dir) != RC_NOT_CONNECTED)
  299. {
  300. const int ax = cx + rcGetDirOffsetX(dir);
  301. const int ay = cy + rcGetDirOffsetY(dir);
  302. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(cs, dir);
  303. if (chf.areas[ai] != area)
  304. continue;
  305. if (chf.dist[ai] >= lev && srcReg[ai] == 0)
  306. {
  307. srcReg[ai] = r;
  308. srcDist[ai] = 0;
  309. stack.push_back(LevelStackEntry(ax, ay, ai));
  310. }
  311. }
  312. }
  313. }
  314. return count > 0;
  315. }
  316. // Struct to keep track of entries in the region table that have been changed.
  317. struct DirtyEntry
  318. {
  319. DirtyEntry(int index_, unsigned short region_, unsigned short distance2_)
  320. : index(index_), region(region_), distance2(distance2_) {}
  321. int index;
  322. unsigned short region;
  323. unsigned short distance2;
  324. };
  325. static void expandRegions(int maxIter, unsigned short level,
  326. rcCompactHeightfield& chf,
  327. unsigned short* srcReg, unsigned short* srcDist,
  328. rcTempVector<LevelStackEntry>& stack,
  329. bool fillStack)
  330. {
  331. const int w = chf.width;
  332. const int h = chf.height;
  333. if (fillStack)
  334. {
  335. // Find cells revealed by the raised level.
  336. stack.clear();
  337. for (int y = 0; y < h; ++y)
  338. {
  339. for (int x = 0; x < w; ++x)
  340. {
  341. const rcCompactCell& c = chf.cells[x+y*w];
  342. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  343. {
  344. if (chf.dist[i] >= level && srcReg[i] == 0 && chf.areas[i] != RC_NULL_AREA)
  345. {
  346. stack.push_back(LevelStackEntry(x, y, i));
  347. }
  348. }
  349. }
  350. }
  351. }
  352. else // use cells in the input stack
  353. {
  354. // mark all cells which already have a region
  355. for (int j=0; j<stack.size(); j++)
  356. {
  357. int i = stack[j].index;
  358. if (srcReg[i] != 0)
  359. stack[j].index = -1;
  360. }
  361. }
  362. rcTempVector<DirtyEntry> dirtyEntries;
  363. int iter = 0;
  364. while (stack.size() > 0)
  365. {
  366. int failed = 0;
  367. dirtyEntries.clear();
  368. for (int j = 0; j < stack.size(); j++)
  369. {
  370. int x = stack[j].x;
  371. int y = stack[j].y;
  372. int i = stack[j].index;
  373. if (i < 0)
  374. {
  375. failed++;
  376. continue;
  377. }
  378. unsigned short r = srcReg[i];
  379. unsigned short d2 = 0xffff;
  380. const unsigned char area = chf.areas[i];
  381. const rcCompactSpan& s = chf.spans[i];
  382. for (int dir = 0; dir < 4; ++dir)
  383. {
  384. if (rcGetCon(s, dir) == RC_NOT_CONNECTED) continue;
  385. const int ax = x + rcGetDirOffsetX(dir);
  386. const int ay = y + rcGetDirOffsetY(dir);
  387. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
  388. if (chf.areas[ai] != area) continue;
  389. if (srcReg[ai] > 0 && (srcReg[ai] & RC_BORDER_REG) == 0)
  390. {
  391. if ((int)srcDist[ai]+2 < (int)d2)
  392. {
  393. r = srcReg[ai];
  394. d2 = srcDist[ai]+2;
  395. }
  396. }
  397. }
  398. if (r)
  399. {
  400. stack[j].index = -1; // mark as used
  401. dirtyEntries.push_back(DirtyEntry(i, r, d2));
  402. }
  403. else
  404. {
  405. failed++;
  406. }
  407. }
  408. // Copy entries that differ between src and dst to keep them in sync.
  409. for (int i = 0; i < dirtyEntries.size(); i++) {
  410. int idx = dirtyEntries[i].index;
  411. srcReg[idx] = dirtyEntries[i].region;
  412. srcDist[idx] = dirtyEntries[i].distance2;
  413. }
  414. if (failed == stack.size())
  415. break;
  416. if (level > 0)
  417. {
  418. ++iter;
  419. if (iter >= maxIter)
  420. break;
  421. }
  422. }
  423. }
  424. static void sortCellsByLevel(unsigned short startLevel,
  425. rcCompactHeightfield& chf,
  426. const unsigned short* srcReg,
  427. unsigned int nbStacks, rcTempVector<LevelStackEntry>* stacks,
  428. unsigned short loglevelsPerStack) // the levels per stack (2 in our case) as a bit shift
  429. {
  430. const int w = chf.width;
  431. const int h = chf.height;
  432. startLevel = startLevel >> loglevelsPerStack;
  433. for (unsigned int j=0; j<nbStacks; ++j)
  434. stacks[j].clear();
  435. // put all cells in the level range into the appropriate stacks
  436. for (int y = 0; y < h; ++y)
  437. {
  438. for (int x = 0; x < w; ++x)
  439. {
  440. const rcCompactCell& c = chf.cells[x+y*w];
  441. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  442. {
  443. if (chf.areas[i] == RC_NULL_AREA || srcReg[i] != 0)
  444. continue;
  445. int level = chf.dist[i] >> loglevelsPerStack;
  446. int sId = startLevel - level;
  447. if (sId >= (int)nbStacks)
  448. continue;
  449. if (sId < 0)
  450. sId = 0;
  451. stacks[sId].push_back(LevelStackEntry(x, y, i));
  452. }
  453. }
  454. }
  455. }
  456. static void appendStacks(const rcTempVector<LevelStackEntry>& srcStack,
  457. rcTempVector<LevelStackEntry>& dstStack,
  458. const unsigned short* srcReg)
  459. {
  460. for (int j=0; j<srcStack.size(); j++)
  461. {
  462. int i = srcStack[j].index;
  463. if ((i < 0) || (srcReg[i] != 0))
  464. continue;
  465. dstStack.push_back(srcStack[j]);
  466. }
  467. }
  468. struct rcRegion
  469. {
  470. inline rcRegion(unsigned short i) :
  471. spanCount(0),
  472. id(i),
  473. areaType(0),
  474. remap(false),
  475. visited(false),
  476. overlap(false),
  477. connectsToBorder(false),
  478. ymin(0xffff),
  479. ymax(0)
  480. {}
  481. int spanCount; // Number of spans belonging to this region
  482. unsigned short id; // ID of the region
  483. unsigned char areaType; // Are type.
  484. bool remap;
  485. bool visited;
  486. bool overlap;
  487. bool connectsToBorder;
  488. unsigned short ymin, ymax;
  489. rcIntArray connections;
  490. rcIntArray floors;
  491. };
  492. static void removeAdjacentNeighbours(rcRegion& reg)
  493. {
  494. // Remove adjacent duplicates.
  495. for (int i = 0; i < reg.connections.size() && reg.connections.size() > 1; )
  496. {
  497. int ni = (i+1) % reg.connections.size();
  498. if (reg.connections[i] == reg.connections[ni])
  499. {
  500. // Remove duplicate
  501. for (int j = i; j < reg.connections.size()-1; ++j)
  502. reg.connections[j] = reg.connections[j+1];
  503. reg.connections.pop();
  504. }
  505. else
  506. ++i;
  507. }
  508. }
  509. static void replaceNeighbour(rcRegion& reg, unsigned short oldId, unsigned short newId)
  510. {
  511. bool neiChanged = false;
  512. for (int i = 0; i < reg.connections.size(); ++i)
  513. {
  514. if (reg.connections[i] == oldId)
  515. {
  516. reg.connections[i] = newId;
  517. neiChanged = true;
  518. }
  519. }
  520. for (int i = 0; i < reg.floors.size(); ++i)
  521. {
  522. if (reg.floors[i] == oldId)
  523. reg.floors[i] = newId;
  524. }
  525. if (neiChanged)
  526. removeAdjacentNeighbours(reg);
  527. }
  528. static bool canMergeWithRegion(const rcRegion& rega, const rcRegion& regb)
  529. {
  530. if (rega.areaType != regb.areaType)
  531. return false;
  532. int n = 0;
  533. for (int i = 0; i < rega.connections.size(); ++i)
  534. {
  535. if (rega.connections[i] == regb.id)
  536. n++;
  537. }
  538. if (n > 1)
  539. return false;
  540. for (int i = 0; i < rega.floors.size(); ++i)
  541. {
  542. if (rega.floors[i] == regb.id)
  543. return false;
  544. }
  545. return true;
  546. }
  547. static void addUniqueFloorRegion(rcRegion& reg, int n)
  548. {
  549. for (int i = 0; i < reg.floors.size(); ++i)
  550. if (reg.floors[i] == n)
  551. return;
  552. reg.floors.push(n);
  553. }
  554. static bool mergeRegions(rcRegion& rega, rcRegion& regb)
  555. {
  556. unsigned short aid = rega.id;
  557. unsigned short bid = regb.id;
  558. // Duplicate current neighbourhood.
  559. rcIntArray acon;
  560. acon.resize(rega.connections.size());
  561. for (int i = 0; i < rega.connections.size(); ++i)
  562. acon[i] = rega.connections[i];
  563. rcIntArray& bcon = regb.connections;
  564. // Find insertion point on A.
  565. int insa = -1;
  566. for (int i = 0; i < acon.size(); ++i)
  567. {
  568. if (acon[i] == bid)
  569. {
  570. insa = i;
  571. break;
  572. }
  573. }
  574. if (insa == -1)
  575. return false;
  576. // Find insertion point on B.
  577. int insb = -1;
  578. for (int i = 0; i < bcon.size(); ++i)
  579. {
  580. if (bcon[i] == aid)
  581. {
  582. insb = i;
  583. break;
  584. }
  585. }
  586. if (insb == -1)
  587. return false;
  588. // Merge neighbours.
  589. rega.connections.clear();
  590. for (int i = 0, ni = acon.size(); i < ni-1; ++i)
  591. rega.connections.push(acon[(insa+1+i) % ni]);
  592. for (int i = 0, ni = bcon.size(); i < ni-1; ++i)
  593. rega.connections.push(bcon[(insb+1+i) % ni]);
  594. removeAdjacentNeighbours(rega);
  595. for (int j = 0; j < regb.floors.size(); ++j)
  596. addUniqueFloorRegion(rega, regb.floors[j]);
  597. rega.spanCount += regb.spanCount;
  598. regb.spanCount = 0;
  599. regb.connections.resize(0);
  600. return true;
  601. }
  602. static bool isRegionConnectedToBorder(const rcRegion& reg)
  603. {
  604. // Region is connected to border if
  605. // one of the neighbours is null id.
  606. for (int i = 0; i < reg.connections.size(); ++i)
  607. {
  608. if (reg.connections[i] == 0)
  609. return true;
  610. }
  611. return false;
  612. }
  613. static bool isSolidEdge(rcCompactHeightfield& chf, const unsigned short* srcReg,
  614. int x, int y, int i, int dir)
  615. {
  616. const rcCompactSpan& s = chf.spans[i];
  617. unsigned short r = 0;
  618. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  619. {
  620. const int ax = x + rcGetDirOffsetX(dir);
  621. const int ay = y + rcGetDirOffsetY(dir);
  622. const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
  623. r = srcReg[ai];
  624. }
  625. if (r == srcReg[i])
  626. return false;
  627. return true;
  628. }
  629. static void walkContour(int x, int y, int i, int dir,
  630. rcCompactHeightfield& chf,
  631. const unsigned short* srcReg,
  632. rcIntArray& cont)
  633. {
  634. int startDir = dir;
  635. int starti = i;
  636. const rcCompactSpan& ss = chf.spans[i];
  637. unsigned short curReg = 0;
  638. if (rcGetCon(ss, dir) != RC_NOT_CONNECTED)
  639. {
  640. const int ax = x + rcGetDirOffsetX(dir);
  641. const int ay = y + rcGetDirOffsetY(dir);
  642. const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(ss, dir);
  643. curReg = srcReg[ai];
  644. }
  645. cont.push(curReg);
  646. int iter = 0;
  647. while (++iter < 40000)
  648. {
  649. const rcCompactSpan& s = chf.spans[i];
  650. if (isSolidEdge(chf, srcReg, x, y, i, dir))
  651. {
  652. // Choose the edge corner
  653. unsigned short r = 0;
  654. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  655. {
  656. const int ax = x + rcGetDirOffsetX(dir);
  657. const int ay = y + rcGetDirOffsetY(dir);
  658. const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
  659. r = srcReg[ai];
  660. }
  661. if (r != curReg)
  662. {
  663. curReg = r;
  664. cont.push(curReg);
  665. }
  666. dir = (dir+1) & 0x3; // Rotate CW
  667. }
  668. else
  669. {
  670. int ni = -1;
  671. const int nx = x + rcGetDirOffsetX(dir);
  672. const int ny = y + rcGetDirOffsetY(dir);
  673. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  674. {
  675. const rcCompactCell& nc = chf.cells[nx+ny*chf.width];
  676. ni = (int)nc.index + rcGetCon(s, dir);
  677. }
  678. if (ni == -1)
  679. {
  680. // Should not happen.
  681. return;
  682. }
  683. x = nx;
  684. y = ny;
  685. i = ni;
  686. dir = (dir+3) & 0x3; // Rotate CCW
  687. }
  688. if (starti == i && startDir == dir)
  689. {
  690. break;
  691. }
  692. }
  693. // Remove adjacent duplicates.
  694. if (cont.size() > 1)
  695. {
  696. for (int j = 0; j < cont.size(); )
  697. {
  698. int nj = (j+1) % cont.size();
  699. if (cont[j] == cont[nj])
  700. {
  701. for (int k = j; k < cont.size()-1; ++k)
  702. cont[k] = cont[k+1];
  703. cont.pop();
  704. }
  705. else
  706. ++j;
  707. }
  708. }
  709. }
  710. static bool mergeAndFilterRegions(rcContext* ctx, int minRegionArea, int mergeRegionSize,
  711. unsigned short& maxRegionId,
  712. rcCompactHeightfield& chf,
  713. unsigned short* srcReg, rcIntArray& overlaps)
  714. {
  715. const int w = chf.width;
  716. const int h = chf.height;
  717. const int nreg = maxRegionId+1;
  718. rcTempVector<rcRegion> regions;
  719. if (!regions.reserve(nreg)) {
  720. ctx->log(RC_LOG_ERROR, "mergeAndFilterRegions: Out of memory 'regions' (%d).", nreg);
  721. return false;
  722. }
  723. // Construct regions
  724. for (int i = 0; i < nreg; ++i)
  725. regions.push_back(rcRegion((unsigned short) i));
  726. // Find edge of a region and find connections around the contour.
  727. for (int y = 0; y < h; ++y)
  728. {
  729. for (int x = 0; x < w; ++x)
  730. {
  731. const rcCompactCell& c = chf.cells[x+y*w];
  732. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  733. {
  734. unsigned short r = srcReg[i];
  735. if (r == 0 || r >= nreg)
  736. continue;
  737. rcRegion& reg = regions[r];
  738. reg.spanCount++;
  739. // Update floors.
  740. for (int j = (int)c.index; j < ni; ++j)
  741. {
  742. if (i == j) continue;
  743. unsigned short floorId = srcReg[j];
  744. if (floorId == 0 || floorId >= nreg)
  745. continue;
  746. if (floorId == r)
  747. reg.overlap = true;
  748. addUniqueFloorRegion(reg, floorId);
  749. }
  750. // Have found contour
  751. if (reg.connections.size() > 0)
  752. continue;
  753. reg.areaType = chf.areas[i];
  754. // Check if this cell is next to a border.
  755. int ndir = -1;
  756. for (int dir = 0; dir < 4; ++dir)
  757. {
  758. if (isSolidEdge(chf, srcReg, x, y, i, dir))
  759. {
  760. ndir = dir;
  761. break;
  762. }
  763. }
  764. if (ndir != -1)
  765. {
  766. // The cell is at border.
  767. // Walk around the contour to find all the neighbours.
  768. walkContour(x, y, i, ndir, chf, srcReg, reg.connections);
  769. }
  770. }
  771. }
  772. }
  773. // Remove too small regions.
  774. rcIntArray stack(32);
  775. rcIntArray trace(32);
  776. for (int i = 0; i < nreg; ++i)
  777. {
  778. rcRegion& reg = regions[i];
  779. if (reg.id == 0 || (reg.id & RC_BORDER_REG))
  780. continue;
  781. if (reg.spanCount == 0)
  782. continue;
  783. if (reg.visited)
  784. continue;
  785. // Count the total size of all the connected regions.
  786. // Also keep track of the regions connects to a tile border.
  787. bool connectsToBorder = false;
  788. int spanCount = 0;
  789. stack.clear();
  790. trace.clear();
  791. reg.visited = true;
  792. stack.push(i);
  793. while (stack.size())
  794. {
  795. // Pop
  796. int ri = stack.pop();
  797. rcRegion& creg = regions[ri];
  798. spanCount += creg.spanCount;
  799. trace.push(ri);
  800. for (int j = 0; j < creg.connections.size(); ++j)
  801. {
  802. if (creg.connections[j] & RC_BORDER_REG)
  803. {
  804. connectsToBorder = true;
  805. continue;
  806. }
  807. rcRegion& neireg = regions[creg.connections[j]];
  808. if (neireg.visited)
  809. continue;
  810. if (neireg.id == 0 || (neireg.id & RC_BORDER_REG))
  811. continue;
  812. // Visit
  813. stack.push(neireg.id);
  814. neireg.visited = true;
  815. }
  816. }
  817. // If the accumulated regions size is too small, remove it.
  818. // Do not remove areas which connect to tile borders
  819. // as their size cannot be estimated correctly and removing them
  820. // can potentially remove necessary areas.
  821. if (spanCount < minRegionArea && !connectsToBorder)
  822. {
  823. // Kill all visited regions.
  824. for (int j = 0; j < trace.size(); ++j)
  825. {
  826. regions[trace[j]].spanCount = 0;
  827. regions[trace[j]].id = 0;
  828. }
  829. }
  830. }
  831. // Merge too small regions to neighbour regions.
  832. int mergeCount = 0 ;
  833. do
  834. {
  835. mergeCount = 0;
  836. for (int i = 0; i < nreg; ++i)
  837. {
  838. rcRegion& reg = regions[i];
  839. if (reg.id == 0 || (reg.id & RC_BORDER_REG))
  840. continue;
  841. if (reg.overlap)
  842. continue;
  843. if (reg.spanCount == 0)
  844. continue;
  845. // Check to see if the region should be merged.
  846. if (reg.spanCount > mergeRegionSize && isRegionConnectedToBorder(reg))
  847. continue;
  848. // Small region with more than 1 connection.
  849. // Or region which is not connected to a border at all.
  850. // Find smallest neighbour region that connects to this one.
  851. int smallest = 0xfffffff;
  852. unsigned short mergeId = reg.id;
  853. for (int j = 0; j < reg.connections.size(); ++j)
  854. {
  855. if (reg.connections[j] & RC_BORDER_REG) continue;
  856. rcRegion& mreg = regions[reg.connections[j]];
  857. if (mreg.id == 0 || (mreg.id & RC_BORDER_REG) || mreg.overlap) continue;
  858. if (mreg.spanCount < smallest &&
  859. canMergeWithRegion(reg, mreg) &&
  860. canMergeWithRegion(mreg, reg))
  861. {
  862. smallest = mreg.spanCount;
  863. mergeId = mreg.id;
  864. }
  865. }
  866. // Found new id.
  867. if (mergeId != reg.id)
  868. {
  869. unsigned short oldId = reg.id;
  870. rcRegion& target = regions[mergeId];
  871. // Merge neighbours.
  872. if (mergeRegions(target, reg))
  873. {
  874. // Fixup regions pointing to current region.
  875. for (int j = 0; j < nreg; ++j)
  876. {
  877. if (regions[j].id == 0 || (regions[j].id & RC_BORDER_REG)) continue;
  878. // If another region was already merged into current region
  879. // change the nid of the previous region too.
  880. if (regions[j].id == oldId)
  881. regions[j].id = mergeId;
  882. // Replace the current region with the new one if the
  883. // current regions is neighbour.
  884. replaceNeighbour(regions[j], oldId, mergeId);
  885. }
  886. mergeCount++;
  887. }
  888. }
  889. }
  890. }
  891. while (mergeCount > 0);
  892. // Compress region Ids.
  893. for (int i = 0; i < nreg; ++i)
  894. {
  895. regions[i].remap = false;
  896. if (regions[i].id == 0) continue; // Skip nil regions.
  897. if (regions[i].id & RC_BORDER_REG) continue; // Skip external regions.
  898. regions[i].remap = true;
  899. }
  900. unsigned short regIdGen = 0;
  901. for (int i = 0; i < nreg; ++i)
  902. {
  903. if (!regions[i].remap)
  904. continue;
  905. unsigned short oldId = regions[i].id;
  906. unsigned short newId = ++regIdGen;
  907. for (int j = i; j < nreg; ++j)
  908. {
  909. if (regions[j].id == oldId)
  910. {
  911. regions[j].id = newId;
  912. regions[j].remap = false;
  913. }
  914. }
  915. }
  916. maxRegionId = regIdGen;
  917. // Remap regions.
  918. for (int i = 0; i < chf.spanCount; ++i)
  919. {
  920. if ((srcReg[i] & RC_BORDER_REG) == 0)
  921. srcReg[i] = regions[srcReg[i]].id;
  922. }
  923. // Return regions that we found to be overlapping.
  924. for (int i = 0; i < nreg; ++i)
  925. if (regions[i].overlap)
  926. overlaps.push(regions[i].id);
  927. return true;
  928. }
  929. static void addUniqueConnection(rcRegion& reg, int n)
  930. {
  931. for (int i = 0; i < reg.connections.size(); ++i)
  932. if (reg.connections[i] == n)
  933. return;
  934. reg.connections.push(n);
  935. }
  936. static bool mergeAndFilterLayerRegions(rcContext* ctx, int minRegionArea,
  937. unsigned short& maxRegionId,
  938. rcCompactHeightfield& chf,
  939. unsigned short* srcReg)
  940. {
  941. const int w = chf.width;
  942. const int h = chf.height;
  943. const int nreg = maxRegionId+1;
  944. rcTempVector<rcRegion> regions;
  945. // Construct regions
  946. if (!regions.reserve(nreg)) {
  947. ctx->log(RC_LOG_ERROR, "mergeAndFilterLayerRegions: Out of memory 'regions' (%d).", nreg);
  948. return false;
  949. }
  950. for (int i = 0; i < nreg; ++i)
  951. regions.push_back(rcRegion((unsigned short) i));
  952. // Find region neighbours and overlapping regions.
  953. rcIntArray lregs(32);
  954. for (int y = 0; y < h; ++y)
  955. {
  956. for (int x = 0; x < w; ++x)
  957. {
  958. const rcCompactCell& c = chf.cells[x+y*w];
  959. lregs.clear();
  960. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  961. {
  962. const rcCompactSpan& s = chf.spans[i];
  963. const unsigned short ri = srcReg[i];
  964. if (ri == 0 || ri >= nreg) continue;
  965. rcRegion& reg = regions[ri];
  966. reg.spanCount++;
  967. reg.ymin = rcMin(reg.ymin, s.y);
  968. reg.ymax = rcMax(reg.ymax, s.y);
  969. // Collect all region layers.
  970. lregs.push(ri);
  971. // Update neighbours
  972. for (int dir = 0; dir < 4; ++dir)
  973. {
  974. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  975. {
  976. const int ax = x + rcGetDirOffsetX(dir);
  977. const int ay = y + rcGetDirOffsetY(dir);
  978. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
  979. const unsigned short rai = srcReg[ai];
  980. if (rai > 0 && rai < nreg && rai != ri)
  981. addUniqueConnection(reg, rai);
  982. if (rai & RC_BORDER_REG)
  983. reg.connectsToBorder = true;
  984. }
  985. }
  986. }
  987. // Update overlapping regions.
  988. for (int i = 0; i < lregs.size()-1; ++i)
  989. {
  990. for (int j = i+1; j < lregs.size(); ++j)
  991. {
  992. if (lregs[i] != lregs[j])
  993. {
  994. rcRegion& ri = regions[lregs[i]];
  995. rcRegion& rj = regions[lregs[j]];
  996. addUniqueFloorRegion(ri, lregs[j]);
  997. addUniqueFloorRegion(rj, lregs[i]);
  998. }
  999. }
  1000. }
  1001. }
  1002. }
  1003. // Create 2D layers from regions.
  1004. unsigned short layerId = 1;
  1005. for (int i = 0; i < nreg; ++i)
  1006. regions[i].id = 0;
  1007. // Merge montone regions to create non-overlapping areas.
  1008. rcIntArray stack(32);
  1009. for (int i = 1; i < nreg; ++i)
  1010. {
  1011. rcRegion& root = regions[i];
  1012. // Skip already visited.
  1013. if (root.id != 0)
  1014. continue;
  1015. // Start search.
  1016. root.id = layerId;
  1017. stack.clear();
  1018. stack.push(i);
  1019. while (stack.size() > 0)
  1020. {
  1021. // Pop front
  1022. rcRegion& reg = regions[stack[0]];
  1023. for (int j = 0; j < stack.size()-1; ++j)
  1024. stack[j] = stack[j+1];
  1025. stack.resize(stack.size()-1);
  1026. const int ncons = (int)reg.connections.size();
  1027. for (int j = 0; j < ncons; ++j)
  1028. {
  1029. const int nei = reg.connections[j];
  1030. rcRegion& regn = regions[nei];
  1031. // Skip already visited.
  1032. if (regn.id != 0)
  1033. continue;
  1034. // Skip if the neighbour is overlapping root region.
  1035. bool overlap = false;
  1036. for (int k = 0; k < root.floors.size(); k++)
  1037. {
  1038. if (root.floors[k] == nei)
  1039. {
  1040. overlap = true;
  1041. break;
  1042. }
  1043. }
  1044. if (overlap)
  1045. continue;
  1046. // Deepen
  1047. stack.push(nei);
  1048. // Mark layer id
  1049. regn.id = layerId;
  1050. // Merge current layers to root.
  1051. for (int k = 0; k < regn.floors.size(); ++k)
  1052. addUniqueFloorRegion(root, regn.floors[k]);
  1053. root.ymin = rcMin(root.ymin, regn.ymin);
  1054. root.ymax = rcMax(root.ymax, regn.ymax);
  1055. root.spanCount += regn.spanCount;
  1056. regn.spanCount = 0;
  1057. root.connectsToBorder = root.connectsToBorder || regn.connectsToBorder;
  1058. }
  1059. }
  1060. layerId++;
  1061. }
  1062. // Remove small regions
  1063. for (int i = 0; i < nreg; ++i)
  1064. {
  1065. if (regions[i].spanCount > 0 && regions[i].spanCount < minRegionArea && !regions[i].connectsToBorder)
  1066. {
  1067. unsigned short reg = regions[i].id;
  1068. for (int j = 0; j < nreg; ++j)
  1069. if (regions[j].id == reg)
  1070. regions[j].id = 0;
  1071. }
  1072. }
  1073. // Compress region Ids.
  1074. for (int i = 0; i < nreg; ++i)
  1075. {
  1076. regions[i].remap = false;
  1077. if (regions[i].id == 0) continue; // Skip nil regions.
  1078. if (regions[i].id & RC_BORDER_REG) continue; // Skip external regions.
  1079. regions[i].remap = true;
  1080. }
  1081. unsigned short regIdGen = 0;
  1082. for (int i = 0; i < nreg; ++i)
  1083. {
  1084. if (!regions[i].remap)
  1085. continue;
  1086. unsigned short oldId = regions[i].id;
  1087. unsigned short newId = ++regIdGen;
  1088. for (int j = i; j < nreg; ++j)
  1089. {
  1090. if (regions[j].id == oldId)
  1091. {
  1092. regions[j].id = newId;
  1093. regions[j].remap = false;
  1094. }
  1095. }
  1096. }
  1097. maxRegionId = regIdGen;
  1098. // Remap regions.
  1099. for (int i = 0; i < chf.spanCount; ++i)
  1100. {
  1101. if ((srcReg[i] & RC_BORDER_REG) == 0)
  1102. srcReg[i] = regions[srcReg[i]].id;
  1103. }
  1104. return true;
  1105. }
  1106. /// @par
  1107. ///
  1108. /// This is usually the second to the last step in creating a fully built
  1109. /// compact heightfield. This step is required before regions are built
  1110. /// using #rcBuildRegions or #rcBuildRegionsMonotone.
  1111. ///
  1112. /// After this step, the distance data is available via the rcCompactHeightfield::maxDistance
  1113. /// and rcCompactHeightfield::dist fields.
  1114. ///
  1115. /// @see rcCompactHeightfield, rcBuildRegions, rcBuildRegionsMonotone
  1116. bool rcBuildDistanceField(rcContext* ctx, rcCompactHeightfield& chf)
  1117. {
  1118. rcAssert(ctx);
  1119. rcScopedTimer timer(ctx, RC_TIMER_BUILD_DISTANCEFIELD);
  1120. if (chf.dist)
  1121. {
  1122. rcFree(chf.dist);
  1123. chf.dist = 0;
  1124. }
  1125. unsigned short* src = (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP);
  1126. if (!src)
  1127. {
  1128. ctx->log(RC_LOG_ERROR, "rcBuildDistanceField: Out of memory 'src' (%d).", chf.spanCount);
  1129. return false;
  1130. }
  1131. unsigned short* dst = (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP);
  1132. if (!dst)
  1133. {
  1134. ctx->log(RC_LOG_ERROR, "rcBuildDistanceField: Out of memory 'dst' (%d).", chf.spanCount);
  1135. rcFree(src);
  1136. return false;
  1137. }
  1138. unsigned short maxDist = 0;
  1139. {
  1140. rcScopedTimer timerDist(ctx, RC_TIMER_BUILD_DISTANCEFIELD_DIST);
  1141. calculateDistanceField(chf, src, maxDist);
  1142. chf.maxDistance = maxDist;
  1143. }
  1144. {
  1145. rcScopedTimer timerBlur(ctx, RC_TIMER_BUILD_DISTANCEFIELD_BLUR);
  1146. // Blur
  1147. if (boxBlur(chf, 1, src, dst) != src)
  1148. rcSwap(src, dst);
  1149. // Store distance.
  1150. chf.dist = src;
  1151. }
  1152. rcFree(dst);
  1153. return true;
  1154. }
  1155. static void paintRectRegion(int minx, int maxx, int miny, int maxy, unsigned short regId,
  1156. rcCompactHeightfield& chf, unsigned short* srcReg)
  1157. {
  1158. const int w = chf.width;
  1159. for (int y = miny; y < maxy; ++y)
  1160. {
  1161. for (int x = minx; x < maxx; ++x)
  1162. {
  1163. const rcCompactCell& c = chf.cells[x+y*w];
  1164. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  1165. {
  1166. if (chf.areas[i] != RC_NULL_AREA)
  1167. srcReg[i] = regId;
  1168. }
  1169. }
  1170. }
  1171. }
  1172. static const unsigned short RC_NULL_NEI = 0xffff;
  1173. struct rcSweepSpan
  1174. {
  1175. unsigned short rid; // row id
  1176. unsigned short id; // region id
  1177. unsigned short ns; // number samples
  1178. unsigned short nei; // neighbour id
  1179. };
  1180. /// @par
  1181. ///
  1182. /// Non-null regions will consist of connected, non-overlapping walkable spans that form a single contour.
  1183. /// Contours will form simple polygons.
  1184. ///
  1185. /// If multiple regions form an area that is smaller than @p minRegionArea, then all spans will be
  1186. /// re-assigned to the zero (null) region.
  1187. ///
  1188. /// Partitioning can result in smaller than necessary regions. @p mergeRegionArea helps
  1189. /// reduce unecessarily small regions.
  1190. ///
  1191. /// See the #rcConfig documentation for more information on the configuration parameters.
  1192. ///
  1193. /// The region data will be available via the rcCompactHeightfield::maxRegions
  1194. /// and rcCompactSpan::reg fields.
  1195. ///
  1196. /// @warning The distance field must be created using #rcBuildDistanceField before attempting to build regions.
  1197. ///
  1198. /// @see rcCompactHeightfield, rcCompactSpan, rcBuildDistanceField, rcBuildRegionsMonotone, rcConfig
  1199. bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf,
  1200. const int borderSize, const int minRegionArea, const int mergeRegionArea)
  1201. {
  1202. rcAssert(ctx);
  1203. rcScopedTimer timer(ctx, RC_TIMER_BUILD_REGIONS);
  1204. const int w = chf.width;
  1205. const int h = chf.height;
  1206. unsigned short id = 1;
  1207. rcScopedDelete<unsigned short> srcReg((unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP));
  1208. if (!srcReg)
  1209. {
  1210. ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'src' (%d).", chf.spanCount);
  1211. return false;
  1212. }
  1213. memset(srcReg,0,sizeof(unsigned short)*chf.spanCount);
  1214. const int nsweeps = rcMax(chf.width,chf.height);
  1215. rcScopedDelete<rcSweepSpan> sweeps((rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP));
  1216. if (!sweeps)
  1217. {
  1218. ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'sweeps' (%d).", nsweeps);
  1219. return false;
  1220. }
  1221. // Mark border regions.
  1222. if (borderSize > 0)
  1223. {
  1224. // Make sure border will not overflow.
  1225. const int bw = rcMin(w, borderSize);
  1226. const int bh = rcMin(h, borderSize);
  1227. // Paint regions
  1228. paintRectRegion(0, bw, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
  1229. paintRectRegion(w-bw, w, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
  1230. paintRectRegion(0, w, 0, bh, id|RC_BORDER_REG, chf, srcReg); id++;
  1231. paintRectRegion(0, w, h-bh, h, id|RC_BORDER_REG, chf, srcReg); id++;
  1232. }
  1233. chf.borderSize = borderSize;
  1234. rcIntArray prev(256);
  1235. // Sweep one line at a time.
  1236. for (int y = borderSize; y < h-borderSize; ++y)
  1237. {
  1238. // Collect spans from this row.
  1239. prev.resize(id+1);
  1240. memset(&prev[0],0,sizeof(int)*id);
  1241. unsigned short rid = 1;
  1242. for (int x = borderSize; x < w-borderSize; ++x)
  1243. {
  1244. const rcCompactCell& c = chf.cells[x+y*w];
  1245. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  1246. {
  1247. const rcCompactSpan& s = chf.spans[i];
  1248. if (chf.areas[i] == RC_NULL_AREA) continue;
  1249. // -x
  1250. unsigned short previd = 0;
  1251. if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
  1252. {
  1253. const int ax = x + rcGetDirOffsetX(0);
  1254. const int ay = y + rcGetDirOffsetY(0);
  1255. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0);
  1256. if ((srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai])
  1257. previd = srcReg[ai];
  1258. }
  1259. if (!previd)
  1260. {
  1261. previd = rid++;
  1262. sweeps[previd].rid = previd;
  1263. sweeps[previd].ns = 0;
  1264. sweeps[previd].nei = 0;
  1265. }
  1266. // -y
  1267. if (rcGetCon(s,3) != RC_NOT_CONNECTED)
  1268. {
  1269. const int ax = x + rcGetDirOffsetX(3);
  1270. const int ay = y + rcGetDirOffsetY(3);
  1271. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3);
  1272. if (srcReg[ai] && (srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai])
  1273. {
  1274. unsigned short nr = srcReg[ai];
  1275. if (!sweeps[previd].nei || sweeps[previd].nei == nr)
  1276. {
  1277. sweeps[previd].nei = nr;
  1278. sweeps[previd].ns++;
  1279. prev[nr]++;
  1280. }
  1281. else
  1282. {
  1283. sweeps[previd].nei = RC_NULL_NEI;
  1284. }
  1285. }
  1286. }
  1287. srcReg[i] = previd;
  1288. }
  1289. }
  1290. // Create unique ID.
  1291. for (int i = 1; i < rid; ++i)
  1292. {
  1293. if (sweeps[i].nei != RC_NULL_NEI && sweeps[i].nei != 0 &&
  1294. prev[sweeps[i].nei] == (int)sweeps[i].ns)
  1295. {
  1296. sweeps[i].id = sweeps[i].nei;
  1297. }
  1298. else
  1299. {
  1300. sweeps[i].id = id++;
  1301. }
  1302. }
  1303. // Remap IDs
  1304. for (int x = borderSize; x < w-borderSize; ++x)
  1305. {
  1306. const rcCompactCell& c = chf.cells[x+y*w];
  1307. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  1308. {
  1309. if (srcReg[i] > 0 && srcReg[i] < rid)
  1310. srcReg[i] = sweeps[srcReg[i]].id;
  1311. }
  1312. }
  1313. }
  1314. {
  1315. rcScopedTimer timerFilter(ctx, RC_TIMER_BUILD_REGIONS_FILTER);
  1316. // Merge regions and filter out small regions.
  1317. rcIntArray overlaps;
  1318. chf.maxRegions = id;
  1319. if (!mergeAndFilterRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg, overlaps))
  1320. return false;
  1321. // Monotone partitioning does not generate overlapping regions.
  1322. }
  1323. // Store the result out.
  1324. for (int i = 0; i < chf.spanCount; ++i)
  1325. chf.spans[i].reg = srcReg[i];
  1326. return true;
  1327. }
  1328. /// @par
  1329. ///
  1330. /// Non-null regions will consist of connected, non-overlapping walkable spans that form a single contour.
  1331. /// Contours will form simple polygons.
  1332. ///
  1333. /// If multiple regions form an area that is smaller than @p minRegionArea, then all spans will be
  1334. /// re-assigned to the zero (null) region.
  1335. ///
  1336. /// Watershed partitioning can result in smaller than necessary regions, especially in diagonal corridors.
  1337. /// @p mergeRegionArea helps reduce unecessarily small regions.
  1338. ///
  1339. /// See the #rcConfig documentation for more information on the configuration parameters.
  1340. ///
  1341. /// The region data will be available via the rcCompactHeightfield::maxRegions
  1342. /// and rcCompactSpan::reg fields.
  1343. ///
  1344. /// @warning The distance field must be created using #rcBuildDistanceField before attempting to build regions.
  1345. ///
  1346. /// @see rcCompactHeightfield, rcCompactSpan, rcBuildDistanceField, rcBuildRegionsMonotone, rcConfig
  1347. bool rcBuildRegions(rcContext* ctx, rcCompactHeightfield& chf,
  1348. const int borderSize, const int minRegionArea, const int mergeRegionArea)
  1349. {
  1350. rcAssert(ctx);
  1351. rcScopedTimer timer(ctx, RC_TIMER_BUILD_REGIONS);
  1352. const int w = chf.width;
  1353. const int h = chf.height;
  1354. rcScopedDelete<unsigned short> buf((unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount*2, RC_ALLOC_TEMP));
  1355. if (!buf)
  1356. {
  1357. ctx->log(RC_LOG_ERROR, "rcBuildRegions: Out of memory 'tmp' (%d).", chf.spanCount*4);
  1358. return false;
  1359. }
  1360. ctx->startTimer(RC_TIMER_BUILD_REGIONS_WATERSHED);
  1361. const int LOG_NB_STACKS = 3;
  1362. const int NB_STACKS = 1 << LOG_NB_STACKS;
  1363. rcTempVector<LevelStackEntry> lvlStacks[NB_STACKS];
  1364. for (int i=0; i<NB_STACKS; ++i)
  1365. lvlStacks[i].reserve(256);
  1366. rcTempVector<LevelStackEntry> stack;
  1367. stack.reserve(256);
  1368. unsigned short* srcReg = buf;
  1369. unsigned short* srcDist = buf+chf.spanCount;
  1370. memset(srcReg, 0, sizeof(unsigned short)*chf.spanCount);
  1371. memset(srcDist, 0, sizeof(unsigned short)*chf.spanCount);
  1372. unsigned short regionId = 1;
  1373. unsigned short level = (chf.maxDistance+1) & ~1;
  1374. // TODO: Figure better formula, expandIters defines how much the
  1375. // watershed "overflows" and simplifies the regions. Tying it to
  1376. // agent radius was usually good indication how greedy it could be.
  1377. // const int expandIters = 4 + walkableRadius * 2;
  1378. const int expandIters = 8;
  1379. if (borderSize > 0)
  1380. {
  1381. // Make sure border will not overflow.
  1382. const int bw = rcMin(w, borderSize);
  1383. const int bh = rcMin(h, borderSize);
  1384. // Paint regions
  1385. paintRectRegion(0, bw, 0, h, regionId|RC_BORDER_REG, chf, srcReg); regionId++;
  1386. paintRectRegion(w-bw, w, 0, h, regionId|RC_BORDER_REG, chf, srcReg); regionId++;
  1387. paintRectRegion(0, w, 0, bh, regionId|RC_BORDER_REG, chf, srcReg); regionId++;
  1388. paintRectRegion(0, w, h-bh, h, regionId|RC_BORDER_REG, chf, srcReg); regionId++;
  1389. }
  1390. chf.borderSize = borderSize;
  1391. int sId = -1;
  1392. while (level > 0)
  1393. {
  1394. level = level >= 2 ? level-2 : 0;
  1395. sId = (sId+1) & (NB_STACKS-1);
  1396. // ctx->startTimer(RC_TIMER_DIVIDE_TO_LEVELS);
  1397. if (sId == 0)
  1398. sortCellsByLevel(level, chf, srcReg, NB_STACKS, lvlStacks, 1);
  1399. else
  1400. appendStacks(lvlStacks[sId-1], lvlStacks[sId], srcReg); // copy left overs from last level
  1401. // ctx->stopTimer(RC_TIMER_DIVIDE_TO_LEVELS);
  1402. {
  1403. rcScopedTimer timerExpand(ctx, RC_TIMER_BUILD_REGIONS_EXPAND);
  1404. // Expand current regions until no empty connected cells found.
  1405. expandRegions(expandIters, level, chf, srcReg, srcDist, lvlStacks[sId], false);
  1406. }
  1407. {
  1408. rcScopedTimer timerFloor(ctx, RC_TIMER_BUILD_REGIONS_FLOOD);
  1409. // Mark new regions with IDs.
  1410. for (int j = 0; j<lvlStacks[sId].size(); j++)
  1411. {
  1412. LevelStackEntry current = lvlStacks[sId][j];
  1413. int x = current.x;
  1414. int y = current.y;
  1415. int i = current.index;
  1416. if (i >= 0 && srcReg[i] == 0)
  1417. {
  1418. if (floodRegion(x, y, i, level, regionId, chf, srcReg, srcDist, stack))
  1419. {
  1420. if (regionId == 0xFFFF)
  1421. {
  1422. ctx->log(RC_LOG_ERROR, "rcBuildRegions: Region ID overflow");
  1423. return false;
  1424. }
  1425. regionId++;
  1426. }
  1427. }
  1428. }
  1429. }
  1430. }
  1431. // Expand current regions until no empty connected cells found.
  1432. expandRegions(expandIters*8, 0, chf, srcReg, srcDist, stack, true);
  1433. ctx->stopTimer(RC_TIMER_BUILD_REGIONS_WATERSHED);
  1434. {
  1435. rcScopedTimer timerFilter(ctx, RC_TIMER_BUILD_REGIONS_FILTER);
  1436. // Merge regions and filter out smalle regions.
  1437. rcIntArray overlaps;
  1438. chf.maxRegions = regionId;
  1439. if (!mergeAndFilterRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg, overlaps))
  1440. return false;
  1441. // If overlapping regions were found during merging, split those regions.
  1442. if (overlaps.size() > 0)
  1443. {
  1444. ctx->log(RC_LOG_ERROR, "rcBuildRegions: %d overlapping regions.", overlaps.size());
  1445. }
  1446. }
  1447. // Write the result out.
  1448. for (int i = 0; i < chf.spanCount; ++i)
  1449. chf.spans[i].reg = srcReg[i];
  1450. return true;
  1451. }
  1452. bool rcBuildLayerRegions(rcContext* ctx, rcCompactHeightfield& chf,
  1453. const int borderSize, const int minRegionArea)
  1454. {
  1455. rcAssert(ctx);
  1456. rcScopedTimer timer(ctx, RC_TIMER_BUILD_REGIONS);
  1457. const int w = chf.width;
  1458. const int h = chf.height;
  1459. unsigned short id = 1;
  1460. rcScopedDelete<unsigned short> srcReg((unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP));
  1461. if (!srcReg)
  1462. {
  1463. ctx->log(RC_LOG_ERROR, "rcBuildLayerRegions: Out of memory 'src' (%d).", chf.spanCount);
  1464. return false;
  1465. }
  1466. memset(srcReg,0,sizeof(unsigned short)*chf.spanCount);
  1467. const int nsweeps = rcMax(chf.width,chf.height);
  1468. rcScopedDelete<rcSweepSpan> sweeps((rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP));
  1469. if (!sweeps)
  1470. {
  1471. ctx->log(RC_LOG_ERROR, "rcBuildLayerRegions: Out of memory 'sweeps' (%d).", nsweeps);
  1472. return false;
  1473. }
  1474. // Mark border regions.
  1475. if (borderSize > 0)
  1476. {
  1477. // Make sure border will not overflow.
  1478. const int bw = rcMin(w, borderSize);
  1479. const int bh = rcMin(h, borderSize);
  1480. // Paint regions
  1481. paintRectRegion(0, bw, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
  1482. paintRectRegion(w-bw, w, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
  1483. paintRectRegion(0, w, 0, bh, id|RC_BORDER_REG, chf, srcReg); id++;
  1484. paintRectRegion(0, w, h-bh, h, id|RC_BORDER_REG, chf, srcReg); id++;
  1485. }
  1486. chf.borderSize = borderSize;
  1487. rcIntArray prev(256);
  1488. // Sweep one line at a time.
  1489. for (int y = borderSize; y < h-borderSize; ++y)
  1490. {
  1491. // Collect spans from this row.
  1492. prev.resize(id+1);
  1493. memset(&prev[0],0,sizeof(int)*id);
  1494. unsigned short rid = 1;
  1495. for (int x = borderSize; x < w-borderSize; ++x)
  1496. {
  1497. const rcCompactCell& c = chf.cells[x+y*w];
  1498. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  1499. {
  1500. const rcCompactSpan& s = chf.spans[i];
  1501. if (chf.areas[i] == RC_NULL_AREA) continue;
  1502. // -x
  1503. unsigned short previd = 0;
  1504. if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
  1505. {
  1506. const int ax = x + rcGetDirOffsetX(0);
  1507. const int ay = y + rcGetDirOffsetY(0);
  1508. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0);
  1509. if ((srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai])
  1510. previd = srcReg[ai];
  1511. }
  1512. if (!previd)
  1513. {
  1514. previd = rid++;
  1515. sweeps[previd].rid = previd;
  1516. sweeps[previd].ns = 0;
  1517. sweeps[previd].nei = 0;
  1518. }
  1519. // -y
  1520. if (rcGetCon(s,3) != RC_NOT_CONNECTED)
  1521. {
  1522. const int ax = x + rcGetDirOffsetX(3);
  1523. const int ay = y + rcGetDirOffsetY(3);
  1524. const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3);
  1525. if (srcReg[ai] && (srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai])
  1526. {
  1527. unsigned short nr = srcReg[ai];
  1528. if (!sweeps[previd].nei || sweeps[previd].nei == nr)
  1529. {
  1530. sweeps[previd].nei = nr;
  1531. sweeps[previd].ns++;
  1532. prev[nr]++;
  1533. }
  1534. else
  1535. {
  1536. sweeps[previd].nei = RC_NULL_NEI;
  1537. }
  1538. }
  1539. }
  1540. srcReg[i] = previd;
  1541. }
  1542. }
  1543. // Create unique ID.
  1544. for (int i = 1; i < rid; ++i)
  1545. {
  1546. if (sweeps[i].nei != RC_NULL_NEI && sweeps[i].nei != 0 &&
  1547. prev[sweeps[i].nei] == (int)sweeps[i].ns)
  1548. {
  1549. sweeps[i].id = sweeps[i].nei;
  1550. }
  1551. else
  1552. {
  1553. sweeps[i].id = id++;
  1554. }
  1555. }
  1556. // Remap IDs
  1557. for (int x = borderSize; x < w-borderSize; ++x)
  1558. {
  1559. const rcCompactCell& c = chf.cells[x+y*w];
  1560. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  1561. {
  1562. if (srcReg[i] > 0 && srcReg[i] < rid)
  1563. srcReg[i] = sweeps[srcReg[i]].id;
  1564. }
  1565. }
  1566. }
  1567. {
  1568. rcScopedTimer timerFilter(ctx, RC_TIMER_BUILD_REGIONS_FILTER);
  1569. // Merge monotone regions to layers and remove small regions.
  1570. chf.maxRegions = id;
  1571. if (!mergeAndFilterLayerRegions(ctx, minRegionArea, chf.maxRegions, chf, srcReg))
  1572. return false;
  1573. }
  1574. // Store the result out.
  1575. for (int i = 0; i < chf.spanCount; ++i)
  1576. chf.spans[i].reg = srcReg[i];
  1577. return true;
  1578. }