CCAutoPolygon.cpp 23 KB

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