RecastMesh.cpp 39 KB

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