RecastMeshDetail.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  1. //
  2. // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
  3. //
  4. // This software is provided 'as-is', without any express or implied
  5. // warranty. In no event will the authors be held liable for any damages
  6. // arising from the use of this software.
  7. // Permission is granted to anyone to use this software for any purpose,
  8. // including commercial applications, and to alter it and redistribute it
  9. // freely, subject to the following restrictions:
  10. // 1. The origin of this software must not be misrepresented; you must not
  11. // claim that you wrote the original software. If you use this software
  12. // in a product, an acknowledgment in the product documentation would be
  13. // appreciated but is not required.
  14. // 2. Altered source versions must be plainly marked as such, and must not be
  15. // misrepresented as being the original software.
  16. // 3. This notice may not be removed or altered from any source distribution.
  17. //
  18. #include <float.h>
  19. #define _USE_MATH_DEFINES
  20. #include <math.h>
  21. #include <string.h>
  22. #include <stdlib.h>
  23. #include <stdio.h>
  24. #include "Recast.h"
  25. #include "RecastAlloc.h"
  26. #include "RecastAssert.h"
  27. static const unsigned RC_UNSET_HEIGHT = 0xffff;
  28. struct rcHeightPatch
  29. {
  30. inline rcHeightPatch() : data(0), xmin(0), ymin(0), width(0), height(0) {}
  31. inline ~rcHeightPatch() { rcFree(data); }
  32. unsigned short* data;
  33. int xmin, ymin, width, height;
  34. };
  35. inline float vdot2(const float* a, const float* b)
  36. {
  37. return a[0]*b[0] + a[2]*b[2];
  38. }
  39. inline float vdistSq2(const float* p, const float* q)
  40. {
  41. const float dx = q[0] - p[0];
  42. const float dy = q[2] - p[2];
  43. return dx*dx + dy*dy;
  44. }
  45. inline float vdist2(const float* p, const float* q)
  46. {
  47. return sqrtf(vdistSq2(p,q));
  48. }
  49. inline float vcross2(const float* p1, const float* p2, const float* p3)
  50. {
  51. const float u1 = p2[0] - p1[0];
  52. const float v1 = p2[2] - p1[2];
  53. const float u2 = p3[0] - p1[0];
  54. const float v2 = p3[2] - p1[2];
  55. return u1 * v2 - v1 * u2;
  56. }
  57. static bool circumCircle(const float* p1, const float* p2, const float* p3,
  58. float* c, float& r)
  59. {
  60. static const float EPS = 1e-6f;
  61. // Calculate the circle relative to p1, to avoid some precision issues.
  62. const float v1[3] = {0,0,0};
  63. float v2[3], v3[3];
  64. rcVsub(v2, p2,p1);
  65. rcVsub(v3, p3,p1);
  66. const float cp = vcross2(v1, v2, v3);
  67. if (fabsf(cp) > EPS)
  68. {
  69. const float v1Sq = vdot2(v1,v1);
  70. const float v2Sq = vdot2(v2,v2);
  71. const float v3Sq = vdot2(v3,v3);
  72. c[0] = (v1Sq*(v2[2]-v3[2]) + v2Sq*(v3[2]-v1[2]) + v3Sq*(v1[2]-v2[2])) / (2*cp);
  73. c[1] = 0;
  74. c[2] = (v1Sq*(v3[0]-v2[0]) + v2Sq*(v1[0]-v3[0]) + v3Sq*(v2[0]-v1[0])) / (2*cp);
  75. r = vdist2(c, v1);
  76. rcVadd(c, c, p1);
  77. return true;
  78. }
  79. rcVcopy(c, p1);
  80. r = 0;
  81. return false;
  82. }
  83. static float distPtTri(const float* p, const float* a, const float* b, const float* c)
  84. {
  85. float v0[3], v1[3], v2[3];
  86. rcVsub(v0, c,a);
  87. rcVsub(v1, b,a);
  88. rcVsub(v2, p,a);
  89. const float dot00 = vdot2(v0, v0);
  90. const float dot01 = vdot2(v0, v1);
  91. const float dot02 = vdot2(v0, v2);
  92. const float dot11 = vdot2(v1, v1);
  93. const float dot12 = vdot2(v1, v2);
  94. // Compute barycentric coordinates
  95. const float invDenom = 1.0f / (dot00 * dot11 - dot01 * dot01);
  96. const float u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  97. float v = (dot00 * dot12 - dot01 * dot02) * invDenom;
  98. // If point lies inside the triangle, return interpolated y-coord.
  99. static const float EPS = 1e-4f;
  100. if (u >= -EPS && v >= -EPS && (u+v) <= 1+EPS)
  101. {
  102. const float y = a[1] + v0[1]*u + v1[1]*v;
  103. return fabsf(y-p[1]);
  104. }
  105. return FLT_MAX;
  106. }
  107. static float distancePtSeg(const float* pt, const float* p, const float* q)
  108. {
  109. float pqx = q[0] - p[0];
  110. float pqy = q[1] - p[1];
  111. float pqz = q[2] - p[2];
  112. float dx = pt[0] - p[0];
  113. float dy = pt[1] - p[1];
  114. float dz = pt[2] - p[2];
  115. float d = pqx*pqx + pqy*pqy + pqz*pqz;
  116. float t = pqx*dx + pqy*dy + pqz*dz;
  117. if (d > 0)
  118. t /= d;
  119. if (t < 0)
  120. t = 0;
  121. else if (t > 1)
  122. t = 1;
  123. dx = p[0] + t*pqx - pt[0];
  124. dy = p[1] + t*pqy - pt[1];
  125. dz = p[2] + t*pqz - pt[2];
  126. return dx*dx + dy*dy + dz*dz;
  127. }
  128. static float distancePtSeg2d(const float* pt, const float* p, const float* q)
  129. {
  130. float pqx = q[0] - p[0];
  131. float pqz = q[2] - p[2];
  132. float dx = pt[0] - p[0];
  133. float dz = pt[2] - p[2];
  134. float d = pqx*pqx + pqz*pqz;
  135. float t = pqx*dx + pqz*dz;
  136. if (d > 0)
  137. t /= d;
  138. if (t < 0)
  139. t = 0;
  140. else if (t > 1)
  141. t = 1;
  142. dx = p[0] + t*pqx - pt[0];
  143. dz = p[2] + t*pqz - pt[2];
  144. return dx*dx + dz*dz;
  145. }
  146. static float distToTriMesh(const float* p, const float* verts, const int /*nverts*/, const int* tris, const int ntris)
  147. {
  148. float dmin = FLT_MAX;
  149. for (int i = 0; i < ntris; ++i)
  150. {
  151. const float* va = &verts[tris[i*4+0]*3];
  152. const float* vb = &verts[tris[i*4+1]*3];
  153. const float* vc = &verts[tris[i*4+2]*3];
  154. float d = distPtTri(p, va,vb,vc);
  155. if (d < dmin)
  156. dmin = d;
  157. }
  158. if (dmin == FLT_MAX) return -1;
  159. return dmin;
  160. }
  161. static float distToPoly(int nvert, const float* verts, const float* p)
  162. {
  163. float dmin = FLT_MAX;
  164. int i, j, c = 0;
  165. for (i = 0, j = nvert-1; i < nvert; j = i++)
  166. {
  167. const float* vi = &verts[i*3];
  168. const float* vj = &verts[j*3];
  169. if (((vi[2] > p[2]) != (vj[2] > p[2])) &&
  170. (p[0] < (vj[0]-vi[0]) * (p[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) )
  171. c = !c;
  172. dmin = rcMin(dmin, distancePtSeg2d(p, vj, vi));
  173. }
  174. return c ? -dmin : dmin;
  175. }
  176. static unsigned short getHeight(const float fx, const float fy, const float fz,
  177. const float /*cs*/, const float ics, const float ch,
  178. const int radius, const rcHeightPatch& hp)
  179. {
  180. int ix = (int)floorf(fx*ics + 0.01f);
  181. int iz = (int)floorf(fz*ics + 0.01f);
  182. ix = rcClamp(ix-hp.xmin, 0, hp.width - 1);
  183. iz = rcClamp(iz-hp.ymin, 0, hp.height - 1);
  184. unsigned short h = hp.data[ix+iz*hp.width];
  185. if (h == RC_UNSET_HEIGHT)
  186. {
  187. // Special case when data might be bad.
  188. // Walk adjacent cells in a spiral up to 'radius', and look
  189. // for a pixel which has a valid height.
  190. int x = 1, z = 0, dx = 1, dz = 0;
  191. int maxSize = radius * 2 + 1;
  192. int maxIter = maxSize * maxSize - 1;
  193. int nextRingIterStart = 8;
  194. int nextRingIters = 16;
  195. float dmin = FLT_MAX;
  196. for (int i = 0; i < maxIter; i++)
  197. {
  198. const int nx = ix + x;
  199. const int nz = iz + z;
  200. if (nx >= 0 && nz >= 0 && nx < hp.width && nz < hp.height)
  201. {
  202. const unsigned short nh = hp.data[nx + nz*hp.width];
  203. if (nh != RC_UNSET_HEIGHT)
  204. {
  205. const float d = fabsf(nh*ch - fy);
  206. if (d < dmin)
  207. {
  208. h = nh;
  209. dmin = d;
  210. }
  211. }
  212. }
  213. // We are searching in a grid which looks approximately like this:
  214. // __________
  215. // |2 ______ 2|
  216. // | |1 __ 1| |
  217. // | | |__| | |
  218. // | |______| |
  219. // |__________|
  220. // We want to find the best height as close to the center cell as possible. This means that
  221. // if we find a height in one of the neighbor cells to the center, we don't want to
  222. // expand further out than the 8 neighbors - we want to limit our search to the closest
  223. // of these "rings", but the best height in the ring.
  224. // For example, the center is just 1 cell. We checked that at the entrance to the function.
  225. // The next "ring" contains 8 cells (marked 1 above). Those are all the neighbors to the center cell.
  226. // The next one again contains 16 cells (marked 2). In general each ring has 8 additional cells, which
  227. // can be thought of as adding 2 cells around the "center" of each side when we expand the ring.
  228. // Here we detect if we are about to enter the next ring, and if we are and we have found
  229. // a height, we abort the search.
  230. if (i + 1 == nextRingIterStart)
  231. {
  232. if (h != RC_UNSET_HEIGHT)
  233. break;
  234. nextRingIterStart += nextRingIters;
  235. nextRingIters += 8;
  236. }
  237. if ((x == z) || ((x < 0) && (x == -z)) || ((x > 0) && (x == 1 - z)))
  238. {
  239. int tmp = dx;
  240. dx = -dz;
  241. dz = tmp;
  242. }
  243. x += dx;
  244. z += dz;
  245. }
  246. }
  247. return h;
  248. }
  249. enum EdgeValues
  250. {
  251. EV_UNDEF = -1,
  252. EV_HULL = -2,
  253. };
  254. static int findEdge(const int* edges, int nedges, int s, int t)
  255. {
  256. for (int i = 0; i < nedges; i++)
  257. {
  258. const int* e = &edges[i*4];
  259. if ((e[0] == s && e[1] == t) || (e[0] == t && e[1] == s))
  260. return i;
  261. }
  262. return EV_UNDEF;
  263. }
  264. static int addEdge(rcContext* ctx, int* edges, int& nedges, const int maxEdges, int s, int t, int l, int r)
  265. {
  266. if (nedges >= maxEdges)
  267. {
  268. ctx->log(RC_LOG_ERROR, "addEdge: Too many edges (%d/%d).", nedges, maxEdges);
  269. return EV_UNDEF;
  270. }
  271. // Add edge if not already in the triangulation.
  272. int e = findEdge(edges, nedges, s, t);
  273. if (e == EV_UNDEF)
  274. {
  275. int* edge = &edges[nedges*4];
  276. edge[0] = s;
  277. edge[1] = t;
  278. edge[2] = l;
  279. edge[3] = r;
  280. return nedges++;
  281. }
  282. else
  283. {
  284. return EV_UNDEF;
  285. }
  286. }
  287. static void updateLeftFace(int* e, int s, int t, int f)
  288. {
  289. if (e[0] == s && e[1] == t && e[2] == EV_UNDEF)
  290. e[2] = f;
  291. else if (e[1] == s && e[0] == t && e[3] == EV_UNDEF)
  292. e[3] = f;
  293. }
  294. static int overlapSegSeg2d(const float* a, const float* b, const float* c, const float* d)
  295. {
  296. const float a1 = vcross2(a, b, d);
  297. const float a2 = vcross2(a, b, c);
  298. if (a1*a2 < 0.0f)
  299. {
  300. float a3 = vcross2(c, d, a);
  301. float a4 = a3 + a2 - a1;
  302. if (a3 * a4 < 0.0f)
  303. return 1;
  304. }
  305. return 0;
  306. }
  307. static bool overlapEdges(const float* pts, const int* edges, int nedges, int s1, int t1)
  308. {
  309. for (int i = 0; i < nedges; ++i)
  310. {
  311. const int s0 = edges[i*4+0];
  312. const int t0 = edges[i*4+1];
  313. // Same or connected edges do not overlap.
  314. if (s0 == s1 || s0 == t1 || t0 == s1 || t0 == t1)
  315. continue;
  316. if (overlapSegSeg2d(&pts[s0*3],&pts[t0*3], &pts[s1*3],&pts[t1*3]))
  317. return true;
  318. }
  319. return false;
  320. }
  321. static void completeFacet(rcContext* ctx, const float* pts, int npts, int* edges, int& nedges, const int maxEdges, int& nfaces, int e)
  322. {
  323. static const float EPS = 1e-5f;
  324. int* edge = &edges[e*4];
  325. // Cache s and t.
  326. int s,t;
  327. if (edge[2] == EV_UNDEF)
  328. {
  329. s = edge[0];
  330. t = edge[1];
  331. }
  332. else if (edge[3] == EV_UNDEF)
  333. {
  334. s = edge[1];
  335. t = edge[0];
  336. }
  337. else
  338. {
  339. // Edge already completed.
  340. return;
  341. }
  342. // Find best point on left of edge.
  343. int pt = npts;
  344. float c[3] = {0,0,0};
  345. float r = -1;
  346. for (int u = 0; u < npts; ++u)
  347. {
  348. if (u == s || u == t) continue;
  349. if (vcross2(&pts[s*3], &pts[t*3], &pts[u*3]) > EPS)
  350. {
  351. if (r < 0)
  352. {
  353. // The circle is not updated yet, do it now.
  354. pt = u;
  355. circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
  356. continue;
  357. }
  358. const float d = vdist2(c, &pts[u*3]);
  359. const float tol = 0.001f;
  360. if (d > r*(1+tol))
  361. {
  362. // Outside current circumcircle, skip.
  363. continue;
  364. }
  365. else if (d < r*(1-tol))
  366. {
  367. // Inside safe circumcircle, update circle.
  368. pt = u;
  369. circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
  370. }
  371. else
  372. {
  373. // Inside epsilon circum circle, do extra tests to make sure the edge is valid.
  374. // s-u and t-u cannot overlap with s-pt nor t-pt if they exists.
  375. if (overlapEdges(pts, edges, nedges, s,u))
  376. continue;
  377. if (overlapEdges(pts, edges, nedges, t,u))
  378. continue;
  379. // Edge is valid.
  380. pt = u;
  381. circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
  382. }
  383. }
  384. }
  385. // Add new triangle or update edge info if s-t is on hull.
  386. if (pt < npts)
  387. {
  388. // Update face information of edge being completed.
  389. updateLeftFace(&edges[e*4], s, t, nfaces);
  390. // Add new edge or update face info of old edge.
  391. e = findEdge(edges, nedges, pt, s);
  392. if (e == EV_UNDEF)
  393. addEdge(ctx, edges, nedges, maxEdges, pt, s, nfaces, EV_UNDEF);
  394. else
  395. updateLeftFace(&edges[e*4], pt, s, nfaces);
  396. // Add new edge or update face info of old edge.
  397. e = findEdge(edges, nedges, t, pt);
  398. if (e == EV_UNDEF)
  399. addEdge(ctx, edges, nedges, maxEdges, t, pt, nfaces, EV_UNDEF);
  400. else
  401. updateLeftFace(&edges[e*4], t, pt, nfaces);
  402. nfaces++;
  403. }
  404. else
  405. {
  406. updateLeftFace(&edges[e*4], s, t, EV_HULL);
  407. }
  408. }
  409. static void delaunayHull(rcContext* ctx, const int npts, const float* pts,
  410. const int nhull, const int* hull,
  411. rcIntArray& tris, rcIntArray& edges)
  412. {
  413. int nfaces = 0;
  414. int nedges = 0;
  415. const int maxEdges = npts*10;
  416. edges.resize(maxEdges*4);
  417. for (int i = 0, j = nhull-1; i < nhull; j=i++)
  418. addEdge(ctx, &edges[0], nedges, maxEdges, hull[j],hull[i], EV_HULL, EV_UNDEF);
  419. int currentEdge = 0;
  420. while (currentEdge < nedges)
  421. {
  422. if (edges[currentEdge*4+2] == EV_UNDEF)
  423. completeFacet(ctx, pts, npts, &edges[0], nedges, maxEdges, nfaces, currentEdge);
  424. if (edges[currentEdge*4+3] == EV_UNDEF)
  425. completeFacet(ctx, pts, npts, &edges[0], nedges, maxEdges, nfaces, currentEdge);
  426. currentEdge++;
  427. }
  428. // Create tris
  429. tris.resize(nfaces*4);
  430. for (int i = 0; i < nfaces*4; ++i)
  431. tris[i] = -1;
  432. for (int i = 0; i < nedges; ++i)
  433. {
  434. const int* e = &edges[i*4];
  435. if (e[3] >= 0)
  436. {
  437. // Left face
  438. int* t = &tris[e[3]*4];
  439. if (t[0] == -1)
  440. {
  441. t[0] = e[0];
  442. t[1] = e[1];
  443. }
  444. else if (t[0] == e[1])
  445. t[2] = e[0];
  446. else if (t[1] == e[0])
  447. t[2] = e[1];
  448. }
  449. if (e[2] >= 0)
  450. {
  451. // Right
  452. int* t = &tris[e[2]*4];
  453. if (t[0] == -1)
  454. {
  455. t[0] = e[1];
  456. t[1] = e[0];
  457. }
  458. else if (t[0] == e[0])
  459. t[2] = e[1];
  460. else if (t[1] == e[1])
  461. t[2] = e[0];
  462. }
  463. }
  464. for (int i = 0; i < tris.size()/4; ++i)
  465. {
  466. int* t = &tris[i*4];
  467. if (t[0] == -1 || t[1] == -1 || t[2] == -1)
  468. {
  469. ctx->log(RC_LOG_WARNING, "delaunayHull: Removing dangling face %d [%d,%d,%d].", i, t[0],t[1],t[2]);
  470. t[0] = tris[tris.size()-4];
  471. t[1] = tris[tris.size()-3];
  472. t[2] = tris[tris.size()-2];
  473. t[3] = tris[tris.size()-1];
  474. tris.resize(tris.size()-4);
  475. --i;
  476. }
  477. }
  478. }
  479. // Calculate minimum extend of the polygon.
  480. static float polyMinExtent(const float* verts, const int nverts)
  481. {
  482. float minDist = FLT_MAX;
  483. for (int i = 0; i < nverts; i++)
  484. {
  485. const int ni = (i+1) % nverts;
  486. const float* p1 = &verts[i*3];
  487. const float* p2 = &verts[ni*3];
  488. float maxEdgeDist = 0;
  489. for (int j = 0; j < nverts; j++)
  490. {
  491. if (j == i || j == ni) continue;
  492. float d = distancePtSeg2d(&verts[j*3], p1,p2);
  493. maxEdgeDist = rcMax(maxEdgeDist, d);
  494. }
  495. minDist = rcMin(minDist, maxEdgeDist);
  496. }
  497. return rcSqrt(minDist);
  498. }
  499. // Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
  500. inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
  501. inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
  502. static void triangulateHull(const int /*nverts*/, const float* verts, const int nhull, const int* hull, rcIntArray& tris)
  503. {
  504. int start = 0, left = 1, right = nhull-1;
  505. // Start from an ear with shortest perimeter.
  506. // This tends to favor well formed triangles as starting point.
  507. float dmin = 0;
  508. for (int i = 0; i < nhull; i++)
  509. {
  510. int pi = prev(i, nhull);
  511. int ni = next(i, nhull);
  512. const float* pv = &verts[hull[pi]*3];
  513. const float* cv = &verts[hull[i]*3];
  514. const float* nv = &verts[hull[ni]*3];
  515. const float d = vdist2(pv,cv) + vdist2(cv,nv) + vdist2(nv,pv);
  516. if (d < dmin)
  517. {
  518. start = i;
  519. left = ni;
  520. right = pi;
  521. dmin = d;
  522. }
  523. }
  524. // Add first triangle
  525. tris.push(hull[start]);
  526. tris.push(hull[left]);
  527. tris.push(hull[right]);
  528. tris.push(0);
  529. // Triangulate the polygon by moving left or right,
  530. // depending on which triangle has shorter perimeter.
  531. // This heuristic was chose emprically, since it seems
  532. // handle tesselated straight edges well.
  533. while (next(left, nhull) != right)
  534. {
  535. // Check to see if se should advance left or right.
  536. int nleft = next(left, nhull);
  537. int nright = prev(right, nhull);
  538. const float* cvleft = &verts[hull[left]*3];
  539. const float* nvleft = &verts[hull[nleft]*3];
  540. const float* cvright = &verts[hull[right]*3];
  541. const float* nvright = &verts[hull[nright]*3];
  542. const float dleft = vdist2(cvleft, nvleft) + vdist2(nvleft, cvright);
  543. const float dright = vdist2(cvright, nvright) + vdist2(cvleft, nvright);
  544. if (dleft < dright)
  545. {
  546. tris.push(hull[left]);
  547. tris.push(hull[nleft]);
  548. tris.push(hull[right]);
  549. tris.push(0);
  550. left = nleft;
  551. }
  552. else
  553. {
  554. tris.push(hull[left]);
  555. tris.push(hull[nright]);
  556. tris.push(hull[right]);
  557. tris.push(0);
  558. right = nright;
  559. }
  560. }
  561. }
  562. inline float getJitterX(const int i)
  563. {
  564. return (((i * 0x8da6b343) & 0xffff) / 65535.0f * 2.0f) - 1.0f;
  565. }
  566. inline float getJitterY(const int i)
  567. {
  568. return (((i * 0xd8163841) & 0xffff) / 65535.0f * 2.0f) - 1.0f;
  569. }
  570. static bool buildPolyDetail(rcContext* ctx, const float* in, const int nin,
  571. const float sampleDist, const float sampleMaxError,
  572. const int heightSearchRadius, const rcCompactHeightfield& chf,
  573. const rcHeightPatch& hp, float* verts, int& nverts,
  574. rcIntArray& tris, rcIntArray& edges, rcIntArray& samples)
  575. {
  576. static const int MAX_VERTS = 127;
  577. static const int MAX_TRIS = 255; // Max tris for delaunay is 2n-2-k (n=num verts, k=num hull verts).
  578. static const int MAX_VERTS_PER_EDGE = 32;
  579. float edge[(MAX_VERTS_PER_EDGE+1)*3];
  580. int hull[MAX_VERTS];
  581. int nhull = 0;
  582. nverts = nin;
  583. for (int i = 0; i < nin; ++i)
  584. rcVcopy(&verts[i*3], &in[i*3]);
  585. edges.resize(0);
  586. tris.resize(0);
  587. const float cs = chf.cs;
  588. const float ics = 1.0f/cs;
  589. // Calculate minimum extents of the polygon based on input data.
  590. float minExtent = polyMinExtent(verts, nverts);
  591. // Tessellate outlines.
  592. // This is done in separate pass in order to ensure
  593. // seamless height values across the ply boundaries.
  594. if (sampleDist > 0)
  595. {
  596. for (int i = 0, j = nin-1; i < nin; j=i++)
  597. {
  598. const float* vj = &in[j*3];
  599. const float* vi = &in[i*3];
  600. bool swapped = false;
  601. // Make sure the segments are always handled in same order
  602. // using lexological sort or else there will be seams.
  603. if (fabsf(vj[0]-vi[0]) < 1e-6f)
  604. {
  605. if (vj[2] > vi[2])
  606. {
  607. rcSwap(vj,vi);
  608. swapped = true;
  609. }
  610. }
  611. else
  612. {
  613. if (vj[0] > vi[0])
  614. {
  615. rcSwap(vj,vi);
  616. swapped = true;
  617. }
  618. }
  619. // Create samples along the edge.
  620. float dx = vi[0] - vj[0];
  621. float dy = vi[1] - vj[1];
  622. float dz = vi[2] - vj[2];
  623. float d = sqrtf(dx*dx + dz*dz);
  624. int nn = 1 + (int)floorf(d/sampleDist);
  625. if (nn >= MAX_VERTS_PER_EDGE) nn = MAX_VERTS_PER_EDGE-1;
  626. if (nverts+nn >= MAX_VERTS)
  627. nn = MAX_VERTS-1-nverts;
  628. for (int k = 0; k <= nn; ++k)
  629. {
  630. float u = (float)k/(float)nn;
  631. float* pos = &edge[k*3];
  632. pos[0] = vj[0] + dx*u;
  633. pos[1] = vj[1] + dy*u;
  634. pos[2] = vj[2] + dz*u;
  635. pos[1] = getHeight(pos[0],pos[1],pos[2], cs, ics, chf.ch, heightSearchRadius, hp)*chf.ch;
  636. }
  637. // Simplify samples.
  638. int idx[MAX_VERTS_PER_EDGE] = {0,nn};
  639. int nidx = 2;
  640. for (int k = 0; k < nidx-1; )
  641. {
  642. const int a = idx[k];
  643. const int b = idx[k+1];
  644. const float* va = &edge[a*3];
  645. const float* vb = &edge[b*3];
  646. // Find maximum deviation along the segment.
  647. float maxd = 0;
  648. int maxi = -1;
  649. for (int m = a+1; m < b; ++m)
  650. {
  651. float dev = distancePtSeg(&edge[m*3],va,vb);
  652. if (dev > maxd)
  653. {
  654. maxd = dev;
  655. maxi = m;
  656. }
  657. }
  658. // If the max deviation is larger than accepted error,
  659. // add new point, else continue to next segment.
  660. if (maxi != -1 && maxd > rcSqr(sampleMaxError))
  661. {
  662. for (int m = nidx; m > k; --m)
  663. idx[m] = idx[m-1];
  664. idx[k+1] = maxi;
  665. nidx++;
  666. }
  667. else
  668. {
  669. ++k;
  670. }
  671. }
  672. hull[nhull++] = j;
  673. // Add new vertices.
  674. if (swapped)
  675. {
  676. for (int k = nidx-2; k > 0; --k)
  677. {
  678. rcVcopy(&verts[nverts*3], &edge[idx[k]*3]);
  679. hull[nhull++] = nverts;
  680. nverts++;
  681. }
  682. }
  683. else
  684. {
  685. for (int k = 1; k < nidx-1; ++k)
  686. {
  687. rcVcopy(&verts[nverts*3], &edge[idx[k]*3]);
  688. hull[nhull++] = nverts;
  689. nverts++;
  690. }
  691. }
  692. }
  693. }
  694. // If the polygon minimum extent is small (sliver or small triangle), do not try to add internal points.
  695. if (minExtent < sampleDist*2)
  696. {
  697. triangulateHull(nverts, verts, nhull, hull, tris);
  698. return true;
  699. }
  700. // Tessellate the base mesh.
  701. // We're using the triangulateHull instead of delaunayHull as it tends to
  702. // create a bit better triangulation for long thin triangles when there
  703. // are no internal points.
  704. triangulateHull(nverts, verts, nhull, hull, tris);
  705. if (tris.size() == 0)
  706. {
  707. // Could not triangulate the poly, make sure there is some valid data there.
  708. ctx->log(RC_LOG_WARNING, "buildPolyDetail: Could not triangulate polygon (%d verts).", nverts);
  709. return true;
  710. }
  711. if (sampleDist > 0)
  712. {
  713. // Create sample locations in a grid.
  714. float bmin[3], bmax[3];
  715. rcVcopy(bmin, in);
  716. rcVcopy(bmax, in);
  717. for (int i = 1; i < nin; ++i)
  718. {
  719. rcVmin(bmin, &in[i*3]);
  720. rcVmax(bmax, &in[i*3]);
  721. }
  722. int x0 = (int)floorf(bmin[0]/sampleDist);
  723. int x1 = (int)ceilf(bmax[0]/sampleDist);
  724. int z0 = (int)floorf(bmin[2]/sampleDist);
  725. int z1 = (int)ceilf(bmax[2]/sampleDist);
  726. samples.resize(0);
  727. for (int z = z0; z < z1; ++z)
  728. {
  729. for (int x = x0; x < x1; ++x)
  730. {
  731. float pt[3];
  732. pt[0] = x*sampleDist;
  733. pt[1] = (bmax[1]+bmin[1])*0.5f;
  734. pt[2] = z*sampleDist;
  735. // Make sure the samples are not too close to the edges.
  736. if (distToPoly(nin,in,pt) > -sampleDist/2) continue;
  737. samples.push(x);
  738. samples.push(getHeight(pt[0], pt[1], pt[2], cs, ics, chf.ch, heightSearchRadius, hp));
  739. samples.push(z);
  740. samples.push(0); // Not added
  741. }
  742. }
  743. // Add the samples starting from the one that has the most
  744. // error. The procedure stops when all samples are added
  745. // or when the max error is within treshold.
  746. const int nsamples = samples.size()/4;
  747. for (int iter = 0; iter < nsamples; ++iter)
  748. {
  749. if (nverts >= MAX_VERTS)
  750. break;
  751. // Find sample with most error.
  752. float bestpt[3] = {0,0,0};
  753. float bestd = 0;
  754. int besti = -1;
  755. for (int i = 0; i < nsamples; ++i)
  756. {
  757. const int* s = &samples[i*4];
  758. if (s[3]) continue; // skip added.
  759. float pt[3];
  760. // The sample location is jittered to get rid of some bad triangulations
  761. // which are cause by symmetrical data from the grid structure.
  762. pt[0] = s[0]*sampleDist + getJitterX(i)*cs*0.1f;
  763. pt[1] = s[1]*chf.ch;
  764. pt[2] = s[2]*sampleDist + getJitterY(i)*cs*0.1f;
  765. float d = distToTriMesh(pt, verts, nverts, &tris[0], tris.size()/4);
  766. if (d < 0) continue; // did not hit the mesh.
  767. if (d > bestd)
  768. {
  769. bestd = d;
  770. besti = i;
  771. rcVcopy(bestpt,pt);
  772. }
  773. }
  774. // If the max error is within accepted threshold, stop tesselating.
  775. if (bestd <= sampleMaxError || besti == -1)
  776. break;
  777. // Mark sample as added.
  778. samples[besti*4+3] = 1;
  779. // Add the new sample point.
  780. rcVcopy(&verts[nverts*3],bestpt);
  781. nverts++;
  782. // Create new triangulation.
  783. // TODO: Incremental add instead of full rebuild.
  784. edges.resize(0);
  785. tris.resize(0);
  786. delaunayHull(ctx, nverts, verts, nhull, hull, tris, edges);
  787. }
  788. }
  789. const int ntris = tris.size()/4;
  790. if (ntris > MAX_TRIS)
  791. {
  792. tris.resize(MAX_TRIS*4);
  793. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Shrinking triangle count from %d to max %d.", ntris, MAX_TRIS);
  794. }
  795. return true;
  796. }
  797. static void seedArrayWithPolyCenter(rcContext* ctx, const rcCompactHeightfield& chf,
  798. const unsigned short* poly, const int npoly,
  799. const unsigned short* verts, const int bs,
  800. rcHeightPatch& hp, rcIntArray& array)
  801. {
  802. // Note: Reads to the compact heightfield are offset by border size (bs)
  803. // since border size offset is already removed from the polymesh vertices.
  804. static const int offset[9*2] =
  805. {
  806. 0,0, -1,-1, 0,-1, 1,-1, 1,0, 1,1, 0,1, -1,1, -1,0,
  807. };
  808. // Find cell closest to a poly vertex
  809. int startCellX = 0, startCellY = 0, startSpanIndex = -1;
  810. int dmin = RC_UNSET_HEIGHT;
  811. for (int j = 0; j < npoly && dmin > 0; ++j)
  812. {
  813. for (int k = 0; k < 9 && dmin > 0; ++k)
  814. {
  815. const int ax = (int)verts[poly[j]*3+0] + offset[k*2+0];
  816. const int ay = (int)verts[poly[j]*3+1];
  817. const int az = (int)verts[poly[j]*3+2] + offset[k*2+1];
  818. if (ax < hp.xmin || ax >= hp.xmin+hp.width ||
  819. az < hp.ymin || az >= hp.ymin+hp.height)
  820. continue;
  821. const rcCompactCell& c = chf.cells[(ax+bs)+(az+bs)*chf.width];
  822. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni && dmin > 0; ++i)
  823. {
  824. const rcCompactSpan& s = chf.spans[i];
  825. int d = rcAbs(ay - (int)s.y);
  826. if (d < dmin)
  827. {
  828. startCellX = ax;
  829. startCellY = az;
  830. startSpanIndex = i;
  831. dmin = d;
  832. }
  833. }
  834. }
  835. }
  836. rcAssert(startSpanIndex != -1);
  837. // Find center of the polygon
  838. int pcx = 0, pcy = 0;
  839. for (int j = 0; j < npoly; ++j)
  840. {
  841. pcx += (int)verts[poly[j]*3+0];
  842. pcy += (int)verts[poly[j]*3+2];
  843. }
  844. pcx /= npoly;
  845. pcy /= npoly;
  846. // Use seeds array as a stack for DFS
  847. array.resize(0);
  848. array.push(startCellX);
  849. array.push(startCellY);
  850. array.push(startSpanIndex);
  851. int dirs[] = { 0, 1, 2, 3 };
  852. memset(hp.data, 0, sizeof(unsigned short)*hp.width*hp.height);
  853. // DFS to move to the center. Note that we need a DFS here and can not just move
  854. // directly towards the center without recording intermediate nodes, even though the polygons
  855. // are convex. In very rare we can get stuck due to contour simplification if we do not
  856. // record nodes.
  857. int cx = -1, cy = -1, ci = -1;
  858. while (true)
  859. {
  860. if (array.size() < 3)
  861. {
  862. ctx->log(RC_LOG_WARNING, "Walk towards polygon center failed to reach center");
  863. break;
  864. }
  865. ci = array.pop();
  866. cy = array.pop();
  867. cx = array.pop();
  868. if (cx == pcx && cy == pcy)
  869. break;
  870. // If we are already at the correct X-position, prefer direction
  871. // directly towards the center in the Y-axis; otherwise prefer
  872. // direction in the X-axis
  873. int directDir;
  874. if (cx == pcx)
  875. directDir = rcGetDirForOffset(0, pcy > cy ? 1 : -1);
  876. else
  877. directDir = rcGetDirForOffset(pcx > cx ? 1 : -1, 0);
  878. // Push the direct dir last so we start with this on next iteration
  879. rcSwap(dirs[directDir], dirs[3]);
  880. const rcCompactSpan& cs = chf.spans[ci];
  881. for (int i = 0; i < 4; i++)
  882. {
  883. int dir = dirs[i];
  884. if (rcGetCon(cs, dir) == RC_NOT_CONNECTED)
  885. continue;
  886. int newX = cx + rcGetDirOffsetX(dir);
  887. int newY = cy + rcGetDirOffsetY(dir);
  888. int hpx = newX - hp.xmin;
  889. int hpy = newY - hp.ymin;
  890. if (hpx < 0 || hpx >= hp.width || hpy < 0 || hpy >= hp.height)
  891. continue;
  892. if (hp.data[hpx+hpy*hp.width] != 0)
  893. continue;
  894. hp.data[hpx+hpy*hp.width] = 1;
  895. array.push(newX);
  896. array.push(newY);
  897. array.push((int)chf.cells[(newX+bs)+(newY+bs)*chf.width].index + rcGetCon(cs, dir));
  898. }
  899. rcSwap(dirs[directDir], dirs[3]);
  900. }
  901. array.resize(0);
  902. // getHeightData seeds are given in coordinates with borders
  903. array.push(cx+bs);
  904. array.push(cy+bs);
  905. array.push(ci);
  906. memset(hp.data, 0xff, sizeof(unsigned short)*hp.width*hp.height);
  907. const rcCompactSpan& cs = chf.spans[ci];
  908. hp.data[cx-hp.xmin+(cy-hp.ymin)*hp.width] = cs.y;
  909. }
  910. static void push3(rcIntArray& queue, int v1, int v2, int v3)
  911. {
  912. queue.resize(queue.size() + 3);
  913. queue[queue.size() - 3] = v1;
  914. queue[queue.size() - 2] = v2;
  915. queue[queue.size() - 1] = v3;
  916. }
  917. static void getHeightData(rcContext* ctx, const rcCompactHeightfield& chf,
  918. const unsigned short* poly, const int npoly,
  919. const unsigned short* verts, const int bs,
  920. rcHeightPatch& hp, rcIntArray& queue,
  921. int region)
  922. {
  923. // Note: Reads to the compact heightfield are offset by border size (bs)
  924. // since border size offset is already removed from the polymesh vertices.
  925. queue.resize(0);
  926. // Set all heights to RC_UNSET_HEIGHT.
  927. memset(hp.data, 0xff, sizeof(unsigned short)*hp.width*hp.height);
  928. bool empty = true;
  929. // We cannot sample from this poly if it was created from polys
  930. // of different regions. If it was then it could potentially be overlapping
  931. // with polys of that region and the heights sampled here could be wrong.
  932. if (region != RC_MULTIPLE_REGS)
  933. {
  934. // Copy the height from the same region, and mark region borders
  935. // as seed points to fill the rest.
  936. for (int hy = 0; hy < hp.height; hy++)
  937. {
  938. int y = hp.ymin + hy + bs;
  939. for (int hx = 0; hx < hp.width; hx++)
  940. {
  941. int x = hp.xmin + hx + bs;
  942. const rcCompactCell& c = chf.cells[x + y*chf.width];
  943. for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; ++i)
  944. {
  945. const rcCompactSpan& s = chf.spans[i];
  946. if (s.reg == region)
  947. {
  948. // Store height
  949. hp.data[hx + hy*hp.width] = s.y;
  950. empty = false;
  951. // If any of the neighbours is not in same region,
  952. // add the current location as flood fill start
  953. bool border = false;
  954. for (int dir = 0; dir < 4; ++dir)
  955. {
  956. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  957. {
  958. const int ax = x + rcGetDirOffsetX(dir);
  959. const int ay = y + rcGetDirOffsetY(dir);
  960. const int ai = (int)chf.cells[ax + ay*chf.width].index + rcGetCon(s, dir);
  961. const rcCompactSpan& as = chf.spans[ai];
  962. if (as.reg != region)
  963. {
  964. border = true;
  965. break;
  966. }
  967. }
  968. }
  969. if (border)
  970. push3(queue, x, y, i);
  971. break;
  972. }
  973. }
  974. }
  975. }
  976. }
  977. // if the polygon does not contain any points from the current region (rare, but happens)
  978. // or if it could potentially be overlapping polygons of the same region,
  979. // then use the center as the seed point.
  980. if (empty)
  981. seedArrayWithPolyCenter(ctx, chf, poly, npoly, verts, bs, hp, queue);
  982. static const int RETRACT_SIZE = 256;
  983. int head = 0;
  984. // We assume the seed is centered in the polygon, so a BFS to collect
  985. // height data will ensure we do not move onto overlapping polygons and
  986. // sample wrong heights.
  987. while (head*3 < queue.size())
  988. {
  989. int cx = queue[head*3+0];
  990. int cy = queue[head*3+1];
  991. int ci = queue[head*3+2];
  992. head++;
  993. if (head >= RETRACT_SIZE)
  994. {
  995. head = 0;
  996. if (queue.size() > RETRACT_SIZE*3)
  997. memmove(&queue[0], &queue[RETRACT_SIZE*3], sizeof(int)*(queue.size()-RETRACT_SIZE*3));
  998. queue.resize(queue.size()-RETRACT_SIZE*3);
  999. }
  1000. const rcCompactSpan& cs = chf.spans[ci];
  1001. for (int dir = 0; dir < 4; ++dir)
  1002. {
  1003. if (rcGetCon(cs, dir) == RC_NOT_CONNECTED) continue;
  1004. const int ax = cx + rcGetDirOffsetX(dir);
  1005. const int ay = cy + rcGetDirOffsetY(dir);
  1006. const int hx = ax - hp.xmin - bs;
  1007. const int hy = ay - hp.ymin - bs;
  1008. if ((unsigned int)hx >= (unsigned int)hp.width || (unsigned int)hy >= (unsigned int)hp.height)
  1009. continue;
  1010. if (hp.data[hx + hy*hp.width] != RC_UNSET_HEIGHT)
  1011. continue;
  1012. const int ai = (int)chf.cells[ax + ay*chf.width].index + rcGetCon(cs, dir);
  1013. const rcCompactSpan& as = chf.spans[ai];
  1014. hp.data[hx + hy*hp.width] = as.y;
  1015. push3(queue, ax, ay, ai);
  1016. }
  1017. }
  1018. }
  1019. static unsigned char getEdgeFlags(const float* va, const float* vb,
  1020. const float* vpoly, const int npoly)
  1021. {
  1022. // Return true if edge (va,vb) is part of the polygon.
  1023. static const float thrSqr = rcSqr(0.001f);
  1024. for (int i = 0, j = npoly-1; i < npoly; j=i++)
  1025. {
  1026. if (distancePtSeg2d(va, &vpoly[j*3], &vpoly[i*3]) < thrSqr &&
  1027. distancePtSeg2d(vb, &vpoly[j*3], &vpoly[i*3]) < thrSqr)
  1028. return 1;
  1029. }
  1030. return 0;
  1031. }
  1032. static unsigned char getTriFlags(const float* va, const float* vb, const float* vc,
  1033. const float* vpoly, const int npoly)
  1034. {
  1035. unsigned char flags = 0;
  1036. flags |= getEdgeFlags(va,vb,vpoly,npoly) << 0;
  1037. flags |= getEdgeFlags(vb,vc,vpoly,npoly) << 2;
  1038. flags |= getEdgeFlags(vc,va,vpoly,npoly) << 4;
  1039. return flags;
  1040. }
  1041. /// @par
  1042. ///
  1043. /// See the #rcConfig documentation for more information on the configuration parameters.
  1044. ///
  1045. /// @see rcAllocPolyMeshDetail, rcPolyMesh, rcCompactHeightfield, rcPolyMeshDetail, rcConfig
  1046. bool rcBuildPolyMeshDetail(rcContext* ctx, const rcPolyMesh& mesh, const rcCompactHeightfield& chf,
  1047. const float sampleDist, const float sampleMaxError,
  1048. rcPolyMeshDetail& dmesh)
  1049. {
  1050. rcAssert(ctx);
  1051. rcScopedTimer timer(ctx, RC_TIMER_BUILD_POLYMESHDETAIL);
  1052. if (mesh.nverts == 0 || mesh.npolys == 0)
  1053. return true;
  1054. const int nvp = mesh.nvp;
  1055. const float cs = mesh.cs;
  1056. const float ch = mesh.ch;
  1057. const float* orig = mesh.bmin;
  1058. const int borderSize = mesh.borderSize;
  1059. const int heightSearchRadius = rcMax(1, (int)ceilf(mesh.maxEdgeError));
  1060. rcIntArray edges(64);
  1061. rcIntArray tris(512);
  1062. rcIntArray arr(512);
  1063. rcIntArray samples(512);
  1064. float verts[256*3];
  1065. rcHeightPatch hp;
  1066. int nPolyVerts = 0;
  1067. int maxhw = 0, maxhh = 0;
  1068. rcScopedDelete<int> bounds((int*)rcAlloc(sizeof(int)*mesh.npolys*4, RC_ALLOC_TEMP));
  1069. if (!bounds)
  1070. {
  1071. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'bounds' (%d).", mesh.npolys*4);
  1072. return false;
  1073. }
  1074. rcScopedDelete<float> poly((float*)rcAlloc(sizeof(float)*nvp*3, RC_ALLOC_TEMP));
  1075. if (!poly)
  1076. {
  1077. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'poly' (%d).", nvp*3);
  1078. return false;
  1079. }
  1080. // Find max size for a polygon area.
  1081. for (int i = 0; i < mesh.npolys; ++i)
  1082. {
  1083. const unsigned short* p = &mesh.polys[i*nvp*2];
  1084. int& xmin = bounds[i*4+0];
  1085. int& xmax = bounds[i*4+1];
  1086. int& ymin = bounds[i*4+2];
  1087. int& ymax = bounds[i*4+3];
  1088. xmin = chf.width;
  1089. xmax = 0;
  1090. ymin = chf.height;
  1091. ymax = 0;
  1092. for (int j = 0; j < nvp; ++j)
  1093. {
  1094. if(p[j] == RC_MESH_NULL_IDX) break;
  1095. const unsigned short* v = &mesh.verts[p[j]*3];
  1096. xmin = rcMin(xmin, (int)v[0]);
  1097. xmax = rcMax(xmax, (int)v[0]);
  1098. ymin = rcMin(ymin, (int)v[2]);
  1099. ymax = rcMax(ymax, (int)v[2]);
  1100. nPolyVerts++;
  1101. }
  1102. xmin = rcMax(0,xmin-1);
  1103. xmax = rcMin(chf.width,xmax+1);
  1104. ymin = rcMax(0,ymin-1);
  1105. ymax = rcMin(chf.height,ymax+1);
  1106. if (xmin >= xmax || ymin >= ymax) continue;
  1107. maxhw = rcMax(maxhw, xmax-xmin);
  1108. maxhh = rcMax(maxhh, ymax-ymin);
  1109. }
  1110. hp.data = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxhw*maxhh, RC_ALLOC_TEMP);
  1111. if (!hp.data)
  1112. {
  1113. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'hp.data' (%d).", maxhw*maxhh);
  1114. return false;
  1115. }
  1116. dmesh.nmeshes = mesh.npolys;
  1117. dmesh.nverts = 0;
  1118. dmesh.ntris = 0;
  1119. dmesh.meshes = (unsigned int*)rcAlloc(sizeof(unsigned int)*dmesh.nmeshes*4, RC_ALLOC_PERM);
  1120. if (!dmesh.meshes)
  1121. {
  1122. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.meshes' (%d).", dmesh.nmeshes*4);
  1123. return false;
  1124. }
  1125. int vcap = nPolyVerts+nPolyVerts/2;
  1126. int tcap = vcap*2;
  1127. dmesh.nverts = 0;
  1128. dmesh.verts = (float*)rcAlloc(sizeof(float)*vcap*3, RC_ALLOC_PERM);
  1129. if (!dmesh.verts)
  1130. {
  1131. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.verts' (%d).", vcap*3);
  1132. return false;
  1133. }
  1134. dmesh.ntris = 0;
  1135. dmesh.tris = (unsigned char*)rcAlloc(sizeof(unsigned char)*tcap*4, RC_ALLOC_PERM);
  1136. if (!dmesh.tris)
  1137. {
  1138. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.tris' (%d).", tcap*4);
  1139. return false;
  1140. }
  1141. for (int i = 0; i < mesh.npolys; ++i)
  1142. {
  1143. const unsigned short* p = &mesh.polys[i*nvp*2];
  1144. // Store polygon vertices for processing.
  1145. int npoly = 0;
  1146. for (int j = 0; j < nvp; ++j)
  1147. {
  1148. if(p[j] == RC_MESH_NULL_IDX) break;
  1149. const unsigned short* v = &mesh.verts[p[j]*3];
  1150. poly[j*3+0] = v[0]*cs;
  1151. poly[j*3+1] = v[1]*ch;
  1152. poly[j*3+2] = v[2]*cs;
  1153. npoly++;
  1154. }
  1155. // Get the height data from the area of the polygon.
  1156. hp.xmin = bounds[i*4+0];
  1157. hp.ymin = bounds[i*4+2];
  1158. hp.width = bounds[i*4+1]-bounds[i*4+0];
  1159. hp.height = bounds[i*4+3]-bounds[i*4+2];
  1160. getHeightData(ctx, chf, p, npoly, mesh.verts, borderSize, hp, arr, mesh.regs[i]);
  1161. // Build detail mesh.
  1162. int nverts = 0;
  1163. if (!buildPolyDetail(ctx, poly, npoly,
  1164. sampleDist, sampleMaxError,
  1165. heightSearchRadius, chf, hp,
  1166. verts, nverts, tris,
  1167. edges, samples))
  1168. {
  1169. return false;
  1170. }
  1171. // Move detail verts to world space.
  1172. for (int j = 0; j < nverts; ++j)
  1173. {
  1174. verts[j*3+0] += orig[0];
  1175. verts[j*3+1] += orig[1] + chf.ch; // Is this offset necessary?
  1176. verts[j*3+2] += orig[2];
  1177. }
  1178. // Offset poly too, will be used to flag checking.
  1179. for (int j = 0; j < npoly; ++j)
  1180. {
  1181. poly[j*3+0] += orig[0];
  1182. poly[j*3+1] += orig[1];
  1183. poly[j*3+2] += orig[2];
  1184. }
  1185. // Store detail submesh.
  1186. const int ntris = tris.size()/4;
  1187. dmesh.meshes[i*4+0] = (unsigned int)dmesh.nverts;
  1188. dmesh.meshes[i*4+1] = (unsigned int)nverts;
  1189. dmesh.meshes[i*4+2] = (unsigned int)dmesh.ntris;
  1190. dmesh.meshes[i*4+3] = (unsigned int)ntris;
  1191. // Store vertices, allocate more memory if necessary.
  1192. if (dmesh.nverts+nverts > vcap)
  1193. {
  1194. while (dmesh.nverts+nverts > vcap)
  1195. vcap += 256;
  1196. float* newv = (float*)rcAlloc(sizeof(float)*vcap*3, RC_ALLOC_PERM);
  1197. if (!newv)
  1198. {
  1199. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'newv' (%d).", vcap*3);
  1200. return false;
  1201. }
  1202. if (dmesh.nverts)
  1203. memcpy(newv, dmesh.verts, sizeof(float)*3*dmesh.nverts);
  1204. rcFree(dmesh.verts);
  1205. dmesh.verts = newv;
  1206. }
  1207. for (int j = 0; j < nverts; ++j)
  1208. {
  1209. dmesh.verts[dmesh.nverts*3+0] = verts[j*3+0];
  1210. dmesh.verts[dmesh.nverts*3+1] = verts[j*3+1];
  1211. dmesh.verts[dmesh.nverts*3+2] = verts[j*3+2];
  1212. dmesh.nverts++;
  1213. }
  1214. // Store triangles, allocate more memory if necessary.
  1215. if (dmesh.ntris+ntris > tcap)
  1216. {
  1217. while (dmesh.ntris+ntris > tcap)
  1218. tcap += 256;
  1219. unsigned char* newt = (unsigned char*)rcAlloc(sizeof(unsigned char)*tcap*4, RC_ALLOC_PERM);
  1220. if (!newt)
  1221. {
  1222. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'newt' (%d).", tcap*4);
  1223. return false;
  1224. }
  1225. if (dmesh.ntris)
  1226. memcpy(newt, dmesh.tris, sizeof(unsigned char)*4*dmesh.ntris);
  1227. rcFree(dmesh.tris);
  1228. dmesh.tris = newt;
  1229. }
  1230. for (int j = 0; j < ntris; ++j)
  1231. {
  1232. const int* t = &tris[j*4];
  1233. dmesh.tris[dmesh.ntris*4+0] = (unsigned char)t[0];
  1234. dmesh.tris[dmesh.ntris*4+1] = (unsigned char)t[1];
  1235. dmesh.tris[dmesh.ntris*4+2] = (unsigned char)t[2];
  1236. dmesh.tris[dmesh.ntris*4+3] = getTriFlags(&verts[t[0]*3], &verts[t[1]*3], &verts[t[2]*3], poly, npoly);
  1237. dmesh.ntris++;
  1238. }
  1239. }
  1240. return true;
  1241. }
  1242. /// @see rcAllocPolyMeshDetail, rcPolyMeshDetail
  1243. bool rcMergePolyMeshDetails(rcContext* ctx, rcPolyMeshDetail** meshes, const int nmeshes, rcPolyMeshDetail& mesh)
  1244. {
  1245. rcAssert(ctx);
  1246. rcScopedTimer timer(ctx, RC_TIMER_MERGE_POLYMESHDETAIL);
  1247. int maxVerts = 0;
  1248. int maxTris = 0;
  1249. int maxMeshes = 0;
  1250. for (int i = 0; i < nmeshes; ++i)
  1251. {
  1252. if (!meshes[i]) continue;
  1253. maxVerts += meshes[i]->nverts;
  1254. maxTris += meshes[i]->ntris;
  1255. maxMeshes += meshes[i]->nmeshes;
  1256. }
  1257. mesh.nmeshes = 0;
  1258. mesh.meshes = (unsigned int*)rcAlloc(sizeof(unsigned int)*maxMeshes*4, RC_ALLOC_PERM);
  1259. if (!mesh.meshes)
  1260. {
  1261. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'pmdtl.meshes' (%d).", maxMeshes*4);
  1262. return false;
  1263. }
  1264. mesh.ntris = 0;
  1265. mesh.tris = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxTris*4, RC_ALLOC_PERM);
  1266. if (!mesh.tris)
  1267. {
  1268. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.tris' (%d).", maxTris*4);
  1269. return false;
  1270. }
  1271. mesh.nverts = 0;
  1272. mesh.verts = (float*)rcAlloc(sizeof(float)*maxVerts*3, RC_ALLOC_PERM);
  1273. if (!mesh.verts)
  1274. {
  1275. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.verts' (%d).", maxVerts*3);
  1276. return false;
  1277. }
  1278. // Merge datas.
  1279. for (int i = 0; i < nmeshes; ++i)
  1280. {
  1281. rcPolyMeshDetail* dm = meshes[i];
  1282. if (!dm) continue;
  1283. for (int j = 0; j < dm->nmeshes; ++j)
  1284. {
  1285. unsigned int* dst = &mesh.meshes[mesh.nmeshes*4];
  1286. unsigned int* src = &dm->meshes[j*4];
  1287. dst[0] = (unsigned int)mesh.nverts+src[0];
  1288. dst[1] = src[1];
  1289. dst[2] = (unsigned int)mesh.ntris+src[2];
  1290. dst[3] = src[3];
  1291. mesh.nmeshes++;
  1292. }
  1293. for (int k = 0; k < dm->nverts; ++k)
  1294. {
  1295. rcVcopy(&mesh.verts[mesh.nverts*3], &dm->verts[k*3]);
  1296. mesh.nverts++;
  1297. }
  1298. for (int k = 0; k < dm->ntris; ++k)
  1299. {
  1300. mesh.tris[mesh.ntris*4+0] = dm->tris[k*4+0];
  1301. mesh.tris[mesh.ntris*4+1] = dm->tris[k*4+1];
  1302. mesh.tris[mesh.ntris*4+2] = dm->tris[k*4+2];
  1303. mesh.tris[mesh.ntris*4+3] = dm->tris[k*4+3];
  1304. mesh.ntris++;
  1305. }
  1306. }
  1307. return true;
  1308. }