RecastMeshDetail.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412
  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 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. // Find nearest neighbour pixel which has valid height.
  189. const int off[8*2] = { -1,0, -1,-1, 0,-1, 1,-1, 1,0, 1,1, 0,1, -1,1};
  190. float dmin = FLT_MAX;
  191. for (int i = 0; i < 8; ++i)
  192. {
  193. const int nx = ix+off[i*2+0];
  194. const int nz = iz+off[i*2+1];
  195. if (nx < 0 || nz < 0 || nx >= hp.width || nz >= hp.height) continue;
  196. const unsigned short nh = hp.data[nx+nz*hp.width];
  197. if (nh == RC_UNSET_HEIGHT) continue;
  198. const float d = fabsf(nh*ch - fy);
  199. if (d < dmin)
  200. {
  201. h = nh;
  202. dmin = d;
  203. }
  204. }
  205. }
  206. return h;
  207. }
  208. enum EdgeValues
  209. {
  210. EV_UNDEF = -1,
  211. EV_HULL = -2,
  212. };
  213. static int findEdge(const int* edges, int nedges, int s, int t)
  214. {
  215. for (int i = 0; i < nedges; i++)
  216. {
  217. const int* e = &edges[i*4];
  218. if ((e[0] == s && e[1] == t) || (e[0] == t && e[1] == s))
  219. return i;
  220. }
  221. return EV_UNDEF;
  222. }
  223. static int addEdge(rcContext* ctx, int* edges, int& nedges, const int maxEdges, int s, int t, int l, int r)
  224. {
  225. if (nedges >= maxEdges)
  226. {
  227. ctx->log(RC_LOG_ERROR, "addEdge: Too many edges (%d/%d).", nedges, maxEdges);
  228. return EV_UNDEF;
  229. }
  230. // Add edge if not already in the triangulation.
  231. int e = findEdge(edges, nedges, s, t);
  232. if (e == EV_UNDEF)
  233. {
  234. int* edge = &edges[nedges*4];
  235. edge[0] = s;
  236. edge[1] = t;
  237. edge[2] = l;
  238. edge[3] = r;
  239. return nedges++;
  240. }
  241. else
  242. {
  243. return EV_UNDEF;
  244. }
  245. }
  246. static void updateLeftFace(int* e, int s, int t, int f)
  247. {
  248. if (e[0] == s && e[1] == t && e[2] == EV_UNDEF)
  249. e[2] = f;
  250. else if (e[1] == s && e[0] == t && e[3] == EV_UNDEF)
  251. e[3] = f;
  252. }
  253. static int overlapSegSeg2d(const float* a, const float* b, const float* c, const float* d)
  254. {
  255. const float a1 = vcross2(a, b, d);
  256. const float a2 = vcross2(a, b, c);
  257. if (a1*a2 < 0.0f)
  258. {
  259. float a3 = vcross2(c, d, a);
  260. float a4 = a3 + a2 - a1;
  261. if (a3 * a4 < 0.0f)
  262. return 1;
  263. }
  264. return 0;
  265. }
  266. static bool overlapEdges(const float* pts, const int* edges, int nedges, int s1, int t1)
  267. {
  268. for (int i = 0; i < nedges; ++i)
  269. {
  270. const int s0 = edges[i*4+0];
  271. const int t0 = edges[i*4+1];
  272. // Same or connected edges do not overlap.
  273. if (s0 == s1 || s0 == t1 || t0 == s1 || t0 == t1)
  274. continue;
  275. if (overlapSegSeg2d(&pts[s0*3],&pts[t0*3], &pts[s1*3],&pts[t1*3]))
  276. return true;
  277. }
  278. return false;
  279. }
  280. static void completeFacet(rcContext* ctx, const float* pts, int npts, int* edges, int& nedges, const int maxEdges, int& nfaces, int e)
  281. {
  282. static const float EPS = 1e-5f;
  283. int* edge = &edges[e*4];
  284. // Cache s and t.
  285. int s,t;
  286. if (edge[2] == EV_UNDEF)
  287. {
  288. s = edge[0];
  289. t = edge[1];
  290. }
  291. else if (edge[3] == EV_UNDEF)
  292. {
  293. s = edge[1];
  294. t = edge[0];
  295. }
  296. else
  297. {
  298. // Edge already completed.
  299. return;
  300. }
  301. // Find best point on left of edge.
  302. int pt = npts;
  303. float c[3] = {0,0,0};
  304. float r = -1;
  305. for (int u = 0; u < npts; ++u)
  306. {
  307. if (u == s || u == t) continue;
  308. if (vcross2(&pts[s*3], &pts[t*3], &pts[u*3]) > EPS)
  309. {
  310. if (r < 0)
  311. {
  312. // The circle is not updated yet, do it now.
  313. pt = u;
  314. circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
  315. continue;
  316. }
  317. const float d = vdist2(c, &pts[u*3]);
  318. const float tol = 0.001f;
  319. if (d > r*(1+tol))
  320. {
  321. // Outside current circumcircle, skip.
  322. continue;
  323. }
  324. else if (d < r*(1-tol))
  325. {
  326. // Inside safe circumcircle, update circle.
  327. pt = u;
  328. circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
  329. }
  330. else
  331. {
  332. // Inside epsilon circum circle, do extra tests to make sure the edge is valid.
  333. // s-u and t-u cannot overlap with s-pt nor t-pt if they exists.
  334. if (overlapEdges(pts, edges, nedges, s,u))
  335. continue;
  336. if (overlapEdges(pts, edges, nedges, t,u))
  337. continue;
  338. // Edge is valid.
  339. pt = u;
  340. circumCircle(&pts[s*3], &pts[t*3], &pts[u*3], c, r);
  341. }
  342. }
  343. }
  344. // Add new triangle or update edge info if s-t is on hull.
  345. if (pt < npts)
  346. {
  347. // Update face information of edge being completed.
  348. updateLeftFace(&edges[e*4], s, t, nfaces);
  349. // Add new edge or update face info of old edge.
  350. e = findEdge(edges, nedges, pt, s);
  351. if (e == EV_UNDEF)
  352. addEdge(ctx, edges, nedges, maxEdges, pt, s, nfaces, EV_UNDEF);
  353. else
  354. updateLeftFace(&edges[e*4], pt, s, nfaces);
  355. // Add new edge or update face info of old edge.
  356. e = findEdge(edges, nedges, t, pt);
  357. if (e == EV_UNDEF)
  358. addEdge(ctx, edges, nedges, maxEdges, t, pt, nfaces, EV_UNDEF);
  359. else
  360. updateLeftFace(&edges[e*4], t, pt, nfaces);
  361. nfaces++;
  362. }
  363. else
  364. {
  365. updateLeftFace(&edges[e*4], s, t, EV_HULL);
  366. }
  367. }
  368. static void delaunayHull(rcContext* ctx, const int npts, const float* pts,
  369. const int nhull, const int* hull,
  370. rcIntArray& tris, rcIntArray& edges)
  371. {
  372. int nfaces = 0;
  373. int nedges = 0;
  374. const int maxEdges = npts*10;
  375. edges.resize(maxEdges*4);
  376. for (int i = 0, j = nhull-1; i < nhull; j=i++)
  377. addEdge(ctx, &edges[0], nedges, maxEdges, hull[j],hull[i], EV_HULL, EV_UNDEF);
  378. int currentEdge = 0;
  379. while (currentEdge < nedges)
  380. {
  381. if (edges[currentEdge*4+2] == EV_UNDEF)
  382. completeFacet(ctx, pts, npts, &edges[0], nedges, maxEdges, nfaces, currentEdge);
  383. if (edges[currentEdge*4+3] == EV_UNDEF)
  384. completeFacet(ctx, pts, npts, &edges[0], nedges, maxEdges, nfaces, currentEdge);
  385. currentEdge++;
  386. }
  387. // Create tris
  388. tris.resize(nfaces*4);
  389. for (int i = 0; i < nfaces*4; ++i)
  390. tris[i] = -1;
  391. for (int i = 0; i < nedges; ++i)
  392. {
  393. const int* e = &edges[i*4];
  394. if (e[3] >= 0)
  395. {
  396. // Left face
  397. int* t = &tris[e[3]*4];
  398. if (t[0] == -1)
  399. {
  400. t[0] = e[0];
  401. t[1] = e[1];
  402. }
  403. else if (t[0] == e[1])
  404. t[2] = e[0];
  405. else if (t[1] == e[0])
  406. t[2] = e[1];
  407. }
  408. if (e[2] >= 0)
  409. {
  410. // Right
  411. int* t = &tris[e[2]*4];
  412. if (t[0] == -1)
  413. {
  414. t[0] = e[1];
  415. t[1] = e[0];
  416. }
  417. else if (t[0] == e[0])
  418. t[2] = e[1];
  419. else if (t[1] == e[1])
  420. t[2] = e[0];
  421. }
  422. }
  423. for (int i = 0; i < tris.size()/4; ++i)
  424. {
  425. int* t = &tris[i*4];
  426. if (t[0] == -1 || t[1] == -1 || t[2] == -1)
  427. {
  428. ctx->log(RC_LOG_WARNING, "delaunayHull: Removing dangling face %d [%d,%d,%d].", i, t[0],t[1],t[2]);
  429. t[0] = tris[tris.size()-4];
  430. t[1] = tris[tris.size()-3];
  431. t[2] = tris[tris.size()-2];
  432. t[3] = tris[tris.size()-1];
  433. tris.resize(tris.size()-4);
  434. --i;
  435. }
  436. }
  437. }
  438. // Calculate minimum extend of the polygon.
  439. static float polyMinExtent(const float* verts, const int nverts)
  440. {
  441. float minDist = FLT_MAX;
  442. for (int i = 0; i < nverts; i++)
  443. {
  444. const int ni = (i+1) % nverts;
  445. const float* p1 = &verts[i*3];
  446. const float* p2 = &verts[ni*3];
  447. float maxEdgeDist = 0;
  448. for (int j = 0; j < nverts; j++)
  449. {
  450. if (j == i || j == ni) continue;
  451. float d = distancePtSeg2d(&verts[j*3], p1,p2);
  452. maxEdgeDist = rcMax(maxEdgeDist, d);
  453. }
  454. minDist = rcMin(minDist, maxEdgeDist);
  455. }
  456. return rcSqrt(minDist);
  457. }
  458. // Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
  459. inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
  460. inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
  461. static void triangulateHull(const int nverts, const float* verts, const int nhull, const int* hull, rcIntArray& tris)
  462. {
  463. int start = 0, left = 1, right = nhull-1;
  464. // Start from an ear with shortest perimeter.
  465. // This tends to favor well formed triangles as starting point.
  466. float dmin = 0;
  467. for (int i = 0; i < nhull; i++)
  468. {
  469. int pi = prev(i, nhull);
  470. int ni = next(i, nhull);
  471. const float* pv = &verts[hull[pi]*3];
  472. const float* cv = &verts[hull[i]*3];
  473. const float* nv = &verts[hull[ni]*3];
  474. const float d = vdist2(pv,cv) + vdist2(cv,nv) + vdist2(nv,pv);
  475. if (d < dmin)
  476. {
  477. start = i;
  478. left = ni;
  479. right = pi;
  480. dmin = d;
  481. }
  482. }
  483. // Add first triangle
  484. tris.push(hull[start]);
  485. tris.push(hull[left]);
  486. tris.push(hull[right]);
  487. tris.push(0);
  488. // Triangulate the polygon by moving left or right,
  489. // depending on which triangle has shorter perimeter.
  490. // This heuristic was chose emprically, since it seems
  491. // handle tesselated straight edges well.
  492. while (next(left, nhull) != right)
  493. {
  494. // Check to see if se should advance left or right.
  495. int nleft = next(left, nhull);
  496. int nright = prev(right, nhull);
  497. const float* cvleft = &verts[hull[left]*3];
  498. const float* nvleft = &verts[hull[nleft]*3];
  499. const float* cvright = &verts[hull[right]*3];
  500. const float* nvright = &verts[hull[nright]*3];
  501. const float dleft = vdist2(cvleft, nvleft) + vdist2(nvleft, cvright);
  502. const float dright = vdist2(cvright, nvright) + vdist2(cvleft, nvright);
  503. if (dleft < dright)
  504. {
  505. tris.push(hull[left]);
  506. tris.push(hull[nleft]);
  507. tris.push(hull[right]);
  508. tris.push(0);
  509. left = nleft;
  510. }
  511. else
  512. {
  513. tris.push(hull[left]);
  514. tris.push(hull[nright]);
  515. tris.push(hull[right]);
  516. tris.push(0);
  517. right = nright;
  518. }
  519. }
  520. }
  521. inline float getJitterX(const int i)
  522. {
  523. return (((i * 0x8da6b343) & 0xffff) / 65535.0f * 2.0f) - 1.0f;
  524. }
  525. inline float getJitterY(const int i)
  526. {
  527. return (((i * 0xd8163841) & 0xffff) / 65535.0f * 2.0f) - 1.0f;
  528. }
  529. static bool buildPolyDetail(rcContext* ctx, const float* in, const int nin,
  530. const float sampleDist, const float sampleMaxError,
  531. const rcCompactHeightfield& chf, const rcHeightPatch& hp,
  532. float* verts, int& nverts, rcIntArray& tris,
  533. rcIntArray& edges, rcIntArray& samples)
  534. {
  535. static const int MAX_VERTS = 127;
  536. static const int MAX_TRIS = 255; // Max tris for delaunay is 2n-2-k (n=num verts, k=num hull verts).
  537. static const int MAX_VERTS_PER_EDGE = 32;
  538. float edge[(MAX_VERTS_PER_EDGE+1)*3];
  539. int hull[MAX_VERTS];
  540. int nhull = 0;
  541. nverts = 0;
  542. for (int i = 0; i < nin; ++i)
  543. rcVcopy(&verts[i*3], &in[i*3]);
  544. nverts = nin;
  545. edges.resize(0);
  546. tris.resize(0);
  547. const float cs = chf.cs;
  548. const float ics = 1.0f/cs;
  549. // Calculate minimum extents of the polygon based on input data.
  550. float minExtent = polyMinExtent(verts, nverts);
  551. // Tessellate outlines.
  552. // This is done in separate pass in order to ensure
  553. // seamless height values across the ply boundaries.
  554. if (sampleDist > 0)
  555. {
  556. for (int i = 0, j = nin-1; i < nin; j=i++)
  557. {
  558. const float* vj = &in[j*3];
  559. const float* vi = &in[i*3];
  560. bool swapped = false;
  561. // Make sure the segments are always handled in same order
  562. // using lexological sort or else there will be seams.
  563. if (fabsf(vj[0]-vi[0]) < 1e-6f)
  564. {
  565. if (vj[2] > vi[2])
  566. {
  567. rcSwap(vj,vi);
  568. swapped = true;
  569. }
  570. }
  571. else
  572. {
  573. if (vj[0] > vi[0])
  574. {
  575. rcSwap(vj,vi);
  576. swapped = true;
  577. }
  578. }
  579. // Create samples along the edge.
  580. float dx = vi[0] - vj[0];
  581. float dy = vi[1] - vj[1];
  582. float dz = vi[2] - vj[2];
  583. float d = sqrtf(dx*dx + dz*dz);
  584. int nn = 1 + (int)floorf(d/sampleDist);
  585. if (nn >= MAX_VERTS_PER_EDGE) nn = MAX_VERTS_PER_EDGE-1;
  586. if (nverts+nn >= MAX_VERTS)
  587. nn = MAX_VERTS-1-nverts;
  588. for (int k = 0; k <= nn; ++k)
  589. {
  590. float u = (float)k/(float)nn;
  591. float* pos = &edge[k*3];
  592. pos[0] = vj[0] + dx*u;
  593. pos[1] = vj[1] + dy*u;
  594. pos[2] = vj[2] + dz*u;
  595. pos[1] = getHeight(pos[0],pos[1],pos[2], cs, ics, chf.ch, hp)*chf.ch;
  596. }
  597. // Simplify samples.
  598. int idx[MAX_VERTS_PER_EDGE] = {0,nn};
  599. int nidx = 2;
  600. for (int k = 0; k < nidx-1; )
  601. {
  602. const int a = idx[k];
  603. const int b = idx[k+1];
  604. const float* va = &edge[a*3];
  605. const float* vb = &edge[b*3];
  606. // Find maximum deviation along the segment.
  607. float maxd = 0;
  608. int maxi = -1;
  609. for (int m = a+1; m < b; ++m)
  610. {
  611. float dev = distancePtSeg(&edge[m*3],va,vb);
  612. if (dev > maxd)
  613. {
  614. maxd = dev;
  615. maxi = m;
  616. }
  617. }
  618. // If the max deviation is larger than accepted error,
  619. // add new point, else continue to next segment.
  620. if (maxi != -1 && maxd > rcSqr(sampleMaxError))
  621. {
  622. for (int m = nidx; m > k; --m)
  623. idx[m] = idx[m-1];
  624. idx[k+1] = maxi;
  625. nidx++;
  626. }
  627. else
  628. {
  629. ++k;
  630. }
  631. }
  632. hull[nhull++] = j;
  633. // Add new vertices.
  634. if (swapped)
  635. {
  636. for (int k = nidx-2; k > 0; --k)
  637. {
  638. rcVcopy(&verts[nverts*3], &edge[idx[k]*3]);
  639. hull[nhull++] = nverts;
  640. nverts++;
  641. }
  642. }
  643. else
  644. {
  645. for (int k = 1; k < nidx-1; ++k)
  646. {
  647. rcVcopy(&verts[nverts*3], &edge[idx[k]*3]);
  648. hull[nhull++] = nverts;
  649. nverts++;
  650. }
  651. }
  652. }
  653. }
  654. // If the polygon minimum extent is small (sliver or small triangle), do not try to add internal points.
  655. if (minExtent < sampleDist*2)
  656. {
  657. triangulateHull(nverts, verts, nhull, hull, tris);
  658. return true;
  659. }
  660. // Tessellate the base mesh.
  661. // We're using the triangulateHull instead of delaunayHull as it tends to
  662. // create a bit better triangulation for long thing triangles when there
  663. // are no internal points.
  664. triangulateHull(nverts, verts, nhull, hull, tris);
  665. if (tris.size() == 0)
  666. {
  667. // Could not triangulate the poly, make sure there is some valid data there.
  668. ctx->log(RC_LOG_WARNING, "buildPolyDetail: Could not triangulate polygon (%d verts).", nverts);
  669. return true;
  670. }
  671. if (sampleDist > 0)
  672. {
  673. // Create sample locations in a grid.
  674. float bmin[3], bmax[3];
  675. rcVcopy(bmin, in);
  676. rcVcopy(bmax, in);
  677. for (int i = 1; i < nin; ++i)
  678. {
  679. rcVmin(bmin, &in[i*3]);
  680. rcVmax(bmax, &in[i*3]);
  681. }
  682. int x0 = (int)floorf(bmin[0]/sampleDist);
  683. int x1 = (int)ceilf(bmax[0]/sampleDist);
  684. int z0 = (int)floorf(bmin[2]/sampleDist);
  685. int z1 = (int)ceilf(bmax[2]/sampleDist);
  686. samples.resize(0);
  687. for (int z = z0; z < z1; ++z)
  688. {
  689. for (int x = x0; x < x1; ++x)
  690. {
  691. float pt[3];
  692. pt[0] = x*sampleDist;
  693. pt[1] = (bmax[1]+bmin[1])*0.5f;
  694. pt[2] = z*sampleDist;
  695. // Make sure the samples are not too close to the edges.
  696. if (distToPoly(nin,in,pt) > -sampleDist/2) continue;
  697. samples.push(x);
  698. samples.push(getHeight(pt[0], pt[1], pt[2], cs, ics, chf.ch, hp));
  699. samples.push(z);
  700. samples.push(0); // Not added
  701. }
  702. }
  703. // Add the samples starting from the one that has the most
  704. // error. The procedure stops when all samples are added
  705. // or when the max error is within treshold.
  706. const int nsamples = samples.size()/4;
  707. for (int iter = 0; iter < nsamples; ++iter)
  708. {
  709. if (nverts >= MAX_VERTS)
  710. break;
  711. // Find sample with most error.
  712. float bestpt[3] = {0,0,0};
  713. float bestd = 0;
  714. int besti = -1;
  715. for (int i = 0; i < nsamples; ++i)
  716. {
  717. const int* s = &samples[i*4];
  718. if (s[3]) continue; // skip added.
  719. float pt[3];
  720. // The sample location is jittered to get rid of some bad triangulations
  721. // which are cause by symmetrical data from the grid structure.
  722. pt[0] = s[0]*sampleDist + getJitterX(i)*cs*0.1f;
  723. pt[1] = s[1]*chf.ch;
  724. pt[2] = s[2]*sampleDist + getJitterY(i)*cs*0.1f;
  725. float d = distToTriMesh(pt, verts, nverts, &tris[0], tris.size()/4);
  726. if (d < 0) continue; // did not hit the mesh.
  727. if (d > bestd)
  728. {
  729. bestd = d;
  730. besti = i;
  731. rcVcopy(bestpt,pt);
  732. }
  733. }
  734. // If the max error is within accepted threshold, stop tesselating.
  735. if (bestd <= sampleMaxError || besti == -1)
  736. break;
  737. // Mark sample as added.
  738. samples[besti*4+3] = 1;
  739. // Add the new sample point.
  740. rcVcopy(&verts[nverts*3],bestpt);
  741. nverts++;
  742. // Create new triangulation.
  743. // TODO: Incremental add instead of full rebuild.
  744. edges.resize(0);
  745. tris.resize(0);
  746. delaunayHull(ctx, nverts, verts, nhull, hull, tris, edges);
  747. }
  748. }
  749. const int ntris = tris.size()/4;
  750. if (ntris > MAX_TRIS)
  751. {
  752. tris.resize(MAX_TRIS*4);
  753. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Shrinking triangle count from %d to max %d.", ntris, MAX_TRIS);
  754. }
  755. return true;
  756. }
  757. static void getHeightDataSeedsFromVertices(const rcCompactHeightfield& chf,
  758. const unsigned short* poly, const int npoly,
  759. const unsigned short* verts, const int bs,
  760. rcHeightPatch& hp, rcIntArray& stack)
  761. {
  762. // Floodfill the heightfield to get 2D height data,
  763. // starting at vertex locations as seeds.
  764. // Note: Reads to the compact heightfield are offset by border size (bs)
  765. // since border size offset is already removed from the polymesh vertices.
  766. memset(hp.data, 0, sizeof(unsigned short)*hp.width*hp.height);
  767. stack.resize(0);
  768. static const int offset[9*2] =
  769. {
  770. 0,0, -1,-1, 0,-1, 1,-1, 1,0, 1,1, 0,1, -1,1, -1,0,
  771. };
  772. // Use poly vertices as seed points for the flood fill.
  773. for (int j = 0; j < npoly; ++j)
  774. {
  775. int cx = 0, cz = 0, ci =-1;
  776. int dmin = RC_UNSET_HEIGHT;
  777. for (int k = 0; k < 9; ++k)
  778. {
  779. const int ax = (int)verts[poly[j]*3+0] + offset[k*2+0];
  780. const int ay = (int)verts[poly[j]*3+1];
  781. const int az = (int)verts[poly[j]*3+2] + offset[k*2+1];
  782. if (ax < hp.xmin || ax >= hp.xmin+hp.width ||
  783. az < hp.ymin || az >= hp.ymin+hp.height)
  784. continue;
  785. const rcCompactCell& c = chf.cells[(ax+bs)+(az+bs)*chf.width];
  786. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  787. {
  788. const rcCompactSpan& s = chf.spans[i];
  789. int d = rcAbs(ay - (int)s.y);
  790. if (d < dmin)
  791. {
  792. cx = ax;
  793. cz = az;
  794. ci = i;
  795. dmin = d;
  796. }
  797. }
  798. }
  799. if (ci != -1)
  800. {
  801. stack.push(cx);
  802. stack.push(cz);
  803. stack.push(ci);
  804. }
  805. }
  806. // Find center of the polygon using flood fill.
  807. int pcx = 0, pcz = 0;
  808. for (int j = 0; j < npoly; ++j)
  809. {
  810. pcx += (int)verts[poly[j]*3+0];
  811. pcz += (int)verts[poly[j]*3+2];
  812. }
  813. pcx /= npoly;
  814. pcz /= npoly;
  815. for (int i = 0; i < stack.size(); i += 3)
  816. {
  817. int cx = stack[i+0];
  818. int cy = stack[i+1];
  819. int idx = cx-hp.xmin+(cy-hp.ymin)*hp.width;
  820. hp.data[idx] = 1;
  821. }
  822. while (stack.size() > 0)
  823. {
  824. int ci = stack.pop();
  825. int cy = stack.pop();
  826. int cx = stack.pop();
  827. // Check if close to center of the polygon.
  828. if (rcAbs(cx-pcx) <= 1 && rcAbs(cy-pcz) <= 1)
  829. {
  830. stack.resize(0);
  831. stack.push(cx);
  832. stack.push(cy);
  833. stack.push(ci);
  834. break;
  835. }
  836. const rcCompactSpan& cs = chf.spans[ci];
  837. for (int dir = 0; dir < 4; ++dir)
  838. {
  839. if (rcGetCon(cs, dir) == RC_NOT_CONNECTED) continue;
  840. const int ax = cx + rcGetDirOffsetX(dir);
  841. const int ay = cy + rcGetDirOffsetY(dir);
  842. if (ax < hp.xmin || ax >= (hp.xmin+hp.width) ||
  843. ay < hp.ymin || ay >= (hp.ymin+hp.height))
  844. continue;
  845. if (hp.data[ax-hp.xmin+(ay-hp.ymin)*hp.width] != 0)
  846. continue;
  847. const int ai = (int)chf.cells[(ax+bs)+(ay+bs)*chf.width].index + rcGetCon(cs, dir);
  848. int idx = ax-hp.xmin+(ay-hp.ymin)*hp.width;
  849. hp.data[idx] = 1;
  850. stack.push(ax);
  851. stack.push(ay);
  852. stack.push(ai);
  853. }
  854. }
  855. memset(hp.data, 0xff, sizeof(unsigned short)*hp.width*hp.height);
  856. // Mark start locations.
  857. for (int i = 0; i < stack.size(); i += 3)
  858. {
  859. int cx = stack[i+0];
  860. int cy = stack[i+1];
  861. int ci = stack[i+2];
  862. int idx = cx-hp.xmin+(cy-hp.ymin)*hp.width;
  863. const rcCompactSpan& cs = chf.spans[ci];
  864. hp.data[idx] = cs.y;
  865. // getHeightData seeds are given in coordinates with borders
  866. stack[i+0] += bs;
  867. stack[i+1] += bs;
  868. }
  869. }
  870. static void getHeightData(const rcCompactHeightfield& chf,
  871. const unsigned short* poly, const int npoly,
  872. const unsigned short* verts, const int bs,
  873. rcHeightPatch& hp, rcIntArray& stack,
  874. int region)
  875. {
  876. // Note: Reads to the compact heightfield are offset by border size (bs)
  877. // since border size offset is already removed from the polymesh vertices.
  878. stack.resize(0);
  879. memset(hp.data, 0xff, sizeof(unsigned short)*hp.width*hp.height);
  880. bool empty = true;
  881. // Copy the height from the same region, and mark region borders
  882. // as seed points to fill the rest.
  883. for (int hy = 0; hy < hp.height; hy++)
  884. {
  885. int y = hp.ymin + hy + bs;
  886. for (int hx = 0; hx < hp.width; hx++)
  887. {
  888. int x = hp.xmin + hx + bs;
  889. const rcCompactCell& c = chf.cells[x+y*chf.width];
  890. for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
  891. {
  892. const rcCompactSpan& s = chf.spans[i];
  893. if (s.reg == region)
  894. {
  895. // Store height
  896. hp.data[hx + hy*hp.width] = s.y;
  897. empty = false;
  898. // If any of the neighbours is not in same region,
  899. // add the current location as flood fill start
  900. bool border = false;
  901. for (int dir = 0; dir < 4; ++dir)
  902. {
  903. if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
  904. {
  905. const int ax = x + rcGetDirOffsetX(dir);
  906. const int ay = y + rcGetDirOffsetY(dir);
  907. const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
  908. const rcCompactSpan& as = chf.spans[ai];
  909. if (as.reg != region)
  910. {
  911. border = true;
  912. break;
  913. }
  914. }
  915. }
  916. if (border)
  917. {
  918. stack.push(x);
  919. stack.push(y);
  920. stack.push(i);
  921. }
  922. break;
  923. }
  924. }
  925. }
  926. }
  927. // if the polygon does not contian any points from the current region (rare, but happens)
  928. // then use the cells closest to the polygon vertices as seeds to fill the height field
  929. if (empty)
  930. getHeightDataSeedsFromVertices(chf, poly, npoly, verts, bs, hp, stack);
  931. static const int RETRACT_SIZE = 256;
  932. int head = 0;
  933. while (head*3 < stack.size())
  934. {
  935. int cx = stack[head*3+0];
  936. int cy = stack[head*3+1];
  937. int ci = stack[head*3+2];
  938. head++;
  939. if (head >= RETRACT_SIZE)
  940. {
  941. head = 0;
  942. if (stack.size() > RETRACT_SIZE*3)
  943. memmove(&stack[0], &stack[RETRACT_SIZE*3], sizeof(int)*(stack.size()-RETRACT_SIZE*3));
  944. stack.resize(stack.size()-RETRACT_SIZE*3);
  945. }
  946. const rcCompactSpan& cs = chf.spans[ci];
  947. for (int dir = 0; dir < 4; ++dir)
  948. {
  949. if (rcGetCon(cs, dir) == RC_NOT_CONNECTED) continue;
  950. const int ax = cx + rcGetDirOffsetX(dir);
  951. const int ay = cy + rcGetDirOffsetY(dir);
  952. const int hx = ax - hp.xmin - bs;
  953. const int hy = ay - hp.ymin - bs;
  954. if (hx < 0 || hx >= hp.width || hy < 0 || hy >= hp.height)
  955. continue;
  956. if (hp.data[hx + hy*hp.width] != RC_UNSET_HEIGHT)
  957. continue;
  958. const int ai = (int)chf.cells[ax + ay*chf.width].index + rcGetCon(cs, dir);
  959. const rcCompactSpan& as = chf.spans[ai];
  960. hp.data[hx + hy*hp.width] = as.y;
  961. stack.push(ax);
  962. stack.push(ay);
  963. stack.push(ai);
  964. }
  965. }
  966. }
  967. static unsigned char getEdgeFlags(const float* va, const float* vb,
  968. const float* vpoly, const int npoly)
  969. {
  970. // Return true if edge (va,vb) is part of the polygon.
  971. static const float thrSqr = rcSqr(0.001f);
  972. for (int i = 0, j = npoly-1; i < npoly; j=i++)
  973. {
  974. if (distancePtSeg2d(va, &vpoly[j*3], &vpoly[i*3]) < thrSqr &&
  975. distancePtSeg2d(vb, &vpoly[j*3], &vpoly[i*3]) < thrSqr)
  976. return 1;
  977. }
  978. return 0;
  979. }
  980. static unsigned char getTriFlags(const float* va, const float* vb, const float* vc,
  981. const float* vpoly, const int npoly)
  982. {
  983. unsigned char flags = 0;
  984. flags |= getEdgeFlags(va,vb,vpoly,npoly) << 0;
  985. flags |= getEdgeFlags(vb,vc,vpoly,npoly) << 2;
  986. flags |= getEdgeFlags(vc,va,vpoly,npoly) << 4;
  987. return flags;
  988. }
  989. /// @par
  990. ///
  991. /// See the #rcConfig documentation for more information on the configuration parameters.
  992. ///
  993. /// @see rcAllocPolyMeshDetail, rcPolyMesh, rcCompactHeightfield, rcPolyMeshDetail, rcConfig
  994. bool rcBuildPolyMeshDetail(rcContext* ctx, const rcPolyMesh& mesh, const rcCompactHeightfield& chf,
  995. const float sampleDist, const float sampleMaxError,
  996. rcPolyMeshDetail& dmesh)
  997. {
  998. rcAssert(ctx);
  999. ctx->startTimer(RC_TIMER_BUILD_POLYMESHDETAIL);
  1000. if (mesh.nverts == 0 || mesh.npolys == 0)
  1001. return true;
  1002. const int nvp = mesh.nvp;
  1003. const float cs = mesh.cs;
  1004. const float ch = mesh.ch;
  1005. const float* orig = mesh.bmin;
  1006. const int borderSize = mesh.borderSize;
  1007. rcIntArray edges(64);
  1008. rcIntArray tris(512);
  1009. rcIntArray stack(512);
  1010. rcIntArray samples(512);
  1011. float verts[256*3];
  1012. rcHeightPatch hp;
  1013. int nPolyVerts = 0;
  1014. int maxhw = 0, maxhh = 0;
  1015. rcScopedDelete<int> bounds = (int*)rcAlloc(sizeof(int)*mesh.npolys*4, RC_ALLOC_TEMP);
  1016. if (!bounds)
  1017. {
  1018. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'bounds' (%d).", mesh.npolys*4);
  1019. return false;
  1020. }
  1021. rcScopedDelete<float> poly = (float*)rcAlloc(sizeof(float)*nvp*3, RC_ALLOC_TEMP);
  1022. if (!poly)
  1023. {
  1024. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'poly' (%d).", nvp*3);
  1025. return false;
  1026. }
  1027. // Find max size for a polygon area.
  1028. for (int i = 0; i < mesh.npolys; ++i)
  1029. {
  1030. const unsigned short* p = &mesh.polys[i*nvp*2];
  1031. int& xmin = bounds[i*4+0];
  1032. int& xmax = bounds[i*4+1];
  1033. int& ymin = bounds[i*4+2];
  1034. int& ymax = bounds[i*4+3];
  1035. xmin = chf.width;
  1036. xmax = 0;
  1037. ymin = chf.height;
  1038. ymax = 0;
  1039. for (int j = 0; j < nvp; ++j)
  1040. {
  1041. if(p[j] == RC_MESH_NULL_IDX) break;
  1042. const unsigned short* v = &mesh.verts[p[j]*3];
  1043. xmin = rcMin(xmin, (int)v[0]);
  1044. xmax = rcMax(xmax, (int)v[0]);
  1045. ymin = rcMin(ymin, (int)v[2]);
  1046. ymax = rcMax(ymax, (int)v[2]);
  1047. nPolyVerts++;
  1048. }
  1049. xmin = rcMax(0,xmin-1);
  1050. xmax = rcMin(chf.width,xmax+1);
  1051. ymin = rcMax(0,ymin-1);
  1052. ymax = rcMin(chf.height,ymax+1);
  1053. if (xmin >= xmax || ymin >= ymax) continue;
  1054. maxhw = rcMax(maxhw, xmax-xmin);
  1055. maxhh = rcMax(maxhh, ymax-ymin);
  1056. }
  1057. hp.data = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxhw*maxhh, RC_ALLOC_TEMP);
  1058. if (!hp.data)
  1059. {
  1060. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'hp.data' (%d).", maxhw*maxhh);
  1061. return false;
  1062. }
  1063. dmesh.nmeshes = mesh.npolys;
  1064. dmesh.nverts = 0;
  1065. dmesh.ntris = 0;
  1066. dmesh.meshes = (unsigned int*)rcAlloc(sizeof(unsigned int)*dmesh.nmeshes*4, RC_ALLOC_PERM);
  1067. if (!dmesh.meshes)
  1068. {
  1069. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.meshes' (%d).", dmesh.nmeshes*4);
  1070. return false;
  1071. }
  1072. int vcap = nPolyVerts+nPolyVerts/2;
  1073. int tcap = vcap*2;
  1074. dmesh.nverts = 0;
  1075. dmesh.verts = (float*)rcAlloc(sizeof(float)*vcap*3, RC_ALLOC_PERM);
  1076. if (!dmesh.verts)
  1077. {
  1078. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.verts' (%d).", vcap*3);
  1079. return false;
  1080. }
  1081. dmesh.ntris = 0;
  1082. dmesh.tris = (unsigned char*)rcAlloc(sizeof(unsigned char)*tcap*4, RC_ALLOC_PERM);
  1083. if (!dmesh.tris)
  1084. {
  1085. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.tris' (%d).", tcap*4);
  1086. return false;
  1087. }
  1088. for (int i = 0; i < mesh.npolys; ++i)
  1089. {
  1090. const unsigned short* p = &mesh.polys[i*nvp*2];
  1091. // Store polygon vertices for processing.
  1092. int npoly = 0;
  1093. for (int j = 0; j < nvp; ++j)
  1094. {
  1095. if(p[j] == RC_MESH_NULL_IDX) break;
  1096. const unsigned short* v = &mesh.verts[p[j]*3];
  1097. poly[j*3+0] = v[0]*cs;
  1098. poly[j*3+1] = v[1]*ch;
  1099. poly[j*3+2] = v[2]*cs;
  1100. npoly++;
  1101. }
  1102. // Get the height data from the area of the polygon.
  1103. hp.xmin = bounds[i*4+0];
  1104. hp.ymin = bounds[i*4+2];
  1105. hp.width = bounds[i*4+1]-bounds[i*4+0];
  1106. hp.height = bounds[i*4+3]-bounds[i*4+2];
  1107. getHeightData(chf, p, npoly, mesh.verts, borderSize, hp, stack, mesh.regs[i]);
  1108. // Build detail mesh.
  1109. int nverts = 0;
  1110. if (!buildPolyDetail(ctx, poly, npoly,
  1111. sampleDist, sampleMaxError,
  1112. chf, hp, verts, nverts, tris,
  1113. edges, samples))
  1114. {
  1115. return false;
  1116. }
  1117. // Move detail verts to world space.
  1118. for (int j = 0; j < nverts; ++j)
  1119. {
  1120. verts[j*3+0] += orig[0];
  1121. verts[j*3+1] += orig[1] + chf.ch; // Is this offset necessary?
  1122. verts[j*3+2] += orig[2];
  1123. }
  1124. // Offset poly too, will be used to flag checking.
  1125. for (int j = 0; j < npoly; ++j)
  1126. {
  1127. poly[j*3+0] += orig[0];
  1128. poly[j*3+1] += orig[1];
  1129. poly[j*3+2] += orig[2];
  1130. }
  1131. // Store detail submesh.
  1132. const int ntris = tris.size()/4;
  1133. dmesh.meshes[i*4+0] = (unsigned int)dmesh.nverts;
  1134. dmesh.meshes[i*4+1] = (unsigned int)nverts;
  1135. dmesh.meshes[i*4+2] = (unsigned int)dmesh.ntris;
  1136. dmesh.meshes[i*4+3] = (unsigned int)ntris;
  1137. // Store vertices, allocate more memory if necessary.
  1138. if (dmesh.nverts+nverts > vcap)
  1139. {
  1140. while (dmesh.nverts+nverts > vcap)
  1141. vcap += 256;
  1142. float* newv = (float*)rcAlloc(sizeof(float)*vcap*3, RC_ALLOC_PERM);
  1143. if (!newv)
  1144. {
  1145. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'newv' (%d).", vcap*3);
  1146. return false;
  1147. }
  1148. if (dmesh.nverts)
  1149. memcpy(newv, dmesh.verts, sizeof(float)*3*dmesh.nverts);
  1150. rcFree(dmesh.verts);
  1151. dmesh.verts = newv;
  1152. }
  1153. for (int j = 0; j < nverts; ++j)
  1154. {
  1155. dmesh.verts[dmesh.nverts*3+0] = verts[j*3+0];
  1156. dmesh.verts[dmesh.nverts*3+1] = verts[j*3+1];
  1157. dmesh.verts[dmesh.nverts*3+2] = verts[j*3+2];
  1158. dmesh.nverts++;
  1159. }
  1160. // Store triangles, allocate more memory if necessary.
  1161. if (dmesh.ntris+ntris > tcap)
  1162. {
  1163. while (dmesh.ntris+ntris > tcap)
  1164. tcap += 256;
  1165. unsigned char* newt = (unsigned char*)rcAlloc(sizeof(unsigned char)*tcap*4, RC_ALLOC_PERM);
  1166. if (!newt)
  1167. {
  1168. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'newt' (%d).", tcap*4);
  1169. return false;
  1170. }
  1171. if (dmesh.ntris)
  1172. memcpy(newt, dmesh.tris, sizeof(unsigned char)*4*dmesh.ntris);
  1173. rcFree(dmesh.tris);
  1174. dmesh.tris = newt;
  1175. }
  1176. for (int j = 0; j < ntris; ++j)
  1177. {
  1178. const int* t = &tris[j*4];
  1179. dmesh.tris[dmesh.ntris*4+0] = (unsigned char)t[0];
  1180. dmesh.tris[dmesh.ntris*4+1] = (unsigned char)t[1];
  1181. dmesh.tris[dmesh.ntris*4+2] = (unsigned char)t[2];
  1182. dmesh.tris[dmesh.ntris*4+3] = getTriFlags(&verts[t[0]*3], &verts[t[1]*3], &verts[t[2]*3], poly, npoly);
  1183. dmesh.ntris++;
  1184. }
  1185. }
  1186. ctx->stopTimer(RC_TIMER_BUILD_POLYMESHDETAIL);
  1187. return true;
  1188. }
  1189. /// @see rcAllocPolyMeshDetail, rcPolyMeshDetail
  1190. bool rcMergePolyMeshDetails(rcContext* ctx, rcPolyMeshDetail** meshes, const int nmeshes, rcPolyMeshDetail& mesh)
  1191. {
  1192. rcAssert(ctx);
  1193. ctx->startTimer(RC_TIMER_MERGE_POLYMESHDETAIL);
  1194. int maxVerts = 0;
  1195. int maxTris = 0;
  1196. int maxMeshes = 0;
  1197. for (int i = 0; i < nmeshes; ++i)
  1198. {
  1199. if (!meshes[i]) continue;
  1200. maxVerts += meshes[i]->nverts;
  1201. maxTris += meshes[i]->ntris;
  1202. maxMeshes += meshes[i]->nmeshes;
  1203. }
  1204. mesh.nmeshes = 0;
  1205. mesh.meshes = (unsigned int*)rcAlloc(sizeof(unsigned int)*maxMeshes*4, RC_ALLOC_PERM);
  1206. if (!mesh.meshes)
  1207. {
  1208. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'pmdtl.meshes' (%d).", maxMeshes*4);
  1209. return false;
  1210. }
  1211. mesh.ntris = 0;
  1212. mesh.tris = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxTris*4, RC_ALLOC_PERM);
  1213. if (!mesh.tris)
  1214. {
  1215. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.tris' (%d).", maxTris*4);
  1216. return false;
  1217. }
  1218. mesh.nverts = 0;
  1219. mesh.verts = (float*)rcAlloc(sizeof(float)*maxVerts*3, RC_ALLOC_PERM);
  1220. if (!mesh.verts)
  1221. {
  1222. ctx->log(RC_LOG_ERROR, "rcBuildPolyMeshDetail: Out of memory 'dmesh.verts' (%d).", maxVerts*3);
  1223. return false;
  1224. }
  1225. // Merge datas.
  1226. for (int i = 0; i < nmeshes; ++i)
  1227. {
  1228. rcPolyMeshDetail* dm = meshes[i];
  1229. if (!dm) continue;
  1230. for (int j = 0; j < dm->nmeshes; ++j)
  1231. {
  1232. unsigned int* dst = &mesh.meshes[mesh.nmeshes*4];
  1233. unsigned int* src = &dm->meshes[j*4];
  1234. dst[0] = (unsigned int)mesh.nverts+src[0];
  1235. dst[1] = src[1];
  1236. dst[2] = (unsigned int)mesh.ntris+src[2];
  1237. dst[3] = src[3];
  1238. mesh.nmeshes++;
  1239. }
  1240. for (int k = 0; k < dm->nverts; ++k)
  1241. {
  1242. rcVcopy(&mesh.verts[mesh.nverts*3], &dm->verts[k*3]);
  1243. mesh.nverts++;
  1244. }
  1245. for (int k = 0; k < dm->ntris; ++k)
  1246. {
  1247. mesh.tris[mesh.ntris*4+0] = dm->tris[k*4+0];
  1248. mesh.tris[mesh.ntris*4+1] = dm->tris[k*4+1];
  1249. mesh.tris[mesh.ntris*4+2] = dm->tris[k*4+2];
  1250. mesh.tris[mesh.ntris*4+3] = dm->tris[k*4+3];
  1251. mesh.ntris++;
  1252. }
  1253. }
  1254. ctx->stopTimer(RC_TIMER_MERGE_POLYMESHDETAIL);
  1255. return true;
  1256. }