2
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
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.
19
#define _USE_MATH_DEFINES
24
#include "RecastAlloc.h"
25
#include "RecastAssert.h"
28
static int getCornerHeight(int x, int y, int i, int dir,
29
const rcCompactHeightfield& chf,
32
const rcCompactSpan& s = chf.spans[i];
34
int dirp = (dir+1) & 0x3;
36
unsigned int regs[4] = {0,0,0,0};
38
// Combine region and area codes in order to prevent
39
// border vertices which are in between two areas to be removed.
40
regs[0] = chf.spans[i].reg | (chf.areas[i] << 16);
42
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
44
const int ax = x + rcGetDirOffsetX(dir);
45
const int ay = y + rcGetDirOffsetY(dir);
46
const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
47
const rcCompactSpan& as = chf.spans[ai];
48
ch = rcMax(ch, (int)as.y);
49
regs[1] = chf.spans[ai].reg | (chf.areas[ai] << 16);
50
if (rcGetCon(as, dirp) != RC_NOT_CONNECTED)
52
const int ax2 = ax + rcGetDirOffsetX(dirp);
53
const int ay2 = ay + rcGetDirOffsetY(dirp);
54
const int ai2 = (int)chf.cells[ax2+ay2*chf.width].index + rcGetCon(as, dirp);
55
const rcCompactSpan& as2 = chf.spans[ai2];
56
ch = rcMax(ch, (int)as2.y);
57
regs[2] = chf.spans[ai2].reg | (chf.areas[ai2] << 16);
60
if (rcGetCon(s, dirp) != RC_NOT_CONNECTED)
62
const int ax = x + rcGetDirOffsetX(dirp);
63
const int ay = y + rcGetDirOffsetY(dirp);
64
const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dirp);
65
const rcCompactSpan& as = chf.spans[ai];
66
ch = rcMax(ch, (int)as.y);
67
regs[3] = chf.spans[ai].reg | (chf.areas[ai] << 16);
68
if (rcGetCon(as, dir) != RC_NOT_CONNECTED)
70
const int ax2 = ax + rcGetDirOffsetX(dir);
71
const int ay2 = ay + rcGetDirOffsetY(dir);
72
const int ai2 = (int)chf.cells[ax2+ay2*chf.width].index + rcGetCon(as, dir);
73
const rcCompactSpan& as2 = chf.spans[ai2];
74
ch = rcMax(ch, (int)as2.y);
75
regs[2] = chf.spans[ai2].reg | (chf.areas[ai2] << 16);
79
// Check if the vertex is special edge vertex, these vertices will be removed later.
80
for (int j = 0; j < 4; ++j)
83
const int b = (j+1) & 0x3;
84
const int c = (j+2) & 0x3;
85
const int d = (j+3) & 0x3;
87
// The vertex is a border vertex there are two same exterior cells in a row,
88
// followed by two interior cells and none of the regions are out of bounds.
89
const bool twoSameExts = (regs[a] & regs[b] & RC_BORDER_REG) != 0 && regs[a] == regs[b];
90
const bool twoInts = ((regs[c] | regs[d]) & RC_BORDER_REG) == 0;
91
const bool intsSameArea = (regs[c]>>16) == (regs[d]>>16);
92
const bool noZeros = regs[a] != 0 && regs[b] != 0 && regs[c] != 0 && regs[d] != 0;
93
if (twoSameExts && twoInts && intsSameArea && noZeros)
95
isBorderVertex = true;
103
static void walkContour(int x, int y, int i,
104
rcCompactHeightfield& chf,
105
unsigned char* flags, rcIntArray& points)
107
// Choose the first non-connected edge
108
unsigned char dir = 0;
109
while ((flags[i] & (1 << dir)) == 0)
112
unsigned char startDir = dir;
115
const unsigned char area = chf.areas[i];
118
while (++iter < 40000)
120
if (flags[i] & (1 << dir))
122
// Choose the edge corner
123
bool isBorderVertex = false;
124
bool isAreaBorder = false;
126
int py = getCornerHeight(x, y, i, dir, chf, isBorderVertex);
131
case 1: px++; pz++; break;
135
const rcCompactSpan& s = chf.spans[i];
136
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
138
const int ax = x + rcGetDirOffsetX(dir);
139
const int ay = y + rcGetDirOffsetY(dir);
140
const int ai = (int)chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
141
r = (int)chf.spans[ai].reg;
142
if (area != chf.areas[ai])
146
r |= RC_BORDER_VERTEX;
154
flags[i] &= ~(1 << dir); // Remove visited edges
155
dir = (dir+1) & 0x3; // Rotate CW
160
const int nx = x + rcGetDirOffsetX(dir);
161
const int ny = y + rcGetDirOffsetY(dir);
162
const rcCompactSpan& s = chf.spans[i];
163
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
165
const rcCompactCell& nc = chf.cells[nx+ny*chf.width];
166
ni = (int)nc.index + rcGetCon(s, dir);
170
// Should not happen.
176
dir = (dir+3) & 0x3; // Rotate CCW
179
if (starti == i && startDir == dir)
186
static float distancePtSeg(const int x, const int z,
187
const int px, const int pz,
188
const int qx, const int qz)
190
/* float pqx = (float)(qx - px);
191
float pqy = (float)(qy - py);
192
float pqz = (float)(qz - pz);
193
float dx = (float)(x - px);
194
float dy = (float)(y - py);
195
float dz = (float)(z - pz);
196
float d = pqx*pqx + pqy*pqy + pqz*pqz;
197
float t = pqx*dx + pqy*dy + pqz*dz;
209
return dx*dx + dy*dy + dz*dz;*/
211
float pqx = (float)(qx - px);
212
float pqz = (float)(qz - pz);
213
float dx = (float)(x - px);
214
float dz = (float)(z - pz);
215
float d = pqx*pqx + pqz*pqz;
216
float t = pqx*dx + pqz*dz;
227
return dx*dx + dz*dz;
230
static void simplifyContour(rcIntArray& points, rcIntArray& simplified,
231
const float maxError, const int maxEdgeLen, const int buildFlags)
233
// Add initial points.
234
bool hasConnections = false;
235
for (int i = 0; i < points.size(); i += 4)
237
if ((points[i+3] & RC_CONTOUR_REG_MASK) != 0)
239
hasConnections = true;
246
// The contour has some portals to other regions.
247
// Add a new point to every location where the region changes.
248
for (int i = 0, ni = points.size()/4; i < ni; ++i)
251
const bool differentRegs = (points[i*4+3] & RC_CONTOUR_REG_MASK) != (points[ii*4+3] & RC_CONTOUR_REG_MASK);
252
const bool areaBorders = (points[i*4+3] & RC_AREA_BORDER) != (points[ii*4+3] & RC_AREA_BORDER);
253
if (differentRegs || areaBorders)
255
simplified.push(points[i*4+0]);
256
simplified.push(points[i*4+1]);
257
simplified.push(points[i*4+2]);
263
if (simplified.size() == 0)
265
// If there is no connections at all,
266
// create some initial points for the simplification process.
267
// Find lower-left and upper-right vertices of the contour.
276
for (int i = 0; i < points.size(); i += 4)
281
if (x < llx || (x == llx && z < llz))
288
if (x > urx || (x == urx && z > urz))
296
simplified.push(llx);
297
simplified.push(lly);
298
simplified.push(llz);
299
simplified.push(lli);
301
simplified.push(urx);
302
simplified.push(ury);
303
simplified.push(urz);
304
simplified.push(uri);
307
// Add points until all raw points are within
308
// error tolerance to the simplified shape.
309
const int pn = points.size()/4;
310
for (int i = 0; i < simplified.size()/4; )
312
int ii = (i+1) % (simplified.size()/4);
314
const int ax = simplified[i*4+0];
315
const int az = simplified[i*4+2];
316
const int ai = simplified[i*4+3];
318
const int bx = simplified[ii*4+0];
319
const int bz = simplified[ii*4+2];
320
const int bi = simplified[ii*4+3];
322
// Find maximum deviation from the segment.
327
// Traverse the segment in lexilogical order so that the
328
// max deviation is calculated similarly when traversing
329
// opposite segments.
330
if (bx > ax || (bx == ax && bz > az))
343
// Tessellate only outer edges or edges between areas.
344
if ((points[ci*4+3] & RC_CONTOUR_REG_MASK) == 0 ||
345
(points[ci*4+3] & RC_AREA_BORDER))
349
float d = distancePtSeg(points[ci*4+0], points[ci*4+2], ax, az, bx, bz);
360
// If the max deviation is larger than accepted error,
361
// add new point, else continue to next segment.
362
if (maxi != -1 && maxd > (maxError*maxError))
364
// Add space for the new point.
365
simplified.resize(simplified.size()+4);
366
const int n = simplified.size()/4;
367
for (int j = n-1; j > i; --j)
369
simplified[j*4+0] = simplified[(j-1)*4+0];
370
simplified[j*4+1] = simplified[(j-1)*4+1];
371
simplified[j*4+2] = simplified[(j-1)*4+2];
372
simplified[j*4+3] = simplified[(j-1)*4+3];
375
simplified[(i+1)*4+0] = points[maxi*4+0];
376
simplified[(i+1)*4+1] = points[maxi*4+1];
377
simplified[(i+1)*4+2] = points[maxi*4+2];
378
simplified[(i+1)*4+3] = maxi;
386
// Split too long edges.
387
if (maxEdgeLen > 0 && (buildFlags & (RC_CONTOUR_TESS_WALL_EDGES|RC_CONTOUR_TESS_AREA_EDGES)) != 0)
389
for (int i = 0; i < simplified.size()/4; )
391
const int ii = (i+1) % (simplified.size()/4);
393
const int ax = simplified[i*4+0];
394
const int az = simplified[i*4+2];
395
const int ai = simplified[i*4+3];
397
const int bx = simplified[ii*4+0];
398
const int bz = simplified[ii*4+2];
399
const int bi = simplified[ii*4+3];
401
// Find maximum deviation from the segment.
403
int ci = (ai+1) % pn;
405
// Tessellate only outer edges or edges between areas.
408
if ((buildFlags & RC_CONTOUR_TESS_WALL_EDGES) && (points[ci*4+3] & RC_CONTOUR_REG_MASK) == 0)
410
// Edges between areas.
411
if ((buildFlags & RC_CONTOUR_TESS_AREA_EDGES) && (points[ci*4+3] & RC_AREA_BORDER))
418
if (dx*dx + dz*dz > maxEdgeLen*maxEdgeLen)
420
// Round based on the segments in lexilogical order so that the
421
// max tesselation is consistent regardles in which direction
422
// segments are traversed.
423
if (bx > ax || (bx == ax && bz > az))
425
const int n = bi < ai ? (bi+pn - ai) : (bi - ai);
426
maxi = (ai + n/2) % pn;
430
const int n = bi < ai ? (bi+pn - ai) : (bi - ai);
431
maxi = (ai + (n+1)/2) % pn;
436
// If the max deviation is larger than accepted error,
437
// add new point, else continue to next segment.
440
// Add space for the new point.
441
simplified.resize(simplified.size()+4);
442
const int n = simplified.size()/4;
443
for (int j = n-1; j > i; --j)
445
simplified[j*4+0] = simplified[(j-1)*4+0];
446
simplified[j*4+1] = simplified[(j-1)*4+1];
447
simplified[j*4+2] = simplified[(j-1)*4+2];
448
simplified[j*4+3] = simplified[(j-1)*4+3];
451
simplified[(i+1)*4+0] = points[maxi*4+0];
452
simplified[(i+1)*4+1] = points[maxi*4+1];
453
simplified[(i+1)*4+2] = points[maxi*4+2];
454
simplified[(i+1)*4+3] = maxi;
463
for (int i = 0; i < simplified.size()/4; ++i)
465
// The edge vertex flag is take from the current raw point,
466
// and the neighbour region is take from the next raw point.
467
const int ai = (simplified[i*4+3]+1) % pn;
468
const int bi = simplified[i*4+3];
469
simplified[i*4+3] = (points[ai*4+3] & RC_CONTOUR_REG_MASK) | (points[bi*4+3] & RC_BORDER_VERTEX);
474
static void removeDegenerateSegments(rcIntArray& simplified)
476
// Remove adjacent vertices which are equal on xz-plane,
477
// or else the triangulator will get confused.
478
for (int i = 0; i < simplified.size()/4; ++i)
481
if (ni >= (simplified.size()/4))
484
if (simplified[i*4+0] == simplified[ni*4+0] &&
485
simplified[i*4+2] == simplified[ni*4+2])
487
// Degenerate segment, remove.
488
for (int j = i; j < simplified.size()/4-1; ++j)
490
simplified[j*4+0] = simplified[(j+1)*4+0];
491
simplified[j*4+1] = simplified[(j+1)*4+1];
492
simplified[j*4+2] = simplified[(j+1)*4+2];
493
simplified[j*4+3] = simplified[(j+1)*4+3];
495
simplified.resize(simplified.size()-4);
500
static int calcAreaOfPolygon2D(const int* verts, const int nverts)
503
for (int i = 0, j = nverts-1; i < nverts; j=i++)
505
const int* vi = &verts[i*4];
506
const int* vj = &verts[j*4];
507
area += vi[0] * vj[2] - vj[0] * vi[2];
512
inline bool ileft(const int* a, const int* b, const int* c)
514
return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]) <= 0;
517
static void getClosestIndices(const int* vertsa, const int nvertsa,
518
const int* vertsb, const int nvertsb,
521
int closestDist = 0xfffffff;
523
for (int i = 0; i < nvertsa; ++i)
525
const int in = (i+1) % nvertsa;
526
const int ip = (i+nvertsa-1) % nvertsa;
527
const int* va = &vertsa[i*4];
528
const int* van = &vertsa[in*4];
529
const int* vap = &vertsa[ip*4];
531
for (int j = 0; j < nvertsb; ++j)
533
const int* vb = &vertsb[j*4];
534
// vb must be "infront" of va.
535
if (ileft(vap,va,vb) && ileft(va,van,vb))
537
const int dx = vb[0] - va[0];
538
const int dz = vb[2] - va[2];
539
const int d = dx*dx + dz*dz;
551
static bool mergeContours(rcContour& ca, rcContour& cb, int ia, int ib)
553
const int maxVerts = ca.nverts + cb.nverts + 2;
554
int* verts = (int*)rcAlloc(sizeof(int)*maxVerts*4, RC_ALLOC_PERM);
561
for (int i = 0; i <= ca.nverts; ++i)
563
int* dst = &verts[nv*4];
564
const int* src = &ca.verts[((ia+i)%ca.nverts)*4];
573
for (int i = 0; i <= cb.nverts; ++i)
575
int* dst = &verts[nv*4];
576
const int* src = &cb.verts[((ib+i)%cb.nverts)*4];
597
/// The raw contours will match the region outlines exactly. The @p maxError and @p maxEdgeLen
598
/// parameters control how closely the simplified contours will match the raw contours.
600
/// Simplified contours are generated such that the vertices for portals between areas match up.
601
/// (They are considered mandatory vertices.)
603
/// Setting @p maxEdgeLength to zero will disabled the edge length feature.
605
/// See the #rcConfig documentation for more information on the configuration parameters.
607
/// @see rcAllocContourSet, rcCompactHeightfield, rcContourSet, rcConfig
608
bool rcBuildContours(rcContext* ctx, rcCompactHeightfield& chf,
609
const float maxError, const int maxEdgeLen,
610
rcContourSet& cset, const int buildFlags)
614
const int w = chf.width;
615
const int h = chf.height;
616
const int borderSize = chf.borderSize;
618
ctx->startTimer(RC_TIMER_BUILD_CONTOURS);
620
rcVcopy(cset.bmin, chf.bmin);
621
rcVcopy(cset.bmax, chf.bmax);
624
// If the heightfield was build with bordersize, remove the offset.
625
const float pad = borderSize*chf.cs;
633
cset.width = chf.width - chf.borderSize*2;
634
cset.height = chf.height - chf.borderSize*2;
635
cset.borderSize = chf.borderSize;
637
int maxContours = rcMax((int)chf.maxRegions, 8);
638
cset.conts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM);
643
rcScopedDelete<unsigned char> flags = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
646
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'flags' (%d).", chf.spanCount);
650
ctx->startTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
653
for (int y = 0; y < h; ++y)
655
for (int x = 0; x < w; ++x)
657
const rcCompactCell& c = chf.cells[x+y*w];
658
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
660
unsigned char res = 0;
661
const rcCompactSpan& s = chf.spans[i];
662
if (!chf.spans[i].reg || (chf.spans[i].reg & RC_BORDER_REG))
667
for (int dir = 0; dir < 4; ++dir)
669
unsigned short r = 0;
670
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
672
const int ax = x + rcGetDirOffsetX(dir);
673
const int ay = y + rcGetDirOffsetY(dir);
674
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
675
r = chf.spans[ai].reg;
677
if (r == chf.spans[i].reg)
680
flags[i] = res ^ 0xf; // Inverse, mark non connected edges.
685
ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
687
rcIntArray verts(256);
688
rcIntArray simplified(64);
690
for (int y = 0; y < h; ++y)
692
for (int x = 0; x < w; ++x)
694
const rcCompactCell& c = chf.cells[x+y*w];
695
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
697
if (flags[i] == 0 || flags[i] == 0xf)
702
const unsigned short reg = chf.spans[i].reg;
703
if (!reg || (reg & RC_BORDER_REG))
705
const unsigned char area = chf.areas[i];
708
simplified.resize(0);
710
ctx->startTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
711
walkContour(x, y, i, chf, flags, verts);
712
ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_TRACE);
714
ctx->startTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY);
715
simplifyContour(verts, simplified, maxError, maxEdgeLen, buildFlags);
716
removeDegenerateSegments(simplified);
717
ctx->stopTimer(RC_TIMER_BUILD_CONTOURS_SIMPLIFY);
720
// Store region->contour remap info.
722
if (simplified.size()/4 >= 3)
724
if (cset.nconts >= maxContours)
726
// Allocate more contours.
727
// This can happen when there are tiny holes in the heightfield.
728
const int oldMax = maxContours;
730
rcContour* newConts = (rcContour*)rcAlloc(sizeof(rcContour)*maxContours, RC_ALLOC_PERM);
731
for (int j = 0; j < cset.nconts; ++j)
733
newConts[j] = cset.conts[j];
734
// Reset source pointers to prevent data deletion.
735
cset.conts[j].verts = 0;
736
cset.conts[j].rverts = 0;
739
cset.conts = newConts;
741
ctx->log(RC_LOG_WARNING, "rcBuildContours: Expanding max contours from %d to %d.", oldMax, maxContours);
744
rcContour* cont = &cset.conts[cset.nconts++];
746
cont->nverts = simplified.size()/4;
747
cont->verts = (int*)rcAlloc(sizeof(int)*cont->nverts*4, RC_ALLOC_PERM);
750
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'verts' (%d).", cont->nverts);
753
memcpy(cont->verts, &simplified[0], sizeof(int)*cont->nverts*4);
756
// If the heightfield was build with bordersize, remove the offset.
757
for (int i = 0; i < cont->nverts; ++i)
759
int* v = &cont->verts[i*4];
765
cont->nrverts = verts.size()/4;
766
cont->rverts = (int*)rcAlloc(sizeof(int)*cont->nrverts*4, RC_ALLOC_PERM);
769
ctx->log(RC_LOG_ERROR, "rcBuildContours: Out of memory 'rverts' (%d).", cont->nrverts);
772
memcpy(cont->rverts, &verts[0], sizeof(int)*cont->nrverts*4);
775
// If the heightfield was build with bordersize, remove the offset.
776
for (int i = 0; i < cont->nrverts; ++i)
778
int* v = &cont->rverts[i*4];
784
/* cont->cx = cont->cy = cont->cz = 0;
785
for (int i = 0; i < cont->nverts; ++i)
787
cont->cx += cont->verts[i*4+0];
788
cont->cy += cont->verts[i*4+1];
789
cont->cz += cont->verts[i*4+2];
791
cont->cx /= cont->nverts;
792
cont->cy /= cont->nverts;
793
cont->cz /= cont->nverts;*/
802
// Check and merge droppings.
803
// Sometimes the previous algorithms can fail and create several contours
804
// per area. This pass will try to merge the holes into the main region.
805
for (int i = 0; i < cset.nconts; ++i)
807
rcContour& cont = cset.conts[i];
808
// Check if the contour is would backwards.
809
if (calcAreaOfPolygon2D(cont.verts, cont.nverts) < 0)
811
// Find another contour which has the same region ID.
813
for (int j = 0; j < cset.nconts; ++j)
815
if (i == j) continue;
816
if (cset.conts[j].nverts && cset.conts[j].reg == cont.reg)
818
// Make sure the polygon is correctly oriented.
819
if (calcAreaOfPolygon2D(cset.conts[j].verts, cset.conts[j].nverts))
828
ctx->log(RC_LOG_WARNING, "rcBuildContours: Could not find merge target for bad contour %d.", i);
832
rcContour& mcont = cset.conts[mergeIdx];
833
// Merge by closest points.
835
getClosestIndices(mcont.verts, mcont.nverts, cont.verts, cont.nverts, ia, ib);
836
if (ia == -1 || ib == -1)
838
ctx->log(RC_LOG_WARNING, "rcBuildContours: Failed to find merge points for %d and %d.", i, mergeIdx);
841
if (!mergeContours(mcont, cont, ia, ib))
843
ctx->log(RC_LOG_WARNING, "rcBuildContours: Failed to merge contours %d and %d.", i, mergeIdx);
850
ctx->stopTimer(RC_TIMER_BUILD_CONTOURS);