RecastMesh.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  1. //
  2. // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
  3. //
  4. // This software is provided 'as-is', without any express or implied
  5. // warranty. In no event will the authors be held liable for any damages
  6. // arising from the use of this software.
  7. // Permission is granted to anyone to use this software for any purpose,
  8. // including commercial applications, and to alter it and redistribute it
  9. // freely, subject to the following restrictions:
  10. // 1. The origin of this software must not be misrepresented; you must not
  11. // claim that you wrote the original software. If you use this software
  12. // in a product, an acknowledgment in the product documentation would be
  13. // appreciated but is not required.
  14. // 2. Altered source versions must be plainly marked as such, and must not be
  15. // misrepresented as being the original software.
  16. // 3. This notice may not be removed or altered from any source distribution.
  17. //
  18. #include <math.h>
  19. #include <string.h>
  20. #include <stdio.h>
  21. #include "Recast.h"
  22. #include "RecastAlloc.h"
  23. #include "RecastAssert.h"
  24. struct rcEdge
  25. {
  26. unsigned short vert[2];
  27. unsigned short polyEdge[2];
  28. unsigned short poly[2];
  29. };
  30. static bool buildMeshAdjacency(unsigned short* polys, const int npolys,
  31. const int nverts, const int vertsPerPoly)
  32. {
  33. // Based on code by Eric Lengyel from:
  34. // https://web.archive.org/web/20080704083314/http://www.terathon.com/code/edges.php
  35. int maxEdgeCount = npolys*vertsPerPoly;
  36. unsigned short* firstEdge = (unsigned short*)rcAlloc(sizeof(unsigned short)*(nverts + maxEdgeCount), RC_ALLOC_TEMP);
  37. if (!firstEdge)
  38. return false;
  39. unsigned short* nextEdge = firstEdge + nverts;
  40. int edgeCount = 0;
  41. rcEdge* edges = (rcEdge*)rcAlloc(sizeof(rcEdge)*maxEdgeCount, RC_ALLOC_TEMP);
  42. if (!edges)
  43. {
  44. rcFree(firstEdge);
  45. return false;
  46. }
  47. for (int i = 0; i < nverts; i++)
  48. firstEdge[i] = RC_MESH_NULL_IDX;
  49. for (int i = 0; i < npolys; ++i)
  50. {
  51. unsigned short* t = &polys[i*vertsPerPoly*2];
  52. for (int j = 0; j < vertsPerPoly; ++j)
  53. {
  54. if (t[j] == RC_MESH_NULL_IDX) break;
  55. unsigned short v0 = t[j];
  56. unsigned short v1 = (j+1 >= vertsPerPoly || t[j+1] == RC_MESH_NULL_IDX) ? t[0] : t[j+1];
  57. if (v0 < v1)
  58. {
  59. rcEdge& edge = edges[edgeCount];
  60. edge.vert[0] = v0;
  61. edge.vert[1] = v1;
  62. edge.poly[0] = (unsigned short)i;
  63. edge.polyEdge[0] = (unsigned short)j;
  64. edge.poly[1] = (unsigned short)i;
  65. edge.polyEdge[1] = 0;
  66. // Insert edge
  67. nextEdge[edgeCount] = firstEdge[v0];
  68. firstEdge[v0] = (unsigned short)edgeCount;
  69. edgeCount++;
  70. }
  71. }
  72. }
  73. for (int i = 0; i < npolys; ++i)
  74. {
  75. unsigned short* t = &polys[i*vertsPerPoly*2];
  76. for (int j = 0; j < vertsPerPoly; ++j)
  77. {
  78. if (t[j] == RC_MESH_NULL_IDX) break;
  79. unsigned short v0 = t[j];
  80. unsigned short v1 = (j+1 >= vertsPerPoly || t[j+1] == RC_MESH_NULL_IDX) ? t[0] : t[j+1];
  81. if (v0 > v1)
  82. {
  83. for (unsigned short e = firstEdge[v1]; e != RC_MESH_NULL_IDX; e = nextEdge[e])
  84. {
  85. rcEdge& edge = edges[e];
  86. if (edge.vert[1] == v0 && edge.poly[0] == edge.poly[1])
  87. {
  88. edge.poly[1] = (unsigned short)i;
  89. edge.polyEdge[1] = (unsigned short)j;
  90. break;
  91. }
  92. }
  93. }
  94. }
  95. }
  96. // Store adjacency
  97. for (int i = 0; i < edgeCount; ++i)
  98. {
  99. const rcEdge& e = edges[i];
  100. if (e.poly[0] != e.poly[1])
  101. {
  102. unsigned short* p0 = &polys[e.poly[0]*vertsPerPoly*2];
  103. unsigned short* p1 = &polys[e.poly[1]*vertsPerPoly*2];
  104. p0[vertsPerPoly + e.polyEdge[0]] = e.poly[1];
  105. p1[vertsPerPoly + e.polyEdge[1]] = e.poly[0];
  106. }
  107. }
  108. rcFree(firstEdge);
  109. rcFree(edges);
  110. return true;
  111. }
  112. static const int VERTEX_BUCKET_COUNT = (1<<12);
  113. inline int computeVertexHash(int x, int y, int z)
  114. {
  115. const unsigned int h1 = 0x8da6b343; // Large multiplicative constants;
  116. const unsigned int h2 = 0xd8163841; // here arbitrarily chosen primes
  117. const unsigned int h3 = 0xcb1ab31f;
  118. unsigned int n = h1 * x + h2 * y + h3 * z;
  119. return (int)(n & (VERTEX_BUCKET_COUNT-1));
  120. }
  121. static unsigned short addVertex(unsigned short x, unsigned short y, unsigned short z,
  122. unsigned short* verts, int* firstVert, int* nextVert, int& nv)
  123. {
  124. int bucket = computeVertexHash(x, 0, z);
  125. int i = firstVert[bucket];
  126. while (i != -1)
  127. {
  128. const unsigned short* v = &verts[i*3];
  129. if (v[0] == x && (rcAbs(v[1] - y) <= 2) && v[2] == z)
  130. return (unsigned short)i;
  131. i = nextVert[i]; // next
  132. }
  133. // Could not find, create new.
  134. i = nv; nv++;
  135. unsigned short* v = &verts[i*3];
  136. v[0] = x;
  137. v[1] = y;
  138. v[2] = z;
  139. nextVert[i] = firstVert[bucket];
  140. firstVert[bucket] = i;
  141. return (unsigned short)i;
  142. }
  143. // Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
  144. inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
  145. inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
  146. inline int area2(const int* a, const int* b, const int* c)
  147. {
  148. return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]);
  149. }
  150. // Exclusive or: true iff exactly one argument is true.
  151. // The arguments are negated to ensure that they are 0/1
  152. // values. Then the bitwise Xor operator may apply.
  153. // (This idea is due to Michael Baldwin.)
  154. inline bool xorb(bool x, bool y)
  155. {
  156. return !x ^ !y;
  157. }
  158. // Returns true iff c is strictly to the left of the directed
  159. // line through a to b.
  160. inline bool left(const int* a, const int* b, const int* c)
  161. {
  162. return area2(a, b, c) < 0;
  163. }
  164. inline bool leftOn(const int* a, const int* b, const int* c)
  165. {
  166. return area2(a, b, c) <= 0;
  167. }
  168. inline bool collinear(const int* a, const int* b, const int* c)
  169. {
  170. return area2(a, b, c) == 0;
  171. }
  172. // Returns true iff ab properly intersects cd: they share
  173. // a point interior to both segments. The properness of the
  174. // intersection is ensured by using strict leftness.
  175. static bool intersectProp(const int* a, const int* b, const int* c, const int* d)
  176. {
  177. // Eliminate improper cases.
  178. if (collinear(a,b,c) || collinear(a,b,d) ||
  179. collinear(c,d,a) || collinear(c,d,b))
  180. return false;
  181. return xorb(left(a,b,c), left(a,b,d)) && xorb(left(c,d,a), left(c,d,b));
  182. }
  183. // Returns T iff (a,b,c) are collinear and point c lies
  184. // on the closed segement ab.
  185. static bool between(const int* a, const int* b, const int* c)
  186. {
  187. if (!collinear(a, b, c))
  188. return false;
  189. // If ab not vertical, check betweenness on x; else on y.
  190. if (a[0] != b[0])
  191. return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0]));
  192. else
  193. return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2]));
  194. }
  195. // Returns true iff segments ab and cd intersect, properly or improperly.
  196. static bool intersect(const int* a, const int* b, const int* c, const int* d)
  197. {
  198. if (intersectProp(a, b, c, d))
  199. return true;
  200. else if (between(a, b, c) || between(a, b, d) ||
  201. between(c, d, a) || between(c, d, b))
  202. return true;
  203. else
  204. return false;
  205. }
  206. static bool vequal(const int* a, const int* b)
  207. {
  208. return a[0] == b[0] && a[2] == b[2];
  209. }
  210. // Returns T iff (v_i, v_j) is a proper internal *or* external
  211. // diagonal of P, *ignoring edges incident to v_i and v_j*.
  212. static bool diagonalie(int i, int j, int n, const int* verts, int* indices)
  213. {
  214. const int* d0 = &verts[(indices[i] & 0x0fffffff) * 4];
  215. const int* d1 = &verts[(indices[j] & 0x0fffffff) * 4];
  216. // For each edge (k,k+1) of P
  217. for (int k = 0; k < n; k++)
  218. {
  219. int k1 = next(k, n);
  220. // Skip edges incident to i or j
  221. if (!((k == i) || (k1 == i) || (k == j) || (k1 == j)))
  222. {
  223. const int* p0 = &verts[(indices[k] & 0x0fffffff) * 4];
  224. const int* p1 = &verts[(indices[k1] & 0x0fffffff) * 4];
  225. if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
  226. continue;
  227. if (intersect(d0, d1, p0, p1))
  228. return false;
  229. }
  230. }
  231. return true;
  232. }
  233. // Returns true iff the diagonal (i,j) is strictly internal to the
  234. // polygon P in the neighborhood of the i endpoint.
  235. static bool inCone(int i, int j, int n, const int* verts, int* indices)
  236. {
  237. const int* pi = &verts[(indices[i] & 0x0fffffff) * 4];
  238. const int* pj = &verts[(indices[j] & 0x0fffffff) * 4];
  239. const int* pi1 = &verts[(indices[next(i, n)] & 0x0fffffff) * 4];
  240. const int* pin1 = &verts[(indices[prev(i, n)] & 0x0fffffff) * 4];
  241. // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
  242. if (leftOn(pin1, pi, pi1))
  243. return left(pi, pj, pin1) && left(pj, pi, pi1);
  244. // Assume (i-1,i,i+1) not collinear.
  245. // else P[i] is reflex.
  246. return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
  247. }
  248. // Returns T iff (v_i, v_j) is a proper internal
  249. // diagonal of P.
  250. static bool diagonal(int i, int j, int n, const int* verts, int* indices)
  251. {
  252. return inCone(i, j, n, verts, indices) && diagonalie(i, j, n, verts, indices);
  253. }
  254. static bool diagonalieLoose(int i, int j, int n, const int* verts, int* indices)
  255. {
  256. const int* d0 = &verts[(indices[i] & 0x0fffffff) * 4];
  257. const int* d1 = &verts[(indices[j] & 0x0fffffff) * 4];
  258. // For each edge (k,k+1) of P
  259. for (int k = 0; k < n; k++)
  260. {
  261. int k1 = next(k, n);
  262. // Skip edges incident to i or j
  263. if (!((k == i) || (k1 == i) || (k == j) || (k1 == j)))
  264. {
  265. const int* p0 = &verts[(indices[k] & 0x0fffffff) * 4];
  266. const int* p1 = &verts[(indices[k1] & 0x0fffffff) * 4];
  267. if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
  268. continue;
  269. if (intersectProp(d0, d1, p0, p1))
  270. return false;
  271. }
  272. }
  273. return true;
  274. }
  275. static bool inConeLoose(int i, int j, int n, const int* verts, int* indices)
  276. {
  277. const int* pi = &verts[(indices[i] & 0x0fffffff) * 4];
  278. const int* pj = &verts[(indices[j] & 0x0fffffff) * 4];
  279. const int* pi1 = &verts[(indices[next(i, n)] & 0x0fffffff) * 4];
  280. const int* pin1 = &verts[(indices[prev(i, n)] & 0x0fffffff) * 4];
  281. // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
  282. if (leftOn(pin1, pi, pi1))
  283. return leftOn(pi, pj, pin1) && leftOn(pj, pi, pi1);
  284. // Assume (i-1,i,i+1) not collinear.
  285. // else P[i] is reflex.
  286. return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
  287. }
  288. static bool diagonalLoose(int i, int j, int n, const int* verts, int* indices)
  289. {
  290. return inConeLoose(i, j, n, verts, indices) && diagonalieLoose(i, j, n, verts, indices);
  291. }
  292. static int triangulate(int n, const int* verts, int* indices, int* tris)
  293. {
  294. int ntris = 0;
  295. int* dst = tris;
  296. // The last bit of the index is used to indicate if the vertex can be removed.
  297. for (int i = 0; i < n; i++)
  298. {
  299. int i1 = next(i, n);
  300. int i2 = next(i1, n);
  301. if (diagonal(i, i2, n, verts, indices))
  302. indices[i1] |= 0x80000000;
  303. }
  304. while (n > 3)
  305. {
  306. int minLen = -1;
  307. int mini = -1;
  308. for (int i = 0; i < n; i++)
  309. {
  310. int i1 = next(i, n);
  311. if (indices[i1] & 0x80000000)
  312. {
  313. const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4];
  314. const int* p2 = &verts[(indices[next(i1, n)] & 0x0fffffff) * 4];
  315. int dx = p2[0] - p0[0];
  316. int dy = p2[2] - p0[2];
  317. int len = dx*dx + dy*dy;
  318. if (minLen < 0 || len < minLen)
  319. {
  320. minLen = len;
  321. mini = i;
  322. }
  323. }
  324. }
  325. if (mini == -1)
  326. {
  327. // We might get here because the contour has overlapping segments, like this:
  328. //
  329. // A o-o=====o---o B
  330. // / |C D| \.
  331. // o o o o
  332. // : : : :
  333. // We'll try to recover by loosing up the inCone test a bit so that a diagonal
  334. // like A-B or C-D can be found and we can continue.
  335. minLen = -1;
  336. mini = -1;
  337. for (int i = 0; i < n; i++)
  338. {
  339. int i1 = next(i, n);
  340. int i2 = next(i1, n);
  341. if (diagonalLoose(i, i2, n, verts, indices))
  342. {
  343. const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4];
  344. const int* p2 = &verts[(indices[next(i2, n)] & 0x0fffffff) * 4];
  345. int dx = p2[0] - p0[0];
  346. int dy = p2[2] - p0[2];
  347. int len = dx*dx + dy*dy;
  348. if (minLen < 0 || len < minLen)
  349. {
  350. minLen = len;
  351. mini = i;
  352. }
  353. }
  354. }
  355. if (mini == -1)
  356. {
  357. // The contour is messed up. This sometimes happens
  358. // if the contour simplification is too aggressive.
  359. return -ntris;
  360. }
  361. }
  362. int i = mini;
  363. int i1 = next(i, n);
  364. int i2 = next(i1, n);
  365. *dst++ = indices[i] & 0x0fffffff;
  366. *dst++ = indices[i1] & 0x0fffffff;
  367. *dst++ = indices[i2] & 0x0fffffff;
  368. ntris++;
  369. // Removes P[i1] by copying P[i+1]...P[n-1] left one index.
  370. n--;
  371. for (int k = i1; k < n; k++)
  372. indices[k] = indices[k+1];
  373. if (i1 >= n) i1 = 0;
  374. i = prev(i1,n);
  375. // Update diagonal flags.
  376. if (diagonal(prev(i, n), i1, n, verts, indices))
  377. indices[i] |= 0x80000000;
  378. else
  379. indices[i] &= 0x0fffffff;
  380. if (diagonal(i, next(i1, n), n, verts, indices))
  381. indices[i1] |= 0x80000000;
  382. else
  383. indices[i1] &= 0x0fffffff;
  384. }
  385. // Append the remaining triangle.
  386. *dst++ = indices[0] & 0x0fffffff;
  387. *dst++ = indices[1] & 0x0fffffff;
  388. *dst++ = indices[2] & 0x0fffffff;
  389. ntris++;
  390. return ntris;
  391. }
  392. static int countPolyVerts(const unsigned short* p, const int nvp)
  393. {
  394. for (int i = 0; i < nvp; ++i)
  395. if (p[i] == RC_MESH_NULL_IDX)
  396. return i;
  397. return nvp;
  398. }
  399. inline bool uleft(const unsigned short* a, const unsigned short* b, const unsigned short* c)
  400. {
  401. return ((int)b[0] - (int)a[0]) * ((int)c[2] - (int)a[2]) -
  402. ((int)c[0] - (int)a[0]) * ((int)b[2] - (int)a[2]) < 0;
  403. }
  404. static int getPolyMergeValue(unsigned short* pa, unsigned short* pb,
  405. const unsigned short* verts, int& ea, int& eb,
  406. const int nvp)
  407. {
  408. const int na = countPolyVerts(pa, nvp);
  409. const int nb = countPolyVerts(pb, nvp);
  410. // If the merged polygon would be too big, do not merge.
  411. if (na+nb-2 > nvp)
  412. return -1;
  413. // Check if the polygons share an edge.
  414. ea = -1;
  415. eb = -1;
  416. for (int i = 0; i < na; ++i)
  417. {
  418. unsigned short va0 = pa[i];
  419. unsigned short va1 = pa[(i+1) % na];
  420. if (va0 > va1)
  421. rcSwap(va0, va1);
  422. for (int j = 0; j < nb; ++j)
  423. {
  424. unsigned short vb0 = pb[j];
  425. unsigned short vb1 = pb[(j+1) % nb];
  426. if (vb0 > vb1)
  427. rcSwap(vb0, vb1);
  428. if (va0 == vb0 && va1 == vb1)
  429. {
  430. ea = i;
  431. eb = j;
  432. break;
  433. }
  434. }
  435. }
  436. // No common edge, cannot merge.
  437. if (ea == -1 || eb == -1)
  438. return -1;
  439. // Check to see if the merged polygon would be convex.
  440. unsigned short va, vb, vc;
  441. va = pa[(ea+na-1) % na];
  442. vb = pa[ea];
  443. vc = pb[(eb+2) % nb];
  444. if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3]))
  445. return -1;
  446. va = pb[(eb+nb-1) % nb];
  447. vb = pb[eb];
  448. vc = pa[(ea+2) % na];
  449. if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3]))
  450. return -1;
  451. va = pa[ea];
  452. vb = pa[(ea+1)%na];
  453. int dx = (int)verts[va*3+0] - (int)verts[vb*3+0];
  454. int dy = (int)verts[va*3+2] - (int)verts[vb*3+2];
  455. return dx*dx + dy*dy;
  456. }
  457. static void mergePolyVerts(unsigned short* pa, unsigned short* pb, int ea, int eb,
  458. unsigned short* tmp, const int nvp)
  459. {
  460. const int na = countPolyVerts(pa, nvp);
  461. const int nb = countPolyVerts(pb, nvp);
  462. // Merge polygons.
  463. memset(tmp, 0xff, sizeof(unsigned short)*nvp);
  464. int n = 0;
  465. // Add pa
  466. for (int i = 0; i < na-1; ++i)
  467. tmp[n++] = pa[(ea+1+i) % na];
  468. // Add pb
  469. for (int i = 0; i < nb-1; ++i)
  470. tmp[n++] = pb[(eb+1+i) % nb];
  471. memcpy(pa, tmp, sizeof(unsigned short)*nvp);
  472. }
  473. static void pushFront(int v, int* arr, int& an)
  474. {
  475. an++;
  476. for (int i = an-1; i > 0; --i) arr[i] = arr[i-1];
  477. arr[0] = v;
  478. }
  479. static void pushBack(int v, int* arr, int& an)
  480. {
  481. arr[an] = v;
  482. an++;
  483. }
  484. static bool canRemoveVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short rem)
  485. {
  486. const int nvp = mesh.nvp;
  487. // Count number of polygons to remove.
  488. int numTouchedVerts = 0;
  489. int numRemainingEdges = 0;
  490. for (int i = 0; i < mesh.npolys; ++i)
  491. {
  492. unsigned short* p = &mesh.polys[i*nvp*2];
  493. const int nv = countPolyVerts(p, nvp);
  494. int numRemoved = 0;
  495. int numVerts = 0;
  496. for (int j = 0; j < nv; ++j)
  497. {
  498. if (p[j] == rem)
  499. {
  500. numTouchedVerts++;
  501. numRemoved++;
  502. }
  503. numVerts++;
  504. }
  505. if (numRemoved)
  506. {
  507. numRemainingEdges += numVerts-(numRemoved+1);
  508. }
  509. }
  510. // There would be too few edges remaining to create a polygon.
  511. // This can happen for example when a tip of a triangle is marked
  512. // as deletion, but there are no other polys that share the vertex.
  513. // In this case, the vertex should not be removed.
  514. if (numRemainingEdges <= 2)
  515. return false;
  516. // Find edges which share the removed vertex.
  517. const int maxEdges = numTouchedVerts*2;
  518. int nedges = 0;
  519. rcScopedDelete<int> edges((int*)rcAlloc(sizeof(int)*maxEdges*3, RC_ALLOC_TEMP));
  520. if (!edges)
  521. {
  522. ctx->log(RC_LOG_WARNING, "canRemoveVertex: Out of memory 'edges' (%d).", maxEdges*3);
  523. return false;
  524. }
  525. for (int i = 0; i < mesh.npolys; ++i)
  526. {
  527. unsigned short* p = &mesh.polys[i*nvp*2];
  528. const int nv = countPolyVerts(p, nvp);
  529. // Collect edges which touches the removed vertex.
  530. for (int j = 0, k = nv-1; j < nv; k = j++)
  531. {
  532. if (p[j] == rem || p[k] == rem)
  533. {
  534. // Arrange edge so that a=rem.
  535. int a = p[j], b = p[k];
  536. if (b == rem)
  537. rcSwap(a,b);
  538. // Check if the edge exists
  539. bool exists = false;
  540. for (int m = 0; m < nedges; ++m)
  541. {
  542. int* e = &edges[m*3];
  543. if (e[1] == b)
  544. {
  545. // Exists, increment vertex share count.
  546. e[2]++;
  547. exists = true;
  548. }
  549. }
  550. // Add new edge.
  551. if (!exists)
  552. {
  553. int* e = &edges[nedges*3];
  554. e[0] = a;
  555. e[1] = b;
  556. e[2] = 1;
  557. nedges++;
  558. }
  559. }
  560. }
  561. }
  562. // There should be no more than 2 open edges.
  563. // This catches the case that two non-adjacent polygons
  564. // share the removed vertex. In that case, do not remove the vertex.
  565. int numOpenEdges = 0;
  566. for (int i = 0; i < nedges; ++i)
  567. {
  568. if (edges[i*3+2] < 2)
  569. numOpenEdges++;
  570. }
  571. if (numOpenEdges > 2)
  572. return false;
  573. return true;
  574. }
  575. static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short rem, const int maxTris)
  576. {
  577. const int nvp = mesh.nvp;
  578. // Count number of polygons to remove.
  579. int numRemovedVerts = 0;
  580. for (int i = 0; i < mesh.npolys; ++i)
  581. {
  582. unsigned short* p = &mesh.polys[i*nvp*2];
  583. const int nv = countPolyVerts(p, nvp);
  584. for (int j = 0; j < nv; ++j)
  585. {
  586. if (p[j] == rem)
  587. numRemovedVerts++;
  588. }
  589. }
  590. int nedges = 0;
  591. rcScopedDelete<int> edges((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp*4, RC_ALLOC_TEMP));
  592. if (!edges)
  593. {
  594. ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'edges' (%d).", numRemovedVerts*nvp*4);
  595. return false;
  596. }
  597. int nhole = 0;
  598. rcScopedDelete<int> hole((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
  599. if (!hole)
  600. {
  601. ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hole' (%d).", numRemovedVerts*nvp);
  602. return false;
  603. }
  604. int nhreg = 0;
  605. rcScopedDelete<int> hreg((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
  606. if (!hreg)
  607. {
  608. ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hreg' (%d).", numRemovedVerts*nvp);
  609. return false;
  610. }
  611. int nharea = 0;
  612. rcScopedDelete<int> harea((int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP));
  613. if (!harea)
  614. {
  615. ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'harea' (%d).", numRemovedVerts*nvp);
  616. return false;
  617. }
  618. for (int i = 0; i < mesh.npolys; ++i)
  619. {
  620. unsigned short* p = &mesh.polys[i*nvp*2];
  621. const int nv = countPolyVerts(p, nvp);
  622. bool hasRem = false;
  623. for (int j = 0; j < nv; ++j)
  624. if (p[j] == rem) hasRem = true;
  625. if (hasRem)
  626. {
  627. // Collect edges which does not touch the removed vertex.
  628. for (int j = 0, k = nv-1; j < nv; k = j++)
  629. {
  630. if (p[j] != rem && p[k] != rem)
  631. {
  632. int* e = &edges[nedges*4];
  633. e[0] = p[k];
  634. e[1] = p[j];
  635. e[2] = mesh.regs[i];
  636. e[3] = mesh.areas[i];
  637. nedges++;
  638. }
  639. }
  640. // Remove the polygon.
  641. unsigned short* p2 = &mesh.polys[(mesh.npolys-1)*nvp*2];
  642. if (p != p2)
  643. memcpy(p,p2,sizeof(unsigned short)*nvp);
  644. memset(p+nvp,0xff,sizeof(unsigned short)*nvp);
  645. mesh.regs[i] = mesh.regs[mesh.npolys-1];
  646. mesh.areas[i] = mesh.areas[mesh.npolys-1];
  647. mesh.npolys--;
  648. --i;
  649. }
  650. }
  651. // Remove vertex.
  652. for (int i = (int)rem; i < mesh.nverts - 1; ++i)
  653. {
  654. mesh.verts[i*3+0] = mesh.verts[(i+1)*3+0];
  655. mesh.verts[i*3+1] = mesh.verts[(i+1)*3+1];
  656. mesh.verts[i*3+2] = mesh.verts[(i+1)*3+2];
  657. }
  658. mesh.nverts--;
  659. // Adjust indices to match the removed vertex layout.
  660. for (int i = 0; i < mesh.npolys; ++i)
  661. {
  662. unsigned short* p = &mesh.polys[i*nvp*2];
  663. const int nv = countPolyVerts(p, nvp);
  664. for (int j = 0; j < nv; ++j)
  665. if (p[j] > rem) p[j]--;
  666. }
  667. for (int i = 0; i < nedges; ++i)
  668. {
  669. if (edges[i*4+0] > rem) edges[i*4+0]--;
  670. if (edges[i*4+1] > rem) edges[i*4+1]--;
  671. }
  672. if (nedges == 0)
  673. return true;
  674. // Start with one vertex, keep appending connected
  675. // segments to the start and end of the hole.
  676. pushBack(edges[0], hole, nhole);
  677. pushBack(edges[2], hreg, nhreg);
  678. pushBack(edges[3], harea, nharea);
  679. while (nedges)
  680. {
  681. bool match = false;
  682. for (int i = 0; i < nedges; ++i)
  683. {
  684. const int ea = edges[i*4+0];
  685. const int eb = edges[i*4+1];
  686. const int r = edges[i*4+2];
  687. const int a = edges[i*4+3];
  688. bool add = false;
  689. if (hole[0] == eb)
  690. {
  691. // The segment matches the beginning of the hole boundary.
  692. pushFront(ea, hole, nhole);
  693. pushFront(r, hreg, nhreg);
  694. pushFront(a, harea, nharea);
  695. add = true;
  696. }
  697. else if (hole[nhole-1] == ea)
  698. {
  699. // The segment matches the end of the hole boundary.
  700. pushBack(eb, hole, nhole);
  701. pushBack(r, hreg, nhreg);
  702. pushBack(a, harea, nharea);
  703. add = true;
  704. }
  705. if (add)
  706. {
  707. // The edge segment was added, remove it.
  708. edges[i*4+0] = edges[(nedges-1)*4+0];
  709. edges[i*4+1] = edges[(nedges-1)*4+1];
  710. edges[i*4+2] = edges[(nedges-1)*4+2];
  711. edges[i*4+3] = edges[(nedges-1)*4+3];
  712. --nedges;
  713. match = true;
  714. --i;
  715. }
  716. }
  717. if (!match)
  718. break;
  719. }
  720. rcScopedDelete<int> tris((int*)rcAlloc(sizeof(int)*nhole*3, RC_ALLOC_TEMP));
  721. if (!tris)
  722. {
  723. ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tris' (%d).", nhole*3);
  724. return false;
  725. }
  726. rcScopedDelete<int> tverts((int*)rcAlloc(sizeof(int)*nhole*4, RC_ALLOC_TEMP));
  727. if (!tverts)
  728. {
  729. ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tverts' (%d).", nhole*4);
  730. return false;
  731. }
  732. rcScopedDelete<int> thole((int*)rcAlloc(sizeof(int)*nhole, RC_ALLOC_TEMP));
  733. if (!thole)
  734. {
  735. ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'thole' (%d).", nhole);
  736. return false;
  737. }
  738. // Generate temp vertex array for triangulation.
  739. for (int i = 0; i < nhole; ++i)
  740. {
  741. const int pi = hole[i];
  742. tverts[i*4+0] = mesh.verts[pi*3+0];
  743. tverts[i*4+1] = mesh.verts[pi*3+1];
  744. tverts[i*4+2] = mesh.verts[pi*3+2];
  745. tverts[i*4+3] = 0;
  746. thole[i] = i;
  747. }
  748. // Triangulate the hole.
  749. int ntris = triangulate(nhole, &tverts[0], &thole[0], tris);
  750. if (ntris < 0)
  751. {
  752. ntris = -ntris;
  753. ctx->log(RC_LOG_WARNING, "removeVertex: triangulate() returned bad results.");
  754. }
  755. // Merge the hole triangles back to polygons.
  756. rcScopedDelete<unsigned short> polys((unsigned short*)rcAlloc(sizeof(unsigned short)*(ntris+1)*nvp, RC_ALLOC_TEMP));
  757. if (!polys)
  758. {
  759. ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'polys' (%d).", (ntris+1)*nvp);
  760. return false;
  761. }
  762. rcScopedDelete<unsigned short> pregs((unsigned short*)rcAlloc(sizeof(unsigned short)*ntris, RC_ALLOC_TEMP));
  763. if (!pregs)
  764. {
  765. ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pregs' (%d).", ntris);
  766. return false;
  767. }
  768. rcScopedDelete<unsigned char> pareas((unsigned char*)rcAlloc(sizeof(unsigned char)*ntris, RC_ALLOC_TEMP));
  769. if (!pareas)
  770. {
  771. ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pareas' (%d).", ntris);
  772. return false;
  773. }
  774. unsigned short* tmpPoly = &polys[ntris*nvp];
  775. // Build initial polygons.
  776. int npolys = 0;
  777. memset(polys, 0xff, ntris*nvp*sizeof(unsigned short));
  778. for (int j = 0; j < ntris; ++j)
  779. {
  780. int* t = &tris[j*3];
  781. if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])
  782. {
  783. polys[npolys*nvp+0] = (unsigned short)hole[t[0]];
  784. polys[npolys*nvp+1] = (unsigned short)hole[t[1]];
  785. polys[npolys*nvp+2] = (unsigned short)hole[t[2]];
  786. // If this polygon covers multiple region types then
  787. // mark it as such
  788. if (hreg[t[0]] != hreg[t[1]] || hreg[t[1]] != hreg[t[2]])
  789. pregs[npolys] = RC_MULTIPLE_REGS;
  790. else
  791. pregs[npolys] = (unsigned short)hreg[t[0]];
  792. pareas[npolys] = (unsigned char)harea[t[0]];
  793. npolys++;
  794. }
  795. }
  796. if (!npolys)
  797. return true;
  798. // Merge polygons.
  799. if (nvp > 3)
  800. {
  801. for (;;)
  802. {
  803. // Find best polygons to merge.
  804. int bestMergeVal = 0;
  805. int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0;
  806. for (int j = 0; j < npolys-1; ++j)
  807. {
  808. unsigned short* pj = &polys[j*nvp];
  809. for (int k = j+1; k < npolys; ++k)
  810. {
  811. unsigned short* pk = &polys[k*nvp];
  812. int ea, eb;
  813. int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb, nvp);
  814. if (v > bestMergeVal)
  815. {
  816. bestMergeVal = v;
  817. bestPa = j;
  818. bestPb = k;
  819. bestEa = ea;
  820. bestEb = eb;
  821. }
  822. }
  823. }
  824. if (bestMergeVal > 0)
  825. {
  826. // Found best, merge.
  827. unsigned short* pa = &polys[bestPa*nvp];
  828. unsigned short* pb = &polys[bestPb*nvp];
  829. mergePolyVerts(pa, pb, bestEa, bestEb, tmpPoly, nvp);
  830. if (pregs[bestPa] != pregs[bestPb])
  831. pregs[bestPa] = RC_MULTIPLE_REGS;
  832. unsigned short* last = &polys[(npolys-1)*nvp];
  833. if (pb != last)
  834. memcpy(pb, last, sizeof(unsigned short)*nvp);
  835. pregs[bestPb] = pregs[npolys-1];
  836. pareas[bestPb] = pareas[npolys-1];
  837. npolys--;
  838. }
  839. else
  840. {
  841. // Could not merge any polygons, stop.
  842. break;
  843. }
  844. }
  845. }
  846. // Store polygons.
  847. for (int i = 0; i < npolys; ++i)
  848. {
  849. if (mesh.npolys >= maxTris) break;
  850. unsigned short* p = &mesh.polys[mesh.npolys*nvp*2];
  851. memset(p,0xff,sizeof(unsigned short)*nvp*2);
  852. for (int j = 0; j < nvp; ++j)
  853. p[j] = polys[i*nvp+j];
  854. mesh.regs[mesh.npolys] = pregs[i];
  855. mesh.areas[mesh.npolys] = pareas[i];
  856. mesh.npolys++;
  857. if (mesh.npolys > maxTris)
  858. {
  859. ctx->log(RC_LOG_ERROR, "removeVertex: Too many polygons %d (max:%d).", mesh.npolys, maxTris);
  860. return false;
  861. }
  862. }
  863. return true;
  864. }
  865. /// @par
  866. ///
  867. /// @note If the mesh data is to be used to construct a Detour navigation mesh, then the upper
  868. /// limit must be retricted to <= #DT_VERTS_PER_POLYGON.
  869. ///
  870. /// @see rcAllocPolyMesh, rcContourSet, rcPolyMesh, rcConfig
  871. bool rcBuildPolyMesh(rcContext* ctx, const rcContourSet& cset, const int nvp, rcPolyMesh& mesh)
  872. {
  873. rcAssert(ctx);
  874. rcScopedTimer timer(ctx, RC_TIMER_BUILD_POLYMESH);
  875. rcVcopy(mesh.bmin, cset.bmin);
  876. rcVcopy(mesh.bmax, cset.bmax);
  877. mesh.cs = cset.cs;
  878. mesh.ch = cset.ch;
  879. mesh.borderSize = cset.borderSize;
  880. mesh.maxEdgeError = cset.maxError;
  881. int maxVertices = 0;
  882. int maxTris = 0;
  883. int maxVertsPerCont = 0;
  884. for (int i = 0; i < cset.nconts; ++i)
  885. {
  886. // Skip null contours.
  887. if (cset.conts[i].nverts < 3) continue;
  888. maxVertices += cset.conts[i].nverts;
  889. maxTris += cset.conts[i].nverts - 2;
  890. maxVertsPerCont = rcMax(maxVertsPerCont, cset.conts[i].nverts);
  891. }
  892. if (maxVertices >= 0xfffe)
  893. {
  894. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Too many vertices %d.", maxVertices);
  895. return false;
  896. }
  897. rcScopedDelete<unsigned char> vflags((unsigned char*)rcAlloc(sizeof(unsigned char)*maxVertices, RC_ALLOC_TEMP));
  898. if (!vflags)
  899. {
  900. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'vflags' (%d).", maxVertices);
  901. return false;
  902. }
  903. memset(vflags, 0, maxVertices);
  904. mesh.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertices*3, RC_ALLOC_PERM);
  905. if (!mesh.verts)
  906. {
  907. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.verts' (%d).", maxVertices);
  908. return false;
  909. }
  910. mesh.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxTris*nvp*2, RC_ALLOC_PERM);
  911. if (!mesh.polys)
  912. {
  913. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.polys' (%d).", maxTris*nvp*2);
  914. return false;
  915. }
  916. mesh.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxTris, RC_ALLOC_PERM);
  917. if (!mesh.regs)
  918. {
  919. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.regs' (%d).", maxTris);
  920. return false;
  921. }
  922. mesh.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxTris, RC_ALLOC_PERM);
  923. if (!mesh.areas)
  924. {
  925. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.areas' (%d).", maxTris);
  926. return false;
  927. }
  928. mesh.nverts = 0;
  929. mesh.npolys = 0;
  930. mesh.nvp = nvp;
  931. mesh.maxpolys = maxTris;
  932. memset(mesh.verts, 0, sizeof(unsigned short)*maxVertices*3);
  933. memset(mesh.polys, 0xff, sizeof(unsigned short)*maxTris*nvp*2);
  934. memset(mesh.regs, 0, sizeof(unsigned short)*maxTris);
  935. memset(mesh.areas, 0, sizeof(unsigned char)*maxTris);
  936. rcScopedDelete<int> nextVert((int*)rcAlloc(sizeof(int)*maxVertices, RC_ALLOC_TEMP));
  937. if (!nextVert)
  938. {
  939. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'nextVert' (%d).", maxVertices);
  940. return false;
  941. }
  942. memset(nextVert, 0, sizeof(int)*maxVertices);
  943. rcScopedDelete<int> firstVert((int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP));
  944. if (!firstVert)
  945. {
  946. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT);
  947. return false;
  948. }
  949. for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i)
  950. firstVert[i] = -1;
  951. rcScopedDelete<int> indices((int*)rcAlloc(sizeof(int)*maxVertsPerCont, RC_ALLOC_TEMP));
  952. if (!indices)
  953. {
  954. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'indices' (%d).", maxVertsPerCont);
  955. return false;
  956. }
  957. rcScopedDelete<int> tris((int*)rcAlloc(sizeof(int)*maxVertsPerCont*3, RC_ALLOC_TEMP));
  958. if (!tris)
  959. {
  960. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'tris' (%d).", maxVertsPerCont*3);
  961. return false;
  962. }
  963. rcScopedDelete<unsigned short> polys((unsigned short*)rcAlloc(sizeof(unsigned short)*(maxVertsPerCont+1)*nvp, RC_ALLOC_TEMP));
  964. if (!polys)
  965. {
  966. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'polys' (%d).", maxVertsPerCont*nvp);
  967. return false;
  968. }
  969. unsigned short* tmpPoly = &polys[maxVertsPerCont*nvp];
  970. for (int i = 0; i < cset.nconts; ++i)
  971. {
  972. rcContour& cont = cset.conts[i];
  973. // Skip null contours.
  974. if (cont.nverts < 3)
  975. continue;
  976. // Triangulate contour
  977. for (int j = 0; j < cont.nverts; ++j)
  978. indices[j] = j;
  979. int ntris = triangulate(cont.nverts, cont.verts, &indices[0], &tris[0]);
  980. if (ntris <= 0)
  981. {
  982. // Bad triangulation, should not happen.
  983. /* printf("\tconst float bmin[3] = {%ff,%ff,%ff};\n", cset.bmin[0], cset.bmin[1], cset.bmin[2]);
  984. printf("\tconst float cs = %ff;\n", cset.cs);
  985. printf("\tconst float ch = %ff;\n", cset.ch);
  986. printf("\tconst int verts[] = {\n");
  987. for (int k = 0; k < cont.nverts; ++k)
  988. {
  989. const int* v = &cont.verts[k*4];
  990. printf("\t\t%d,%d,%d,%d,\n", v[0], v[1], v[2], v[3]);
  991. }
  992. printf("\t};\n\tconst int nverts = sizeof(verts)/(sizeof(int)*4);\n");*/
  993. ctx->log(RC_LOG_WARNING, "rcBuildPolyMesh: Bad triangulation Contour %d.", i);
  994. ntris = -ntris;
  995. }
  996. // Add and merge vertices.
  997. for (int j = 0; j < cont.nverts; ++j)
  998. {
  999. const int* v = &cont.verts[j*4];
  1000. indices[j] = addVertex((unsigned short)v[0], (unsigned short)v[1], (unsigned short)v[2],
  1001. mesh.verts, firstVert, nextVert, mesh.nverts);
  1002. if (v[3] & RC_BORDER_VERTEX)
  1003. {
  1004. // This vertex should be removed.
  1005. vflags[indices[j]] = 1;
  1006. }
  1007. }
  1008. // Build initial polygons.
  1009. int npolys = 0;
  1010. memset(polys, 0xff, maxVertsPerCont*nvp*sizeof(unsigned short));
  1011. for (int j = 0; j < ntris; ++j)
  1012. {
  1013. int* t = &tris[j*3];
  1014. if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])
  1015. {
  1016. polys[npolys*nvp+0] = (unsigned short)indices[t[0]];
  1017. polys[npolys*nvp+1] = (unsigned short)indices[t[1]];
  1018. polys[npolys*nvp+2] = (unsigned short)indices[t[2]];
  1019. npolys++;
  1020. }
  1021. }
  1022. if (!npolys)
  1023. continue;
  1024. // Merge polygons.
  1025. if (nvp > 3)
  1026. {
  1027. for(;;)
  1028. {
  1029. // Find best polygons to merge.
  1030. int bestMergeVal = 0;
  1031. int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0;
  1032. for (int j = 0; j < npolys-1; ++j)
  1033. {
  1034. unsigned short* pj = &polys[j*nvp];
  1035. for (int k = j+1; k < npolys; ++k)
  1036. {
  1037. unsigned short* pk = &polys[k*nvp];
  1038. int ea, eb;
  1039. int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb, nvp);
  1040. if (v > bestMergeVal)
  1041. {
  1042. bestMergeVal = v;
  1043. bestPa = j;
  1044. bestPb = k;
  1045. bestEa = ea;
  1046. bestEb = eb;
  1047. }
  1048. }
  1049. }
  1050. if (bestMergeVal > 0)
  1051. {
  1052. // Found best, merge.
  1053. unsigned short* pa = &polys[bestPa*nvp];
  1054. unsigned short* pb = &polys[bestPb*nvp];
  1055. mergePolyVerts(pa, pb, bestEa, bestEb, tmpPoly, nvp);
  1056. unsigned short* lastPoly = &polys[(npolys-1)*nvp];
  1057. if (pb != lastPoly)
  1058. memcpy(pb, lastPoly, sizeof(unsigned short)*nvp);
  1059. npolys--;
  1060. }
  1061. else
  1062. {
  1063. // Could not merge any polygons, stop.
  1064. break;
  1065. }
  1066. }
  1067. }
  1068. // Store polygons.
  1069. for (int j = 0; j < npolys; ++j)
  1070. {
  1071. unsigned short* p = &mesh.polys[mesh.npolys*nvp*2];
  1072. unsigned short* q = &polys[j*nvp];
  1073. for (int k = 0; k < nvp; ++k)
  1074. p[k] = q[k];
  1075. mesh.regs[mesh.npolys] = cont.reg;
  1076. mesh.areas[mesh.npolys] = cont.area;
  1077. mesh.npolys++;
  1078. if (mesh.npolys > maxTris)
  1079. {
  1080. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Too many polygons %d (max:%d).", mesh.npolys, maxTris);
  1081. return false;
  1082. }
  1083. }
  1084. }
  1085. // Remove edge vertices.
  1086. for (int i = 0; i < mesh.nverts; ++i)
  1087. {
  1088. if (vflags[i])
  1089. {
  1090. if (!canRemoveVertex(ctx, mesh, (unsigned short)i))
  1091. continue;
  1092. if (!removeVertex(ctx, mesh, (unsigned short)i, maxTris))
  1093. {
  1094. // Failed to remove vertex
  1095. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Failed to remove edge vertex %d.", i);
  1096. return false;
  1097. }
  1098. // Remove vertex
  1099. // Note: mesh.nverts is already decremented inside removeVertex()!
  1100. // Fixup vertex flags
  1101. for (int j = i; j < mesh.nverts; ++j)
  1102. vflags[j] = vflags[j+1];
  1103. --i;
  1104. }
  1105. }
  1106. // Calculate adjacency.
  1107. if (!buildMeshAdjacency(mesh.polys, mesh.npolys, mesh.nverts, nvp))
  1108. {
  1109. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Adjacency failed.");
  1110. return false;
  1111. }
  1112. // Find portal edges
  1113. if (mesh.borderSize > 0)
  1114. {
  1115. const int w = cset.width;
  1116. const int h = cset.height;
  1117. for (int i = 0; i < mesh.npolys; ++i)
  1118. {
  1119. unsigned short* p = &mesh.polys[i*2*nvp];
  1120. for (int j = 0; j < nvp; ++j)
  1121. {
  1122. if (p[j] == RC_MESH_NULL_IDX) break;
  1123. // Skip connected edges.
  1124. if (p[nvp+j] != RC_MESH_NULL_IDX)
  1125. continue;
  1126. int nj = j+1;
  1127. if (nj >= nvp || p[nj] == RC_MESH_NULL_IDX) nj = 0;
  1128. const unsigned short* va = &mesh.verts[p[j]*3];
  1129. const unsigned short* vb = &mesh.verts[p[nj]*3];
  1130. if ((int)va[0] == 0 && (int)vb[0] == 0)
  1131. p[nvp+j] = 0x8000 | 0;
  1132. else if ((int)va[2] == h && (int)vb[2] == h)
  1133. p[nvp+j] = 0x8000 | 1;
  1134. else if ((int)va[0] == w && (int)vb[0] == w)
  1135. p[nvp+j] = 0x8000 | 2;
  1136. else if ((int)va[2] == 0 && (int)vb[2] == 0)
  1137. p[nvp+j] = 0x8000 | 3;
  1138. }
  1139. }
  1140. }
  1141. // Just allocate the mesh flags array. The user is resposible to fill it.
  1142. mesh.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*mesh.npolys, RC_ALLOC_PERM);
  1143. if (!mesh.flags)
  1144. {
  1145. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.flags' (%d).", mesh.npolys);
  1146. return false;
  1147. }
  1148. memset(mesh.flags, 0, sizeof(unsigned short) * mesh.npolys);
  1149. if (mesh.nverts > 0xffff)
  1150. {
  1151. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: The resulting mesh has too many vertices %d (max %d). Data can be corrupted.", mesh.nverts, 0xffff);
  1152. }
  1153. if (mesh.npolys > 0xffff)
  1154. {
  1155. ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff);
  1156. }
  1157. return true;
  1158. }
  1159. /// @see rcAllocPolyMesh, rcPolyMesh
  1160. bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, rcPolyMesh& mesh)
  1161. {
  1162. rcAssert(ctx);
  1163. if (!nmeshes || !meshes)
  1164. return true;
  1165. rcScopedTimer timer(ctx, RC_TIMER_MERGE_POLYMESH);
  1166. mesh.nvp = meshes[0]->nvp;
  1167. mesh.cs = meshes[0]->cs;
  1168. mesh.ch = meshes[0]->ch;
  1169. rcVcopy(mesh.bmin, meshes[0]->bmin);
  1170. rcVcopy(mesh.bmax, meshes[0]->bmax);
  1171. int maxVerts = 0;
  1172. int maxPolys = 0;
  1173. int maxVertsPerMesh = 0;
  1174. for (int i = 0; i < nmeshes; ++i)
  1175. {
  1176. rcVmin(mesh.bmin, meshes[i]->bmin);
  1177. rcVmax(mesh.bmax, meshes[i]->bmax);
  1178. maxVertsPerMesh = rcMax(maxVertsPerMesh, meshes[i]->nverts);
  1179. maxVerts += meshes[i]->nverts;
  1180. maxPolys += meshes[i]->npolys;
  1181. }
  1182. mesh.nverts = 0;
  1183. mesh.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVerts*3, RC_ALLOC_PERM);
  1184. if (!mesh.verts)
  1185. {
  1186. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.verts' (%d).", maxVerts*3);
  1187. return false;
  1188. }
  1189. mesh.npolys = 0;
  1190. mesh.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys*2*mesh.nvp, RC_ALLOC_PERM);
  1191. if (!mesh.polys)
  1192. {
  1193. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.polys' (%d).", maxPolys*2*mesh.nvp);
  1194. return false;
  1195. }
  1196. memset(mesh.polys, 0xff, sizeof(unsigned short)*maxPolys*2*mesh.nvp);
  1197. mesh.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys, RC_ALLOC_PERM);
  1198. if (!mesh.regs)
  1199. {
  1200. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.regs' (%d).", maxPolys);
  1201. return false;
  1202. }
  1203. memset(mesh.regs, 0, sizeof(unsigned short)*maxPolys);
  1204. mesh.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxPolys, RC_ALLOC_PERM);
  1205. if (!mesh.areas)
  1206. {
  1207. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.areas' (%d).", maxPolys);
  1208. return false;
  1209. }
  1210. memset(mesh.areas, 0, sizeof(unsigned char)*maxPolys);
  1211. mesh.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys, RC_ALLOC_PERM);
  1212. if (!mesh.flags)
  1213. {
  1214. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.flags' (%d).", maxPolys);
  1215. return false;
  1216. }
  1217. memset(mesh.flags, 0, sizeof(unsigned short)*maxPolys);
  1218. rcScopedDelete<int> nextVert((int*)rcAlloc(sizeof(int)*maxVerts, RC_ALLOC_TEMP));
  1219. if (!nextVert)
  1220. {
  1221. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'nextVert' (%d).", maxVerts);
  1222. return false;
  1223. }
  1224. memset(nextVert, 0, sizeof(int)*maxVerts);
  1225. rcScopedDelete<int> firstVert((int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP));
  1226. if (!firstVert)
  1227. {
  1228. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT);
  1229. return false;
  1230. }
  1231. for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i)
  1232. firstVert[i] = -1;
  1233. rcScopedDelete<unsigned short> vremap((unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertsPerMesh, RC_ALLOC_PERM));
  1234. if (!vremap)
  1235. {
  1236. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'vremap' (%d).", maxVertsPerMesh);
  1237. return false;
  1238. }
  1239. memset(vremap, 0, sizeof(unsigned short)*maxVertsPerMesh);
  1240. for (int i = 0; i < nmeshes; ++i)
  1241. {
  1242. const rcPolyMesh* pmesh = meshes[i];
  1243. const unsigned short ox = (unsigned short)floorf((pmesh->bmin[0]-mesh.bmin[0])/mesh.cs+0.5f);
  1244. const unsigned short oz = (unsigned short)floorf((pmesh->bmin[2]-mesh.bmin[2])/mesh.cs+0.5f);
  1245. bool isMinX = (ox == 0);
  1246. bool isMinZ = (oz == 0);
  1247. bool isMaxX = ((unsigned short)floorf((mesh.bmax[0] - pmesh->bmax[0]) / mesh.cs + 0.5f)) == 0;
  1248. bool isMaxZ = ((unsigned short)floorf((mesh.bmax[2] - pmesh->bmax[2]) / mesh.cs + 0.5f)) == 0;
  1249. bool isOnBorder = (isMinX || isMinZ || isMaxX || isMaxZ);
  1250. for (int j = 0; j < pmesh->nverts; ++j)
  1251. {
  1252. unsigned short* v = &pmesh->verts[j*3];
  1253. vremap[j] = addVertex(v[0]+ox, v[1], v[2]+oz,
  1254. mesh.verts, firstVert, nextVert, mesh.nverts);
  1255. }
  1256. for (int j = 0; j < pmesh->npolys; ++j)
  1257. {
  1258. unsigned short* tgt = &mesh.polys[mesh.npolys*2*mesh.nvp];
  1259. unsigned short* src = &pmesh->polys[j*2*mesh.nvp];
  1260. mesh.regs[mesh.npolys] = pmesh->regs[j];
  1261. mesh.areas[mesh.npolys] = pmesh->areas[j];
  1262. mesh.flags[mesh.npolys] = pmesh->flags[j];
  1263. mesh.npolys++;
  1264. for (int k = 0; k < mesh.nvp; ++k)
  1265. {
  1266. if (src[k] == RC_MESH_NULL_IDX) break;
  1267. tgt[k] = vremap[src[k]];
  1268. }
  1269. if (isOnBorder)
  1270. {
  1271. for (int k = mesh.nvp; k < mesh.nvp * 2; ++k)
  1272. {
  1273. if (src[k] & 0x8000 && src[k] != 0xffff)
  1274. {
  1275. unsigned short dir = src[k] & 0xf;
  1276. switch (dir)
  1277. {
  1278. case 0: // Portal x-
  1279. if (isMinX)
  1280. tgt[k] = src[k];
  1281. break;
  1282. case 1: // Portal z+
  1283. if (isMaxZ)
  1284. tgt[k] = src[k];
  1285. break;
  1286. case 2: // Portal x+
  1287. if (isMaxX)
  1288. tgt[k] = src[k];
  1289. break;
  1290. case 3: // Portal z-
  1291. if (isMinZ)
  1292. tgt[k] = src[k];
  1293. break;
  1294. }
  1295. }
  1296. }
  1297. }
  1298. }
  1299. }
  1300. // Calculate adjacency.
  1301. if (!buildMeshAdjacency(mesh.polys, mesh.npolys, mesh.nverts, mesh.nvp))
  1302. {
  1303. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Adjacency failed.");
  1304. return false;
  1305. }
  1306. if (mesh.nverts > 0xffff)
  1307. {
  1308. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: The resulting mesh has too many vertices %d (max %d). Data can be corrupted.", mesh.nverts, 0xffff);
  1309. }
  1310. if (mesh.npolys > 0xffff)
  1311. {
  1312. ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff);
  1313. }
  1314. return true;
  1315. }
  1316. bool rcCopyPolyMesh(rcContext* ctx, const rcPolyMesh& src, rcPolyMesh& dst)
  1317. {
  1318. rcAssert(ctx);
  1319. // Destination must be empty.
  1320. rcAssert(dst.verts == 0);
  1321. rcAssert(dst.polys == 0);
  1322. rcAssert(dst.regs == 0);
  1323. rcAssert(dst.areas == 0);
  1324. rcAssert(dst.flags == 0);
  1325. dst.nverts = src.nverts;
  1326. dst.npolys = src.npolys;
  1327. dst.maxpolys = src.npolys;
  1328. dst.nvp = src.nvp;
  1329. rcVcopy(dst.bmin, src.bmin);
  1330. rcVcopy(dst.bmax, src.bmax);
  1331. dst.cs = src.cs;
  1332. dst.ch = src.ch;
  1333. dst.borderSize = src.borderSize;
  1334. dst.maxEdgeError = src.maxEdgeError;
  1335. dst.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.nverts*3, RC_ALLOC_PERM);
  1336. if (!dst.verts)
  1337. {
  1338. ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.verts' (%d).", src.nverts*3);
  1339. return false;
  1340. }
  1341. memcpy(dst.verts, src.verts, sizeof(unsigned short)*src.nverts*3);
  1342. dst.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys*2*src.nvp, RC_ALLOC_PERM);
  1343. if (!dst.polys)
  1344. {
  1345. ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.polys' (%d).", src.npolys*2*src.nvp);
  1346. return false;
  1347. }
  1348. memcpy(dst.polys, src.polys, sizeof(unsigned short)*src.npolys*2*src.nvp);
  1349. dst.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM);
  1350. if (!dst.regs)
  1351. {
  1352. ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.regs' (%d).", src.npolys);
  1353. return false;
  1354. }
  1355. memcpy(dst.regs, src.regs, sizeof(unsigned short)*src.npolys);
  1356. dst.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*src.npolys, RC_ALLOC_PERM);
  1357. if (!dst.areas)
  1358. {
  1359. ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.areas' (%d).", src.npolys);
  1360. return false;
  1361. }
  1362. memcpy(dst.areas, src.areas, sizeof(unsigned char)*src.npolys);
  1363. dst.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM);
  1364. if (!dst.flags)
  1365. {
  1366. ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.flags' (%d).", src.npolys);
  1367. return false;
  1368. }
  1369. memcpy(dst.flags, src.flags, sizeof(unsigned short)*src.npolys);
  1370. return true;
  1371. }