Debian Codegraph @

DetourTileCache/Source/DetourTileCacheBuilder.cpp

raw symbols SCIP
1 //
2 // Copyright (c) 2009-2010 Mikko Mononen [email protected]
3 //
4 // This software is provided 'as-is', without any express or implied
5 // warranty. In no event will the authors be held liable for any damages
6 // arising from the use of this software.
7 // Permission is granted to anyone to use this software for any purpose,
8 // including commercial applications, and to alter it and redistribute it
9 // freely, subject to the following restrictions:
10 // 1. The origin of this software must not be misrepresented; you must not
11 // claim that you wrote the original software. If you use this software
12 // in a product, an acknowledgment in the product documentation would be
13 // appreciated but is not required.
14 // 2. Altered source versions must be plainly marked as such, and must not be
15 // misrepresented as being the original software.
16 // 3. This notice may not be removed or altered from any source distribution.
17 //
18
19 #include "DetourCommon.h"
20 #include "DetourMath.h"
21 #include "DetourStatus.h"
22 #include "DetourAssert.h"
23 #include "DetourTileCacheBuilder.h"
24 #include <string.h>
25
26 dtTileCacheAlloc::~dtTileCacheAlloc()
27 {
28 // Defined out of line to fix the weak v-tables warning
29 }
30
31 dtTileCacheCompressor::~dtTileCacheCompressor()
32 {
33 // Defined out of line to fix the weak v-tables warning
34 }
35
36 template<class T> class dtFixedArray
37 {
38 dtTileCacheAlloc* m_alloc;
39 T* m_ptr;
40 const int m_size;
41 inline void operator=(dtFixedArray<T>& p);
42 public:
43 inline dtFixedArray(dtTileCacheAlloc* a, const int s) : m_alloc(a), m_ptr((T*)a->alloc(sizeof(T)*s)), m_size(s) {}
44 inline ~dtFixedArray() { if (m_alloc) m_alloc->free(m_ptr); }
45 inline operator T*() { return m_ptr; }
46 inline int size() const { return m_size; }
47 };
48
49 inline int getDirOffsetX(int dir)
50 {
51 const int offset[4] = { -1, 0, 1, 0, };
52 return offset[dir&0x03];
53 }
54
55 inline int getDirOffsetY(int dir)
56 {
57 const int offset[4] = { 0, 1, 0, -1 };
58 return offset[dir&0x03];
59 }
60
61 static const int MAX_VERTS_PER_POLY = 6; // TODO: use the DT_VERTS_PER_POLYGON
62 static const int MAX_REM_EDGES = 48; // TODO: make this an expression.
63
64
65
66 dtTileCacheContourSet* dtAllocTileCacheContourSet(dtTileCacheAlloc* alloc)
67 {
68 dtAssert(alloc);
69
70 dtTileCacheContourSet* cset = (dtTileCacheContourSet*)alloc->alloc(sizeof(dtTileCacheContourSet));
71 memset(cset, 0, sizeof(dtTileCacheContourSet));
72 return cset;
73 }
74
75 void dtFreeTileCacheContourSet(dtTileCacheAlloc* alloc, dtTileCacheContourSet* cset)
76 {
77 dtAssert(alloc);
78
79 if (!cset) return;
80 for (int i = 0; i < cset->nconts; ++i)
81 alloc->free(cset->conts[i].verts);
82 alloc->free(cset->conts);
83 alloc->free(cset);
84 }
85
86 dtTileCachePolyMesh* dtAllocTileCachePolyMesh(dtTileCacheAlloc* alloc)
87 {
88 dtAssert(alloc);
89
90 dtTileCachePolyMesh* lmesh = (dtTileCachePolyMesh*)alloc->alloc(sizeof(dtTileCachePolyMesh));
91 memset(lmesh, 0, sizeof(dtTileCachePolyMesh));
92 return lmesh;
93 }
94
95 void dtFreeTileCachePolyMesh(dtTileCacheAlloc* alloc, dtTileCachePolyMesh* lmesh)
96 {
97 dtAssert(alloc);
98
99 if (!lmesh) return;
100 alloc->free(lmesh->verts);
101 alloc->free(lmesh->polys);
102 alloc->free(lmesh->flags);
103 alloc->free(lmesh->areas);
104 alloc->free(lmesh);
105 }
106
107
108
109 struct dtLayerSweepSpan
110 {
111 unsigned short ns; // number samples
112 unsigned char id; // region id
113 unsigned char nei; // neighbour id
114 };
115
116 static const int DT_LAYER_MAX_NEIS = 16;
117
118 struct dtLayerMonotoneRegion
119 {
120 int area;
121 unsigned char neis[DT_LAYER_MAX_NEIS];
122 unsigned char nneis;
123 unsigned char regId;
124 unsigned char areaId;
125 };
126
127 struct dtTempContour
128 {
129 inline dtTempContour(unsigned char* vbuf, const int nvbuf,
130 unsigned short* pbuf, const int npbuf) :
131 verts(vbuf), nverts(0), cverts(nvbuf),
132 poly(pbuf), npoly(0), cpoly(npbuf)
133 {
134 }
135 unsigned char* verts;
136 int nverts;
137 int cverts;
138 unsigned short* poly;
139 int npoly;
140 int cpoly;
141 };
142
143
144
145
146 inline bool overlapRangeExl(const unsigned short amin, const unsigned short amax,
147 const unsigned short bmin, const unsigned short bmax)
148 {
149 return (amin >= bmax || amax <= bmin) ? false : true;
150 }
151
152 static void addUniqueLast(unsigned char* a, unsigned char& an, unsigned char v)
153 {
154 const int n = (int)an;
155 if (n > 0 && a[n-1] == v) return;
156 a[an] = v;
157 an++;
158 }
159
160 inline bool isConnected(const dtTileCacheLayer& layer,
161 const int ia, const int ib, const int walkableClimb)
162 {
163 if (layer.areas[ia] != layer.areas[ib]) return false;
164 if (dtAbs((int)layer.heights[ia] - (int)layer.heights[ib]) > walkableClimb) return false;
165 return true;
166 }
167
168 static bool canMerge(unsigned char oldRegId, unsigned char newRegId, const dtLayerMonotoneRegion* regs, const int nregs)
169 {
170 int count = 0;
171 for (int i = 0; i < nregs; ++i)
172 {
173 const dtLayerMonotoneRegion& reg = regs[i];
174 if (reg.regId != oldRegId) continue;
175 const int nnei = (int)reg.nneis;
176 for (int j = 0; j < nnei; ++j)
177 {
178 if (regs[reg.neis[j]].regId == newRegId)
179 count++;
180 }
181 }
182 return count == 1;
183 }
184
185
186 dtStatus dtBuildTileCacheRegions(dtTileCacheAlloc* alloc,
187 dtTileCacheLayer& layer,
188 const int walkableClimb)
189 {
190 dtAssert(alloc);
191
192 const int w = (int)layer.header->width;
193 const int h = (int)layer.header->height;
194
195 memset(layer.regs,0xff,sizeof(unsigned char)*w*h);
196
197 const int nsweeps = w;
198 dtFixedArray<dtLayerSweepSpan> sweeps(alloc, nsweeps);
199 if (!sweeps)
200 return DT_FAILURE | DT_OUT_OF_MEMORY;
201 memset(sweeps,0,sizeof(dtLayerSweepSpan)*nsweeps);
202
203 // Partition walkable area into monotone regions.
204 unsigned char prevCount[256];
205 unsigned char regId = 0;
206
207 for (int y = 0; y < h; ++y)
208 {
209 if (regId > 0)
210 memset(prevCount,0,sizeof(unsigned char)*regId);
211 unsigned char sweepId = 0;
212
213 for (int x = 0; x < w; ++x)
214 {
215 const int idx = x + y*w;
216 if (layer.areas[idx] == DT_TILECACHE_NULL_AREA) continue;
217
218 unsigned char sid = 0xff;
219
220 // -x
221 const int xidx = (x-1)+y*w;
222 if (x > 0 && isConnected(layer, idx, xidx, walkableClimb))
223 {
224 if (layer.regs[xidx] != 0xff)
225 sid = layer.regs[xidx];
226 }
227
228 if (sid == 0xff)
229 {
230 sid = sweepId++;
231 sweeps[sid].nei = 0xff;
232 sweeps[sid].ns = 0;
233 }
234
235 // -y
236 const int yidx = x+(y-1)*w;
237 if (y > 0 && isConnected(layer, idx, yidx, walkableClimb))
238 {
239 const unsigned char nr = layer.regs[yidx];
240 if (nr != 0xff)
241 {
242 // Set neighbour when first valid neighbour is encoutered.
243 if (sweeps[sid].ns == 0)
244 sweeps[sid].nei = nr;
245
246 if (sweeps[sid].nei == nr)
247 {
248 // Update existing neighbour
249 sweeps[sid].ns++;
250 prevCount[nr]++;
251 }
252 else
253 {
254 // This is hit if there is nore than one neighbour.
255 // Invalidate the neighbour.
256 sweeps[sid].nei = 0xff;
257 }
258 }
259 }
260
261 layer.regs[idx] = sid;
262 }
263
264 // Create unique ID.
265 for (int i = 0; i < sweepId; ++i)
266 {
267 // If the neighbour is set and there is only one continuous connection to it,
268 // the sweep will be merged with the previous one, else new region is created.
269 if (sweeps[i].nei != 0xff && (unsigned short)prevCount[sweeps[i].nei] == sweeps[i].ns)
270 {
271 sweeps[i].id = sweeps[i].nei;
272 }
273 else
274 {
275 if (regId == 255)
276 {
277 // Region ID's overflow.
278 return DT_FAILURE | DT_BUFFER_TOO_SMALL;
279 }
280 sweeps[i].id = regId++;
281 }
282 }
283
284 // Remap local sweep ids to region ids.
285 for (int x = 0; x < w; ++x)
286 {
287 const int idx = x+y*w;
288 if (layer.regs[idx] != 0xff)
289 layer.regs[idx] = sweeps[layer.regs[idx]].id;
290 }
291 }
292
293 // Allocate and init layer regions.
294 const int nregs = (int)regId;
295 dtFixedArray<dtLayerMonotoneRegion> regs(alloc, nregs);
296 if (!regs)
297 return DT_FAILURE | DT_OUT_OF_MEMORY;
298
299 memset(regs, 0, sizeof(dtLayerMonotoneRegion)*nregs);
300 for (int i = 0; i < nregs; ++i)
301 regs[i].regId = 0xff;
302
303 // Find region neighbours.
304 for (int y = 0; y < h; ++y)
305 {
306 for (int x = 0; x < w; ++x)
307 {
308 const int idx = x+y*w;
309 const unsigned char ri = layer.regs[idx];
310 if (ri == 0xff)
311 continue;
312
313 // Update area.
314 regs[ri].area++;
315 regs[ri].areaId = layer.areas[idx];
316
317 // Update neighbours
318 const int ymi = x+(y-1)*w;
319 if (y > 0 && isConnected(layer, idx, ymi, walkableClimb))
320 {
321 const unsigned char rai = layer.regs[ymi];
322 if (rai != 0xff && rai != ri)
323 {
324 addUniqueLast(regs[ri].neis, regs[ri].nneis, rai);
325 addUniqueLast(regs[rai].neis, regs[rai].nneis, ri);
326 }
327 }
328 }
329 }
330
331 for (int i = 0; i < nregs; ++i)
332 regs[i].regId = (unsigned char)i;
333
334 for (int i = 0; i < nregs; ++i)
335 {
336 dtLayerMonotoneRegion& reg = regs[i];
337
338 int merge = -1;
339 int mergea = 0;
340 for (int j = 0; j < (int)reg.nneis; ++j)
341 {
342 const unsigned char nei = reg.neis[j];
343 dtLayerMonotoneRegion& regn = regs[nei];
344 if (reg.regId == regn.regId)
345 continue;
346 if (reg.areaId != regn.areaId)
347 continue;
348 if (regn.area > mergea)
349 {
350 if (canMerge(reg.regId, regn.regId, regs, nregs))
351 {
352 mergea = regn.area;
353 merge = (int)nei;
354 }
355 }
356 }
357 if (merge != -1)
358 {
359 const unsigned char oldId = reg.regId;
360 const unsigned char newId = regs[merge].regId;
361 for (int j = 0; j < nregs; ++j)
362 if (regs[j].regId == oldId)
363 regs[j].regId = newId;
364 }
365 }
366
367 // Compact ids.
368 unsigned char remap[256];
369 memset(remap, 0, 256);
370 // Find number of unique regions.
371 regId = 0;
372 for (int i = 0; i < nregs; ++i)
373 remap[regs[i].regId] = 1;
374 for (int i = 0; i < 256; ++i)
375 if (remap[i])
376 remap[i] = regId++;
377 // Remap ids.
378 for (int i = 0; i < nregs; ++i)
379 regs[i].regId = remap[regs[i].regId];
380
381 layer.regCount = regId;
382
383 for (int i = 0; i < w*h; ++i)
384 {
385 if (layer.regs[i] != 0xff)
386 layer.regs[i] = regs[layer.regs[i]].regId;
387 }
388
389 return DT_SUCCESS;
390 }
391
392
393
394 static bool appendVertex(dtTempContour& cont, const int x, const int y, const int z, const int r)
395 {
396 // Try to merge with existing segments.
397 if (cont.nverts > 1)
398 {
399 unsigned char* pa = &cont.verts[(cont.nverts-2)*4];
400 unsigned char* pb = &cont.verts[(cont.nverts-1)*4];
401 if ((int)pb[3] == r)
402 {
403 if (pa[0] == pb[0] && (int)pb[0] == x)
404 {
405 // The verts are aligned aling x-axis, update z.
406 pb[1] = (unsigned char)y;
407 pb[2] = (unsigned char)z;
408 return true;
409 }
410 else if (pa[2] == pb[2] && (int)pb[2] == z)
411 {
412 // The verts are aligned aling z-axis, update x.
413 pb[0] = (unsigned char)x;
414 pb[1] = (unsigned char)y;
415 return true;
416 }
417 }
418 }
419
420 // Add new point.
421 if (cont.nverts+1 > cont.cverts)
422 return false;
423
424 unsigned char* v = &cont.verts[cont.nverts*4];
425 v[0] = (unsigned char)x;
426 v[1] = (unsigned char)y;
427 v[2] = (unsigned char)z;
428 v[3] = (unsigned char)r;
429 cont.nverts++;
430
431 return true;
432 }
433
434
435 static unsigned char getNeighbourReg(dtTileCacheLayer& layer,
436 const int ax, const int ay, const int dir)
437 {
438 const int w = (int)layer.header->width;
439 const int ia = ax + ay*w;
440
441 const unsigned char con = layer.cons[ia] & 0xf;
442 const unsigned char portal = layer.cons[ia] >> 4;
443 const unsigned char mask = (unsigned char)(1<<dir);
444
445 if ((con & mask) == 0)
446 {
447 // No connection, return portal or hard edge.
448 if (portal & mask)
449 return 0xf8 + (unsigned char)dir;
450 return 0xff;
451 }
452
453 const int bx = ax + getDirOffsetX(dir);
454 const int by = ay + getDirOffsetY(dir);
455 const int ib = bx + by*w;
456
457 return layer.regs[ib];
458 }
459
460 static bool walkContour(dtTileCacheLayer& layer, int x, int y, dtTempContour& cont)
461 {
462 const int w = (int)layer.header->width;
463 const int h = (int)layer.header->height;
464
465 cont.nverts = 0;
466
467 int startX = x;
468 int startY = y;
469 int startDir = -1;
470
471 for (int i = 0; i < 4; ++i)
472 {
473 const int dir = (i+3)&3;
474 unsigned char rn = getNeighbourReg(layer, x, y, dir);
475 if (rn != layer.regs[x+y*w])
476 {
477 startDir = dir;
478 break;
479 }
480 }
481 if (startDir == -1)
482 return true;
483
484 int dir = startDir;
485 const int maxIter = w*h;
486
487 int iter = 0;
488 while (iter < maxIter)
489 {
490 unsigned char rn = getNeighbourReg(layer, x, y, dir);
491
492 int nx = x;
493 int ny = y;
494 int ndir = dir;
495
496 if (rn != layer.regs[x+y*w])
497 {
498 // Solid edge.
499 int px = x;
500 int pz = y;
501 switch(dir)
502 {
503 case 0: pz++; break;
504 case 1: px++; pz++; break;
505 case 2: px++; break;
506 }
507
508 // Try to merge with previous vertex.
509 if (!appendVertex(cont, px, (int)layer.heights[x+y*w], pz,rn))
510 return false;
511
512 ndir = (dir+1) & 0x3; // Rotate CW
513 }
514 else
515 {
516 // Move to next.
517 nx = x + getDirOffsetX(dir);
518 ny = y + getDirOffsetY(dir);
519 ndir = (dir+3) & 0x3; // Rotate CCW
520 }
521
522 if (iter > 0 && x == startX && y == startY && dir == startDir)
523 break;
524
525 x = nx;
526 y = ny;
527 dir = ndir;
528
529 iter++;
530 }
531
532 // Remove last vertex if it is duplicate of the first one.
533 unsigned char* pa = &cont.verts[(cont.nverts-1)*4];
534 unsigned char* pb = &cont.verts[0];
535 if (pa[0] == pb[0] && pa[2] == pb[2])
536 cont.nverts--;
537
538 return true;
539 }
540
541
542 static float distancePtSeg(const int x, const int z,
543 const int px, const int pz,
544 const int qx, const int qz)
545 {
546 float pqx = (float)(qx - px);
547 float pqz = (float)(qz - pz);
548 float dx = (float)(x - px);
549 float dz = (float)(z - pz);
550 float d = pqx*pqx + pqz*pqz;
551 float t = pqx*dx + pqz*dz;
552 if (d > 0)
553 t /= d;
554 if (t < 0)
555 t = 0;
556 else if (t > 1)
557 t = 1;
558
559 dx = px + t*pqx - x;
560 dz = pz + t*pqz - z;
561
562 return dx*dx + dz*dz;
563 }
564
565 static void simplifyContour(dtTempContour& cont, const float maxError)
566 {
567 cont.npoly = 0;
568
569 for (int i = 0; i < cont.nverts; ++i)
570 {
571 int j = (i+1) % cont.nverts;
572 // Check for start of a wall segment.
573 unsigned char ra = cont.verts[j*4+3];
574 unsigned char rb = cont.verts[i*4+3];
575 if (ra != rb)
576 cont.poly[cont.npoly++] = (unsigned short)i;
577 }
578 if (cont.npoly < 2)
579 {
580 // If there is no transitions at all,
581 // create some initial points for the simplification process.
582 // Find lower-left and upper-right vertices of the contour.
583 int llx = cont.verts[0];
584 int llz = cont.verts[2];
585 int lli = 0;
586 int urx = cont.verts[0];
587 int urz = cont.verts[2];
588 int uri = 0;
589 for (int i = 1; i < cont.nverts; ++i)
590 {
591 int x = cont.verts[i*4+0];
592 int z = cont.verts[i*4+2];
593 if (x < llx || (x == llx && z < llz))
594 {
595 llx = x;
596 llz = z;
597 lli = i;
598 }
599 if (x > urx || (x == urx && z > urz))
600 {
601 urx = x;
602 urz = z;
603 uri = i;
604 }
605 }
606 cont.npoly = 0;
607 cont.poly[cont.npoly++] = (unsigned short)lli;
608 cont.poly[cont.npoly++] = (unsigned short)uri;
609 }
610
611 // Add points until all raw points are within
612 // error tolerance to the simplified shape.
613 for (int i = 0; i < cont.npoly; )
614 {
615 int ii = (i+1) % cont.npoly;
616
617 const int ai = (int)cont.poly[i];
618 const int ax = (int)cont.verts[ai*4+0];
619 const int az = (int)cont.verts[ai*4+2];
620
621 const int bi = (int)cont.poly[ii];
622 const int bx = (int)cont.verts[bi*4+0];
623 const int bz = (int)cont.verts[bi*4+2];
624
625 // Find maximum deviation from the segment.
626 float maxd = 0;
627 int maxi = -1;
628 int ci, cinc, endi;
629
630 // Traverse the segment in lexilogical order so that the
631 // max deviation is calculated similarly when traversing
632 // opposite segments.
633 if (bx > ax || (bx == ax && bz > az))
634 {
635 cinc = 1;
636 ci = (ai+cinc) % cont.nverts;
637 endi = bi;
638 }
639 else
640 {
641 cinc = cont.nverts-1;
642 ci = (bi+cinc) % cont.nverts;
643 endi = ai;
644 }
645
646 // Tessellate only outer edges or edges between areas.
647 while (ci != endi)
648 {
649 float d = distancePtSeg(cont.verts[ci*4+0], cont.verts[ci*4+2], ax, az, bx, bz);
650 if (d > maxd)
651 {
652 maxd = d;
653 maxi = ci;
654 }
655 ci = (ci+cinc) % cont.nverts;
656 }
657
658
659 // If the max deviation is larger than accepted error,
660 // add new point, else continue to next segment.
661 if (maxi != -1 && maxd > (maxError*maxError))
662 {
663 cont.npoly++;
664 for (int j = cont.npoly-1; j > i; --j)
665 cont.poly[j] = cont.poly[j-1];
666 cont.poly[i+1] = (unsigned short)maxi;
667 }
668 else
669 {
670 ++i;
671 }
672 }
673
674 // Remap vertices
675 int start = 0;
676 for (int i = 1; i < cont.npoly; ++i)
677 if (cont.poly[i] < cont.poly[start])
678 start = i;
679
680 cont.nverts = 0;
681 for (int i = 0; i < cont.npoly; ++i)
682 {
683 const int j = (start+i) % cont.npoly;
684 unsigned char* src = &cont.verts[cont.poly[j]*4];
685 unsigned char* dst = &cont.verts[cont.nverts*4];
686 dst[0] = src[0];
687 dst[1] = src[1];
688 dst[2] = src[2];
689 dst[3] = src[3];
690 cont.nverts++;
691 }
692 }
693
694 static unsigned char getCornerHeight(dtTileCacheLayer& layer,
695 const int x, const int y, const int z,
696 const int walkableClimb,
697 bool& shouldRemove)
698 {
699 const int w = (int)layer.header->width;
700 const int h = (int)layer.header->height;
701
702 int n = 0;
703
704 unsigned char portal = 0xf;
705 unsigned char height = 0;
706 unsigned char preg = 0xff;
707 bool allSameReg = true;
708
709 for (int dz = -1; dz <= 0; ++dz)
710 {
711 for (int dx = -1; dx <= 0; ++dx)
712 {
713 const int px = x+dx;
714 const int pz = z+dz;
715 if (px >= 0 && pz >= 0 && px < w && pz < h)
716 {
717 const int idx = px + pz*w;
718 const int lh = (int)layer.heights[idx];
719 if (dtAbs(lh-y) <= walkableClimb && layer.areas[idx] != DT_TILECACHE_NULL_AREA)
720 {
721 height = dtMax(height, (unsigned char)lh);
722 portal &= (layer.cons[idx] >> 4);
723 if (preg != 0xff && preg != layer.regs[idx])
724 allSameReg = false;
725 preg = layer.regs[idx];
726 n++;
727 }
728 }
729 }
730 }
731
732 int portalCount = 0;
733 for (int dir = 0; dir < 4; ++dir)
734 if (portal & (1<<dir))
735 portalCount++;
736
737 shouldRemove = false;
738 if (n > 1 && portalCount == 1 && allSameReg)
739 {
740 shouldRemove = true;
741 }
742
743 return height;
744 }
745
746
747 // TODO: move this somewhere else, once the layer meshing is done.
748 dtStatus dtBuildTileCacheContours(dtTileCacheAlloc* alloc,
749 dtTileCacheLayer& layer,
750 const int walkableClimb, const float maxError,
751 dtTileCacheContourSet& lcset)
752 {
753 dtAssert(alloc);
754
755 const int w = (int)layer.header->width;
756 const int h = (int)layer.header->height;
757
758 lcset.nconts = layer.regCount;
759 lcset.conts = (dtTileCacheContour*)alloc->alloc(sizeof(dtTileCacheContour)*lcset.nconts);
760 if (!lcset.conts)
761 return DT_FAILURE | DT_OUT_OF_MEMORY;
762 memset(lcset.conts, 0, sizeof(dtTileCacheContour)*lcset.nconts);
763
764 // Allocate temp buffer for contour tracing.
765 const int maxTempVerts = (w+h)*2 * 2; // Twice around the layer.
766
767 dtFixedArray<unsigned char> tempVerts(alloc, maxTempVerts*4);
768 if (!tempVerts)
769 return DT_FAILURE | DT_OUT_OF_MEMORY;
770
771 dtFixedArray<unsigned short> tempPoly(alloc, maxTempVerts);
772 if (!tempPoly)
773 return DT_FAILURE | DT_OUT_OF_MEMORY;
774
775 dtTempContour temp(tempVerts, maxTempVerts, tempPoly, maxTempVerts);
776
777 // Find contours.
778 for (int y = 0; y < h; ++y)
779 {
780 for (int x = 0; x < w; ++x)
781 {
782 const int idx = x+y*w;
783 const unsigned char ri = layer.regs[idx];
784 if (ri == 0xff)
785 continue;
786
787 dtTileCacheContour& cont = lcset.conts[ri];
788
789 if (cont.nverts > 0)
790 continue;
791
792 cont.reg = ri;
793 cont.area = layer.areas[idx];
794
795 if (!walkContour(layer, x, y, temp))
796 {
797 // Too complex contour.
798 // Note: If you hit here ofte, try increasing 'maxTempVerts'.
799 return DT_FAILURE | DT_BUFFER_TOO_SMALL;
800 }
801
802 simplifyContour(temp, maxError);
803
804 // Store contour.
805 cont.nverts = temp.nverts;
806 if (cont.nverts > 0)
807 {
808 cont.verts = (unsigned char*)alloc->alloc(sizeof(unsigned char)*4*temp.nverts);
809 if (!cont.verts)
810 return DT_FAILURE | DT_OUT_OF_MEMORY;
811
812 for (int i = 0, j = temp.nverts-1; i < temp.nverts; j=i++)
813 {
814 unsigned char* dst = &cont.verts[j*4];
815 unsigned char* v = &temp.verts[j*4];
816 unsigned char* vn = &temp.verts[i*4];
817 unsigned char nei = vn[3]; // The neighbour reg is stored at segment vertex of a segment.
818 bool shouldRemove = false;
819 unsigned char lh = getCornerHeight(layer, (int)v[0], (int)v[1], (int)v[2],
820 walkableClimb, shouldRemove);
821
822 dst[0] = v[0];
823 dst[1] = lh;
824 dst[2] = v[2];
825
826 // Store portal direction and remove status to the fourth component.
827 dst[3] = 0x0f;
828 if (nei != 0xff && nei >= 0xf8)
829 dst[3] = nei - 0xf8;
830 if (shouldRemove)
831 dst[3] |= 0x80;
832 }
833 }
834 }
835 }
836
837 return DT_SUCCESS;
838 }
839
840
841
842 static const int VERTEX_BUCKET_COUNT2 = (1<<8);
843
844 inline int computeVertexHash2(int x, int y, int z)
845 {
846 const unsigned int h1 = 0x8da6b343; // Large multiplicative constants;
847 const unsigned int h2 = 0xd8163841; // here arbitrarily chosen primes
848 const unsigned int h3 = 0xcb1ab31f;
849 unsigned int n = h1 * x + h2 * y + h3 * z;
850 return (int)(n & (VERTEX_BUCKET_COUNT2-1));
851 }
852
853 static unsigned short addVertex(unsigned short x, unsigned short y, unsigned short z,
854 unsigned short* verts, unsigned short* firstVert, unsigned short* nextVert, int& nv)
855 {
856 int bucket = computeVertexHash2(x, 0, z);
857 unsigned short i = firstVert[bucket];
858
859 while (i != DT_TILECACHE_NULL_IDX)
860 {
861 const unsigned short* v = &verts[i*3];
862 if (v[0] == x && v[2] == z && (dtAbs(v[1] - y) <= 2))
863 return i;
864 i = nextVert[i]; // next
865 }
866
867 // Could not find, create new.
868 i = (unsigned short)nv; nv++;
869 unsigned short* v = &verts[i*3];
870 v[0] = x;
871 v[1] = y;
872 v[2] = z;
873 nextVert[i] = firstVert[bucket];
874 firstVert[bucket] = i;
875
876 return (unsigned short)i;
877 }
878
879
880 struct rcEdge
881 {
882 unsigned short vert[2];
883 unsigned short polyEdge[2];
884 unsigned short poly[2];
885 };
886
887 static bool buildMeshAdjacency(dtTileCacheAlloc* alloc,
888 unsigned short* polys, const int npolys,
889 const unsigned short* verts, const int nverts,
890 const dtTileCacheContourSet& lcset)
891 {
892 // Based on code by Eric Lengyel from:
893 // https://web.archive.org/web/20080704083314/http://www.terathon.com/code/edges.php
894
895 const int maxEdgeCount = npolys*MAX_VERTS_PER_POLY;
896 dtFixedArray<unsigned short> firstEdge(alloc, nverts + maxEdgeCount);
897 if (!firstEdge)
898 return false;
899 unsigned short* nextEdge = firstEdge + nverts;
900 int edgeCount = 0;
901
902 dtFixedArray<rcEdge> edges(alloc, maxEdgeCount);
903 if (!edges)
904 return false;
905
906 for (int i = 0; i < nverts; i++)
907 firstEdge[i] = DT_TILECACHE_NULL_IDX;
908
909 for (int i = 0; i < npolys; ++i)
910 {
911 unsigned short* t = &polys[i*MAX_VERTS_PER_POLY*2];
912 for (int j = 0; j < MAX_VERTS_PER_POLY; ++j)
913 {
914 if (t[j] == DT_TILECACHE_NULL_IDX) break;
915 unsigned short v0 = t[j];
916 unsigned short v1 = (j+1 >= MAX_VERTS_PER_POLY || t[j+1] == DT_TILECACHE_NULL_IDX) ? t[0] : t[j+1];
917 if (v0 < v1)
918 {
919 rcEdge& edge = edges[edgeCount];
920 edge.vert[0] = v0;
921 edge.vert[1] = v1;
922 edge.poly[0] = (unsigned short)i;
923 edge.polyEdge[0] = (unsigned short)j;
924 edge.poly[1] = (unsigned short)i;
925 edge.polyEdge[1] = 0xff;
926 // Insert edge
927 nextEdge[edgeCount] = firstEdge[v0];
928 firstEdge[v0] = (unsigned short)edgeCount;
929 edgeCount++;
930 }
931 }
932 }
933
934 for (int i = 0; i < npolys; ++i)
935 {
936 unsigned short* t = &polys[i*MAX_VERTS_PER_POLY*2];
937 for (int j = 0; j < MAX_VERTS_PER_POLY; ++j)
938 {
939 if (t[j] == DT_TILECACHE_NULL_IDX) break;
940 unsigned short v0 = t[j];
941 unsigned short v1 = (j+1 >= MAX_VERTS_PER_POLY || t[j+1] == DT_TILECACHE_NULL_IDX) ? t[0] : t[j+1];
942 if (v0 > v1)
943 {
944 bool found = false;
945 for (unsigned short e = firstEdge[v1]; e != DT_TILECACHE_NULL_IDX; e = nextEdge[e])
946 {
947 rcEdge& edge = edges[e];
948 if (edge.vert[1] == v0 && edge.poly[0] == edge.poly[1])
949 {
950 edge.poly[1] = (unsigned short)i;
951 edge.polyEdge[1] = (unsigned short)j;
952 found = true;
953 break;
954 }
955 }
956 if (!found)
957 {
958 // Matching edge not found, it is an open edge, add it.
959 rcEdge& edge = edges[edgeCount];
960 edge.vert[0] = v1;
961 edge.vert[1] = v0;
962 edge.poly[0] = (unsigned short)i;
963 edge.polyEdge[0] = (unsigned short)j;
964 edge.poly[1] = (unsigned short)i;
965 edge.polyEdge[1] = 0xff;
966 // Insert edge
967 nextEdge[edgeCount] = firstEdge[v1];
968 firstEdge[v1] = (unsigned short)edgeCount;
969 edgeCount++;
970 }
971 }
972 }
973 }
974
975 // Mark portal edges.
976 for (int i = 0; i < lcset.nconts; ++i)
977 {
978 dtTileCacheContour& cont = lcset.conts[i];
979 if (cont.nverts < 3)
980 continue;
981
982 for (int j = 0, k = cont.nverts-1; j < cont.nverts; k=j++)
983 {
984 const unsigned char* va = &cont.verts[k*4];
985 const unsigned char* vb = &cont.verts[j*4];
986 const unsigned char dir = va[3] & 0xf;
987 if (dir == 0xf)
988 continue;
989
990 if (dir == 0 || dir == 2)
991 {
992 // Find matching vertical edge
993 const unsigned short x = (unsigned short)va[0];
994 unsigned short zmin = (unsigned short)va[2];
995 unsigned short zmax = (unsigned short)vb[2];
996 if (zmin > zmax)
997 dtSwap(zmin, zmax);
998
999 for (int m = 0; m < edgeCount; ++m)
1000 {
1001 rcEdge& e = edges[m];
1002 // Skip connected edges.
1003 if (e.poly[0] != e.poly[1])
1004 continue;
1005 const unsigned short* eva = &verts[e.vert[0]*3];
1006 const unsigned short* evb = &verts[e.vert[1]*3];
1007 if (eva[0] == x && evb[0] == x)
1008 {
1009 unsigned short ezmin = eva[2];
1010 unsigned short ezmax = evb[2];
1011 if (ezmin > ezmax)
1012 dtSwap(ezmin, ezmax);
1013 if (overlapRangeExl(zmin,zmax, ezmin, ezmax))
1014 {
1015 // Reuse the other polyedge to store dir.
1016 e.polyEdge[1] = dir;
1017 }
1018 }
1019 }
1020 }
1021 else
1022 {
1023 // Find matching vertical edge
1024 const unsigned short z = (unsigned short)va[2];
1025 unsigned short xmin = (unsigned short)va[0];
1026 unsigned short xmax = (unsigned short)vb[0];
1027 if (xmin > xmax)
1028 dtSwap(xmin, xmax);
1029 for (int m = 0; m < edgeCount; ++m)
1030 {
1031 rcEdge& e = edges[m];
1032 // Skip connected edges.
1033 if (e.poly[0] != e.poly[1])
1034 continue;
1035 const unsigned short* eva = &verts[e.vert[0]*3];
1036 const unsigned short* evb = &verts[e.vert[1]*3];
1037 if (eva[2] == z && evb[2] == z)
1038 {
1039 unsigned short exmin = eva[0];
1040 unsigned short exmax = evb[0];
1041 if (exmin > exmax)
1042 dtSwap(exmin, exmax);
1043 if (overlapRangeExl(xmin,xmax, exmin, exmax))
1044 {
1045 // Reuse the other polyedge to store dir.
1046 e.polyEdge[1] = dir;
1047 }
1048 }
1049 }
1050 }
1051 }
1052 }
1053
1054
1055 // Store adjacency
1056 for (int i = 0; i < edgeCount; ++i)
1057 {
1058 const rcEdge& e = edges[i];
1059 if (e.poly[0] != e.poly[1])
1060 {
1061 unsigned short* p0 = &polys[e.poly[0]*MAX_VERTS_PER_POLY*2];
1062 unsigned short* p1 = &polys[e.poly[1]*MAX_VERTS_PER_POLY*2];
1063 p0[MAX_VERTS_PER_POLY + e.polyEdge[0]] = e.poly[1];
1064 p1[MAX_VERTS_PER_POLY + e.polyEdge[1]] = e.poly[0];
1065 }
1066 else if (e.polyEdge[1] != 0xff)
1067 {
1068 unsigned short* p0 = &polys[e.poly[0]*MAX_VERTS_PER_POLY*2];
1069 p0[MAX_VERTS_PER_POLY + e.polyEdge[0]] = 0x8000 | (unsigned short)e.polyEdge[1];
1070 }
1071
1072 }
1073
1074 return true;
1075 }
1076
1077
1078 // Last time I checked the if version got compiled using cmov, which was a lot faster than module (with idiv).
1079 inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
1080 inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
1081
1082 inline int area2(const unsigned char* a, const unsigned char* b, const unsigned char* c)
1083 {
1084 return ((int)b[0] - (int)a[0]) * ((int)c[2] - (int)a[2]) - ((int)c[0] - (int)a[0]) * ((int)b[2] - (int)a[2]);
1085 }
1086
1087 // Exclusive or: true iff exactly one argument is true.
1088 // The arguments are negated to ensure that they are 0/1
1089 // values. Then the bitwise Xor operator may apply.
1090 // (This idea is due to Michael Baldwin.)
1091 inline bool xorb(bool x, bool y)
1092 {
1093 return !x ^ !y;
1094 }
1095
1096 // Returns true iff c is strictly to the left of the directed
1097 // line through a to b.
1098 inline bool left(const unsigned char* a, const unsigned char* b, const unsigned char* c)
1099 {
1100 return area2(a, b, c) < 0;
1101 }
1102
1103 inline bool leftOn(const unsigned char* a, const unsigned char* b, const unsigned char* c)
1104 {
1105 return area2(a, b, c) <= 0;
1106 }
1107
1108 inline bool collinear(const unsigned char* a, const unsigned char* b, const unsigned char* c)
1109 {
1110 return area2(a, b, c) == 0;
1111 }
1112
1113 // Returns true iff ab properly intersects cd: they share
1114 // a point interior to both segments. The properness of the
1115 // intersection is ensured by using strict leftness.
1116 static bool intersectProp(const unsigned char* a, const unsigned char* b,
1117 const unsigned char* c, const unsigned char* d)
1118 {
1119 // Eliminate improper cases.
1120 if (collinear(a,b,c) || collinear(a,b,d) ||
1121 collinear(c,d,a) || collinear(c,d,b))
1122 return false;
1123
1124 return xorb(left(a,b,c), left(a,b,d)) && xorb(left(c,d,a), left(c,d,b));
1125 }
1126
1127 // Returns T iff (a,b,c) are collinear and point c lies
1128 // on the closed segement ab.
1129 static bool between(const unsigned char* a, const unsigned char* b, const unsigned char* c)
1130 {
1131 if (!collinear(a, b, c))
1132 return false;
1133 // If ab not vertical, check betweenness on x; else on y.
1134 if (a[0] != b[0])
1135 return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0]));
1136 else
1137 return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2]));
1138 }
1139
1140 // Returns true iff segments ab and cd intersect, properly or improperly.
1141 static bool intersect(const unsigned char* a, const unsigned char* b,
1142 const unsigned char* c, const unsigned char* d)
1143 {
1144 if (intersectProp(a, b, c, d))
1145 return true;
1146 else if (between(a, b, c) || between(a, b, d) ||
1147 between(c, d, a) || between(c, d, b))
1148 return true;
1149 else
1150 return false;
1151 }
1152
1153 static bool vequal(const unsigned char* a, const unsigned char* b)
1154 {
1155 return a[0] == b[0] && a[2] == b[2];
1156 }
1157
1158 // Returns T iff (v_i, v_j) is a proper internal *or* external
1159 // diagonal of P, *ignoring edges incident to v_i and v_j*.
1160 static bool diagonalie(int i, int j, int n, const unsigned char* verts, const unsigned short* indices)
1161 {
1162 const unsigned char* d0 = &verts[(indices[i] & 0x7fff) * 4];
1163 const unsigned char* d1 = &verts[(indices[j] & 0x7fff) * 4];
1164
1165 // For each edge (k,k+1) of P
1166 for (int k = 0; k < n; k++)
1167 {
1168 int k1 = next(k, n);
1169 // Skip edges incident to i or j
1170 if (!((k == i) || (k1 == i) || (k == j) || (k1 == j)))
1171 {
1172 const unsigned char* p0 = &verts[(indices[k] & 0x7fff) * 4];
1173 const unsigned char* p1 = &verts[(indices[k1] & 0x7fff) * 4];
1174
1175 if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
1176 continue;
1177
1178 if (intersect(d0, d1, p0, p1))
1179 return false;
1180 }
1181 }
1182 return true;
1183 }
1184
1185 // Returns true iff the diagonal (i,j) is strictly internal to the
1186 // polygon P in the neighborhood of the i endpoint.
1187 static bool inCone(int i, int j, int n, const unsigned char* verts, const unsigned short* indices)
1188 {
1189 const unsigned char* pi = &verts[(indices[i] & 0x7fff) * 4];
1190 const unsigned char* pj = &verts[(indices[j] & 0x7fff) * 4];
1191 const unsigned char* pi1 = &verts[(indices[next(i, n)] & 0x7fff) * 4];
1192 const unsigned char* pin1 = &verts[(indices[prev(i, n)] & 0x7fff) * 4];
1193
1194 // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
1195 if (leftOn(pin1, pi, pi1))
1196 return left(pi, pj, pin1) && left(pj, pi, pi1);
1197 // Assume (i-1,i,i+1) not collinear.
1198 // else P[i] is reflex.
1199 return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
1200 }
1201
1202 // Returns T iff (v_i, v_j) is a proper internal
1203 // diagonal of P.
1204 static bool diagonal(int i, int j, int n, const unsigned char* verts, const unsigned short* indices)
1205 {
1206 return inCone(i, j, n, verts, indices) && diagonalie(i, j, n, verts, indices);
1207 }
1208
1209 static int triangulate(int n, const unsigned char* verts, unsigned short* indices, unsigned short* tris)
1210 {
1211 int ntris = 0;
1212 unsigned short* dst = tris;
1213
1214 // The last bit of the index is used to indicate if the vertex can be removed.
1215 for (int i = 0; i < n; i++)
1216 {
1217 int i1 = next(i, n);
1218 int i2 = next(i1, n);
1219 if (diagonal(i, i2, n, verts, indices))
1220 indices[i1] |= 0x8000;
1221 }
1222
1223 while (n > 3)
1224 {
1225 int minLen = -1;
1226 int mini = -1;
1227 for (int i = 0; i < n; i++)
1228 {
1229 int i1 = next(i, n);
1230 if (indices[i1] & 0x8000)
1231 {
1232 const unsigned char* p0 = &verts[(indices[i] & 0x7fff) * 4];
1233 const unsigned char* p2 = &verts[(indices[next(i1, n)] & 0x7fff) * 4];
1234
1235 const int dx = (int)p2[0] - (int)p0[0];
1236 const int dz = (int)p2[2] - (int)p0[2];
1237 const int len = dx*dx + dz*dz;
1238 if (minLen < 0 || len < minLen)
1239 {
1240 minLen = len;
1241 mini = i;
1242 }
1243 }
1244 }
1245
1246 if (mini == -1)
1247 {
1248 // Should not happen.
1249 /* printf("mini == -1 ntris=%d n=%d\n", ntris, n);
1250 for (int i = 0; i < n; i++)
1251 {
1252 printf("%d ", indices[i] & 0x0fffffff);
1253 }
1254 printf("\n");*/
1255 return -ntris;
1256 }
1257
1258 int i = mini;
1259 int i1 = next(i, n);
1260 int i2 = next(i1, n);
1261
1262 *dst++ = indices[i] & 0x7fff;
1263 *dst++ = indices[i1] & 0x7fff;
1264 *dst++ = indices[i2] & 0x7fff;
1265 ntris++;
1266
1267 // Removes P[i1] by copying P[i+1]...P[n-1] left one index.
1268 n--;
1269 for (int k = i1; k < n; k++)
1270 indices[k] = indices[k+1];
1271
1272 if (i1 >= n) i1 = 0;
1273 i = prev(i1,n);
1274 // Update diagonal flags.
1275 if (diagonal(prev(i, n), i1, n, verts, indices))
1276 indices[i] |= 0x8000;
1277 else
1278 indices[i] &= 0x7fff;
1279
1280 if (diagonal(i, next(i1, n), n, verts, indices))
1281 indices[i1] |= 0x8000;
1282 else
1283 indices[i1] &= 0x7fff;
1284 }
1285
1286 // Append the remaining triangle.
1287 *dst++ = indices[0] & 0x7fff;
1288 *dst++ = indices[1] & 0x7fff;
1289 *dst++ = indices[2] & 0x7fff;
1290 ntris++;
1291
1292 return ntris;
1293 }
1294
1295
1296 static int countPolyVerts(const unsigned short* p)
1297 {
1298 for (int i = 0; i < MAX_VERTS_PER_POLY; ++i)
1299 if (p[i] == DT_TILECACHE_NULL_IDX)
1300 return i;
1301 return MAX_VERTS_PER_POLY;
1302 }
1303
1304 inline bool uleft(const unsigned short* a, const unsigned short* b, const unsigned short* c)
1305 {
1306 return ((int)b[0] - (int)a[0]) * ((int)c[2] - (int)a[2]) -
1307 ((int)c[0] - (int)a[0]) * ((int)b[2] - (int)a[2]) < 0;
1308 }
1309
1310 static int getPolyMergeValue(unsigned short* pa, unsigned short* pb,
1311 const unsigned short* verts, int& ea, int& eb)
1312 {
1313 const int na = countPolyVerts(pa);
1314 const int nb = countPolyVerts(pb);
1315
1316 // If the merged polygon would be too big, do not merge.
1317 if (na+nb-2 > MAX_VERTS_PER_POLY)
1318 return -1;
1319
1320 // Check if the polygons share an edge.
1321 ea = -1;
1322 eb = -1;
1323
1324 for (int i = 0; i < na; ++i)
1325 {
1326 unsigned short va0 = pa[i];
1327 unsigned short va1 = pa[(i+1) % na];
1328 if (va0 > va1)
1329 dtSwap(va0, va1);
1330 for (int j = 0; j < nb; ++j)
1331 {
1332 unsigned short vb0 = pb[j];
1333 unsigned short vb1 = pb[(j+1) % nb];
1334 if (vb0 > vb1)
1335 dtSwap(vb0, vb1);
1336 if (va0 == vb0 && va1 == vb1)
1337 {
1338 ea = i;
1339 eb = j;
1340 break;
1341 }
1342 }
1343 }
1344
1345 // No common edge, cannot merge.
1346 if (ea == -1 || eb == -1)
1347 return -1;
1348
1349 // Check to see if the merged polygon would be convex.
1350 unsigned short va, vb, vc;
1351
1352 va = pa[(ea+na-1) % na];
1353 vb = pa[ea];
1354 vc = pb[(eb+2) % nb];
1355 if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3]))
1356 return -1;
1357
1358 va = pb[(eb+nb-1) % nb];
1359 vb = pb[eb];
1360 vc = pa[(ea+2) % na];
1361 if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3]))
1362 return -1;
1363
1364 va = pa[ea];
1365 vb = pa[(ea+1)%na];
1366
1367 int dx = (int)verts[va*3+0] - (int)verts[vb*3+0];
1368 int dy = (int)verts[va*3+2] - (int)verts[vb*3+2];
1369
1370 return dx*dx + dy*dy;
1371 }
1372
1373 static void mergePolys(unsigned short* pa, unsigned short* pb, int ea, int eb)
1374 {
1375 unsigned short tmp[MAX_VERTS_PER_POLY*2];
1376
1377 const int na = countPolyVerts(pa);
1378 const int nb = countPolyVerts(pb);
1379
1380 // Merge polygons.
1381 memset(tmp, 0xff, sizeof(unsigned short)*MAX_VERTS_PER_POLY*2);
1382 int n = 0;
1383 // Add pa
1384 for (int i = 0; i < na-1; ++i)
1385 tmp[n++] = pa[(ea+1+i) % na];
1386 // Add pb
1387 for (int i = 0; i < nb-1; ++i)
1388 tmp[n++] = pb[(eb+1+i) % nb];
1389
1390 memcpy(pa, tmp, sizeof(unsigned short)*MAX_VERTS_PER_POLY);
1391 }
1392
1393
1394 static void pushFront(unsigned short v, unsigned short* arr, int& an)
1395 {
1396 an++;
1397 for (int i = an-1; i > 0; --i)
1398 arr[i] = arr[i-1];
1399 arr[0] = v;
1400 }
1401
1402 static void pushBack(unsigned short v, unsigned short* arr, int& an)
1403 {
1404 arr[an] = v;
1405 an++;
1406 }
1407
1408 static bool canRemoveVertex(dtTileCachePolyMesh& mesh, const unsigned short rem)
1409 {
1410 // Count number of polygons to remove.
1411 int numTouchedVerts = 0;
1412 int numRemainingEdges = 0;
1413 for (int i = 0; i < mesh.npolys; ++i)
1414 {
1415 unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
1416 const int nv = countPolyVerts(p);
1417 int numRemoved = 0;
1418 int numVerts = 0;
1419 for (int j = 0; j < nv; ++j)
1420 {
1421 if (p[j] == rem)
1422 {
1423 numTouchedVerts++;
1424 numRemoved++;
1425 }
1426 numVerts++;
1427 }
1428 if (numRemoved)
1429 {
1430 numRemainingEdges += numVerts-(numRemoved+1);
1431 }
1432 }
1433
1434 // There would be too few edges remaining to create a polygon.
1435 // This can happen for example when a tip of a triangle is marked
1436 // as deletion, but there are no other polys that share the vertex.
1437 // In this case, the vertex should not be removed.
1438 if (numRemainingEdges <= 2)
1439 return false;
1440
1441 // Check that there is enough memory for the test.
1442 const int maxEdges = numTouchedVerts*2;
1443 if (maxEdges > MAX_REM_EDGES)
1444 return false;
1445
1446 // Find edges which share the removed vertex.
1447 unsigned short edges[MAX_REM_EDGES];
1448 int nedges = 0;
1449
1450 for (int i = 0; i < mesh.npolys; ++i)
1451 {
1452 unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
1453 const int nv = countPolyVerts(p);
1454
1455 // Collect edges which touches the removed vertex.
1456 for (int j = 0, k = nv-1; j < nv; k = j++)
1457 {
1458 if (p[j] == rem || p[k] == rem)
1459 {
1460 // Arrange edge so that a=rem.
1461 int a = p[j], b = p[k];
1462 if (b == rem)
1463 dtSwap(a,b);
1464
1465 // Check if the edge exists
1466 bool exists = false;
1467 for (int m = 0; m < nedges; ++m)
1468 {
1469 unsigned short* e = &edges[m*3];
1470 if (e[1] == b)
1471 {
1472 // Exists, increment vertex share count.
1473 e[2]++;
1474 exists = true;
1475 }
1476 }
1477 // Add new edge.
1478 if (!exists)
1479 {
1480 unsigned short* e = &edges[nedges*3];
1481 e[0] = (unsigned short)a;
1482 e[1] = (unsigned short)b;
1483 e[2] = 1;
1484 nedges++;
1485 }
1486 }
1487 }
1488 }
1489
1490 // There should be no more than 2 open edges.
1491 // This catches the case that two non-adjacent polygons
1492 // share the removed vertex. In that case, do not remove the vertex.
1493 int numOpenEdges = 0;
1494 for (int i = 0; i < nedges; ++i)
1495 {
1496 if (edges[i*3+2] < 2)
1497 numOpenEdges++;
1498 }
1499 if (numOpenEdges > 2)
1500 return false;
1501
1502 return true;
1503 }
1504
1505 static dtStatus removeVertex(dtTileCachePolyMesh& mesh, const unsigned short rem, const int maxTris)
1506 {
1507 // Count number of polygons to remove.
1508 int numRemovedVerts = 0;
1509 for (int i = 0; i < mesh.npolys; ++i)
1510 {
1511 unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
1512 const int nv = countPolyVerts(p);
1513 for (int j = 0; j < nv; ++j)
1514 {
1515 if (p[j] == rem)
1516 numRemovedVerts++;
1517 }
1518 }
1519
1520 int nedges = 0;
1521 unsigned short edges[MAX_REM_EDGES*3];
1522 int nhole = 0;
1523 unsigned short hole[MAX_REM_EDGES];
1524 int nharea = 0;
1525 unsigned short harea[MAX_REM_EDGES];
1526
1527 for (int i = 0; i < mesh.npolys; ++i)
1528 {
1529 unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
1530 const int nv = countPolyVerts(p);
1531 bool hasRem = false;
1532 for (int j = 0; j < nv; ++j)
1533 if (p[j] == rem) hasRem = true;
1534 if (hasRem)
1535 {
1536 // Collect edges which does not touch the removed vertex.
1537 for (int j = 0, k = nv-1; j < nv; k = j++)
1538 {
1539 if (p[j] != rem && p[k] != rem)
1540 {
1541 if (nedges >= MAX_REM_EDGES)
1542 return DT_FAILURE | DT_BUFFER_TOO_SMALL;
1543 unsigned short* e = &edges[nedges*3];
1544 e[0] = p[k];
1545 e[1] = p[j];
1546 e[2] = mesh.areas[i];
1547 nedges++;
1548 }
1549 }
1550 // Remove the polygon.
1551 unsigned short* p2 = &mesh.polys[(mesh.npolys-1)*MAX_VERTS_PER_POLY*2];
1552 memcpy(p,p2,sizeof(unsigned short)*MAX_VERTS_PER_POLY);
1553 memset(p+MAX_VERTS_PER_POLY,0xff,sizeof(unsigned short)*MAX_VERTS_PER_POLY);
1554 mesh.areas[i] = mesh.areas[mesh.npolys-1];
1555 mesh.npolys--;
1556 --i;
1557 }
1558 }
1559
1560 // Remove vertex.
1561 for (int i = (int)rem; i < mesh.nverts - 1; ++i)
1562 {
1563 mesh.verts[i*3+0] = mesh.verts[(i+1)*3+0];
1564 mesh.verts[i*3+1] = mesh.verts[(i+1)*3+1];
1565 mesh.verts[i*3+2] = mesh.verts[(i+1)*3+2];
1566 }
1567 mesh.nverts--;
1568
1569 // Adjust indices to match the removed vertex layout.
1570 for (int i = 0; i < mesh.npolys; ++i)
1571 {
1572 unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
1573 const int nv = countPolyVerts(p);
1574 for (int j = 0; j < nv; ++j)
1575 if (p[j] > rem) p[j]--;
1576 }
1577 for (int i = 0; i < nedges; ++i)
1578 {
1579 if (edges[i*3+0] > rem) edges[i*3+0]--;
1580 if (edges[i*3+1] > rem) edges[i*3+1]--;
1581 }
1582
1583 if (nedges == 0)
1584 return DT_SUCCESS;
1585
1586 // Start with one vertex, keep appending connected
1587 // segments to the start and end of the hole.
1588 pushBack(edges[0], hole, nhole);
1589 pushBack(edges[2], harea, nharea);
1590
1591 while (nedges)
1592 {
1593 bool match = false;
1594
1595 for (int i = 0; i < nedges; ++i)
1596 {
1597 const unsigned short ea = edges[i*3+0];
1598 const unsigned short eb = edges[i*3+1];
1599 const unsigned short a = edges[i*3+2];
1600 bool add = false;
1601 if (hole[0] == eb)
1602 {
1603 // The segment matches the beginning of the hole boundary.
1604 if (nhole >= MAX_REM_EDGES)
1605 return DT_FAILURE | DT_BUFFER_TOO_SMALL;
1606 pushFront(ea, hole, nhole);
1607 pushFront(a, harea, nharea);
1608 add = true;
1609 }
1610 else if (hole[nhole-1] == ea)
1611 {
1612 // The segment matches the end of the hole boundary.
1613 if (nhole >= MAX_REM_EDGES)
1614 return DT_FAILURE | DT_BUFFER_TOO_SMALL;
1615 pushBack(eb, hole, nhole);
1616 pushBack(a, harea, nharea);
1617 add = true;
1618 }
1619 if (add)
1620 {
1621 // The edge segment was added, remove it.
1622 edges[i*3+0] = edges[(nedges-1)*3+0];
1623 edges[i*3+1] = edges[(nedges-1)*3+1];
1624 edges[i*3+2] = edges[(nedges-1)*3+2];
1625 --nedges;
1626 match = true;
1627 --i;
1628 }
1629 }
1630
1631 if (!match)
1632 break;
1633 }
1634
1635
1636 unsigned short tris[MAX_REM_EDGES*3];
1637 unsigned char tverts[MAX_REM_EDGES*3];
1638 unsigned short tpoly[MAX_REM_EDGES*3];
1639
1640 // Generate temp vertex array for triangulation.
1641 for (int i = 0; i < nhole; ++i)
1642 {
1643 const unsigned short pi = hole[i];
1644 tverts[i*4+0] = (unsigned char)mesh.verts[pi*3+0];
1645 tverts[i*4+1] = (unsigned char)mesh.verts[pi*3+1];
1646 tverts[i*4+2] = (unsigned char)mesh.verts[pi*3+2];
1647 tverts[i*4+3] = 0;
1648 tpoly[i] = (unsigned short)i;
1649 }
1650
1651 // Triangulate the hole.
1652 int ntris = triangulate(nhole, tverts, tpoly, tris);
1653 if (ntris < 0)
1654 {
1655 // TODO: issue warning!
1656 ntris = -ntris;
1657 }
1658
1659 if (ntris > MAX_REM_EDGES)
1660 return DT_FAILURE | DT_BUFFER_TOO_SMALL;
1661
1662 unsigned short polys[MAX_REM_EDGES*MAX_VERTS_PER_POLY];
1663 unsigned char pareas[MAX_REM_EDGES];
1664
1665 // Build initial polygons.
1666 int npolys = 0;
1667 memset(polys, 0xff, ntris*MAX_VERTS_PER_POLY*sizeof(unsigned short));
1668 for (int j = 0; j < ntris; ++j)
1669 {
1670 unsigned short* t = &tris[j*3];
1671 if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])
1672 {
1673 polys[npolys*MAX_VERTS_PER_POLY+0] = hole[t[0]];
1674 polys[npolys*MAX_VERTS_PER_POLY+1] = hole[t[1]];
1675 polys[npolys*MAX_VERTS_PER_POLY+2] = hole[t[2]];
1676 pareas[npolys] = (unsigned char)harea[t[0]];
1677 npolys++;
1678 }
1679 }
1680 if (!npolys)
1681 return DT_SUCCESS;
1682
1683 // Merge polygons.
1684 int maxVertsPerPoly = MAX_VERTS_PER_POLY;
1685 if (maxVertsPerPoly > 3)
1686 {
1687 for (;;)
1688 {
1689 // Find best polygons to merge.
1690 int bestMergeVal = 0;
1691 int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0;
1692
1693 for (int j = 0; j < npolys-1; ++j)
1694 {
1695 unsigned short* pj = &polys[j*MAX_VERTS_PER_POLY];
1696 for (int k = j+1; k < npolys; ++k)
1697 {
1698 unsigned short* pk = &polys[k*MAX_VERTS_PER_POLY];
1699 int ea, eb;
1700 int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb);
1701 if (v > bestMergeVal)
1702 {
1703 bestMergeVal = v;
1704 bestPa = j;
1705 bestPb = k;
1706 bestEa = ea;
1707 bestEb = eb;
1708 }
1709 }
1710 }
1711
1712 if (bestMergeVal > 0)
1713 {
1714 // Found best, merge.
1715 unsigned short* pa = &polys[bestPa*MAX_VERTS_PER_POLY];
1716 unsigned short* pb = &polys[bestPb*MAX_VERTS_PER_POLY];
1717 mergePolys(pa, pb, bestEa, bestEb);
1718 memcpy(pb, &polys[(npolys-1)*MAX_VERTS_PER_POLY], sizeof(unsigned short)*MAX_VERTS_PER_POLY);
1719 pareas[bestPb] = pareas[npolys-1];
1720 npolys--;
1721 }
1722 else
1723 {
1724 // Could not merge any polygons, stop.
1725 break;
1726 }
1727 }
1728 }
1729
1730 // Store polygons.
1731 for (int i = 0; i < npolys; ++i)
1732 {
1733 if (mesh.npolys >= maxTris) break;
1734 unsigned short* p = &mesh.polys[mesh.npolys*MAX_VERTS_PER_POLY*2];
1735 memset(p,0xff,sizeof(unsigned short)*MAX_VERTS_PER_POLY*2);
1736 for (int j = 0; j < MAX_VERTS_PER_POLY; ++j)
1737 p[j] = polys[i*MAX_VERTS_PER_POLY+j];
1738 mesh.areas[mesh.npolys] = pareas[i];
1739 mesh.npolys++;
1740 if (mesh.npolys > maxTris)
1741 return DT_FAILURE | DT_BUFFER_TOO_SMALL;
1742 }
1743
1744 return DT_SUCCESS;
1745 }
1746
1747
1748 dtStatus dtBuildTileCachePolyMesh(dtTileCacheAlloc* alloc,
1749 dtTileCacheContourSet& lcset,
1750 dtTileCachePolyMesh& mesh)
1751 {
1752 dtAssert(alloc);
1753
1754 int maxVertices = 0;
1755 int maxTris = 0;
1756 int maxVertsPerCont = 0;
1757 for (int i = 0; i < lcset.nconts; ++i)
1758 {
1759 // Skip null contours.
1760 if (lcset.conts[i].nverts < 3) continue;
1761 maxVertices += lcset.conts[i].nverts;
1762 maxTris += lcset.conts[i].nverts - 2;
1763 maxVertsPerCont = dtMax(maxVertsPerCont, lcset.conts[i].nverts);
1764 }
1765
1766 // TODO: warn about too many vertices?
1767
1768 mesh.nvp = MAX_VERTS_PER_POLY;
1769
1770 dtFixedArray<unsigned char> vflags(alloc, maxVertices);
1771 if (!vflags)
1772 return DT_FAILURE | DT_OUT_OF_MEMORY;
1773 memset(vflags, 0, maxVertices);
1774
1775 mesh.verts = (unsigned short*)alloc->alloc(sizeof(unsigned short)*maxVertices*3);
1776 if (!mesh.verts)
1777 return DT_FAILURE | DT_OUT_OF_MEMORY;
1778
1779 mesh.polys = (unsigned short*)alloc->alloc(sizeof(unsigned short)*maxTris*MAX_VERTS_PER_POLY*2);
1780 if (!mesh.polys)
1781 return DT_FAILURE | DT_OUT_OF_MEMORY;
1782
1783 mesh.areas = (unsigned char*)alloc->alloc(sizeof(unsigned char)*maxTris);
1784 if (!mesh.areas)
1785 return DT_FAILURE | DT_OUT_OF_MEMORY;
1786
1787 mesh.flags = (unsigned short*)alloc->alloc(sizeof(unsigned short)*maxTris);
1788 if (!mesh.flags)
1789 return DT_FAILURE | DT_OUT_OF_MEMORY;
1790
1791 // Just allocate and clean the mesh flags array. The user is resposible for filling it.
1792 memset(mesh.flags, 0, sizeof(unsigned short) * maxTris);
1793
1794 mesh.nverts = 0;
1795 mesh.npolys = 0;
1796
1797 memset(mesh.verts, 0, sizeof(unsigned short)*maxVertices*3);
1798 memset(mesh.polys, 0xff, sizeof(unsigned short)*maxTris*MAX_VERTS_PER_POLY*2);
1799 memset(mesh.areas, 0, sizeof(unsigned char)*maxTris);
1800
1801 unsigned short firstVert[VERTEX_BUCKET_COUNT2];
1802 for (int i = 0; i < VERTEX_BUCKET_COUNT2; ++i)
1803 firstVert[i] = DT_TILECACHE_NULL_IDX;
1804
1805 dtFixedArray<unsigned short> nextVert(alloc, maxVertices);
1806 if (!nextVert)
1807 return DT_FAILURE | DT_OUT_OF_MEMORY;
1808 memset(nextVert, 0, sizeof(unsigned short)*maxVertices);
1809
1810 dtFixedArray<unsigned short> indices(alloc, maxVertsPerCont);
1811 if (!indices)
1812 return DT_FAILURE | DT_OUT_OF_MEMORY;
1813
1814 dtFixedArray<unsigned short> tris(alloc, maxVertsPerCont*3);
1815 if (!tris)
1816 return DT_FAILURE | DT_OUT_OF_MEMORY;
1817
1818 dtFixedArray<unsigned short> polys(alloc, maxVertsPerCont*MAX_VERTS_PER_POLY);
1819 if (!polys)
1820 return DT_FAILURE | DT_OUT_OF_MEMORY;
1821
1822 for (int i = 0; i < lcset.nconts; ++i)
1823 {
1824 dtTileCacheContour& cont = lcset.conts[i];
1825
1826 // Skip null contours.
1827 if (cont.nverts < 3)
1828 continue;
1829
1830 // Triangulate contour
1831 for (int j = 0; j < cont.nverts; ++j)
1832 indices[j] = (unsigned short)j;
1833
1834 int ntris = triangulate(cont.nverts, cont.verts, &indices[0], &tris[0]);
1835 if (ntris <= 0)
1836 {
1837 // TODO: issue warning!
1838 ntris = -ntris;
1839 }
1840
1841 // Add and merge vertices.
1842 for (int j = 0; j < cont.nverts; ++j)
1843 {
1844 const unsigned char* v = &cont.verts[j*4];
1845 indices[j] = addVertex((unsigned short)v[0], (unsigned short)v[1], (unsigned short)v[2],
1846 mesh.verts, firstVert, nextVert, mesh.nverts);
1847 if (v[3] & 0x80)
1848 {
1849 // This vertex should be removed.
1850 vflags[indices[j]] = 1;
1851 }
1852 }
1853
1854 // Build initial polygons.
1855 int npolys = 0;
1856 memset(polys, 0xff, sizeof(unsigned short) * maxVertsPerCont * MAX_VERTS_PER_POLY);
1857 for (int j = 0; j < ntris; ++j)
1858 {
1859 const unsigned short* t = &tris[j*3];
1860 if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])
1861 {
1862 polys[npolys*MAX_VERTS_PER_POLY+0] = indices[t[0]];
1863 polys[npolys*MAX_VERTS_PER_POLY+1] = indices[t[1]];
1864 polys[npolys*MAX_VERTS_PER_POLY+2] = indices[t[2]];
1865 npolys++;
1866 }
1867 }
1868 if (!npolys)
1869 continue;
1870
1871 // Merge polygons.
1872 int maxVertsPerPoly =MAX_VERTS_PER_POLY ;
1873 if (maxVertsPerPoly > 3)
1874 {
1875 for(;;)
1876 {
1877 // Find best polygons to merge.
1878 int bestMergeVal = 0;
1879 int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0;
1880
1881 for (int j = 0; j < npolys-1; ++j)
1882 {
1883 unsigned short* pj = &polys[j*MAX_VERTS_PER_POLY];
1884 for (int k = j+1; k < npolys; ++k)
1885 {
1886 unsigned short* pk = &polys[k*MAX_VERTS_PER_POLY];
1887 int ea, eb;
1888 int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb);
1889 if (v > bestMergeVal)
1890 {
1891 bestMergeVal = v;
1892 bestPa = j;
1893 bestPb = k;
1894 bestEa = ea;
1895 bestEb = eb;
1896 }
1897 }
1898 }
1899
1900 if (bestMergeVal > 0)
1901 {
1902 // Found best, merge.
1903 unsigned short* pa = &polys[bestPa*MAX_VERTS_PER_POLY];
1904 unsigned short* pb = &polys[bestPb*MAX_VERTS_PER_POLY];
1905 mergePolys(pa, pb, bestEa, bestEb);
1906 memcpy(pb, &polys[(npolys-1)*MAX_VERTS_PER_POLY], sizeof(unsigned short)*MAX_VERTS_PER_POLY);
1907 npolys--;
1908 }
1909 else
1910 {
1911 // Could not merge any polygons, stop.
1912 break;
1913 }
1914 }
1915 }
1916
1917 // Store polygons.
1918 for (int j = 0; j < npolys; ++j)
1919 {
1920 unsigned short* p = &mesh.polys[mesh.npolys*MAX_VERTS_PER_POLY*2];
1921 unsigned short* q = &polys[j*MAX_VERTS_PER_POLY];
1922 for (int k = 0; k < MAX_VERTS_PER_POLY; ++k)
1923 p[k] = q[k];
1924 mesh.areas[mesh.npolys] = cont.area;
1925 mesh.npolys++;
1926 if (mesh.npolys > maxTris)
1927 return DT_FAILURE | DT_BUFFER_TOO_SMALL;
1928 }
1929 }
1930
1931
1932 // Remove edge vertices.
1933 for (int i = 0; i < mesh.nverts; ++i)
1934 {
1935 if (vflags[i])
1936 {
1937 if (!canRemoveVertex(mesh, (unsigned short)i))
1938 continue;
1939 dtStatus status = removeVertex(mesh, (unsigned short)i, maxTris);
1940 if (dtStatusFailed(status))
1941 return status;
1942 // Remove vertex
1943 // Note: mesh.nverts is already decremented inside removeVertex()!
1944 for (int j = i; j < mesh.nverts; ++j)
1945 vflags[j] = vflags[j+1];
1946 --i;
1947 }
1948 }
1949
1950 // Calculate adjacency.
1951 if (!buildMeshAdjacency(alloc, mesh.polys, mesh.npolys, mesh.verts, mesh.nverts, lcset))
1952 return DT_FAILURE | DT_OUT_OF_MEMORY;
1953
1954 return DT_SUCCESS;
1955 }
1956
1957 dtStatus dtMarkCylinderArea(dtTileCacheLayer& layer, const float* orig, const float cs, const float ch,
1958 const float* pos, const float radius, const float height, const unsigned char areaId)
1959 {
1960 float bmin[3], bmax[3];
1961 bmin[0] = pos[0] - radius;
1962 bmin[1] = pos[1];
1963 bmin[2] = pos[2] - radius;
1964 bmax[0] = pos[0] + radius;
1965 bmax[1] = pos[1] + height;
1966 bmax[2] = pos[2] + radius;
1967 const float r2 = dtSqr(radius/cs + 0.5f);
1968
1969 const int w = (int)layer.header->width;
1970 const int h = (int)layer.header->height;
1971 const float ics = 1.0f/cs;
1972 const float ich = 1.0f/ch;
1973
1974 const float px = (pos[0]-orig[0])*ics;
1975 const float pz = (pos[2]-orig[2])*ics;
1976
1977 int minx = (int)dtMathFloorf((bmin[0]-orig[0])*ics);
1978 int miny = (int)dtMathFloorf((bmin[1]-orig[1])*ich);
1979 int minz = (int)dtMathFloorf((bmin[2]-orig[2])*ics);
1980 int maxx = (int)dtMathFloorf((bmax[0]-orig[0])*ics);
1981 int maxy = (int)dtMathFloorf((bmax[1]-orig[1])*ich);
1982 int maxz = (int)dtMathFloorf((bmax[2]-orig[2])*ics);
1983
1984 if (maxx < 0) return DT_SUCCESS;
1985 if (minx >= w) return DT_SUCCESS;
1986 if (maxz < 0) return DT_SUCCESS;
1987 if (minz >= h) return DT_SUCCESS;
1988
1989 if (minx < 0) minx = 0;
1990 if (maxx >= w) maxx = w-1;
1991 if (minz < 0) minz = 0;
1992 if (maxz >= h) maxz = h-1;
1993
1994 for (int z = minz; z <= maxz; ++z)
1995 {
1996 for (int x = minx; x <= maxx; ++x)
1997 {
1998 const float dx = (float)(x+0.5f) - px;
1999 const float dz = (float)(z+0.5f) - pz;
2000 if (dx*dx + dz*dz > r2)
2001 continue;
2002 const int y = layer.heights[x+z*w];
2003 if (y < miny || y > maxy)
2004 continue;
2005 layer.areas[x+z*w] = areaId;
2006 }
2007 }
2008
2009 return DT_SUCCESS;
2010 }
2011
2012 dtStatus dtMarkBoxArea(dtTileCacheLayer& layer, const float* orig, const float cs, const float ch,
2013 const float* bmin, const float* bmax, const unsigned char areaId)
2014 {
2015 const int w = (int)layer.header->width;
2016 const int h = (int)layer.header->height;
2017 const float ics = 1.0f/cs;
2018 const float ich = 1.0f/ch;
2019
2020 int minx = (int)floorf((bmin[0]-orig[0])*ics);
2021 int miny = (int)floorf((bmin[1]-orig[1])*ich);
2022 int minz = (int)floorf((bmin[2]-orig[2])*ics);
2023 int maxx = (int)floorf((bmax[0]-orig[0])*ics);
2024 int maxy = (int)floorf((bmax[1]-orig[1])*ich);
2025 int maxz = (int)floorf((bmax[2]-orig[2])*ics);
2026
2027 if (maxx < 0) return DT_SUCCESS;
2028 if (minx >= w) return DT_SUCCESS;
2029 if (maxz < 0) return DT_SUCCESS;
2030 if (minz >= h) return DT_SUCCESS;
2031
2032 if (minx < 0) minx = 0;
2033 if (maxx >= w) maxx = w-1;
2034 if (minz < 0) minz = 0;
2035 if (maxz >= h) maxz = h-1;
2036
2037 for (int z = minz; z <= maxz; ++z)
2038 {
2039 for (int x = minx; x <= maxx; ++x)
2040 {
2041 const int y = layer.heights[x+z*w];
2042 if (y < miny || y > maxy)
2043 continue;
2044 layer.areas[x+z*w] = areaId;
2045 }
2046 }
2047
2048 return DT_SUCCESS;
2049 }
2050
2051 dtStatus dtMarkBoxArea(dtTileCacheLayer& layer, const float* orig, const float cs, const float ch,
2052 const float* center, const float* halfExtents, const float* rotAux, const unsigned char areaId)
2053 {
2054 const int w = (int)layer.header->width;
2055 const int h = (int)layer.header->height;
2056 const float ics = 1.0f/cs;
2057 const float ich = 1.0f/ch;
2058
2059 float cx = (center[0] - orig[0])*ics;
2060 float cz = (center[2] - orig[2])*ics;
2061
2062 float maxr = 1.41f*dtMax(halfExtents[0], halfExtents[2]);
2063 int minx = (int)floorf(cx - maxr*ics);
2064 int maxx = (int)floorf(cx + maxr*ics);
2065 int minz = (int)floorf(cz - maxr*ics);
2066 int maxz = (int)floorf(cz + maxr*ics);
2067 int miny = (int)floorf((center[1]-halfExtents[1]-orig[1])*ich);
2068 int maxy = (int)floorf((center[1]+halfExtents[1]-orig[1])*ich);
2069
2070 if (maxx < 0) return DT_SUCCESS;
2071 if (minx >= w) return DT_SUCCESS;
2072 if (maxz < 0) return DT_SUCCESS;
2073 if (minz >= h) return DT_SUCCESS;
2074
2075 if (minx < 0) minx = 0;
2076 if (maxx >= w) maxx = w-1;
2077 if (minz < 0) minz = 0;
2078 if (maxz >= h) maxz = h-1;
2079
2080 float xhalf = halfExtents[0]*ics + 0.5f;
2081 float zhalf = halfExtents[2]*ics + 0.5f;
2082
2083 for (int z = minz; z <= maxz; ++z)
2084 {
2085 for (int x = minx; x <= maxx; ++x)
2086 {
2087 float x2 = 2.0f*(float(x) - cx);
2088 float z2 = 2.0f*(float(z) - cz);
2089 float xrot = rotAux[1]*x2 + rotAux[0]*z2;
2090 if (xrot > xhalf || xrot < -xhalf)
2091 continue;
2092 float zrot = rotAux[1]*z2 - rotAux[0]*x2;
2093 if (zrot > zhalf || zrot < -zhalf)
2094 continue;
2095 const int y = layer.heights[x+z*w];
2096 if (y < miny || y > maxy)
2097 continue;
2098 layer.areas[x+z*w] = areaId;
2099 }
2100 }
2101
2102 return DT_SUCCESS;
2103 }
2104
2105 dtStatus dtBuildTileCacheLayer(dtTileCacheCompressor* comp,
2106 dtTileCacheLayerHeader* header,
2107 const unsigned char* heights,
2108 const unsigned char* areas,
2109 const unsigned char* cons,
2110 unsigned char** outData, int* outDataSize)
2111 {
2112 const int headerSize = dtAlign4(sizeof(dtTileCacheLayerHeader));
2113 const int gridSize = (int)header->width * (int)header->height;
2114 const int maxDataSize = headerSize + comp->maxCompressedSize(gridSize*3);
2115 unsigned char* data = (unsigned char*)dtAlloc(maxDataSize, DT_ALLOC_PERM);
2116 if (!data)
2117 return DT_FAILURE | DT_OUT_OF_MEMORY;
2118 memset(data, 0, maxDataSize);
2119
2120 // Store header
2121 memcpy(data, header, sizeof(dtTileCacheLayerHeader));
2122
2123 // Concatenate grid data for compression.
2124 const int bufferSize = gridSize*3;
2125 unsigned char* buffer = (unsigned char*)dtAlloc(bufferSize, DT_ALLOC_TEMP);
2126 if (!buffer)
2127 {
2128 dtFree(data);
2129 return DT_FAILURE | DT_OUT_OF_MEMORY;
2130 }
2131
2132 memcpy(buffer, heights, gridSize);
2133 memcpy(buffer+gridSize, areas, gridSize);
2134 memcpy(buffer+gridSize*2, cons, gridSize);
2135
2136 // Compress
2137 unsigned char* compressed = data + headerSize;
2138 const int maxCompressedSize = maxDataSize - headerSize;
2139 int compressedSize = 0;
2140 dtStatus status = comp->compress(buffer, bufferSize, compressed, maxCompressedSize, &compressedSize);
2141 if (dtStatusFailed(status))
2142 {
2143 dtFree(buffer);
2144 dtFree(data);
2145 return status;
2146 }
2147
2148 *outData = data;
2149 *outDataSize = headerSize + compressedSize;
2150
2151 dtFree(buffer);
2152
2153 return DT_SUCCESS;
2154 }
2155
2156 void dtFreeTileCacheLayer(dtTileCacheAlloc* alloc, dtTileCacheLayer* layer)
2157 {
2158 dtAssert(alloc);
2159 // The layer is allocated as one conitguous blob of data.
2160 alloc->free(layer);
2161 }
2162
2163 dtStatus dtDecompressTileCacheLayer(dtTileCacheAlloc* alloc, dtTileCacheCompressor* comp,
2164 unsigned char* compressed, const int compressedSize,
2165 dtTileCacheLayer** layerOut)
2166 {
2167 dtAssert(alloc);
2168 dtAssert(comp);
2169
2170 if (!layerOut)
2171 return DT_FAILURE | DT_INVALID_PARAM;
2172 if (!compressed)
2173 return DT_FAILURE | DT_INVALID_PARAM;
2174
2175 *layerOut = 0;
2176
2177 dtTileCacheLayerHeader* compressedHeader = (dtTileCacheLayerHeader*)compressed;
2178 if (compressedHeader->magic != DT_TILECACHE_MAGIC)
2179 return DT_FAILURE | DT_WRONG_MAGIC;
2180 if (compressedHeader->version != DT_TILECACHE_VERSION)
2181 return DT_FAILURE | DT_WRONG_VERSION;
2182
2183 const int layerSize = dtAlign4(sizeof(dtTileCacheLayer));
2184 const int headerSize = dtAlign4(sizeof(dtTileCacheLayerHeader));
2185 const int gridSize = (int)compressedHeader->width * (int)compressedHeader->height;
2186 const int bufferSize = layerSize + headerSize + gridSize*4;
2187
2188 unsigned char* buffer = (unsigned char*)alloc->alloc(bufferSize);
2189 if (!buffer)
2190 return DT_FAILURE | DT_OUT_OF_MEMORY;
2191 memset(buffer, 0, bufferSize);
2192
2193 dtTileCacheLayer* layer = (dtTileCacheLayer*)buffer;
2194 dtTileCacheLayerHeader* header = (dtTileCacheLayerHeader*)(buffer + layerSize);
2195 unsigned char* grids = buffer + layerSize + headerSize;
2196 const int gridsSize = bufferSize - (layerSize + headerSize);
2197
2198 // Copy header
2199 memcpy(header, compressedHeader, headerSize);
2200 // Decompress grid.
2201 int size = 0;
2202 dtStatus status = comp->decompress(compressed+headerSize, compressedSize-headerSize,
2203 grids, gridsSize, &size);
2204 if (dtStatusFailed(status))
2205 {
2206 alloc->free(buffer);
2207 return status;
2208 }
2209
2210 layer->header = header;
2211 layer->heights = grids;
2212 layer->areas = grids + gridSize;
2213 layer->cons = grids + gridSize*2;
2214 layer->regs = grids + gridSize*3;
2215
2216 *layerOut = layer;
2217
2218 return DT_SUCCESS;
2219 }
2220
2221
2222
2223 bool dtTileCacheHeaderSwapEndian(unsigned char* data, const int dataSize)
2224 {
2225 dtIgnoreUnused(dataSize);
2226 dtTileCacheLayerHeader* header = (dtTileCacheLayerHeader*)data;
2227
2228 int swappedMagic = DT_TILECACHE_MAGIC;
2229 int swappedVersion = DT_TILECACHE_VERSION;
2230 dtSwapEndian(&swappedMagic);
2231 dtSwapEndian(&swappedVersion);
2232
2233 if ((header->magic != DT_TILECACHE_MAGIC || header->version != DT_TILECACHE_VERSION) &&
2234 (header->magic != swappedMagic || header->version != swappedVersion))
2235 {
2236 return false;
2237 }
2238
2239 dtSwapEndian(&header->magic);
2240 dtSwapEndian(&header->version);
2241 dtSwapEndian(&header->tx);
2242 dtSwapEndian(&header->ty);
2243 dtSwapEndian(&header->tlayer);
2244 dtSwapEndian(&header->bmin[0]);
2245 dtSwapEndian(&header->bmin[1]);
2246 dtSwapEndian(&header->bmin[2]);
2247 dtSwapEndian(&header->bmax[0]);
2248 dtSwapEndian(&header->bmax[1]);
2249 dtSwapEndian(&header->bmax[2]);
2250 dtSwapEndian(&header->hmin);
2251 dtSwapEndian(&header->hmax);
2252
2253 // width, height, minx, maxx, miny, maxy are unsigned char, no need to swap.
2254
2255 return true;
2256 }
2257