DetourTileCacheBuilder.cpp 54 KB

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