Subversion Repository Public Repository

Divide-Framework

This repository has no backups
This repository's network speed is throttled to 100KB/sec

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty.  In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
//    claim that you wrote the original software. If you use this software
//    in a product, an acknowledgment in the product documentation would be
//    appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//    misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//

#include "DetourCommon.h"
#include "DetourMath.h"
#include "DetourStatus.h"
#include "DetourAssert.h"
#include "DetourTileCacheBuilder.h"
#include <string.h>


template<class T> class dtFixedArray
{
    dtTileCacheAlloc* m_alloc;
    T* m_ptr;
    const int m_size;
    inline T* operator=(T* p);
    inline void operator=(dtFixedArray<T>& p);
    inline dtFixedArray();
public:
    inline dtFixedArray(dtTileCacheAlloc* a, const int s) : m_alloc(a), m_ptr((T*)a->alloc(sizeof(T)*s)), m_size(s) {}
    inline ~dtFixedArray() { if (m_alloc) m_alloc->free(m_ptr); }
    inline operator T*() { return m_ptr; }
    inline int size() const { return m_size; }
};

inline int getDirOffsetX(int dir)
{
    const int offset[4] = { -1, 0, 1, 0, };
    return offset[dir&0x03];
}

inline int getDirOffsetY(int dir)
{
    const int offset[4] = { 0, 1, 0, -1 };
    return offset[dir&0x03];
}

static const int MAX_VERTS_PER_POLY = 6;    // TODO: use the DT_VERTS_PER_POLYGON
static const int MAX_REM_EDGES = 48;        // TODO: make this an expression.



dtTileCacheContourSet* dtAllocTileCacheContourSet(dtTileCacheAlloc* alloc)
{
    dtAssert(alloc);

    dtTileCacheContourSet* cset = (dtTileCacheContourSet*)alloc->alloc(sizeof(dtTileCacheContourSet));
    memset(cset, 0, sizeof(dtTileCacheContourSet));
    return cset;
}

void dtFreeTileCacheContourSet(dtTileCacheAlloc* alloc, dtTileCacheContourSet* cset)
{
    dtAssert(alloc);

    if (!cset) return;
    for (int i = 0; i < cset->nconts; ++i)
        alloc->free(cset->conts[i].verts);
    alloc->free(cset->conts);
    alloc->free(cset);
}

dtTileCachePolyMesh* dtAllocTileCachePolyMesh(dtTileCacheAlloc* alloc)
{
    dtAssert(alloc);

    dtTileCachePolyMesh* lmesh = (dtTileCachePolyMesh*)alloc->alloc(sizeof(dtTileCachePolyMesh));
    memset(lmesh, 0, sizeof(dtTileCachePolyMesh));
    return lmesh;
}

void dtFreeTileCachePolyMesh(dtTileCacheAlloc* alloc, dtTileCachePolyMesh* lmesh)
{
    dtAssert(alloc);
    
    if (!lmesh) return;
    alloc->free(lmesh->verts);
    alloc->free(lmesh->polys);
    alloc->free(lmesh->flags);
    alloc->free(lmesh->areas);
    alloc->free(lmesh);
}



struct dtLayerSweepSpan
{
    unsigned short ns;    // number samples
    unsigned char id;    // region id
    unsigned char nei;    // neighbour id
};

static const int DT_LAYER_MAX_NEIS = 16;

struct dtLayerMonotoneRegion
{
    int area;
    unsigned char neis[DT_LAYER_MAX_NEIS];
    unsigned char nneis;
    unsigned char regId;
    unsigned char areaId;
};

struct dtTempContour
{
    inline dtTempContour(unsigned char* vbuf, const int nvbuf,
                         unsigned short* pbuf, const int npbuf) :
        verts(vbuf), nverts(0), cverts(nvbuf),
        poly(pbuf), npoly(0), cpoly(npbuf) 
    {
    }
    unsigned char* verts;
    int nverts;
    int cverts;
    unsigned short* poly;
    int npoly;
    int cpoly;
};




inline bool overlapRangeExl(const unsigned short amin, const unsigned short amax,
                            const unsigned short bmin, const unsigned short bmax)
{
    return (amin >= bmax || amax <= bmin) ? false : true;
}

static void addUniqueLast(unsigned char* a, unsigned char& an, unsigned char v)
{
    const int n = (int)an;
    if (n > 0 && a[n-1] == v) return;
    a[an] = v;
    an++;
}

inline bool isConnected(const dtTileCacheLayer& layer,
                        const int ia, const int ib, const int walkableClimb)
{
    if (layer.areas[ia] != layer.areas[ib]) return false;
    if (dtAbs((int)layer.heights[ia] - (int)layer.heights[ib]) > walkableClimb) return false;
    return true;
}

static bool canMerge(unsigned char oldRegId, unsigned char newRegId, const dtLayerMonotoneRegion* regs, const int nregs)
{
    int count = 0;
    for (int i = 0; i < nregs; ++i)
    {
        const dtLayerMonotoneRegion& reg = regs[i];
        if (reg.regId != oldRegId) continue;
        const int nnei = (int)reg.nneis;
        for (int j = 0; j < nnei; ++j)
        {
            if (regs[reg.neis[j]].regId == newRegId)
                count++;
        }
    }
    return count == 1;
}


dtStatus dtBuildTileCacheRegions(dtTileCacheAlloc* alloc,
                                 dtTileCacheLayer& layer,
                                 const int walkableClimb)
{
    dtAssert(alloc);
    
    const int w = (int)layer.header->width;
    const int h = (int)layer.header->height;
    
    memset(layer.regs,0xff,sizeof(unsigned char)*w*h);
    
    const int nsweeps = w;
    dtFixedArray<dtLayerSweepSpan> sweeps(alloc, nsweeps);
    if (!sweeps)
        return DT_FAILURE | DT_OUT_OF_MEMORY;
    memset(sweeps,0,sizeof(dtLayerSweepSpan)*nsweeps);
    
    // Partition walkable area into monotone regions.
    unsigned char prevCount[256];
    unsigned char regId = 0;
    
    for (int y = 0; y < h; ++y)
    {
        if (regId > 0)
            memset(prevCount,0,sizeof(unsigned char)*regId);
        unsigned char sweepId = 0;
        
        for (int x = 0; x < w; ++x)
        {
            const int idx = x + y*w;
            if (layer.areas[idx] == DT_TILECACHE_NULL_AREA) continue;
            
            unsigned char sid = 0xff;
            
            // -x
            const int xidx = (x-1)+y*w;
            if (x > 0 && isConnected(layer, idx, xidx, walkableClimb))
            {
                if (layer.regs[xidx] != 0xff)
                    sid = layer.regs[xidx];
            }
            
            if (sid == 0xff)
            {
                sid = sweepId++;
                sweeps[sid].nei = 0xff;
                sweeps[sid].ns = 0;
            }
            
            // -y
            const int yidx = x+(y-1)*w;
            if (y > 0 && isConnected(layer, idx, yidx, walkableClimb))
            {
                const unsigned char nr = layer.regs[yidx];
                if (nr != 0xff)
                {
                    // Set neighbour when first valid neighbour is encoutered.
                    if (sweeps[sid].ns == 0)
                        sweeps[sid].nei = nr;
                    
                    if (sweeps[sid].nei == nr)
                    {
                        // Update existing neighbour
                        sweeps[sid].ns++;
                        prevCount[nr]++;
                    }
                    else
                    {
                        // This is hit if there is nore than one neighbour.
                        // Invalidate the neighbour.
                        sweeps[sid].nei = 0xff;
                    }
                }
            }
            
            layer.regs[idx] = sid;
        }
        
        // Create unique ID.
        for (int i = 0; i < sweepId; ++i)
        {
            // If the neighbour is set and there is only one continuous connection to it,
            // the sweep will be merged with the previous one, else new region is created.
            if (sweeps[i].nei != 0xff && (unsigned short)prevCount[sweeps[i].nei] == sweeps[i].ns)
            {
                sweeps[i].id = sweeps[i].nei;
            }
            else
            {
                if (regId == 255)
                {
                    // Region ID's overflow.
                    return DT_FAILURE | DT_BUFFER_TOO_SMALL;
                }
                sweeps[i].id = regId++;
            }
        }
        
        // Remap local sweep ids to region ids.
        for (int x = 0; x < w; ++x)
        {
            const int idx = x+y*w;
            if (layer.regs[idx] != 0xff)
                layer.regs[idx] = sweeps[layer.regs[idx]].id;
        }
    }
    
    // Allocate and init layer regions.
    const int nregs = (int)regId;
    dtFixedArray<dtLayerMonotoneRegion> regs(alloc, nregs);
    if (!regs)
        return DT_FAILURE | DT_OUT_OF_MEMORY;

    memset(regs, 0, sizeof(dtLayerMonotoneRegion)*nregs);
    for (int i = 0; i < nregs; ++i)
        regs[i].regId = 0xff;
    
    // Find region neighbours.
    for (int y = 0; y < h; ++y)
    {
        for (int x = 0; x < w; ++x)
        {
            const int idx = x+y*w;
            const unsigned char ri = layer.regs[idx];
            if (ri == 0xff)
                continue;
            
            // Update area.
            regs[ri].area++;
            regs[ri].areaId = layer.areas[idx];
            
            // Update neighbours
            const int ymi = x+(y-1)*w;
            if (y > 0 && isConnected(layer, idx, ymi, walkableClimb))
            {
                const unsigned char rai = layer.regs[ymi];
                if (rai != 0xff && rai != ri)
                {
                    addUniqueLast(regs[ri].neis, regs[ri].nneis, rai);
                    addUniqueLast(regs[rai].neis, regs[rai].nneis, ri);
                }
            }
        }
    }
    
    for (int i = 0; i < nregs; ++i)
        regs[i].regId = (unsigned char)i;
    
    for (int i = 0; i < nregs; ++i)
    {
        dtLayerMonotoneRegion& reg = regs[i];
        
        int merge = -1;
        int mergea = 0;
        for (int j = 0; j < (int)reg.nneis; ++j)
        {
            const unsigned char nei = reg.neis[j];
            dtLayerMonotoneRegion& regn = regs[nei];
            if (reg.regId == regn.regId)
                continue;
            if (reg.areaId != regn.areaId)
                continue;
            if (regn.area > mergea)
            {
                if (canMerge(reg.regId, regn.regId, regs, nregs))
                {
                    mergea = regn.area;
                    merge = (int)nei;
                }
            }
        }
        if (merge != -1)
        {
            const unsigned char oldId = reg.regId;
            const unsigned char newId = regs[merge].regId;
            for (int j = 0; j < nregs; ++j)
                if (regs[j].regId == oldId)
                    regs[j].regId = newId;
        }
    }
    
    // Compact ids.
    unsigned char remap[256];
    memset(remap, 0, 256);
    // Find number of unique regions.
    regId = 0;
    for (int i = 0; i < nregs; ++i)
        remap[regs[i].regId] = 1;
    for (int i = 0; i < 256; ++i)
        if (remap[i])
            remap[i] = regId++;
    // Remap ids.
    for (int i = 0; i < nregs; ++i)
        regs[i].regId = remap[regs[i].regId];
    
    layer.regCount = regId;
    
    for (int i = 0; i < w*h; ++i)
    {
        if (layer.regs[i] != 0xff)
            layer.regs[i] = regs[layer.regs[i]].regId;
    }
    
    return DT_SUCCESS;
}



static bool appendVertex(dtTempContour& cont, const int x, const int y, const int z, const int r)
{
    // Try to merge with existing segments.
    if (cont.nverts > 1)
    {
        unsigned char* pa = &cont.verts[(cont.nverts-2)*4];
        unsigned char* pb = &cont.verts[(cont.nverts-1)*4];
        if ((int)pb[3] == r)
        {
            if (pa[0] == pb[0] && (int)pb[0] == x)
            {
                // The verts are aligned aling x-axis, update z.
                pb[1] = (unsigned char)y;
                pb[2] = (unsigned char)z;
                return true;
            }
            else if (pa[2] == pb[2] && (int)pb[2] == z)
            {
                // The verts are aligned aling z-axis, update x.
                pb[0] = (unsigned char)x;
                pb[1] = (unsigned char)y;
                return true;
            }
        }
    }
    
    // Add new point.
    if (cont.nverts+1 > cont.cverts)
        return false;
    
    unsigned char* v = &cont.verts[cont.nverts*4];
    v[0] = (unsigned char)x;
    v[1] = (unsigned char)y;
    v[2] = (unsigned char)z;
    v[3] = (unsigned char)r;
    cont.nverts++;
    
    return true;
}


static unsigned char getNeighbourReg(dtTileCacheLayer& layer,
                                     const int ax, const int ay, const int dir)
{
    const int w = (int)layer.header->width;
    const int ia = ax + ay*w;
    
    const unsigned char con = layer.cons[ia] & 0xf;
    const unsigned char portal = layer.cons[ia] >> 4;
    const unsigned char mask = (unsigned char)(1<<dir);
    
    if ((con & mask) == 0)
    {
        // No connection, return portal or hard edge.
        if (portal & mask)
            return 0xf8 + (unsigned char)dir;
        return 0xff;
    }
    
    const int bx = ax + getDirOffsetX(dir);
    const int by = ay + getDirOffsetY(dir);
    const int ib = bx + by*w;
    
    return layer.regs[ib];
}

static bool walkContour(dtTileCacheLayer& layer, int x, int y, dtTempContour& cont)
{
    const int w = (int)layer.header->width;
    const int h = (int)layer.header->height;
    
    cont.nverts = 0;
    
    int startX = x;
    int startY = y;
    int startDir = -1;
    
    for (int i = 0; i < 4; ++i)
    {
        const int dir = (i+3)&3;
        unsigned char rn = getNeighbourReg(layer, x, y, dir);
        if (rn != layer.regs[x+y*w])
        {
            startDir = dir;
            break;
        }
    }
    if (startDir == -1)
        return true;
    
    int dir = startDir;
    const int maxIter = w*h;
    
    int iter = 0;
    while (iter < maxIter)
    {
        unsigned char rn = getNeighbourReg(layer, x, y, dir);
        
        int nx = x;
        int ny = y;
        int ndir = dir;
        
        if (rn != layer.regs[x+y*w])
        {
            // Solid edge.
            int px = x;
            int pz = y;
            switch(dir)
            {
                case 0: pz++; break;
                case 1: px++; pz++; break;
                case 2: px++; break;
            }
            
            // Try to merge with previous vertex.
            if (!appendVertex(cont, px, (int)layer.heights[x+y*w], pz,rn))
                return false;
            
            ndir = (dir+1) & 0x3;  // Rotate CW
        }
        else
        {
            // Move to next.
            nx = x + getDirOffsetX(dir);
            ny = y + getDirOffsetY(dir);
            ndir = (dir+3) & 0x3;    // Rotate CCW
        }
        
        if (iter > 0 && x == startX && y == startY && dir == startDir)
            break;
        
        x = nx;
        y = ny;
        dir = ndir;
        
        iter++;
    }
    
    // Remove last vertex if it is duplicate of the first one.
    unsigned char* pa = &cont.verts[(cont.nverts-1)*4];
    unsigned char* pb = &cont.verts[0];
    if (pa[0] == pb[0] && pa[2] == pb[2])
        cont.nverts--;
    
    return true;
}    


static float distancePtSeg(const int x, const int z,
                           const int px, const int pz,
                           const int qx, const int qz)
{
    float pqx = (float)(qx - px);
    float pqz = (float)(qz - pz);
    float dx = (float)(x - px);
    float dz = (float)(z - pz);
    float d = pqx*pqx + pqz*pqz;
    float t = pqx*dx + pqz*dz;
    if (d > 0)
        t /= d;
    if (t < 0)
        t = 0;
    else if (t > 1)
        t = 1;
    
    dx = px + t*pqx - x;
    dz = pz + t*pqz - z;
    
    return dx*dx + dz*dz;
}

static void simplifyContour(dtTempContour& cont, const float maxError)
{
    cont.npoly = 0;
    
    for (int i = 0; i < cont.nverts; ++i)
    {
        int j = (i+1) % cont.nverts;
        // Check for start of a wall segment.
        unsigned char ra = cont.verts[j*4+3];
        unsigned char rb = cont.verts[i*4+3];
        if (ra != rb)
            cont.poly[cont.npoly++] = (unsigned short)i;
    }
    if (cont.npoly < 2)
    {
        // If there is no transitions at all,
        // create some initial points for the simplification process. 
        // Find lower-left and upper-right vertices of the contour.
        int llx = cont.verts[0];
        int llz = cont.verts[2];
        int lli = 0;
        int urx = cont.verts[0];
        int urz = cont.verts[2];
        int uri = 0;
        for (int i = 1; i < cont.nverts; ++i)
        {
            int x = cont.verts[i*4+0];
            int z = cont.verts[i*4+2];
            if (x < llx || (x == llx && z < llz))
            {
                llx = x;
                llz = z;
                lli = i;
            }
            if (x > urx || (x == urx && z > urz))
            {
                urx = x;
                urz = z;
                uri = i;
            }
        }
        cont.npoly = 0;
        cont.poly[cont.npoly++] = (unsigned short)lli;
        cont.poly[cont.npoly++] = (unsigned short)uri;
    }
    
    // Add points until all raw points are within
    // error tolerance to the simplified shape.
    for (int i = 0; i < cont.npoly; )
    {
        int ii = (i+1) % cont.npoly;
        
        const int ai = (int)cont.poly[i];
        const int ax = (int)cont.verts[ai*4+0];
        const int az = (int)cont.verts[ai*4+2];
        
        const int bi = (int)cont.poly[ii];
        const int bx = (int)cont.verts[bi*4+0];
        const int bz = (int)cont.verts[bi*4+2];
        
        // Find maximum deviation from the segment.
        float maxd = 0;
        int maxi = -1;
        int ci, cinc, endi;
        
        // Traverse the segment in lexilogical order so that the
        // max deviation is calculated similarly when traversing
        // opposite segments.
        if (bx > ax || (bx == ax && bz > az))
        {
            cinc = 1;
            ci = (ai+cinc) % cont.nverts;
            endi = bi;
        }
        else
        {
            cinc = cont.nverts-1;
            ci = (bi+cinc) % cont.nverts;
            endi = ai;
        }
        
        // Tessellate only outer edges or edges between areas.
        while (ci != endi)
        {
            float d = distancePtSeg(cont.verts[ci*4+0], cont.verts[ci*4+2], ax, az, bx, bz);
            if (d > maxd)
            {
                maxd = d;
                maxi = ci;
            }
            ci = (ci+cinc) % cont.nverts;
        }
        
        
        // If the max deviation is larger than accepted error,
        // add new point, else continue to next segment.
        if (maxi != -1 && maxd > (maxError*maxError))
        {
            cont.npoly++;
            for (int j = cont.npoly-1; j > i; --j)
                cont.poly[j] = cont.poly[j-1];
            cont.poly[i+1] = (unsigned short)maxi;
        }
        else
        {
            ++i;
        }
    }
    
    // Remap vertices
    int start = 0;
    for (int i = 1; i < cont.npoly; ++i)
        if (cont.poly[i] < cont.poly[start])
            start = i;
    
    cont.nverts = 0;
    for (int i = 0; i < cont.npoly; ++i)
    {
        const int j = (start+i) % cont.npoly;
        unsigned char* src = &cont.verts[cont.poly[j]*4];
        unsigned char* dst = &cont.verts[cont.nverts*4];
        dst[0] = src[0];
        dst[1] = src[1];
        dst[2] = src[2];
        dst[3] = src[3];
        cont.nverts++;
    }
}

static unsigned char getCornerHeight(dtTileCacheLayer& layer,
                                     const int x, const int y, const int z,
                                     const int walkableClimb,
                                     bool& shouldRemove)
{
    const int w = (int)layer.header->width;
    const int h = (int)layer.header->height;
    
    int n = 0;
    
    unsigned char portal = 0xf;
    unsigned char height = 0;
    unsigned char preg = 0xff;
    bool allSameReg = true;
    
    for (int dz = -1; dz <= 0; ++dz)
    {
        for (int dx = -1; dx <= 0; ++dx)
        {
            const int px = x+dx;
            const int pz = z+dz;
            if (px >= 0 && pz >= 0 && px < w && pz < h)
            {
                const int idx  = px + pz*w;
                const int lh = (int)layer.heights[idx];
                if (dtAbs(lh-y) <= walkableClimb && layer.areas[idx] != DT_TILECACHE_NULL_AREA)
                {
                    height = dtMax(height, (unsigned char)lh);
                    portal &= (layer.cons[idx] >> 4);
                    if (preg != 0xff && preg != layer.regs[idx])
                        allSameReg = false;
                    preg = layer.regs[idx]; 
                    n++;
                }
            }
        }
    }
    
    int portalCount = 0;
    for (int dir = 0; dir < 4; ++dir)
        if (portal & (1<<dir))
            portalCount++;
    
    shouldRemove = false;
    if (n > 1 && portalCount == 1 && allSameReg)
    {
        shouldRemove = true;
    }
    
    return height;
}


// TODO: move this somewhere else, once the layer meshing is done.
dtStatus dtBuildTileCacheContours(dtTileCacheAlloc* alloc,
                                  dtTileCacheLayer& layer,
                                  const int walkableClimb,     const float maxError,
                                  dtTileCacheContourSet& lcset)
{
    dtAssert(alloc);

    const int w = (int)layer.header->width;
    const int h = (int)layer.header->height;
    
    lcset.nconts = layer.regCount;
    lcset.conts = (dtTileCacheContour*)alloc->alloc(sizeof(dtTileCacheContour)*lcset.nconts);
    if (!lcset.conts)
        return DT_FAILURE | DT_OUT_OF_MEMORY;
    memset(lcset.conts, 0, sizeof(dtTileCacheContour)*lcset.nconts);
    
    // Allocate temp buffer for contour tracing.
    const int maxTempVerts = (w+h)*2 * 2; // Twice around the layer.
    
    dtFixedArray<unsigned char> tempVerts(alloc, maxTempVerts*4);
    if (!tempVerts)
        return DT_FAILURE | DT_OUT_OF_MEMORY;
    
    dtFixedArray<unsigned short> tempPoly(alloc, maxTempVerts);
    if (!tempPoly)
        return DT_FAILURE | DT_OUT_OF_MEMORY;

    dtTempContour temp(tempVerts, maxTempVerts, tempPoly, maxTempVerts);
    
    // Find contours.
    for (int y = 0; y < h; ++y)
    {
        for (int x = 0; x < w; ++x)
        {
            const int idx = x+y*w;
            const unsigned char ri = layer.regs[idx];
            if (ri == 0xff)
                continue;
            
            dtTileCacheContour& cont = lcset.conts[ri];
            
            if (cont.nverts > 0)
                continue;
            
            cont.reg = ri;
            cont.area = layer.areas[idx];
            
            if (!walkContour(layer, x, y, temp))
            {
                // Too complex contour.
                // Note: If you hit here ofte, try increasing 'maxTempVerts'.
                return DT_FAILURE | DT_BUFFER_TOO_SMALL;
            }
            
            simplifyContour(temp, maxError);
            
            // Store contour.
            cont.nverts = temp.nverts;
            if (cont.nverts > 0)
            {
                cont.verts = (unsigned char*)alloc->alloc(sizeof(unsigned char)*4*temp.nverts);
                if (!cont.verts)
                    return DT_FAILURE | DT_OUT_OF_MEMORY;
                
                for (int i = 0, j = temp.nverts-1; i < temp.nverts; j=i++)
                {
                    unsigned char* dst = &cont.verts[j*4];
                    unsigned char* v = &temp.verts[j*4];
                    unsigned char* vn = &temp.verts[i*4];
                    unsigned char nei = vn[3]; // The neighbour reg is stored at segment vertex of a segment. 
                    bool shouldRemove = false;
                    unsigned char lh = getCornerHeight(layer, (int)v[0], (int)v[1], (int)v[2],
                                                       walkableClimb, shouldRemove);
                    
                    dst[0] = v[0];
                    dst[1] = lh;
                    dst[2] = v[2];
                    
                    // Store portal direction and remove status to the fourth component.
                    dst[3] = 0x0f;
                    if (nei != 0xff && nei >= 0xf8)
                        dst[3] = nei - 0xf8;
                    if (shouldRemove)
                        dst[3] |= 0x80;
                }
            }
        }
    }
    
    return DT_SUCCESS;
}    



static const int VERTEX_BUCKET_COUNT2 = (1<<8);

inline int computeVertexHash2(int x, int y, int z)
{
    const unsigned int h1 = 0x8da6b343; // Large multiplicative constants;
    const unsigned int h2 = 0xd8163841; // here arbitrarily chosen primes
    const unsigned int h3 = 0xcb1ab31f;
    unsigned int n = h1 * x + h2 * y + h3 * z;
    return (int)(n & (VERTEX_BUCKET_COUNT2-1));
}

static unsigned short addVertex(unsigned short x, unsigned short y, unsigned short z,
                                unsigned short* verts, unsigned short* firstVert, unsigned short* nextVert, int& nv)
{
    int bucket = computeVertexHash2(x, 0, z);
    unsigned short i = firstVert[bucket];
    
    while (i != DT_TILECACHE_NULL_IDX)
    {
        const unsigned short* v = &verts[i*3];
        if (v[0] == x && v[2] == z && (dtAbs(v[1] - y) <= 2))
            return i;
        i = nextVert[i]; // next
    }
    
    // Could not find, create new.
    i = (unsigned short)nv; nv++;
    unsigned short* v = &verts[i*3];
    v[0] = x;
    v[1] = y;
    v[2] = z;
    nextVert[i] = firstVert[bucket];
    firstVert[bucket] = i;
    
    return (unsigned short)i;
}


struct rcEdge
{
    unsigned short vert[2];
    unsigned short polyEdge[2];
    unsigned short poly[2];
};

static bool buildMeshAdjacency(dtTileCacheAlloc* alloc,
                               unsigned short* polys, const int npolys,
                               const unsigned short* verts, const int nverts,
                               const dtTileCacheContourSet& lcset)
{
    // Based on code by Eric Lengyel from:
    // http://www.terathon.com/code/edges.php
    
    const int maxEdgeCount = npolys*MAX_VERTS_PER_POLY;
    dtFixedArray<unsigned short> firstEdge(alloc, nverts + maxEdgeCount);
    if (!firstEdge)
        return false;
    unsigned short* nextEdge = firstEdge + nverts;
    int edgeCount = 0;
    
    dtFixedArray<rcEdge> edges(alloc, maxEdgeCount);
    if (!edges)
        return false;
    
    for (int i = 0; i < nverts; i++)
        firstEdge[i] = DT_TILECACHE_NULL_IDX;
    
    for (int i = 0; i < npolys; ++i)
    {
        unsigned short* t = &polys[i*MAX_VERTS_PER_POLY*2];
        for (int j = 0; j < MAX_VERTS_PER_POLY; ++j)
        {
            if (t[j] == DT_TILECACHE_NULL_IDX) break;
            unsigned short v0 = t[j];
            unsigned short v1 = (j+1 >= MAX_VERTS_PER_POLY || t[j+1] == DT_TILECACHE_NULL_IDX) ? t[0] : t[j+1];
            if (v0 < v1)
            {
                rcEdge& edge = edges[edgeCount];
                edge.vert[0] = v0;
                edge.vert[1] = v1;
                edge.poly[0] = (unsigned short)i;
                edge.polyEdge[0] = (unsigned short)j;
                edge.poly[1] = (unsigned short)i;
                edge.polyEdge[1] = 0xff;
                // Insert edge
                nextEdge[edgeCount] = firstEdge[v0];
                firstEdge[v0] = (unsigned short)edgeCount;
                edgeCount++;
            }
        }
    }
    
    for (int i = 0; i < npolys; ++i)
    {
        unsigned short* t = &polys[i*MAX_VERTS_PER_POLY*2];
        for (int j = 0; j < MAX_VERTS_PER_POLY; ++j)
        {
            if (t[j] == DT_TILECACHE_NULL_IDX) break;
            unsigned short v0 = t[j];
            unsigned short v1 = (j+1 >= MAX_VERTS_PER_POLY || t[j+1] == DT_TILECACHE_NULL_IDX) ? t[0] : t[j+1];
            if (v0 > v1)
            {
                bool found = false;
                for (unsigned short e = firstEdge[v1]; e != DT_TILECACHE_NULL_IDX; e = nextEdge[e])
                {
                    rcEdge& edge = edges[e];
                    if (edge.vert[1] == v0 && edge.poly[0] == edge.poly[1])
                    {
                        edge.poly[1] = (unsigned short)i;
                        edge.polyEdge[1] = (unsigned short)j;
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    // Matching edge not found, it is an open edge, add it.
                    rcEdge& edge = edges[edgeCount];
                    edge.vert[0] = v1;
                    edge.vert[1] = v0;
                    edge.poly[0] = (unsigned short)i;
                    edge.polyEdge[0] = (unsigned short)j;
                    edge.poly[1] = (unsigned short)i;
                    edge.polyEdge[1] = 0xff;
                    // Insert edge
                    nextEdge[edgeCount] = firstEdge[v1];
                    firstEdge[v1] = (unsigned short)edgeCount;
                    edgeCount++;
                }
            }
        }
    }
    
    // Mark portal edges.
    for (int i = 0; i < lcset.nconts; ++i)
    {
        dtTileCacheContour& cont = lcset.conts[i];
        if (cont.nverts < 3)
            continue;
        
        for (int j = 0, k = cont.nverts-1; j < cont.nverts; k=j++)
        {
            const unsigned char* va = &cont.verts[k*4];
            const unsigned char* vb = &cont.verts[j*4];
            const unsigned char dir = va[3] & 0xf;
            if (dir == 0xf)
                continue;
            
            if (dir == 0 || dir == 2)
            {
                // Find matching vertical edge
                const unsigned short x = (unsigned short)va[0];
                unsigned short zmin = (unsigned short)va[2];
                unsigned short zmax = (unsigned short)vb[2];
                if (zmin > zmax)
                    dtSwap(zmin, zmax);
                
                for (int m = 0; m < edgeCount; ++m)
                {
                    rcEdge& e = edges[m];
                    // Skip connected edges.
                    if (e.poly[0] != e.poly[1])
                        continue;
                    const unsigned short* eva = &verts[e.vert[0]*3];
                    const unsigned short* evb = &verts[e.vert[1]*3];
                    if (eva[0] == x && evb[0] == x)
                    {
                        unsigned short ezmin = eva[2];
                        unsigned short ezmax = evb[2];
                        if (ezmin > ezmax)
                            dtSwap(ezmin, ezmax);
                        if (overlapRangeExl(zmin,zmax, ezmin, ezmax))
                        {
                            // Reuse the other polyedge to store dir.
                            e.polyEdge[1] = dir;
                        }
                    }
                }
            }
            else
            {
                // Find matching vertical edge
                const unsigned short z = (unsigned short)va[2];
                unsigned short xmin = (unsigned short)va[0];
                unsigned short xmax = (unsigned short)vb[0];
                if (xmin > xmax)
                    dtSwap(xmin, xmax);
                for (int m = 0; m < edgeCount; ++m)
                {
                    rcEdge& e = edges[m];
                    // Skip connected edges.
                    if (e.poly[0] != e.poly[1])
                        continue;
                    const unsigned short* eva = &verts[e.vert[0]*3];
                    const unsigned short* evb = &verts[e.vert[1]*3];
                    if (eva[2] == z && evb[2] == z)
                    {
                        unsigned short exmin = eva[0];
                        unsigned short exmax = evb[0];
                        if (exmin > exmax)
                            dtSwap(exmin, exmax);
                        if (overlapRangeExl(xmin,xmax, exmin, exmax))
                        {
                            // Reuse the other polyedge to store dir.
                            e.polyEdge[1] = dir;
                        }
                    }
                }
            }
        }
    }
    
    
    // Store adjacency
    for (int i = 0; i < edgeCount; ++i)
    {
        const rcEdge& e = edges[i];
        if (e.poly[0] != e.poly[1])
        {
            unsigned short* p0 = &polys[e.poly[0]*MAX_VERTS_PER_POLY*2];
            unsigned short* p1 = &polys[e.poly[1]*MAX_VERTS_PER_POLY*2];
            p0[MAX_VERTS_PER_POLY + e.polyEdge[0]] = e.poly[1];
            p1[MAX_VERTS_PER_POLY + e.polyEdge[1]] = e.poly[0];
        }
        else if (e.polyEdge[1] != 0xff)
        {
            unsigned short* p0 = &polys[e.poly[0]*MAX_VERTS_PER_POLY*2];
            p0[MAX_VERTS_PER_POLY + e.polyEdge[0]] = 0x8000 | (unsigned short)e.polyEdge[1];
        }
        
    }
    
    return true;
}


inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }

inline int area2(const unsigned char* a, const unsigned char* b, const unsigned char* c)
{
    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]);
}

//    Exclusive or: true iff exactly one argument is true.
//    The arguments are negated to ensure that they are 0/1
//    values.  Then the bitwise Xor operator may apply.
//    (This idea is due to Michael Baldwin.)
inline bool xorb(bool x, bool y)
{
    return !x ^ !y;
}

// Returns true iff c is strictly to the left of the directed
// line through a to b.
inline bool left(const unsigned char* a, const unsigned char* b, const unsigned char* c)
{
    return area2(a, b, c) < 0;
}

inline bool leftOn(const unsigned char* a, const unsigned char* b, const unsigned char* c)
{
    return area2(a, b, c) <= 0;
}

inline bool collinear(const unsigned char* a, const unsigned char* b, const unsigned char* c)
{
    return area2(a, b, c) == 0;
}

//    Returns true iff ab properly intersects cd: they share
//    a point interior to both segments.  The properness of the
//    intersection is ensured by using strict leftness.
static bool intersectProp(const unsigned char* a, const unsigned char* b,
                          const unsigned char* c, const unsigned char* d)
{
    // Eliminate improper cases.
    if (collinear(a,b,c) || collinear(a,b,d) ||
        collinear(c,d,a) || collinear(c,d,b))
        return false;
    
    return xorb(left(a,b,c), left(a,b,d)) && xorb(left(c,d,a), left(c,d,b));
}

// Returns T iff (a,b,c) are collinear and point c lies 
// on the closed segement ab.
static bool between(const unsigned char* a, const unsigned char* b, const unsigned char* c)
{
    if (!collinear(a, b, c))
        return false;
    // If ab not vertical, check betweenness on x; else on y.
    if (a[0] != b[0])
        return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0]));
    else
        return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2]));
}

// Returns true iff segments ab and cd intersect, properly or improperly.
static bool intersect(const unsigned char* a, const unsigned char* b,
                      const unsigned char* c, const unsigned char* d)
{
    if (intersectProp(a, b, c, d))
        return true;
    else if (between(a, b, c) || between(a, b, d) ||
             between(c, d, a) || between(c, d, b))
        return true;
    else
        return false;
}

static bool vequal(const unsigned char* a, const unsigned char* b)
{
    return a[0] == b[0] && a[2] == b[2];
}

// Returns T iff (v_i, v_j) is a proper internal *or* external
// diagonal of P, *ignoring edges incident to v_i and v_j*.
static bool diagonalie(int i, int j, int n, const unsigned char* verts, const unsigned short* indices)
{
    const unsigned char* d0 = &verts[(indices[i] & 0x7fff) * 4];
    const unsigned char* d1 = &verts[(indices[j] & 0x7fff) * 4];
    
    // For each edge (k,k+1) of P
    for (int k = 0; k < n; k++)
    {
        int k1 = next(k, n);
        // Skip edges incident to i or j
        if (!((k == i) || (k1 == i) || (k == j) || (k1 == j)))
        {
            const unsigned char* p0 = &verts[(indices[k] & 0x7fff) * 4];
            const unsigned char* p1 = &verts[(indices[k1] & 0x7fff) * 4];
            
            if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
                continue;
            
            if (intersect(d0, d1, p0, p1))
                return false;
        }
    }
    return true;
}

// Returns true iff the diagonal (i,j) is strictly internal to the 
// polygon P in the neighborhood of the i endpoint.
static bool    inCone(int i, int j, int n, const unsigned char* verts, const unsigned short* indices)
{
    const unsigned char* pi = &verts[(indices[i] & 0x7fff) * 4];
    const unsigned char* pj = &verts[(indices[j] & 0x7fff) * 4];
    const unsigned char* pi1 = &verts[(indices[next(i, n)] & 0x7fff) * 4];
    const unsigned char* pin1 = &verts[(indices[prev(i, n)] & 0x7fff) * 4];
    
    // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
    if (leftOn(pin1, pi, pi1))
        return left(pi, pj, pin1) && left(pj, pi, pi1);
    // Assume (i-1,i,i+1) not collinear.
    // else P[i] is reflex.
    return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
}

// Returns T iff (v_i, v_j) is a proper internal
// diagonal of P.
static bool diagonal(int i, int j, int n, const unsigned char* verts, const unsigned short* indices)
{
    return inCone(i, j, n, verts, indices) && diagonalie(i, j, n, verts, indices);
}

static int triangulate(int n, const unsigned char* verts, unsigned short* indices, unsigned short* tris)
{
    int ntris = 0;
    unsigned short* dst = tris;
    
    // The last bit of the index is used to indicate if the vertex can be removed.
    for (int i = 0; i < n; i++)
    {
        int i1 = next(i, n);
        int i2 = next(i1, n);
        if (diagonal(i, i2, n, verts, indices))
            indices[i1] |= 0x8000;
    }
    
    while (n > 3)
    {
        int minLen = -1;
        int mini = -1;
        for (int i = 0; i < n; i++)
        {
            int i1 = next(i, n);
            if (indices[i1] & 0x8000)
            {
                const unsigned char* p0 = &verts[(indices[i] & 0x7fff) * 4];
                const unsigned char* p2 = &verts[(indices[next(i1, n)] & 0x7fff) * 4];
                
                const int dx = (int)p2[0] - (int)p0[0];
                const int dz = (int)p2[2] - (int)p0[2];
                const int len = dx*dx + dz*dz;
                if (minLen < 0 || len < minLen)
                {
                    minLen = len;
                    mini = i;
                }
            }
        }
        
        if (mini == -1)
        {
            // Should not happen.
            /*            printf("mini == -1 ntris=%d n=%d\n", ntris, n);
             for (int i = 0; i < n; i++)
             {
             printf("%d ", indices[i] & 0x0fffffff);
             }
             printf("\n");*/
            return -ntris;
        }
        
        int i = mini;
        int i1 = next(i, n);
        int i2 = next(i1, n);
        
        *dst++ = indices[i] & 0x7fff;
        *dst++ = indices[i1] & 0x7fff;
        *dst++ = indices[i2] & 0x7fff;
        ntris++;
        
        // Removes P[i1] by copying P[i+1]...P[n-1] left one index.
        n--;
        for (int k = i1; k < n; k++)
            indices[k] = indices[k+1];
        
        if (i1 >= n) i1 = 0;
        i = prev(i1,n);
        // Update diagonal flags.
        if (diagonal(prev(i, n), i1, n, verts, indices))
            indices[i] |= 0x8000;
        else
            indices[i] &= 0x7fff;
        
        if (diagonal(i, next(i1, n), n, verts, indices))
            indices[i1] |= 0x8000;
        else
            indices[i1] &= 0x7fff;
    }
    
    // Append the remaining triangle.
    *dst++ = indices[0] & 0x7fff;
    *dst++ = indices[1] & 0x7fff;
    *dst++ = indices[2] & 0x7fff;
    ntris++;
    
    return ntris;
}


static int countPolyVerts(const unsigned short* p)
{
    for (int i = 0; i < MAX_VERTS_PER_POLY; ++i)
        if (p[i] == DT_TILECACHE_NULL_IDX)
            return i;
    return MAX_VERTS_PER_POLY;
}

inline bool uleft(const unsigned short* a, const unsigned short* b, const unsigned short* c)
{
    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]) < 0;
}

static int getPolyMergeValue(unsigned short* pa, unsigned short* pb,
                             const unsigned short* verts, int& ea, int& eb)
{
    const int na = countPolyVerts(pa);
    const int nb = countPolyVerts(pb);
    
    // If the merged polygon would be too big, do not merge.
    if (na+nb-2 > MAX_VERTS_PER_POLY)
        return -1;
    
    // Check if the polygons share an edge.
    ea = -1;
    eb = -1;
    
    for (int i = 0; i < na; ++i)
    {
        unsigned short va0 = pa[i];
        unsigned short va1 = pa[(i+1) % na];
        if (va0 > va1)
            dtSwap(va0, va1);
        for (int j = 0; j < nb; ++j)
        {
            unsigned short vb0 = pb[j];
            unsigned short vb1 = pb[(j+1) % nb];
            if (vb0 > vb1)
                dtSwap(vb0, vb1);
            if (va0 == vb0 && va1 == vb1)
            {
                ea = i;
                eb = j;
                break;
            }
        }
    }
    
    // No common edge, cannot merge.
    if (ea == -1 || eb == -1)
        return -1;
    
    // Check to see if the merged polygon would be convex.
    unsigned short va, vb, vc;
    
    va = pa[(ea+na-1) % na];
    vb = pa[ea];
    vc = pb[(eb+2) % nb];
    if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3]))
        return -1;
    
    va = pb[(eb+nb-1) % nb];
    vb = pb[eb];
    vc = pa[(ea+2) % na];
    if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3]))
        return -1;
    
    va = pa[ea];
    vb = pa[(ea+1)%na];
    
    int dx = (int)verts[va*3+0] - (int)verts[vb*3+0];
    int dy = (int)verts[va*3+2] - (int)verts[vb*3+2];
    
    return dx*dx + dy*dy;
}

static void mergePolys(unsigned short* pa, unsigned short* pb, int ea, int eb)
{
    unsigned short tmp[MAX_VERTS_PER_POLY*2];
    
    const int na = countPolyVerts(pa);
    const int nb = countPolyVerts(pb);
    
    // Merge polygons.
    memset(tmp, 0xff, sizeof(unsigned short)*MAX_VERTS_PER_POLY*2);
    int n = 0;
    // Add pa
    for (int i = 0; i < na-1; ++i)
        tmp[n++] = pa[(ea+1+i) % na];
    // Add pb
    for (int i = 0; i < nb-1; ++i)
        tmp[n++] = pb[(eb+1+i) % nb];
    
    memcpy(pa, tmp, sizeof(unsigned short)*MAX_VERTS_PER_POLY);
}


static void pushFront(unsigned short v, unsigned short* arr, int& an)
{
    an++;
    for (int i = an-1; i > 0; --i)
        arr[i] = arr[i-1];
    arr[0] = v;
}

static void pushBack(unsigned short v, unsigned short* arr, int& an)
{
    arr[an] = v;
    an++;
}

static bool canRemoveVertex(dtTileCachePolyMesh& mesh, const unsigned short rem)
{
    // Count number of polygons to remove.
    int numRemovedVerts = 0;
    int numTouchedVerts = 0;
    int numRemainingEdges = 0;
    for (int i = 0; i < mesh.npolys; ++i)
    {
        unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
        const int nv = countPolyVerts(p);
        int numRemoved = 0;
        int numVerts = 0;
        for (int j = 0; j < nv; ++j)
        {
            if (p[j] == rem)
            {
                numTouchedVerts++;
                numRemoved++;
            }
            numVerts++;
        }
        if (numRemoved)
        {
            numRemovedVerts += numRemoved;
            numRemainingEdges += numVerts-(numRemoved+1);
        }
    }
    
    // There would be too few edges remaining to create a polygon.
    // This can happen for example when a tip of a triangle is marked
    // as deletion, but there are no other polys that share the vertex.
    // In this case, the vertex should not be removed.
    if (numRemainingEdges <= 2)
        return false;
    
    // Check that there is enough memory for the test.
    const int maxEdges = numTouchedVerts*2;
    if (maxEdges > MAX_REM_EDGES)
        return false;
    
    // Find edges which share the removed vertex.
    unsigned short edges[MAX_REM_EDGES];
    int nedges = 0;
    
    for (int i = 0; i < mesh.npolys; ++i)
    {
        unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
        const int nv = countPolyVerts(p);
        
        // Collect edges which touches the removed vertex.
        for (int j = 0, k = nv-1; j < nv; k = j++)
        {
            if (p[j] == rem || p[k] == rem)
            {
                // Arrange edge so that a=rem.
                int a = p[j], b = p[k];
                if (b == rem)
                    dtSwap(a,b);
                
                // Check if the edge exists
                bool exists = false;
                for (int m = 0; m < nedges; ++m)
                {
                    unsigned short* e = &edges[m*3];
                    if (e[1] == b)
                    {
                        // Exists, increment vertex share count.
                        e[2]++;
                        exists = true;
                    }
                }
                // Add new edge.
                if (!exists)
                {
                    unsigned short* e = &edges[nedges*3];
                    e[0] = (unsigned short)a;
                    e[1] = (unsigned short)b;
                    e[2] = 1;
                    nedges++;
                }
            }
        }
    }
    
    // There should be no more than 2 open edges.
    // This catches the case that two non-adjacent polygons
    // share the removed vertex. In that case, do not remove the vertex.
    int numOpenEdges = 0;
    for (int i = 0; i < nedges; ++i)
    {
        if (edges[i*3+2] < 2)
            numOpenEdges++;
    }
    if (numOpenEdges > 2)
        return false;
    
    return true;
}

static dtStatus removeVertex(dtTileCachePolyMesh& mesh, const unsigned short rem, const int maxTris)
{
    // Count number of polygons to remove.
    int numRemovedVerts = 0;
    for (int i = 0; i < mesh.npolys; ++i)
    {
        unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
        const int nv = countPolyVerts(p);
        for (int j = 0; j < nv; ++j)
        {
            if (p[j] == rem)
                numRemovedVerts++;
        }
    }
    
    int nedges = 0;
    unsigned short edges[MAX_REM_EDGES*3];
    int nhole = 0;
    unsigned short hole[MAX_REM_EDGES];
    int nharea = 0;
    unsigned short harea[MAX_REM_EDGES];
    
    for (int i = 0; i < mesh.npolys; ++i)
    {
        unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
        const int nv = countPolyVerts(p);
        bool hasRem = false;
        for (int j = 0; j < nv; ++j)
            if (p[j] == rem) hasRem = true;
        if (hasRem)
        {
            // Collect edges which does not touch the removed vertex.
            for (int j = 0, k = nv-1; j < nv; k = j++)
            {
                if (p[j] != rem && p[k] != rem)
                {
                    if (nedges >= MAX_REM_EDGES)
                        return DT_FAILURE | DT_BUFFER_TOO_SMALL;
                    unsigned short* e = &edges[nedges*3];
                    e[0] = p[k];
                    e[1] = p[j];
                    e[2] = mesh.areas[i];
                    nedges++;
                }
            }
            // Remove the polygon.
            unsigned short* p2 = &mesh.polys[(mesh.npolys-1)*MAX_VERTS_PER_POLY*2];
            memcpy(p,p2,sizeof(unsigned short)*MAX_VERTS_PER_POLY);
            memset(p+MAX_VERTS_PER_POLY,0xff,sizeof(unsigned short)*MAX_VERTS_PER_POLY);
            mesh.areas[i] = mesh.areas[mesh.npolys-1];
            mesh.npolys--;
            --i;
        }
    }
    
    // Remove vertex.
    for (int i = (int)rem; i < mesh.nverts; ++i)
    {
        mesh.verts[i*3+0] = mesh.verts[(i+1)*3+0];
        mesh.verts[i*3+1] = mesh.verts[(i+1)*3+1];
        mesh.verts[i*3+2] = mesh.verts[(i+1)*3+2];
    }
    mesh.nverts--;
    
    // Adjust indices to match the removed vertex layout.
    for (int i = 0; i < mesh.npolys; ++i)
    {
        unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
        const int nv = countPolyVerts(p);
        for (int j = 0; j < nv; ++j)
            if (p[j] > rem) p[j]--;
    }
    for (int i = 0; i < nedges; ++i)
    {
        if (edges[i*3+0] > rem) edges[i*3+0]--;
        if (edges[i*3+1] > rem) edges[i*3+1]--;
    }
    
    if (nedges == 0)
        return DT_SUCCESS;
    
    // Start with one vertex, keep appending connected
    // segments to the start and end of the hole.
    pushBack(edges[0], hole, nhole);
    pushBack(edges[2], harea, nharea);
    
    while (nedges)
    {
        bool match = false;
        
        for (int i = 0; i < nedges; ++i)
        {
            const unsigned short ea = edges[i*3+0];
            const unsigned short eb = edges[i*3+1];
            const unsigned short a = edges[i*3+2];
            bool add = false;
            if (hole[0] == eb)
            {
                // The segment matches the beginning of the hole boundary.
                if (nhole >= MAX_REM_EDGES)
                    return DT_FAILURE | DT_BUFFER_TOO_SMALL;
                pushFront(ea, hole, nhole);
                pushFront(a, harea, nharea);
                add = true;
            }
            else if (hole[nhole-1] == ea)
            {
                // The segment matches the end of the hole boundary.
                if (nhole >= MAX_REM_EDGES)
                    return DT_FAILURE | DT_BUFFER_TOO_SMALL;
                pushBack(eb, hole, nhole);
                pushBack(a, harea, nharea);
                add = true;
            }
            if (add)
            {
                // The edge segment was added, remove it.
                edges[i*3+0] = edges[(nedges-1)*3+0];
                edges[i*3+1] = edges[(nedges-1)*3+1];
                edges[i*3+2] = edges[(nedges-1)*3+2];
                --nedges;
                match = true;
                --i;
            }
        }
        
        if (!match)
            break;
    }
    
    
    unsigned short tris[MAX_REM_EDGES*3];
    unsigned char tverts[MAX_REM_EDGES*3];
    unsigned short tpoly[MAX_REM_EDGES*3];
    
    // Generate temp vertex array for triangulation.
    for (int i = 0; i < nhole; ++i)
    {
        const unsigned short pi = hole[i];
        tverts[i*4+0] = (unsigned char)mesh.verts[pi*3+0];
        tverts[i*4+1] = (unsigned char)mesh.verts[pi*3+1];
        tverts[i*4+2] = (unsigned char)mesh.verts[pi*3+2];
        tverts[i*4+3] = 0;
        tpoly[i] = (unsigned short)i;
    }
    
    // Triangulate the hole.
    int ntris = triangulate(nhole, tverts, tpoly, tris);
    if (ntris < 0)
    {
        // TODO: issue warning!
        ntris = -ntris;
    }
    
    if (ntris > MAX_REM_EDGES)
        return DT_FAILURE | DT_BUFFER_TOO_SMALL;
    
    unsigned short polys[MAX_REM_EDGES*MAX_VERTS_PER_POLY];
    unsigned char pareas[MAX_REM_EDGES];
    
    // Build initial polygons.
    int npolys = 0;
    memset(polys, 0xff, ntris*MAX_VERTS_PER_POLY*sizeof(unsigned short));
    for (int j = 0; j < ntris; ++j)
    {
        unsigned short* t = &tris[j*3];
        if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])
        {
            polys[npolys*MAX_VERTS_PER_POLY+0] = hole[t[0]];
            polys[npolys*MAX_VERTS_PER_POLY+1] = hole[t[1]];
            polys[npolys*MAX_VERTS_PER_POLY+2] = hole[t[2]];
            pareas[npolys] = (unsigned char)harea[t[0]];
            npolys++;
        }
    }
    if (!npolys)
        return DT_SUCCESS;
    
    // Merge polygons.
    int maxVertsPerPoly = MAX_VERTS_PER_POLY;
    if (maxVertsPerPoly > 3)
    {
        for (;;)
        {
            // Find best polygons to merge.
            int bestMergeVal = 0;
            int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0;
            
            for (int j = 0; j < npolys-1; ++j)
            {
                unsigned short* pj = &polys[j*MAX_VERTS_PER_POLY];
                for (int k = j+1; k < npolys; ++k)
                {
                    unsigned short* pk = &polys[k*MAX_VERTS_PER_POLY];
                    int ea, eb;
                    int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb);
                    if (v > bestMergeVal)
                    {
                        bestMergeVal = v;
                        bestPa = j;
                        bestPb = k;
                        bestEa = ea;
                        bestEb = eb;
                    }
                }
            }
            
            if (bestMergeVal > 0)
            {
                // Found best, merge.
                unsigned short* pa = &polys[bestPa*MAX_VERTS_PER_POLY];
                unsigned short* pb = &polys[bestPb*MAX_VERTS_PER_POLY];
                mergePolys(pa, pb, bestEa, bestEb);
                memcpy(pb, &polys[(npolys-1)*MAX_VERTS_PER_POLY], sizeof(unsigned short)*MAX_VERTS_PER_POLY);
                pareas[bestPb] = pareas[npolys-1];
                npolys--;
            }
            else
            {
                // Could not merge any polygons, stop.
                break;
            }
        }
    }
    
    // Store polygons.
    for (int i = 0; i < npolys; ++i)
    {
        if (mesh.npolys >= maxTris) break;
        unsigned short* p = &mesh.polys[mesh.npolys*MAX_VERTS_PER_POLY*2];
        memset(p,0xff,sizeof(unsigned short)*MAX_VERTS_PER_POLY*2);
        for (int j = 0; j < MAX_VERTS_PER_POLY; ++j)
            p[j] = polys[i*MAX_VERTS_PER_POLY+j];
        mesh.areas[mesh.npolys] = pareas[i];
        mesh.npolys++;
        if (mesh.npolys > maxTris)
            return DT_FAILURE | DT_BUFFER_TOO_SMALL;
    }
    
    return DT_SUCCESS;
}


dtStatus dtBuildTileCachePolyMesh(dtTileCacheAlloc* alloc,
                                  dtTileCacheContourSet& lcset,
                                  dtTileCachePolyMesh& mesh)
{
    dtAssert(alloc);
    
    int maxVertices = 0;
    int maxTris = 0;
    int maxVertsPerCont = 0;
    for (int i = 0; i < lcset.nconts; ++i)
    {
        // Skip null contours.
        if (lcset.conts[i].nverts < 3) continue;
        maxVertices += lcset.conts[i].nverts;
        maxTris += lcset.conts[i].nverts - 2;
        maxVertsPerCont = dtMax(maxVertsPerCont, lcset.conts[i].nverts);
    }

    // TODO: warn about too many vertices?
    
    mesh.nvp = MAX_VERTS_PER_POLY;
    
    dtFixedArray<unsigned char> vflags(alloc, maxVertices);
    if (!vflags)
        return DT_FAILURE | DT_OUT_OF_MEMORY;
    memset(vflags, 0, maxVertices);
    
    mesh.verts = (unsigned short*)alloc->alloc(sizeof(unsigned short)*maxVertices*3);
    if (!mesh.verts)
        return DT_FAILURE | DT_OUT_OF_MEMORY;
    
    mesh.polys = (unsigned short*)alloc->alloc(sizeof(unsigned short)*maxTris*MAX_VERTS_PER_POLY*2);
    if (!mesh.polys)
        return DT_FAILURE | DT_OUT_OF_MEMORY;

    mesh.areas = (unsigned char*)alloc->alloc(sizeof(unsigned char)*maxTris);
    if (!mesh.areas)
        return DT_FAILURE | DT_OUT_OF_MEMORY;

    mesh.flags = (unsigned short*)alloc->alloc(sizeof(unsigned short)*maxTris);
    if (!mesh.flags)
        return DT_FAILURE | DT_OUT_OF_MEMORY;

    // Just allocate and clean the mesh flags array. The user is resposible for filling it.
    memset(mesh.flags, 0, sizeof(unsigned short) * maxTris);
        
    mesh.nverts = 0;
    mesh.npolys = 0;
    
    memset(mesh.verts, 0, sizeof(unsigned short)*maxVertices*3);
    memset(mesh.polys, 0xff, sizeof(unsigned short)*maxTris*MAX_VERTS_PER_POLY*2);
    memset(mesh.areas, 0, sizeof(unsigned char)*maxTris);
    
    unsigned short firstVert[VERTEX_BUCKET_COUNT2];
    for (int i = 0; i < VERTEX_BUCKET_COUNT2; ++i)
        firstVert[i] = DT_TILECACHE_NULL_IDX;
    
    dtFixedArray<unsigned short> nextVert(alloc, maxVertices);
    if (!nextVert)
        return DT_FAILURE | DT_OUT_OF_MEMORY;
    memset(nextVert, 0, sizeof(unsigned short)*maxVertices);
    
    dtFixedArray<unsigned short> indices(alloc, maxVertsPerCont);
    if (!indices)
        return DT_FAILURE | DT_OUT_OF_MEMORY;
    
    dtFixedArray<unsigned short> tris(alloc, maxVertsPerCont*3);
    if (!tris)
        return DT_FAILURE | DT_OUT_OF_MEMORY;

    dtFixedArray<unsigned short> polys(alloc, maxVertsPerCont*MAX_VERTS_PER_POLY);
    if (!polys)
        return DT_FAILURE | DT_OUT_OF_MEMORY;
    
    for (int i = 0; i < lcset.nconts; ++i)
    {
        dtTileCacheContour& cont = lcset.conts[i];
        
        // Skip null contours.
        if (cont.nverts < 3)
            continue;
        
        // Triangulate contour
        for (int j = 0; j < cont.nverts; ++j)
            indices[j] = (unsigned short)j;
        
        int ntris = triangulate(cont.nverts, cont.verts, &indices[0], &tris[0]);
        if (ntris <= 0)
        {
            // TODO: issue warning!
            ntris = -ntris;
        }
        
        // Add and merge vertices.
        for (int j = 0; j < cont.nverts; ++j)
        {
            const unsigned char* v = &cont.verts[j*4];
            indices[j] = addVertex((unsigned short)v[0], (unsigned short)v[1], (unsigned short)v[2],
                                   mesh.verts, firstVert, nextVert, mesh.nverts);
            if (v[3] & 0x80)
            {
                // This vertex should be removed.
                vflags[indices[j]] = 1;
            }
        }
        
        // Build initial polygons.
        int npolys = 0;
        memset(polys, 0xff, sizeof(unsigned short) * maxVertsPerCont * MAX_VERTS_PER_POLY);
        for (int j = 0; j < ntris; ++j)
        {
            const unsigned short* t = &tris[j*3];
            if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])
            {
                polys[npolys*MAX_VERTS_PER_POLY+0] = indices[t[0]];
                polys[npolys*MAX_VERTS_PER_POLY+1] = indices[t[1]];
                polys[npolys*MAX_VERTS_PER_POLY+2] = indices[t[2]];
                npolys++;
            }
        }
        if (!npolys)
            continue;
        
        // Merge polygons.
        int maxVertsPerPoly =MAX_VERTS_PER_POLY ;
        if (maxVertsPerPoly > 3)
        {
            for(;;)
            {
                // Find best polygons to merge.
                int bestMergeVal = 0;
                int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0;
                
                for (int j = 0; j < npolys-1; ++j)
                {
                    unsigned short* pj = &polys[j*MAX_VERTS_PER_POLY];
                    for (int k = j+1; k < npolys; ++k)
                    {
                        unsigned short* pk = &polys[k*MAX_VERTS_PER_POLY];
                        int ea, eb;
                        int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb);
                        if (v > bestMergeVal)
                        {
                            bestMergeVal = v;
                            bestPa = j;
                            bestPb = k;
                            bestEa = ea;
                            bestEb = eb;
                        }
                    }
                }
                
                if (bestMergeVal > 0)
                {
                    // Found best, merge.
                    unsigned short* pa = &polys[bestPa*MAX_VERTS_PER_POLY];
                    unsigned short* pb = &polys[bestPb*MAX_VERTS_PER_POLY];
                    mergePolys(pa, pb, bestEa, bestEb);
                    memcpy(pb, &polys[(npolys-1)*MAX_VERTS_PER_POLY], sizeof(unsigned short)*MAX_VERTS_PER_POLY);
                    npolys--;
                }
                else
                {
                    // Could not merge any polygons, stop.
                    break;
                }
            }
        }
        
        // Store polygons.
        for (int j = 0; j < npolys; ++j)
        {
            unsigned short* p = &mesh.polys[mesh.npolys*MAX_VERTS_PER_POLY*2];
            unsigned short* q = &polys[j*MAX_VERTS_PER_POLY];
            for (int k = 0; k < MAX_VERTS_PER_POLY; ++k)
                p[k] = q[k];
            mesh.areas[mesh.npolys] = cont.area;
            mesh.npolys++;
            if (mesh.npolys > maxTris)
                return DT_FAILURE | DT_BUFFER_TOO_SMALL;
        }
    }
    
    
    // Remove edge vertices.
    for (int i = 0; i < mesh.nverts; ++i)
    {
        if (vflags[i])
        {
            if (!canRemoveVertex(mesh, (unsigned short)i))
                continue;
            dtStatus status = removeVertex(mesh, (unsigned short)i, maxTris);
            if (dtStatusFailed(status))
                return status;
            // Remove vertex
            // Note: mesh.nverts is already decremented inside removeVertex()!
            for (int j = i; j < mesh.nverts; ++j)
                vflags[j] = vflags[j+1];
            --i;
        }
    }
    
    // Calculate adjacency.
    if (!buildMeshAdjacency(alloc, mesh.polys, mesh.npolys, mesh.verts, mesh.nverts, lcset))
        return DT_FAILURE | DT_OUT_OF_MEMORY;
        
    return DT_SUCCESS;
}

dtStatus dtMarkCylinderArea(dtTileCacheLayer& layer, const float* orig, const float cs, const float ch,
                            const float* pos, const float radius, const float height, const unsigned char areaId)
{
    float bmin[3], bmax[3];
    bmin[0] = pos[0] - radius;
    bmin[1] = pos[1];
    bmin[2] = pos[2] - radius;
    bmax[0] = pos[0] + radius;
    bmax[1] = pos[1] + height;
    bmax[2] = pos[2] + radius;
    const float r2 = dtSqr(radius/cs + 0.5f);

    const int w = (int)layer.header->width;
    const int h = (int)layer.header->height;
    const float ics = 1.0f/cs;
    const float ich = 1.0f/ch;
    
    const float px = (pos[0]-orig[0])*ics;
    const float pz = (pos[2]-orig[2])*ics;
    
    int minx = (int)dtMathFloorf((bmin[0]-orig[0])*ics);
    int miny = (int)dtMathFloorf((bmin[1]-orig[1])*ich);
    int minz = (int)dtMathFloorf((bmin[2]-orig[2])*ics);
    int maxx = (int)dtMathFloorf((bmax[0]-orig[0])*ics);
    int maxy = (int)dtMathFloorf((bmax[1]-orig[1])*ich);
    int maxz = (int)dtMathFloorf((bmax[2]-orig[2])*ics);

    if (maxx < 0) return DT_SUCCESS;
    if (minx >= w) return DT_SUCCESS;
    if (maxz < 0) return DT_SUCCESS;
    if (minz >= h) return DT_SUCCESS;
    
    if (minx < 0) minx = 0;
    if (maxx >= w) maxx = w-1;
    if (minz < 0) minz = 0;
    if (maxz >= h) maxz = h-1;
    
    for (int z = minz; z <= maxz; ++z)
    {
        for (int x = minx; x <= maxx; ++x)
        {
            const float dx = (float)(x+0.5f) - px;
            const float dz = (float)(z+0.5f) - pz;
            if (dx*dx + dz*dz > r2)
                continue;
            const int y = layer.heights[x+z*w];
            if (y < miny || y > maxy)
                continue;
            layer.areas[x+z*w] = areaId;
        }
    }

    return DT_SUCCESS;
}


dtStatus dtBuildTileCacheLayer(dtTileCacheCompressor* comp,
                               dtTileCacheLayerHeader* header,
                               const unsigned char* heights,
                               const unsigned char* areas,
                               const unsigned char* cons,
                               unsigned char** outData, int* outDataSize)
{
    const int headerSize = dtAlign4(sizeof(dtTileCacheLayerHeader));
    const int gridSize = (int)header->width * (int)header->height;
    const int maxDataSize = headerSize + comp->maxCompressedSize(gridSize*3);
    unsigned char* data = (unsigned char*)dtAlloc(maxDataSize, DT_ALLOC_PERM);
    if (!data)
        return DT_FAILURE | DT_OUT_OF_MEMORY;
    memset(data, 0, maxDataSize);
    
    // Store header
    memcpy(data, header, sizeof(dtTileCacheLayerHeader));
    
    // Concatenate grid data for compression.
    const int bufferSize = gridSize*3;
    unsigned char* buffer = (unsigned char*)dtAlloc(bufferSize, DT_ALLOC_TEMP);
    if (!buffer)
        return DT_FAILURE | DT_OUT_OF_MEMORY;
    memcpy(buffer, heights, gridSize);
    memcpy(buffer+gridSize, areas, gridSize);
    memcpy(buffer+gridSize*2, cons, gridSize);
    
    // Compress
    unsigned char* compressed = data + headerSize;
    const int maxCompressedSize = maxDataSize - headerSize;
    int compressedSize = 0;
    dtStatus status = comp->compress(buffer, bufferSize, compressed, maxCompressedSize, &compressedSize);
    if (dtStatusFailed(status))
        return status;

    *outData = data;
    *outDataSize = headerSize + compressedSize;
    
    dtFree(buffer);
    
    return DT_SUCCESS;
}

void dtFreeTileCacheLayer(dtTileCacheAlloc* alloc, dtTileCacheLayer* layer)
{
    dtAssert(alloc);
    // The layer is allocated as one conitguous blob of data.
    alloc->free(layer);
}

dtStatus dtDecompressTileCacheLayer(dtTileCacheAlloc* alloc, dtTileCacheCompressor* comp,
                                    unsigned char* compressed, const int compressedSize,
                                    dtTileCacheLayer** layerOut)
{
    dtAssert(alloc);
    dtAssert(comp);

    if (!layerOut)
        return DT_FAILURE | DT_INVALID_PARAM;
    if (!compressed)
        return DT_FAILURE | DT_INVALID_PARAM;

    *layerOut = 0;

    dtTileCacheLayerHeader* compressedHeader = (dtTileCacheLayerHeader*)compressed;
    if (compressedHeader->magic != DT_TILECACHE_MAGIC)
        return DT_FAILURE | DT_WRONG_MAGIC;
    if (compressedHeader->version != DT_TILECACHE_VERSION)
        return DT_FAILURE | DT_WRONG_VERSION;
    
    const int layerSize = dtAlign4(sizeof(dtTileCacheLayer));
    const int headerSize = dtAlign4(sizeof(dtTileCacheLayerHeader));
    const int gridSize = (int)compressedHeader->width * (int)compressedHeader->height;
    const int bufferSize = layerSize + headerSize + gridSize*4;
    
    unsigned char* buffer = (unsigned char*)alloc->alloc(bufferSize);
    if (!buffer)
        return DT_FAILURE | DT_OUT_OF_MEMORY;
    memset(buffer, 0, bufferSize);

    dtTileCacheLayer* layer = (dtTileCacheLayer*)buffer;
    dtTileCacheLayerHeader* header = (dtTileCacheLayerHeader*)(buffer + layerSize);
    unsigned char* grids = buffer + layerSize + headerSize;
    const int gridsSize = bufferSize - (layerSize + headerSize); 
    
    // Copy header
    memcpy(header, compressedHeader, headerSize);
    // Decompress grid.
    int size = 0;
    dtStatus status = comp->decompress(compressed+headerSize, compressedSize-headerSize,
                                       grids, gridsSize, &size);
    if (dtStatusFailed(status))
    {
        dtFree(buffer);
        return status;
    }
    
    layer->header = header;
    layer->heights = grids;
    layer->areas = grids + gridSize;
    layer->cons = grids + gridSize*2;
    layer->regs = grids + gridSize*3;
    
    *layerOut = layer;
    
    return DT_SUCCESS;
}



bool dtTileCacheHeaderSwapEndian(unsigned char* data, const int dataSize)
{
    dtIgnoreUnused(dataSize);
    dtTileCacheLayerHeader* header = (dtTileCacheLayerHeader*)data;
    
    int swappedMagic = DT_TILECACHE_MAGIC;
    int swappedVersion = DT_TILECACHE_VERSION;
    dtSwapEndian(&swappedMagic);
    dtSwapEndian(&swappedVersion);
    
    if ((header->magic != DT_TILECACHE_MAGIC || header->version != DT_TILECACHE_VERSION) &&
        (header->magic != swappedMagic || header->version != swappedVersion))
    {
        return false;
    }
    
    dtSwapEndian(&header->magic);
    dtSwapEndian(&header->version);
    dtSwapEndian(&header->tx);
    dtSwapEndian(&header->ty);
    dtSwapEndian(&header->tlayer);
    dtSwapEndian(&header->bmin[0]);
    dtSwapEndian(&header->bmin[1]);
    dtSwapEndian(&header->bmin[2]);
    dtSwapEndian(&header->bmax[0]);
    dtSwapEndian(&header->bmax[1]);
    dtSwapEndian(&header->bmax[2]);
    dtSwapEndian(&header->hmin);
    dtSwapEndian(&header->hmax);
    
    // width, height, minx, maxx, miny, maxy are unsigned char, no need to swap.
    
    return true;
}

Commits for Divide-Framework/trunk/Source Code/Libs/src/ReCast/DetourTileCache/Source/DetourTileCacheBuilder.cpp

Diff revisions: vs.
Revision Author Commited Message
337 Diff Diff IonutCava picture IonutCava Wed 17 Dec, 2014 17:25:16 +0000

[Ionut]
- Replaced all tabs with 4 spaces (some spacing may be off now. no way to check all the files.)
- Moved implementation details for ParamHandler, BoundingBox, BoundingSphere and ProfileTimer to proper .inl and .cpp files. (more to follow)
- Update all forward declared enums with the required storage type (as requested by the C++11 standard)

315 Diff Diff IonutCava picture IonutCava Mon 25 Aug, 2014 15:23:33 +0000

[Ionut]
- Update ReCast to the latest version available on GitHub
- Improved nav mesh target point selection
- Added basic “go to enemy flag” logic for the WarScene teams

168 Diff Diff k1ngp1n picture k1ngp1n Sat 26 Oct, 2013 19:03:21 +0000

- Reworked the Camera class[[BR]]
— Now fully quaternion based [[BR]]
— Basic camera types added but not used yet (third person, first person, orbit) [[BR]]
- Cleaned up Material and Texture handling [[BR]]
- Added clipping plane support [[BR]]
— Similar to OpenGL fixed-function clip planes but fully shader driven [[BR]]
— Added a new class, “Plane”, that helps define clip planes [[BR]]
- Optimized the Singleton class to allow faster “getInstance” calls without performance penalties [[BR]]
-- “createInstance” must be called for each singleton class before usage. Or “gerOrCreateInstance” can be used, which is basically the former “getInstance” implementation [[BR]]
- Improved console logging by changing some heap allocations to stack and removing dependencies on the std::string class [[BR]]
- Added a lot of performance optimizations related to coding standards and redundant calculations [[BR]]
— e.g. Frustum AABB check didn’t need to recompute the AABB points as they were calculated already [[BR]]
— e.g. A vector did not need to be set to 0 on initialization as that is already it’s default state on creation [[BR]]
— e.g. Faster Framerate and Timing calculations by using less member variables that are not needed outsied of calling functions [[BR]]
- The SceneState now contains the SceneRenderState and is passed on to the SceneGraph’s update calls [[BR]]
- Better material export/import to/from XML format [[BR]]
- More bug fixes and cleanups [[BR]]

152 Diff Diff k1ngp1n picture k1ngp1n Thu 20 Jun, 2013 14:23:31 +0000

[Ionut] [[BR]]
- New rendering pipeline (experimental and unstable): [[BR]]
— OpenGL 3.x clean context (glLight commands are still used for now, but UBO support is there, but not used yet) [[BR]]
— Custom matrix stacks and UBO based shader data (UBOs cause some link errors on some nVidia cards)[[BR]]
— Multi-threaded texture loading and shader compilation (mt shader compilation disabled for now. needs more tests) [[BR]]
— VAO rendering is self contained (no more enable/disable calls before a draw request) [[BR]]
— Render instance class used for rendering information [[BR]]
[[BR]]
- New unique ID generation base class: GUIDWrapper. Each class that derives from this, gets an application wide unique id on construction [[BR]]
- Added base code for an in-game editor using CEGUI [[BR]]
- Replaced some mutex locks with lockless data structures or atomic data [[BR]]
- CEGUI 0.8.2, FTGL-GL3 and GLIM 0.4 modified to support GLEW_MX if defined [[BR]]
- Dropped VS2008 support [[BR]]
- Networking library, server framework and ReCast files are now projects inside the Divide Framework solution [[BR]]
- New console command “setFov” that modifies the horizontal FoV value in realtime [[BR]]
- New console command “recompileShader” that reparses shader files, recompiles shaders and relinks shader programs who’s names match or contain the argument string [[BR]]
- New debug utility: axis angle drawn in corner of the screen if needed [[BR]]
- More ‘const’-s pasted around the code, more loop performance tweaks (allocations before a loop, tighter loops, etc), more utility member functions added to various classes [[BR]]

151 k1ngp1n picture k1ngp1n Tue 07 May, 2013 00:00:52 +0000

[Ionut] [[BR]]
- Better ReCast integration [[BR]]
— Any entity can be used as an obstacle in the NavMesh if that’s specified in each scene’s assets.xml file for said entity [[BR]]
— New console command, “createNavMesh”, that passes geometry data to ReCast [[BR]]
-— NavMesh generation is not yet complete [[BR]]
- Better PhysX integration [[BR]]
— Each scene passes data to and gets data from the Physics API better and safer[[BR]]
- Multi-threaded support extended: [[BR]]
— Event class replaced with Task [[BR]]
— Kernel uses a threadpool for scene tasks [[BR]]
— Each task can be added to a different threadpool if needed [[BR]]
— Most critical sections use the new boost::atomic wrapper for thread safety [[BR]]
- Rendering system updated [[BR]]
— VBO’s keep track of the geometry type internally [[BR]]
— Rendering by specific element list is internal to the VBO [[BR]]
— VBO’s can draw a “lite” version that doesn’t send Tangent, BiTangent and TexCoord data for depth rendering (disabled) [[BR]]
- Reflectors now offer a preview of the generated reflective texture if needed [[BR]]
- Buttons are now added and rendered by CEGUI [[BR]]
[[BR]]
Deprecation: [[BR]]
- Removed fixed pipeline material system [[BR]]
- Removed BoundingBox late update system [[BR]]
- Shadow references in the material system are now depth references [[BR]]
[[BR]]
Bug fixes: [[BR]]
- Problematic FBO double bind check removed [[BR]]
- Faster terrain rendering via chunk size selection through each scene’s terrain.xml[[BR]]
- Rendering is paused when the window is minimized [[BR]]
- CEGUI and impostors now render properly in deferred rendering mode [[BR]]
- Fixed various level 4 (VS2008) warnings [[BR]]
- Better state management and cleaning [[BR]]
- Better SceneGraph node management and trasformation/AABB update calls [[BR]]
- AITenisScene has proper collisions now [[BR]]