CCAutoPolygon.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2010-2012 cocos2d-x.org
  4. Copyright (c) 2011 Zynga Inc.
  5. Copyright (c) 2013-2017 Chukong Technologies Inc.
  6. http://www.cocos2d-x.org
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. ****************************************************************************/
  23. #include "2d/CCAutoPolygon.h"
  24. #include "poly2tri/poly2tri.h"
  25. #include "base/CCDirector.h"
  26. #include "renderer/CCTextureCache.h"
  27. #include "clipper/clipper.hpp"
  28. #include <algorithm>
  29. #include <math.h>
  30. USING_NS_CC;
  31. static unsigned short quadIndices9[]={
  32. 0+4*0,1+4*0,2+4*0, 3+4*0,2+4*0,1+4*0,
  33. 0+4*1,1+4*1,2+4*1, 3+4*1,2+4*1,1+4*1,
  34. 0+4*2,1+4*2,2+4*2, 3+4*2,2+4*2,1+4*2,
  35. 0+4*3,1+4*3,2+4*3, 3+4*3,2+4*3,1+4*3,
  36. 0+4*4,1+4*4,2+4*4, 3+4*4,2+4*4,1+4*4,
  37. 0+4*5,1+4*5,2+4*5, 3+4*5,2+4*5,1+4*5,
  38. 0+4*6,1+4*6,2+4*6, 3+4*6,2+4*6,1+4*6,
  39. 0+4*7,1+4*7,2+4*7, 3+4*7,2+4*7,1+4*7,
  40. 0+4*8,1+4*8,2+4*8, 3+4*8,2+4*8,1+4*8,
  41. };
  42. const static float PRECISION = 10.0f;
  43. PolygonInfo::PolygonInfo()
  44. : _rect(Rect::ZERO)
  45. , _filename("")
  46. , _isVertsOwner(true)
  47. {
  48. triangles.verts = nullptr;
  49. triangles.indices = nullptr;
  50. triangles.vertCount = 0;
  51. triangles.indexCount = 0;
  52. };
  53. PolygonInfo::PolygonInfo(const PolygonInfo& other)
  54. : triangles()
  55. , _rect()
  56. , _isVertsOwner(true)
  57. {
  58. _filename = other._filename;
  59. _isVertsOwner = true;
  60. _rect = other._rect;
  61. triangles.verts = new (std::nothrow) V3F_C4B_T2F[other.triangles.vertCount];
  62. triangles.indices = new (std::nothrow) unsigned short[other.triangles.indexCount];
  63. CCASSERT(triangles.verts && triangles.indices, "not enough memory");
  64. triangles.vertCount = other.triangles.vertCount;
  65. triangles.indexCount = other.triangles.indexCount;
  66. memcpy(triangles.verts, other.triangles.verts, other.triangles.vertCount * sizeof(other.triangles.verts[0]));
  67. memcpy(triangles.indices, other.triangles.indices, other.triangles.indexCount * sizeof(other.triangles.indices[0]));
  68. };
  69. PolygonInfo& PolygonInfo::operator= (const PolygonInfo& other)
  70. {
  71. if(this != &other)
  72. {
  73. releaseVertsAndIndices();
  74. _filename = other._filename;
  75. _isVertsOwner = true;
  76. _rect = other._rect;
  77. triangles.verts = new (std::nothrow) V3F_C4B_T2F[other.triangles.vertCount];
  78. triangles.indices = new (std::nothrow) unsigned short[other.triangles.indexCount];
  79. CCASSERT(triangles.verts && triangles.indices, "not enough memory");
  80. triangles.vertCount = other.triangles.vertCount;
  81. triangles.indexCount = other.triangles.indexCount;
  82. memcpy(triangles.verts, other.triangles.verts, other.triangles.vertCount * sizeof(other.triangles.verts[0]));
  83. memcpy(triangles.indices, other.triangles.indices, other.triangles.indexCount * sizeof(other.triangles.indices[0]));
  84. }
  85. return *this;
  86. }
  87. PolygonInfo::~PolygonInfo()
  88. {
  89. releaseVertsAndIndices();
  90. }
  91. void PolygonInfo::setQuad(V3F_C4B_T2F_Quad *quad)
  92. {
  93. releaseVertsAndIndices();
  94. _isVertsOwner = false;
  95. triangles.indices = quadIndices9;
  96. triangles.vertCount = 4;
  97. triangles.indexCount = 6;
  98. triangles.verts = (V3F_C4B_T2F*)quad;
  99. }
  100. void PolygonInfo::setQuads(V3F_C4B_T2F_Quad *quad, int numberOfQuads)
  101. {
  102. CCASSERT(numberOfQuads >= 1 && numberOfQuads <= 9, "Invalid number of Quads");
  103. releaseVertsAndIndices();
  104. _isVertsOwner = false;
  105. triangles.indices = quadIndices9;
  106. triangles.vertCount = 4 * numberOfQuads;
  107. triangles.indexCount = 6 * numberOfQuads;
  108. triangles.verts = (V3F_C4B_T2F*)quad;
  109. }
  110. void PolygonInfo::setTriangles(const TrianglesCommand::Triangles& other)
  111. {
  112. this->releaseVertsAndIndices();
  113. _isVertsOwner = false;
  114. this->triangles.vertCount = other.vertCount;
  115. this->triangles.indexCount = other.indexCount;
  116. this->triangles.verts = other.verts;
  117. this->triangles.indices = other.indices;
  118. }
  119. void PolygonInfo::releaseVertsAndIndices()
  120. {
  121. if(_isVertsOwner)
  122. {
  123. if(nullptr != triangles.verts)
  124. {
  125. CC_SAFE_DELETE_ARRAY(triangles.verts);
  126. }
  127. if(nullptr != triangles.indices)
  128. {
  129. CC_SAFE_DELETE_ARRAY(triangles.indices);
  130. }
  131. }
  132. }
  133. unsigned int PolygonInfo::getVertCount() const
  134. {
  135. return (unsigned int)triangles.vertCount;
  136. }
  137. unsigned int PolygonInfo::getTrianglesCount() const
  138. {
  139. return (unsigned int)triangles.indexCount/3;
  140. }
  141. unsigned int PolygonInfo::getTriaglesCount() const
  142. {
  143. return getTrianglesCount();
  144. }
  145. float PolygonInfo::getArea() const
  146. {
  147. float area = 0;
  148. V3F_C4B_T2F *verts = triangles.verts;
  149. unsigned short *indices = triangles.indices;
  150. for(int i = 0; i < triangles.indexCount; i+=3)
  151. {
  152. auto A = verts[indices[i]].vertices;
  153. auto B = verts[indices[i+1]].vertices;
  154. auto C = verts[indices[i+2]].vertices;
  155. area += (A.x*(B.y-C.y) + B.x*(C.y-A.y) + C.x*(A.y - B.y))/2;
  156. }
  157. return area;
  158. }
  159. AutoPolygon::AutoPolygon(const std::string &filename)
  160. :_image(nullptr)
  161. ,_data(nullptr)
  162. ,_filename("")
  163. ,_width(0)
  164. ,_height(0)
  165. ,_scaleFactor(0)
  166. {
  167. _filename = filename;
  168. _image = new (std::nothrow) Image();
  169. _image->initWithImageFile(filename);
  170. CCASSERT(_image->getRenderFormat()==Texture2D::PixelFormat::RGBA8888, "unsupported format, currently only supports rgba8888");
  171. _data = _image->getData();
  172. _width = _image->getWidth();
  173. _height = _image->getHeight();
  174. _scaleFactor = Director::getInstance()->getContentScaleFactor();
  175. }
  176. AutoPolygon::~AutoPolygon()
  177. {
  178. CC_SAFE_DELETE(_image);
  179. }
  180. std::vector<Vec2> AutoPolygon::trace(const Rect& rect, float threshold)
  181. {
  182. Vec2 first = findFirstNoneTransparentPixel(rect, threshold);
  183. return marchSquare(rect, first, threshold);
  184. }
  185. Vec2 AutoPolygon::findFirstNoneTransparentPixel(const Rect& rect, float threshold)
  186. {
  187. bool found = false;
  188. Vec2 i;
  189. for(i.y = rect.origin.y; i.y < rect.origin.y+rect.size.height; i.y++)
  190. {
  191. if(found)break;
  192. for(i.x = rect.origin.x; i.x < rect.origin.x+rect.size.width; i.x++)
  193. {
  194. auto alpha = getAlphaByPos(i);
  195. if(alpha>threshold)
  196. {
  197. found = true;
  198. break;
  199. }
  200. }
  201. }
  202. CCASSERT(found, "image is all transparent!");
  203. return i;
  204. }
  205. unsigned char AutoPolygon::getAlphaByIndex(unsigned int i)
  206. {
  207. return *(_data+i*4+3);
  208. }
  209. unsigned char AutoPolygon::getAlphaByPos(const Vec2& pos)
  210. {
  211. return *(_data+((int)pos.y*_width+(int)pos.x)*4+3);
  212. }
  213. unsigned int AutoPolygon::getSquareValue(unsigned int x, unsigned int y, const Rect& rect, float threshold)
  214. {
  215. /*
  216. checking the 2x2 pixel grid, assigning these values to each pixel, if not transparent
  217. +---+---+
  218. | 1 | 2 |
  219. +---+---+
  220. | 4 | 8 | <- current pixel (curx,cury)
  221. +---+---+
  222. */
  223. unsigned int sv = 0;
  224. //NOTE: due to the way we pick points from texture, rect needs to be smaller, otherwise it goes outside 1 pixel
  225. auto fixedRect = Rect(rect.origin, rect.size-Size(2,2));
  226. Vec2 tl = Vec2(x-1, y-1);
  227. sv += (fixedRect.containsPoint(tl) && getAlphaByPos(tl) > threshold)? 1 : 0;
  228. Vec2 tr = Vec2(x, y-1);
  229. sv += (fixedRect.containsPoint(tr) && getAlphaByPos(tr) > threshold)? 2 : 0;
  230. Vec2 bl = Vec2(x-1, y);
  231. sv += (fixedRect.containsPoint(bl) && getAlphaByPos(bl) > threshold)? 4 : 0;
  232. Vec2 br = Vec2(x, y);
  233. sv += (fixedRect.containsPoint(br) && getAlphaByPos(br) > threshold)? 8 : 0;
  234. CCASSERT(sv != 0 && sv != 15, "square value should not be 0, or 15");
  235. return sv;
  236. }
  237. std::vector<cocos2d::Vec2> AutoPolygon::marchSquare(const Rect& rect, const Vec2& start, float threshold)
  238. {
  239. int stepx = 0;
  240. int stepy = 0;
  241. int prevx = 0;
  242. int prevy = 0;
  243. int startx = start.x;
  244. int starty = start.y;
  245. int curx = startx;
  246. int cury = starty;
  247. unsigned int count = 0;
  248. std::vector<int> case9s;
  249. std::vector<int> case6s;
  250. int i;
  251. std::vector<int>::iterator it;
  252. std::vector<cocos2d::Vec2> _points;
  253. do{
  254. int sv = getSquareValue(curx, cury, rect, threshold);
  255. switch(sv){
  256. case 1:
  257. case 5:
  258. case 13:
  259. /* going UP with these cases:
  260. 1 5 13
  261. +---+---+ +---+---+ +---+---+
  262. | 1 | | | 1 | | | 1 | |
  263. +---+---+ +---+---+ +---+---+
  264. | | | | 4 | | | 4 | 8 |
  265. +---+---+ +---+---+ +---+---+
  266. */
  267. stepx = 0;
  268. stepy = -1;
  269. break;
  270. case 8:
  271. case 10:
  272. case 11:
  273. /* going DOWN with these cases:
  274. 8 10 11
  275. +---+---+ +---+---+ +---+---+
  276. | | | | | 2 | | 1 | 2 |
  277. +---+---+ +---+---+ +---+---+
  278. | | 8 | | | 8 | | | 8 |
  279. +---+---+ +---+---+ +---+---+
  280. */
  281. stepx = 0;
  282. stepy = 1;
  283. break;
  284. case 4:
  285. case 12:
  286. case 14:
  287. /* going LEFT with these cases:
  288. 4 12 14
  289. +---+---+ +---+---+ +---+---+
  290. | | | | | | | | 2 |
  291. +---+---+ +---+---+ +---+---+
  292. | 4 | | | 4 | 8 | | 4 | 8 |
  293. +---+---+ +---+---+ +---+---+
  294. */
  295. stepx = -1;
  296. stepy = 0;
  297. break;
  298. case 2 :
  299. case 3 :
  300. case 7 :
  301. /* going RIGHT with these cases:
  302. 2 3 7
  303. +---+---+ +---+---+ +---+---+
  304. | | 2 | | 1 | 2 | | 1 | 2 |
  305. +---+---+ +---+---+ +---+---+
  306. | | | | | | | 4 | |
  307. +---+---+ +---+---+ +---+---+
  308. */
  309. stepx=1;
  310. stepy=0;
  311. break;
  312. case 9 :
  313. /*
  314. +---+---+
  315. | 1 | |
  316. +---+---+
  317. | | 8 |
  318. +---+---+
  319. this should normally go UP, but if we already been here, we go down
  320. */
  321. //find index from xy;
  322. i = getIndexFromPos(curx, cury);
  323. it = find (case9s.begin(), case9s.end(), i);
  324. if (it != case9s.end())
  325. {
  326. //found, so we go down, and delete from case9s;
  327. stepx = 0;
  328. stepy = 1;
  329. case9s.erase(it);
  330. }
  331. else
  332. {
  333. //not found, we go up, and add to case9s;
  334. stepx = 0;
  335. stepy = -1;
  336. case9s.push_back(i);
  337. }
  338. break;
  339. case 6 :
  340. /*
  341. 6
  342. +---+---+
  343. | | 2 |
  344. +---+---+
  345. | 4 | |
  346. +---+---+
  347. this normally go RIGHT, but if its coming from UP, it should go LEFT
  348. */
  349. i = getIndexFromPos(curx, cury);
  350. it = find (case6s.begin(), case6s.end(), i);
  351. if (it != case6s.end())
  352. {
  353. //found, so we go down, and delete from case9s;
  354. stepx = -1;
  355. stepy = 0;
  356. case6s.erase(it);
  357. }
  358. else{
  359. //not found, we go up, and add to case9s;
  360. stepx = 1;
  361. stepy = 0;
  362. case6s.push_back(i);
  363. }
  364. break;
  365. default:
  366. CCLOG("this shouldn't happen.");
  367. }
  368. //little optimization
  369. // if previous direction is same as current direction,
  370. // then we should modify the last vec to current
  371. curx += stepx;
  372. cury += stepy;
  373. if(stepx == prevx && stepy == prevy)
  374. {
  375. _points.back().x = (float)(curx-rect.origin.x) / _scaleFactor;
  376. _points.back().y = (float)(rect.size.height - cury + rect.origin.y) / _scaleFactor;
  377. }
  378. else
  379. {
  380. _points.push_back(Vec2((float)(curx - rect.origin.x) / _scaleFactor, (float)(rect.size.height - cury + rect.origin.y) / _scaleFactor));
  381. }
  382. count++;
  383. prevx = stepx;
  384. prevy = stepy;
  385. #if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
  386. const auto totalPixel = _width * _height;
  387. CCASSERT(count <= totalPixel, "oh no, marching square cannot find starting position");
  388. #endif
  389. } while(curx != startx || cury != starty);
  390. return _points;
  391. }
  392. float AutoPolygon::perpendicularDistance(const cocos2d::Vec2& i, const cocos2d::Vec2& start, const cocos2d::Vec2& end)
  393. {
  394. float res;
  395. float slope;
  396. float intercept;
  397. if(start.x == end.x)
  398. {
  399. res = fabsf(i.x- end.x);
  400. }
  401. else if (start.y == end.y)
  402. {
  403. res = fabsf(i.y - end.y);
  404. }
  405. else{
  406. slope = (end.y - start.y) / (end.x - start.x);
  407. intercept = start.y - (slope*start.x);
  408. res = fabsf(slope * i.x - i.y + intercept) / sqrtf(powf(slope, 2)+1);
  409. }
  410. return res;
  411. }
  412. std::vector<cocos2d::Vec2> AutoPolygon::rdp(const std::vector<cocos2d::Vec2>& v, float optimization)
  413. {
  414. if(v.size() < 3)
  415. return v;
  416. int index = -1;
  417. float dist = 0;
  418. //not looping first and last point
  419. for(size_t i = 1, size = v.size(); i < size-1; ++i)
  420. {
  421. float cdist = perpendicularDistance(v[i], v.front(), v.back());
  422. if(cdist > dist)
  423. {
  424. dist = cdist;
  425. index = static_cast<int>(i);
  426. }
  427. }
  428. if (dist>optimization)
  429. {
  430. std::vector<Vec2>::const_iterator begin = v.begin();
  431. std::vector<Vec2>::const_iterator end = v.end();
  432. std::vector<Vec2> l1(begin, begin+index+1);
  433. std::vector<Vec2> l2(begin+index, end);
  434. std::vector<Vec2> r1 = rdp(l1, optimization);
  435. std::vector<Vec2> r2 = rdp(l2, optimization);
  436. r1.insert(r1.end(), r2.begin()+1, r2.end());
  437. return r1;
  438. }
  439. else {
  440. std::vector<Vec2> ret;
  441. ret.push_back(v.front());
  442. ret.push_back(v.back());
  443. return ret;
  444. }
  445. }
  446. std::vector<Vec2> AutoPolygon::reduce(const std::vector<Vec2>& points, const Rect& rect, float epsilon)
  447. {
  448. auto size = points.size();
  449. // if there are less than 3 points, then we have nothing
  450. if(size<3)
  451. {
  452. log("AUTOPOLYGON: cannot reduce points for %s that has less than 3 points in input, e: %f", _filename.c_str(), epsilon);
  453. return std::vector<Vec2>();
  454. }
  455. // if there are less than 9 points (but more than 3), then we don't need to reduce it
  456. else if (size < 9)
  457. {
  458. log("AUTOPOLYGON: cannot reduce points for %s e: %f",_filename.c_str(), epsilon);
  459. return points;
  460. }
  461. float maxEp = MIN(rect.size.width, rect.size.height);
  462. float ep = clampf(epsilon, 0.0, maxEp/_scaleFactor/2);
  463. std::vector<Vec2> result = rdp(points, ep);
  464. auto last = result.back();
  465. if (last.y > result.front().y && last.getDistance(result.front()) < ep * 0.5f)
  466. {
  467. result.front().y = last.y;
  468. result.pop_back();
  469. }
  470. return result;
  471. }
  472. std::vector<Vec2> AutoPolygon::expand(const std::vector<Vec2>& points, const cocos2d::Rect &rect, float epsilon)
  473. {
  474. auto size = points.size();
  475. // if there are less than 3 points, then we have nothing
  476. if(size<3)
  477. {
  478. log("AUTOPOLYGON: cannot expand points for %s with less than 3 points, e: %f", _filename.c_str(), epsilon);
  479. return std::vector<Vec2>();
  480. }
  481. ClipperLib::Path subj;
  482. ClipperLib::PolyTree solution;
  483. ClipperLib::PolyTree out;
  484. for(const auto& pt : points)
  485. {
  486. subj << ClipperLib::IntPoint(pt.x* PRECISION, pt.y * PRECISION);
  487. }
  488. ClipperLib::ClipperOffset co;
  489. co.AddPath(subj, ClipperLib::jtMiter, ClipperLib::etClosedPolygon);
  490. co.Execute(solution, epsilon * PRECISION);
  491. ClipperLib::PolyNode* p = solution.GetFirst();
  492. if(!p)
  493. {
  494. log("AUTOPOLYGON: Clipper failed to expand the points");
  495. return points;
  496. }
  497. while(p->IsHole()){
  498. p = p->GetNext();
  499. }
  500. //turn the result into simply polygon (AKA, fix overlap)
  501. //clamp into the specified rect
  502. ClipperLib::Clipper cl;
  503. cl.StrictlySimple(true);
  504. cl.AddPath(p->Contour, ClipperLib::ptSubject, true);
  505. //create the clipping rect
  506. ClipperLib::Path clamp;
  507. clamp.push_back(ClipperLib::IntPoint(0, 0));
  508. clamp.push_back(ClipperLib::IntPoint(rect.size.width/_scaleFactor * PRECISION, 0));
  509. clamp.push_back(ClipperLib::IntPoint(rect.size.width/_scaleFactor * PRECISION, rect.size.height/_scaleFactor * PRECISION));
  510. clamp.push_back(ClipperLib::IntPoint(0, rect.size.height/_scaleFactor * PRECISION));
  511. cl.AddPath(clamp, ClipperLib::ptClip, true);
  512. cl.Execute(ClipperLib::ctIntersection, out);
  513. std::vector<Vec2> outPoints;
  514. ClipperLib::PolyNode* p2 = out.GetFirst();
  515. while(p2->IsHole()){
  516. p2 = p2->GetNext();
  517. }
  518. for(const auto& pt : p2->Contour)
  519. {
  520. outPoints.push_back(Vec2(pt.X/PRECISION, pt.Y/PRECISION));
  521. }
  522. return outPoints;
  523. }
  524. TrianglesCommand::Triangles AutoPolygon::triangulate(const std::vector<Vec2>& points)
  525. {
  526. // if there are less than 3 points, then we can't triangulate
  527. if(points.size()<3)
  528. {
  529. log("AUTOPOLYGON: cannot triangulate %s with less than 3 points", _filename.c_str());
  530. return TrianglesCommand::Triangles();
  531. }
  532. std::vector<p2t::Point*> p2points;
  533. for(const auto& pt : points)
  534. {
  535. p2t::Point * p = new (std::nothrow) p2t::Point(pt.x, pt.y);
  536. p2points.push_back(p);
  537. }
  538. p2t::CDT cdt(p2points);
  539. cdt.Triangulate();
  540. std::vector<p2t::Triangle*> tris = cdt.GetTriangles();
  541. // we won't know the size of verts and indices until we process all of the triangles!
  542. std::vector<V3F_C4B_T2F> verts;
  543. std::vector<unsigned short> indices;
  544. unsigned short idx = 0;
  545. unsigned short vdx = 0;
  546. for(const auto& ite : tris)
  547. {
  548. for(int i = 0; i < 3; ++i)
  549. {
  550. auto p = ite->GetPoint(i);
  551. auto v3 = Vec3(p->x, p->y, 0);
  552. bool found = false;
  553. size_t j;
  554. size_t length = vdx;
  555. for(j = 0; j < length; j++)
  556. {
  557. if(verts[j].vertices == v3)
  558. {
  559. found = true;
  560. break;
  561. }
  562. }
  563. if(found)
  564. {
  565. //if we found the same vertex, don't add to verts, but use the same vertex with indices
  566. indices.push_back(j);
  567. idx++;
  568. }
  569. else
  570. {
  571. //vert does not exist yet, so we need to create a new one,
  572. auto c4b = Color4B::WHITE;
  573. auto t2f = Tex2F(0,0); // don't worry about tex coords now, we calculate that later
  574. V3F_C4B_T2F vert = {v3,c4b,t2f};
  575. verts.push_back(vert);
  576. indices.push_back(vdx);
  577. idx++;
  578. vdx++;
  579. }
  580. }
  581. }
  582. for(auto j : p2points)
  583. {
  584. delete j;
  585. };
  586. // now that we know the size of verts and indices we can create the buffers
  587. V3F_C4B_T2F* vertsBuf = new (std::nothrow) V3F_C4B_T2F[verts.size()];
  588. memcpy(vertsBuf, verts.data(), verts.size() * sizeof(V3F_C4B_T2F));
  589. unsigned short* indicesBuf = new (std::nothrow) unsigned short[indices.size()];
  590. memcpy(indicesBuf, indices.data(), indices.size() * sizeof(short));
  591. // Triangles should really use std::vector and not arrays for verts and indices.
  592. // Then the above memcpy would not be necessary
  593. TrianglesCommand::Triangles triangles = { vertsBuf, indicesBuf, static_cast<int>(verts.size()), static_cast<int>(indices.size()) };
  594. return triangles;
  595. }
  596. void AutoPolygon::calculateUV(const Rect& rect, V3F_C4B_T2F* verts, ssize_t count)
  597. {
  598. /*
  599. whole texture UV coordination
  600. 0,0 1,0
  601. +---------------------+
  602. | |0.1
  603. | |0.2
  604. | +--------+ |0.3
  605. | |texRect | |0.4
  606. | | | |0.5
  607. | | | |0.6
  608. | +--------+ |0.7
  609. | |0.8
  610. | |0.9
  611. +---------------------+
  612. 0,1 1,1
  613. */
  614. CCASSERT(_width && _height, "please specify width and height for this AutoPolygon instance");
  615. float texWidth = _width;
  616. float texHeight = _height;
  617. auto end = &verts[count];
  618. for(auto i = verts; i != end; ++i)
  619. {
  620. // for every point, offset with the center point
  621. float u = (i->vertices.x*_scaleFactor + rect.origin.x) / texWidth;
  622. float v = (rect.origin.y+rect.size.height - i->vertices.y*_scaleFactor) / texHeight;
  623. i->texCoords.u = u;
  624. i->texCoords.v = v;
  625. }
  626. }
  627. Rect AutoPolygon::getRealRect(const Rect& rect)
  628. {
  629. Rect realRect = rect;
  630. //check rect to see if its zero
  631. if(realRect.equals(Rect::ZERO))
  632. {
  633. //if the instance doesn't have width and height, then the whole operation is kaput
  634. CCASSERT(_height && _width, "Please specify a width and height for this instance before using its functions");
  635. realRect = Rect(0,0, _width, _height);
  636. }
  637. else{
  638. //rect is specified, so convert to real rect
  639. realRect = CC_RECT_POINTS_TO_PIXELS(rect);
  640. }
  641. return realRect;
  642. }
  643. PolygonInfo AutoPolygon::generateTriangles(const Rect& rect, float epsilon, float threshold)
  644. {
  645. Rect realRect = getRealRect(rect);
  646. auto p = trace(realRect, threshold);
  647. p = reduce(p, realRect, epsilon);
  648. p = expand(p, realRect, epsilon);
  649. auto tri = triangulate(p);
  650. calculateUV(realRect, tri.verts, tri.vertCount);
  651. PolygonInfo ret;
  652. ret.triangles = tri;
  653. ret.setFilename(_filename);
  654. ret.setRect(realRect);
  655. return ret;
  656. }
  657. PolygonInfo AutoPolygon::generatePolygon(const std::string& filename, const Rect& rect, float epsilon, float threshold)
  658. {
  659. AutoPolygon ap(filename);
  660. return ap.generateTriangles(rect, epsilon, threshold);
  661. }