DetourTileCacheBuilder.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150
  1. //
  2. // Copyright (c) 2009-2010 Mikko Mononen [email protected]
  3. //
  4. // This software is provided 'as-is', without any express or implied
  5. // warranty. In no event will the authors be held liable for any damages
  6. // arising from the use of this software.
  7. // Permission is granted to anyone to use this software for any purpose,
  8. // including commercial applications, and to alter it and redistribute it
  9. // freely, subject to the following restrictions:
  10. // 1. The origin of this software must not be misrepresented; you must not
  11. // claim that you wrote the original software. If you use this software
  12. // in a product, an acknowledgment in the product documentation would be
  13. // appreciated but is not required.
  14. // 2. Altered source versions must be plainly marked as such, and must not be
  15. // misrepresented as being the original software.
  16. // 3. This notice may not be removed or altered from any source distribution.
  17. //
  18. #include "DetourCommon.h"
  19. #include "DetourStatus.h"
  20. #include "DetourAssert.h"
  21. #include "DetourTileCacheBuilder.h"
  22. #include <string.h>
  23. #include <math.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. inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; }
  920. inline int next(int i, int n) { return i+1 < n ? i+1 : 0; }
  921. inline int area2(const unsigned char* a, const unsigned char* b, const unsigned char* c)
  922. {
  923. 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]);
  924. }
  925. // Exclusive or: true iff exactly one argument is true.
  926. // The arguments are negated to ensure that they are 0/1
  927. // values. Then the bitwise Xor operator may apply.
  928. // (This idea is due to Michael Baldwin.)
  929. inline bool xorb(bool x, bool y)
  930. {
  931. return !x ^ !y;
  932. }
  933. // Returns true iff c is strictly to the left of the directed
  934. // line through a to b.
  935. inline bool left(const unsigned char* a, const unsigned char* b, const unsigned char* c)
  936. {
  937. return area2(a, b, c) < 0;
  938. }
  939. inline bool leftOn(const unsigned char* a, const unsigned char* b, const unsigned char* c)
  940. {
  941. return area2(a, b, c) <= 0;
  942. }
  943. inline bool collinear(const unsigned char* a, const unsigned char* b, const unsigned char* c)
  944. {
  945. return area2(a, b, c) == 0;
  946. }
  947. // Returns true iff ab properly intersects cd: they share
  948. // a point interior to both segments. The properness of the
  949. // intersection is ensured by using strict leftness.
  950. static bool intersectProp(const unsigned char* a, const unsigned char* b,
  951. const unsigned char* c, const unsigned char* d)
  952. {
  953. // Eliminate improper cases.
  954. if (collinear(a,b,c) || collinear(a,b,d) ||
  955. collinear(c,d,a) || collinear(c,d,b))
  956. return false;
  957. return xorb(left(a,b,c), left(a,b,d)) && xorb(left(c,d,a), left(c,d,b));
  958. }
  959. // Returns T iff (a,b,c) are collinear and point c lies
  960. // on the closed segement ab.
  961. static bool between(const unsigned char* a, const unsigned char* b, const unsigned char* c)
  962. {
  963. if (!collinear(a, b, c))
  964. return false;
  965. // If ab not vertical, check betweenness on x; else on y.
  966. if (a[0] != b[0])
  967. return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0]));
  968. else
  969. return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2]));
  970. }
  971. // Returns true iff segments ab and cd intersect, properly or improperly.
  972. static bool intersect(const unsigned char* a, const unsigned char* b,
  973. const unsigned char* c, const unsigned char* d)
  974. {
  975. if (intersectProp(a, b, c, d))
  976. return true;
  977. else if (between(a, b, c) || between(a, b, d) ||
  978. between(c, d, a) || between(c, d, b))
  979. return true;
  980. else
  981. return false;
  982. }
  983. static bool vequal(const unsigned char* a, const unsigned char* b)
  984. {
  985. return a[0] == b[0] && a[2] == b[2];
  986. }
  987. // Returns T iff (v_i, v_j) is a proper internal *or* external
  988. // diagonal of P, *ignoring edges incident to v_i and v_j*.
  989. static bool diagonalie(int i, int j, int n, const unsigned char* verts, const unsigned short* indices)
  990. {
  991. const unsigned char* d0 = &verts[(indices[i] & 0x7fff) * 4];
  992. const unsigned char* d1 = &verts[(indices[j] & 0x7fff) * 4];
  993. // For each edge (k,k+1) of P
  994. for (int k = 0; k < n; k++)
  995. {
  996. int k1 = next(k, n);
  997. // Skip edges incident to i or j
  998. if (!((k == i) || (k1 == i) || (k == j) || (k1 == j)))
  999. {
  1000. const unsigned char* p0 = &verts[(indices[k] & 0x7fff) * 4];
  1001. const unsigned char* p1 = &verts[(indices[k1] & 0x7fff) * 4];
  1002. if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1))
  1003. continue;
  1004. if (intersect(d0, d1, p0, p1))
  1005. return false;
  1006. }
  1007. }
  1008. return true;
  1009. }
  1010. // Returns true iff the diagonal (i,j) is strictly internal to the
  1011. // polygon P in the neighborhood of the i endpoint.
  1012. static bool inCone(int i, int j, int n, const unsigned char* verts, const unsigned short* indices)
  1013. {
  1014. const unsigned char* pi = &verts[(indices[i] & 0x7fff) * 4];
  1015. const unsigned char* pj = &verts[(indices[j] & 0x7fff) * 4];
  1016. const unsigned char* pi1 = &verts[(indices[next(i, n)] & 0x7fff) * 4];
  1017. const unsigned char* pin1 = &verts[(indices[prev(i, n)] & 0x7fff) * 4];
  1018. // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ].
  1019. if (leftOn(pin1, pi, pi1))
  1020. return left(pi, pj, pin1) && left(pj, pi, pi1);
  1021. // Assume (i-1,i,i+1) not collinear.
  1022. // else P[i] is reflex.
  1023. return !(leftOn(pi, pj, pi1) && leftOn(pj, pi, pin1));
  1024. }
  1025. // Returns T iff (v_i, v_j) is a proper internal
  1026. // diagonal of P.
  1027. static bool diagonal(int i, int j, int n, const unsigned char* verts, const unsigned short* indices)
  1028. {
  1029. return inCone(i, j, n, verts, indices) && diagonalie(i, j, n, verts, indices);
  1030. }
  1031. static int triangulate(int n, const unsigned char* verts, unsigned short* indices, unsigned short* tris)
  1032. {
  1033. int ntris = 0;
  1034. unsigned short* dst = tris;
  1035. // The last bit of the index is used to indicate if the vertex can be removed.
  1036. for (int i = 0; i < n; i++)
  1037. {
  1038. int i1 = next(i, n);
  1039. int i2 = next(i1, n);
  1040. if (diagonal(i, i2, n, verts, indices))
  1041. indices[i1] |= 0x8000;
  1042. }
  1043. while (n > 3)
  1044. {
  1045. int minLen = -1;
  1046. int mini = -1;
  1047. for (int i = 0; i < n; i++)
  1048. {
  1049. int i1 = next(i, n);
  1050. if (indices[i1] & 0x8000)
  1051. {
  1052. const unsigned char* p0 = &verts[(indices[i] & 0x7fff) * 4];
  1053. const unsigned char* p2 = &verts[(indices[next(i1, n)] & 0x7fff) * 4];
  1054. const int dx = (int)p2[0] - (int)p0[0];
  1055. const int dz = (int)p2[2] - (int)p0[2];
  1056. const int len = dx*dx + dz*dz;
  1057. if (minLen < 0 || len < minLen)
  1058. {
  1059. minLen = len;
  1060. mini = i;
  1061. }
  1062. }
  1063. }
  1064. if (mini == -1)
  1065. {
  1066. // Should not happen.
  1067. /* printf("mini == -1 ntris=%d n=%d\n", ntris, n);
  1068. for (int i = 0; i < n; i++)
  1069. {
  1070. printf("%d ", indices[i] & 0x0fffffff);
  1071. }
  1072. printf("\n");*/
  1073. return -ntris;
  1074. }
  1075. int i = mini;
  1076. int i1 = next(i, n);
  1077. int i2 = next(i1, n);
  1078. *dst++ = indices[i] & 0x7fff;
  1079. *dst++ = indices[i1] & 0x7fff;
  1080. *dst++ = indices[i2] & 0x7fff;
  1081. ntris++;
  1082. // Removes P[i1] by copying P[i+1]...P[n-1] left one index.
  1083. n--;
  1084. for (int k = i1; k < n; k++)
  1085. indices[k] = indices[k+1];
  1086. if (i1 >= n) i1 = 0;
  1087. i = prev(i1,n);
  1088. // Update diagonal flags.
  1089. if (diagonal(prev(i, n), i1, n, verts, indices))
  1090. indices[i] |= 0x8000;
  1091. else
  1092. indices[i] &= 0x7fff;
  1093. if (diagonal(i, next(i1, n), n, verts, indices))
  1094. indices[i1] |= 0x8000;
  1095. else
  1096. indices[i1] &= 0x7fff;
  1097. }
  1098. // Append the remaining triangle.
  1099. *dst++ = indices[0] & 0x7fff;
  1100. *dst++ = indices[1] & 0x7fff;
  1101. *dst++ = indices[2] & 0x7fff;
  1102. ntris++;
  1103. return ntris;
  1104. }
  1105. static int countPolyVerts(const unsigned short* p)
  1106. {
  1107. for (int i = 0; i < MAX_VERTS_PER_POLY; ++i)
  1108. if (p[i] == DT_TILECACHE_NULL_IDX)
  1109. return i;
  1110. return MAX_VERTS_PER_POLY;
  1111. }
  1112. inline bool uleft(const unsigned short* a, const unsigned short* b, const unsigned short* c)
  1113. {
  1114. return ((int)b[0] - (int)a[0]) * ((int)c[2] - (int)a[2]) -
  1115. ((int)c[0] - (int)a[0]) * ((int)b[2] - (int)a[2]) < 0;
  1116. }
  1117. static int getPolyMergeValue(unsigned short* pa, unsigned short* pb,
  1118. const unsigned short* verts, int& ea, int& eb)
  1119. {
  1120. const int na = countPolyVerts(pa);
  1121. const int nb = countPolyVerts(pb);
  1122. // If the merged polygon would be too big, do not merge.
  1123. if (na+nb-2 > MAX_VERTS_PER_POLY)
  1124. return -1;
  1125. // Check if the polygons share an edge.
  1126. ea = -1;
  1127. eb = -1;
  1128. for (int i = 0; i < na; ++i)
  1129. {
  1130. unsigned short va0 = pa[i];
  1131. unsigned short va1 = pa[(i+1) % na];
  1132. if (va0 > va1)
  1133. dtSwap(va0, va1);
  1134. for (int j = 0; j < nb; ++j)
  1135. {
  1136. unsigned short vb0 = pb[j];
  1137. unsigned short vb1 = pb[(j+1) % nb];
  1138. if (vb0 > vb1)
  1139. dtSwap(vb0, vb1);
  1140. if (va0 == vb0 && va1 == vb1)
  1141. {
  1142. ea = i;
  1143. eb = j;
  1144. break;
  1145. }
  1146. }
  1147. }
  1148. // No common edge, cannot merge.
  1149. if (ea == -1 || eb == -1)
  1150. return -1;
  1151. // Check to see if the merged polygon would be convex.
  1152. unsigned short va, vb, vc;
  1153. va = pa[(ea+na-1) % na];
  1154. vb = pa[ea];
  1155. vc = pb[(eb+2) % nb];
  1156. if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3]))
  1157. return -1;
  1158. va = pb[(eb+nb-1) % nb];
  1159. vb = pb[eb];
  1160. vc = pa[(ea+2) % na];
  1161. if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3]))
  1162. return -1;
  1163. va = pa[ea];
  1164. vb = pa[(ea+1)%na];
  1165. int dx = (int)verts[va*3+0] - (int)verts[vb*3+0];
  1166. int dy = (int)verts[va*3+2] - (int)verts[vb*3+2];
  1167. return dx*dx + dy*dy;
  1168. }
  1169. static void mergePolys(unsigned short* pa, unsigned short* pb, int ea, int eb)
  1170. {
  1171. unsigned short tmp[MAX_VERTS_PER_POLY*2];
  1172. const int na = countPolyVerts(pa);
  1173. const int nb = countPolyVerts(pb);
  1174. // Merge polygons.
  1175. memset(tmp, 0xff, sizeof(unsigned short)*MAX_VERTS_PER_POLY*2);
  1176. int n = 0;
  1177. // Add pa
  1178. for (int i = 0; i < na-1; ++i)
  1179. tmp[n++] = pa[(ea+1+i) % na];
  1180. // Add pb
  1181. for (int i = 0; i < nb-1; ++i)
  1182. tmp[n++] = pb[(eb+1+i) % nb];
  1183. memcpy(pa, tmp, sizeof(unsigned short)*MAX_VERTS_PER_POLY);
  1184. }
  1185. static void pushFront(unsigned short v, unsigned short* arr, int& an)
  1186. {
  1187. an++;
  1188. for (int i = an-1; i > 0; --i)
  1189. arr[i] = arr[i-1];
  1190. arr[0] = v;
  1191. }
  1192. static void pushBack(unsigned short v, unsigned short* arr, int& an)
  1193. {
  1194. arr[an] = v;
  1195. an++;
  1196. }
  1197. static bool canRemoveVertex(dtTileCachePolyMesh& mesh, const unsigned short rem)
  1198. {
  1199. // Count number of polygons to remove.
  1200. int numRemovedVerts = 0;
  1201. int numTouchedVerts = 0;
  1202. int numRemainingEdges = 0;
  1203. for (int i = 0; i < mesh.npolys; ++i)
  1204. {
  1205. unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
  1206. const int nv = countPolyVerts(p);
  1207. int numRemoved = 0;
  1208. int numVerts = 0;
  1209. for (int j = 0; j < nv; ++j)
  1210. {
  1211. if (p[j] == rem)
  1212. {
  1213. numTouchedVerts++;
  1214. numRemoved++;
  1215. }
  1216. numVerts++;
  1217. }
  1218. if (numRemoved)
  1219. {
  1220. numRemovedVerts += numRemoved;
  1221. numRemainingEdges += numVerts-(numRemoved+1);
  1222. }
  1223. }
  1224. // There would be too few edges remaining to create a polygon.
  1225. // This can happen for example when a tip of a triangle is marked
  1226. // as deletion, but there are no other polys that share the vertex.
  1227. // In this case, the vertex should not be removed.
  1228. if (numRemainingEdges <= 2)
  1229. return false;
  1230. // Check that there is enough memory for the test.
  1231. const int maxEdges = numTouchedVerts*2;
  1232. if (maxEdges > MAX_REM_EDGES)
  1233. return false;
  1234. // Find edges which share the removed vertex.
  1235. unsigned short edges[MAX_REM_EDGES];
  1236. int nedges = 0;
  1237. for (int i = 0; i < mesh.npolys; ++i)
  1238. {
  1239. unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
  1240. const int nv = countPolyVerts(p);
  1241. // Collect edges which touches the removed vertex.
  1242. for (int j = 0, k = nv-1; j < nv; k = j++)
  1243. {
  1244. if (p[j] == rem || p[k] == rem)
  1245. {
  1246. // Arrange edge so that a=rem.
  1247. int a = p[j], b = p[k];
  1248. if (b == rem)
  1249. dtSwap(a,b);
  1250. // Check if the edge exists
  1251. bool exists = false;
  1252. for (int m = 0; m < nedges; ++m)
  1253. {
  1254. unsigned short* e = &edges[m*3];
  1255. if (e[1] == b)
  1256. {
  1257. // Exists, increment vertex share count.
  1258. e[2]++;
  1259. exists = true;
  1260. }
  1261. }
  1262. // Add new edge.
  1263. if (!exists)
  1264. {
  1265. unsigned short* e = &edges[nedges*3];
  1266. e[0] = (unsigned short)a;
  1267. e[1] = (unsigned short)b;
  1268. e[2] = 1;
  1269. nedges++;
  1270. }
  1271. }
  1272. }
  1273. }
  1274. // There should be no more than 2 open edges.
  1275. // This catches the case that two non-adjacent polygons
  1276. // share the removed vertex. In that case, do not remove the vertex.
  1277. int numOpenEdges = 0;
  1278. for (int i = 0; i < nedges; ++i)
  1279. {
  1280. if (edges[i*3+2] < 2)
  1281. numOpenEdges++;
  1282. }
  1283. if (numOpenEdges > 2)
  1284. return false;
  1285. return true;
  1286. }
  1287. static dtStatus removeVertex(dtTileCachePolyMesh& mesh, const unsigned short rem, const int maxTris)
  1288. {
  1289. // Count number of polygons to remove.
  1290. int numRemovedVerts = 0;
  1291. for (int i = 0; i < mesh.npolys; ++i)
  1292. {
  1293. unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
  1294. const int nv = countPolyVerts(p);
  1295. for (int j = 0; j < nv; ++j)
  1296. {
  1297. if (p[j] == rem)
  1298. numRemovedVerts++;
  1299. }
  1300. }
  1301. int nedges = 0;
  1302. unsigned short edges[MAX_REM_EDGES*3];
  1303. int nhole = 0;
  1304. unsigned short hole[MAX_REM_EDGES];
  1305. int nharea = 0;
  1306. unsigned short harea[MAX_REM_EDGES];
  1307. for (int i = 0; i < mesh.npolys; ++i)
  1308. {
  1309. unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
  1310. const int nv = countPolyVerts(p);
  1311. bool hasRem = false;
  1312. for (int j = 0; j < nv; ++j)
  1313. if (p[j] == rem) hasRem = true;
  1314. if (hasRem)
  1315. {
  1316. // Collect edges which does not touch the removed vertex.
  1317. for (int j = 0, k = nv-1; j < nv; k = j++)
  1318. {
  1319. if (p[j] != rem && p[k] != rem)
  1320. {
  1321. if (nedges >= MAX_REM_EDGES)
  1322. return DT_FAILURE | DT_BUFFER_TOO_SMALL;
  1323. unsigned short* e = &edges[nedges*3];
  1324. e[0] = p[k];
  1325. e[1] = p[j];
  1326. e[2] = mesh.areas[i];
  1327. nedges++;
  1328. }
  1329. }
  1330. // Remove the polygon.
  1331. unsigned short* p2 = &mesh.polys[(mesh.npolys-1)*MAX_VERTS_PER_POLY*2];
  1332. memcpy(p,p2,sizeof(unsigned short)*MAX_VERTS_PER_POLY);
  1333. memset(p+MAX_VERTS_PER_POLY,0xff,sizeof(unsigned short)*MAX_VERTS_PER_POLY);
  1334. mesh.areas[i] = mesh.areas[mesh.npolys-1];
  1335. mesh.npolys--;
  1336. --i;
  1337. }
  1338. }
  1339. // Remove vertex.
  1340. for (int i = (int)rem; i < mesh.nverts; ++i)
  1341. {
  1342. mesh.verts[i*3+0] = mesh.verts[(i+1)*3+0];
  1343. mesh.verts[i*3+1] = mesh.verts[(i+1)*3+1];
  1344. mesh.verts[i*3+2] = mesh.verts[(i+1)*3+2];
  1345. }
  1346. mesh.nverts--;
  1347. // Adjust indices to match the removed vertex layout.
  1348. for (int i = 0; i < mesh.npolys; ++i)
  1349. {
  1350. unsigned short* p = &mesh.polys[i*MAX_VERTS_PER_POLY*2];
  1351. const int nv = countPolyVerts(p);
  1352. for (int j = 0; j < nv; ++j)
  1353. if (p[j] > rem) p[j]--;
  1354. }
  1355. for (int i = 0; i < nedges; ++i)
  1356. {
  1357. if (edges[i*3+0] > rem) edges[i*3+0]--;
  1358. if (edges[i*3+1] > rem) edges[i*3+1]--;
  1359. }
  1360. if (nedges == 0)
  1361. return DT_SUCCESS;
  1362. // Start with one vertex, keep appending connected
  1363. // segments to the start and end of the hole.
  1364. pushBack(edges[0], hole, nhole);
  1365. pushBack(edges[2], harea, nharea);
  1366. while (nedges)
  1367. {
  1368. bool match = false;
  1369. for (int i = 0; i < nedges; ++i)
  1370. {
  1371. const unsigned short ea = edges[i*3+0];
  1372. const unsigned short eb = edges[i*3+1];
  1373. const unsigned short a = edges[i*3+2];
  1374. bool add = false;
  1375. if (hole[0] == eb)
  1376. {
  1377. // The segment matches the beginning of the hole boundary.
  1378. if (nhole >= MAX_REM_EDGES)
  1379. return DT_FAILURE | DT_BUFFER_TOO_SMALL;
  1380. pushFront(ea, hole, nhole);
  1381. pushFront(a, harea, nharea);
  1382. add = true;
  1383. }
  1384. else if (hole[nhole-1] == ea)
  1385. {
  1386. // The segment matches the end of the hole boundary.
  1387. if (nhole >= MAX_REM_EDGES)
  1388. return DT_FAILURE | DT_BUFFER_TOO_SMALL;
  1389. pushBack(eb, hole, nhole);
  1390. pushBack(a, harea, nharea);
  1391. add = true;
  1392. }
  1393. if (add)
  1394. {
  1395. // The edge segment was added, remove it.
  1396. edges[i*3+0] = edges[(nedges-1)*3+0];
  1397. edges[i*3+1] = edges[(nedges-1)*3+1];
  1398. edges[i*3+2] = edges[(nedges-1)*3+2];
  1399. --nedges;
  1400. match = true;
  1401. --i;
  1402. }
  1403. }
  1404. if (!match)
  1405. break;
  1406. }
  1407. unsigned short tris[MAX_REM_EDGES*3];
  1408. unsigned char tverts[MAX_REM_EDGES*3];
  1409. unsigned short tpoly[MAX_REM_EDGES*3];
  1410. // Generate temp vertex array for triangulation.
  1411. for (int i = 0; i < nhole; ++i)
  1412. {
  1413. const unsigned short pi = hole[i];
  1414. tverts[i*4+0] = (unsigned char)mesh.verts[pi*3+0];
  1415. tverts[i*4+1] = (unsigned char)mesh.verts[pi*3+1];
  1416. tverts[i*4+2] = (unsigned char)mesh.verts[pi*3+2];
  1417. tverts[i*4+3] = 0;
  1418. tpoly[i] = (unsigned short)i;
  1419. }
  1420. // Triangulate the hole.
  1421. int ntris = triangulate(nhole, tverts, tpoly, tris);
  1422. if (ntris < 0)
  1423. {
  1424. // TODO: issue warning!
  1425. ntris = -ntris;
  1426. }
  1427. if (ntris > MAX_REM_EDGES)
  1428. return DT_FAILURE | DT_BUFFER_TOO_SMALL;
  1429. unsigned short polys[MAX_REM_EDGES*MAX_VERTS_PER_POLY];
  1430. unsigned char pareas[MAX_REM_EDGES];
  1431. // Build initial polygons.
  1432. int npolys = 0;
  1433. memset(polys, 0xff, ntris*MAX_VERTS_PER_POLY*sizeof(unsigned short));
  1434. for (int j = 0; j < ntris; ++j)
  1435. {
  1436. unsigned short* t = &tris[j*3];
  1437. if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])
  1438. {
  1439. polys[npolys*MAX_VERTS_PER_POLY+0] = hole[t[0]];
  1440. polys[npolys*MAX_VERTS_PER_POLY+1] = hole[t[1]];
  1441. polys[npolys*MAX_VERTS_PER_POLY+2] = hole[t[2]];
  1442. pareas[npolys] = (unsigned char)harea[t[0]];
  1443. npolys++;
  1444. }
  1445. }
  1446. if (!npolys)
  1447. return DT_SUCCESS;
  1448. // Merge polygons.
  1449. int maxVertsPerPoly = MAX_VERTS_PER_POLY;
  1450. if (maxVertsPerPoly > 3)
  1451. {
  1452. for (;;)
  1453. {
  1454. // Find best polygons to merge.
  1455. int bestMergeVal = 0;
  1456. int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0;
  1457. for (int j = 0; j < npolys-1; ++j)
  1458. {
  1459. unsigned short* pj = &polys[j*MAX_VERTS_PER_POLY];
  1460. for (int k = j+1; k < npolys; ++k)
  1461. {
  1462. unsigned short* pk = &polys[k*MAX_VERTS_PER_POLY];
  1463. int ea, eb;
  1464. int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb);
  1465. if (v > bestMergeVal)
  1466. {
  1467. bestMergeVal = v;
  1468. bestPa = j;
  1469. bestPb = k;
  1470. bestEa = ea;
  1471. bestEb = eb;
  1472. }
  1473. }
  1474. }
  1475. if (bestMergeVal > 0)
  1476. {
  1477. // Found best, merge.
  1478. unsigned short* pa = &polys[bestPa*MAX_VERTS_PER_POLY];
  1479. unsigned short* pb = &polys[bestPb*MAX_VERTS_PER_POLY];
  1480. mergePolys(pa, pb, bestEa, bestEb);
  1481. memcpy(pb, &polys[(npolys-1)*MAX_VERTS_PER_POLY], sizeof(unsigned short)*MAX_VERTS_PER_POLY);
  1482. pareas[bestPb] = pareas[npolys-1];
  1483. npolys--;
  1484. }
  1485. else
  1486. {
  1487. // Could not merge any polygons, stop.
  1488. break;
  1489. }
  1490. }
  1491. }
  1492. // Store polygons.
  1493. for (int i = 0; i < npolys; ++i)
  1494. {
  1495. if (mesh.npolys >= maxTris) break;
  1496. unsigned short* p = &mesh.polys[mesh.npolys*MAX_VERTS_PER_POLY*2];
  1497. memset(p,0xff,sizeof(unsigned short)*MAX_VERTS_PER_POLY*2);
  1498. for (int j = 0; j < MAX_VERTS_PER_POLY; ++j)
  1499. p[j] = polys[i*MAX_VERTS_PER_POLY+j];
  1500. mesh.areas[mesh.npolys] = pareas[i];
  1501. mesh.npolys++;
  1502. if (mesh.npolys > maxTris)
  1503. return DT_FAILURE | DT_BUFFER_TOO_SMALL;
  1504. }
  1505. return DT_SUCCESS;
  1506. }
  1507. dtStatus dtBuildTileCachePolyMesh(dtTileCacheAlloc* alloc,
  1508. dtTileCacheContourSet& lcset,
  1509. dtTileCachePolyMesh& mesh)
  1510. {
  1511. dtAssert(alloc);
  1512. int maxVertices = 0;
  1513. int maxTris = 0;
  1514. int maxVertsPerCont = 0;
  1515. for (int i = 0; i < lcset.nconts; ++i)
  1516. {
  1517. // Skip null contours.
  1518. if (lcset.conts[i].nverts < 3) continue;
  1519. maxVertices += lcset.conts[i].nverts;
  1520. maxTris += lcset.conts[i].nverts - 2;
  1521. maxVertsPerCont = dtMax(maxVertsPerCont, lcset.conts[i].nverts);
  1522. }
  1523. // TODO: warn about too many vertices?
  1524. mesh.nvp = MAX_VERTS_PER_POLY;
  1525. dtFixedArray<unsigned char> vflags(alloc, maxVertices);
  1526. if (!vflags)
  1527. return DT_FAILURE | DT_OUT_OF_MEMORY;
  1528. memset(vflags, 0, maxVertices);
  1529. mesh.verts = (unsigned short*)alloc->alloc(sizeof(unsigned short)*maxVertices*3);
  1530. if (!mesh.verts)
  1531. return DT_FAILURE | DT_OUT_OF_MEMORY;
  1532. mesh.polys = (unsigned short*)alloc->alloc(sizeof(unsigned short)*maxTris*MAX_VERTS_PER_POLY*2);
  1533. if (!mesh.polys)
  1534. return DT_FAILURE | DT_OUT_OF_MEMORY;
  1535. mesh.areas = (unsigned char*)alloc->alloc(sizeof(unsigned char)*maxTris);
  1536. if (!mesh.areas)
  1537. return DT_FAILURE | DT_OUT_OF_MEMORY;
  1538. mesh.flags = (unsigned short*)alloc->alloc(sizeof(unsigned short)*maxTris);
  1539. if (!mesh.flags)
  1540. return DT_FAILURE | DT_OUT_OF_MEMORY;
  1541. // Just allocate and clean the mesh flags array. The user is resposible for filling it.
  1542. memset(mesh.flags, 0, sizeof(unsigned short) * maxTris);
  1543. mesh.nverts = 0;
  1544. mesh.npolys = 0;
  1545. memset(mesh.verts, 0, sizeof(unsigned short)*maxVertices*3);
  1546. memset(mesh.polys, 0xff, sizeof(unsigned short)*maxTris*MAX_VERTS_PER_POLY*2);
  1547. memset(mesh.areas, 0, sizeof(unsigned char)*maxTris);
  1548. unsigned short firstVert[VERTEX_BUCKET_COUNT2];
  1549. for (int i = 0; i < VERTEX_BUCKET_COUNT2; ++i)
  1550. firstVert[i] = DT_TILECACHE_NULL_IDX;
  1551. dtFixedArray<unsigned short> nextVert(alloc, maxVertices);
  1552. if (!nextVert)
  1553. return DT_FAILURE | DT_OUT_OF_MEMORY;
  1554. memset(nextVert, 0, sizeof(unsigned short)*maxVertices);
  1555. dtFixedArray<unsigned short> indices(alloc, maxVertsPerCont);
  1556. if (!indices)
  1557. return DT_FAILURE | DT_OUT_OF_MEMORY;
  1558. dtFixedArray<unsigned short> tris(alloc, maxVertsPerCont*3);
  1559. if (!tris)
  1560. return DT_FAILURE | DT_OUT_OF_MEMORY;
  1561. dtFixedArray<unsigned short> polys(alloc, maxVertsPerCont*MAX_VERTS_PER_POLY);
  1562. if (!polys)
  1563. return DT_FAILURE | DT_OUT_OF_MEMORY;
  1564. for (int i = 0; i < lcset.nconts; ++i)
  1565. {
  1566. dtTileCacheContour& cont = lcset.conts[i];
  1567. // Skip null contours.
  1568. if (cont.nverts < 3)
  1569. continue;
  1570. // Triangulate contour
  1571. for (int j = 0; j < cont.nverts; ++j)
  1572. indices[j] = (unsigned short)j;
  1573. int ntris = triangulate(cont.nverts, cont.verts, &indices[0], &tris[0]);
  1574. if (ntris <= 0)
  1575. {
  1576. // TODO: issue warning!
  1577. ntris = -ntris;
  1578. }
  1579. // Add and merge vertices.
  1580. for (int j = 0; j < cont.nverts; ++j)
  1581. {
  1582. const unsigned char* v = &cont.verts[j*4];
  1583. indices[j] = addVertex((unsigned short)v[0], (unsigned short)v[1], (unsigned short)v[2],
  1584. mesh.verts, firstVert, nextVert, mesh.nverts);
  1585. if (v[3] & 0x80)
  1586. {
  1587. // This vertex should be removed.
  1588. vflags[indices[j]] = 1;
  1589. }
  1590. }
  1591. // Build initial polygons.
  1592. int npolys = 0;
  1593. memset(polys, 0xff, sizeof(unsigned short) * maxVertsPerCont * MAX_VERTS_PER_POLY);
  1594. for (int j = 0; j < ntris; ++j)
  1595. {
  1596. const unsigned short* t = &tris[j*3];
  1597. if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])
  1598. {
  1599. polys[npolys*MAX_VERTS_PER_POLY+0] = indices[t[0]];
  1600. polys[npolys*MAX_VERTS_PER_POLY+1] = indices[t[1]];
  1601. polys[npolys*MAX_VERTS_PER_POLY+2] = indices[t[2]];
  1602. npolys++;
  1603. }
  1604. }
  1605. if (!npolys)
  1606. continue;
  1607. // Merge polygons.
  1608. int maxVertsPerPoly =MAX_VERTS_PER_POLY ;
  1609. if (maxVertsPerPoly > 3)
  1610. {
  1611. for(;;)
  1612. {
  1613. // Find best polygons to merge.
  1614. int bestMergeVal = 0;
  1615. int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0;
  1616. for (int j = 0; j < npolys-1; ++j)
  1617. {
  1618. unsigned short* pj = &polys[j*MAX_VERTS_PER_POLY];
  1619. for (int k = j+1; k < npolys; ++k)
  1620. {
  1621. unsigned short* pk = &polys[k*MAX_VERTS_PER_POLY];
  1622. int ea, eb;
  1623. int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb);
  1624. if (v > bestMergeVal)
  1625. {
  1626. bestMergeVal = v;
  1627. bestPa = j;
  1628. bestPb = k;
  1629. bestEa = ea;
  1630. bestEb = eb;
  1631. }
  1632. }
  1633. }
  1634. if (bestMergeVal > 0)
  1635. {
  1636. // Found best, merge.
  1637. unsigned short* pa = &polys[bestPa*MAX_VERTS_PER_POLY];
  1638. unsigned short* pb = &polys[bestPb*MAX_VERTS_PER_POLY];
  1639. mergePolys(pa, pb, bestEa, bestEb);
  1640. memcpy(pb, &polys[(npolys-1)*MAX_VERTS_PER_POLY], sizeof(unsigned short)*MAX_VERTS_PER_POLY);
  1641. npolys--;
  1642. }
  1643. else
  1644. {
  1645. // Could not merge any polygons, stop.
  1646. break;
  1647. }
  1648. }
  1649. }
  1650. // Store polygons.
  1651. for (int j = 0; j < npolys; ++j)
  1652. {
  1653. unsigned short* p = &mesh.polys[mesh.npolys*MAX_VERTS_PER_POLY*2];
  1654. unsigned short* q = &polys[j*MAX_VERTS_PER_POLY];
  1655. for (int k = 0; k < MAX_VERTS_PER_POLY; ++k)
  1656. p[k] = q[k];
  1657. mesh.areas[mesh.npolys] = cont.area;
  1658. mesh.npolys++;
  1659. if (mesh.npolys > maxTris)
  1660. return DT_FAILURE | DT_BUFFER_TOO_SMALL;
  1661. }
  1662. }
  1663. // Remove edge vertices.
  1664. for (int i = 0; i < mesh.nverts; ++i)
  1665. {
  1666. if (vflags[i])
  1667. {
  1668. if (!canRemoveVertex(mesh, (unsigned short)i))
  1669. continue;
  1670. dtStatus status = removeVertex(mesh, (unsigned short)i, maxTris);
  1671. if (dtStatusFailed(status))
  1672. return status;
  1673. // Remove vertex
  1674. // Note: mesh.nverts is already decremented inside removeVertex()!
  1675. for (int j = i; j < mesh.nverts; ++j)
  1676. vflags[j] = vflags[j+1];
  1677. --i;
  1678. }
  1679. }
  1680. // Calculate adjacency.
  1681. if (!buildMeshAdjacency(alloc, mesh.polys, mesh.npolys, mesh.verts, mesh.nverts, lcset))
  1682. return DT_FAILURE | DT_OUT_OF_MEMORY;
  1683. return DT_SUCCESS;
  1684. }
  1685. dtStatus dtMarkCylinderArea(dtTileCacheLayer& layer, const float* orig, const float cs, const float ch,
  1686. const float* pos, const float radius, const float height, const unsigned char areaId)
  1687. {
  1688. float bmin[3], bmax[3];
  1689. bmin[0] = pos[0] - radius;
  1690. bmin[1] = pos[1];
  1691. bmin[2] = pos[2] - radius;
  1692. bmax[0] = pos[0] + radius;
  1693. bmax[1] = pos[1] + height;
  1694. bmax[2] = pos[2] + radius;
  1695. const float r2 = dtSqr(radius/cs + 0.5f);
  1696. const int w = (int)layer.header->width;
  1697. const int h = (int)layer.header->height;
  1698. const float ics = 1.0f/cs;
  1699. const float ich = 1.0f/ch;
  1700. const float px = (pos[0]-orig[0])*ics;
  1701. const float pz = (pos[2]-orig[2])*ics;
  1702. int minx = (int)floorf((bmin[0]-orig[0])*ics);
  1703. int miny = (int)floorf((bmin[1]-orig[1])*ich);
  1704. int minz = (int)floorf((bmin[2]-orig[2])*ics);
  1705. int maxx = (int)floorf((bmax[0]-orig[0])*ics);
  1706. int maxy = (int)floorf((bmax[1]-orig[1])*ich);
  1707. int maxz = (int)floorf((bmax[2]-orig[2])*ics);
  1708. if (maxx < 0) return DT_SUCCESS;
  1709. if (minx >= w) return DT_SUCCESS;
  1710. if (maxz < 0) return DT_SUCCESS;
  1711. if (minz >= h) return DT_SUCCESS;
  1712. if (minx < 0) minx = 0;
  1713. if (maxx >= w) maxx = w-1;
  1714. if (minz < 0) minz = 0;
  1715. if (maxz >= h) maxz = h-1;
  1716. for (int z = minz; z <= maxz; ++z)
  1717. {
  1718. for (int x = minx; x <= maxx; ++x)
  1719. {
  1720. const float dx = (float)(x+0.5f) - px;
  1721. const float dz = (float)(z+0.5f) - pz;
  1722. if (dx*dx + dz*dz > r2)
  1723. continue;
  1724. const int y = layer.heights[x+z*w];
  1725. if (y < miny || y > maxy)
  1726. continue;
  1727. layer.areas[x+z*w] = areaId;
  1728. }
  1729. }
  1730. return DT_SUCCESS;
  1731. }
  1732. dtStatus dtBuildTileCacheLayer(dtTileCacheCompressor* comp,
  1733. dtTileCacheLayerHeader* header,
  1734. const unsigned char* heights,
  1735. const unsigned char* areas,
  1736. const unsigned char* cons,
  1737. unsigned char** outData, int* outDataSize)
  1738. {
  1739. const int headerSize = dtAlign4(sizeof(dtTileCacheLayerHeader));
  1740. const int gridSize = (int)header->width * (int)header->height;
  1741. const int maxDataSize = headerSize + comp->maxCompressedSize(gridSize*3);
  1742. unsigned char* data = (unsigned char*)dtAlloc(maxDataSize, DT_ALLOC_PERM);
  1743. if (!data)
  1744. return DT_FAILURE | DT_OUT_OF_MEMORY;
  1745. memset(data, 0, maxDataSize);
  1746. // Store header
  1747. memcpy(data, header, sizeof(dtTileCacheLayerHeader));
  1748. // Concatenate grid data for compression.
  1749. const int bufferSize = gridSize*3;
  1750. unsigned char* buffer = (unsigned char*)dtAlloc(bufferSize, DT_ALLOC_TEMP);
  1751. if (!buffer)
  1752. return DT_FAILURE | DT_OUT_OF_MEMORY;
  1753. memcpy(buffer, heights, gridSize);
  1754. memcpy(buffer+gridSize, areas, gridSize);
  1755. memcpy(buffer+gridSize*2, cons, gridSize);
  1756. // Compress
  1757. unsigned char* compressed = data + headerSize;
  1758. const int maxCompressedSize = maxDataSize - headerSize;
  1759. int compressedSize = 0;
  1760. dtStatus status = comp->compress(buffer, bufferSize, compressed, maxCompressedSize, &compressedSize);
  1761. if (dtStatusFailed(status))
  1762. return status;
  1763. *outData = data;
  1764. *outDataSize = headerSize + compressedSize;
  1765. dtFree(buffer);
  1766. return DT_SUCCESS;
  1767. }
  1768. void dtFreeTileCacheLayer(dtTileCacheAlloc* alloc, dtTileCacheLayer* layer)
  1769. {
  1770. dtAssert(alloc);
  1771. // The layer is allocated as one conitguous blob of data.
  1772. alloc->free(layer);
  1773. }
  1774. dtStatus dtDecompressTileCacheLayer(dtTileCacheAlloc* alloc, dtTileCacheCompressor* comp,
  1775. unsigned char* compressed, const int compressedSize,
  1776. dtTileCacheLayer** layerOut)
  1777. {
  1778. dtAssert(alloc);
  1779. dtAssert(comp);
  1780. if (!layerOut)
  1781. return DT_FAILURE | DT_INVALID_PARAM;
  1782. if (!compressed)
  1783. return DT_FAILURE | DT_INVALID_PARAM;
  1784. *layerOut = 0;
  1785. dtTileCacheLayerHeader* compressedHeader = (dtTileCacheLayerHeader*)compressed;
  1786. if (compressedHeader->magic != DT_TILECACHE_MAGIC)
  1787. return DT_FAILURE | DT_WRONG_MAGIC;
  1788. if (compressedHeader->version != DT_TILECACHE_VERSION)
  1789. return DT_FAILURE | DT_WRONG_VERSION;
  1790. const int layerSize = dtAlign4(sizeof(dtTileCacheLayer));
  1791. const int headerSize = dtAlign4(sizeof(dtTileCacheLayerHeader));
  1792. const int gridSize = (int)compressedHeader->width * (int)compressedHeader->height;
  1793. const int bufferSize = layerSize + headerSize + gridSize*4;
  1794. unsigned char* buffer = (unsigned char*)alloc->alloc(bufferSize);
  1795. if (!buffer)
  1796. return DT_FAILURE | DT_OUT_OF_MEMORY;
  1797. memset(buffer, 0, bufferSize);
  1798. dtTileCacheLayer* layer = (dtTileCacheLayer*)buffer;
  1799. dtTileCacheLayerHeader* header = (dtTileCacheLayerHeader*)(buffer + layerSize);
  1800. unsigned char* grids = buffer + layerSize + headerSize;
  1801. const int gridsSize = bufferSize - (layerSize + headerSize);
  1802. // Copy header
  1803. memcpy(header, compressedHeader, headerSize);
  1804. // Decompress grid.
  1805. int size = 0;
  1806. dtStatus status = comp->decompress(compressed+headerSize, compressedSize-headerSize,
  1807. grids, gridsSize, &size);
  1808. if (dtStatusFailed(status))
  1809. {
  1810. dtFree(buffer);
  1811. return status;
  1812. }
  1813. layer->header = header;
  1814. layer->heights = grids;
  1815. layer->areas = grids + gridSize;
  1816. layer->cons = grids + gridSize*2;
  1817. layer->regs = grids + gridSize*3;
  1818. *layerOut = layer;
  1819. return DT_SUCCESS;
  1820. }
  1821. bool dtTileCacheHeaderSwapEndian(unsigned char* data, const int dataSize)
  1822. {
  1823. dtTileCacheLayerHeader* header = (dtTileCacheLayerHeader*)data;
  1824. int swappedMagic = DT_TILECACHE_MAGIC;
  1825. int swappedVersion = DT_TILECACHE_VERSION;
  1826. dtSwapEndian(&swappedMagic);
  1827. dtSwapEndian(&swappedVersion);
  1828. if ((header->magic != DT_TILECACHE_MAGIC || header->version != DT_TILECACHE_VERSION) &&
  1829. (header->magic != swappedMagic || header->version != swappedVersion))
  1830. {
  1831. return false;
  1832. }
  1833. dtSwapEndian(&header->magic);
  1834. dtSwapEndian(&header->version);
  1835. dtSwapEndian(&header->tx);
  1836. dtSwapEndian(&header->ty);
  1837. dtSwapEndian(&header->tlayer);
  1838. dtSwapEndian(&header->bmin[0]);
  1839. dtSwapEndian(&header->bmin[1]);
  1840. dtSwapEndian(&header->bmin[2]);
  1841. dtSwapEndian(&header->bmax[0]);
  1842. dtSwapEndian(&header->bmax[1]);
  1843. dtSwapEndian(&header->bmax[2]);
  1844. dtSwapEndian(&header->hmin);
  1845. dtSwapEndian(&header->hmax);
  1846. // width, height, minx, maxx, miny, maxy are unsigned char, no need to swap.
  1847. return true;
  1848. }