RecastRegion.cpp 45 KB

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