You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

649 lines
20 KiB

  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Modifications Copyright (C) 2018 KiCad Developers
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, you may find one here:
  18. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  19. * or you may search the http://www.gnu.org website for the version 2 license,
  20. * or you may write to the Free Software Foundation, Inc.,
  21. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  22. *
  23. * Based on Uniform Plane Subdivision algorithm from Lamot, Marko, and Borut Žalik.
  24. * "A fast polygon triangulation algorithm based on uniform plane subdivision."
  25. * Computers & graphics 27, no. 2 (2003): 239-253.
  26. *
  27. * Code derived from:
  28. * K-3D which is Copyright (c) 2005-2006, Romain Behar, GPL-2, license above
  29. * earcut which is Copyright (c) 2016, Mapbox, ISC
  30. *
  31. * ISC License:
  32. * Permission to use, copy, modify, and/or distribute this software for any purpose
  33. * with or without fee is hereby granted, provided that the above copyright notice
  34. * and this permission notice appear in all copies.
  35. *
  36. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  37. * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  38. * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  39. * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  40. * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  41. * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  42. * THIS SOFTWARE.
  43. *
  44. */
  45. #ifndef __POLYGON_TRIANGULATION_H
  46. #define __POLYGON_TRIANGULATION_H
  47. #include <algorithm>
  48. #include <cmath>
  49. #include <vector>
  50. #include <math/box2.h>
  51. #include "clipper.hpp"
  52. class PolygonTriangulation
  53. {
  54. public:
  55. PolygonTriangulation( SHAPE_POLY_SET::TRIANGULATED_POLYGON& aResult ) :
  56. m_result( aResult )
  57. {};
  58. private:
  59. struct Vertex
  60. {
  61. Vertex( size_t aIndex, double aX, double aY, PolygonTriangulation* aParent ) :
  62. i( aIndex ), x( aX ), y( aY ), parent( aParent )
  63. {
  64. }
  65. Vertex& operator=( const Vertex& ) = delete;
  66. Vertex& operator=( Vertex&& ) = delete;
  67. bool operator==( const Vertex& rhs ) const
  68. {
  69. return this->x == rhs.x && this->y == rhs.y;
  70. }
  71. bool operator!=( const Vertex& rhs ) const { return !( *this == rhs ); }
  72. /**
  73. * Function split
  74. * Splits the referenced polygon between the reference point and
  75. * vertex b, assuming they are in the same polygon. Notes that while we
  76. * create a new vertex pointer for the linked list, we maintain the same
  77. * vertex index value from the original polygon. In this way, we have
  78. * two polygons that both share the same vertices.
  79. *
  80. * Returns the pointer to the newly created vertex in the polygon that
  81. * does not include the reference vertex.
  82. */
  83. Vertex* split( Vertex* b )
  84. {
  85. parent->m_vertices.emplace_back( i, x, y, parent );
  86. Vertex* a2 = &parent->m_vertices.back();
  87. parent->m_vertices.emplace_back( b->i, b->x, b->y, parent );
  88. Vertex* b2 = &parent->m_vertices.back();
  89. Vertex* an = next;
  90. Vertex* bp = b->prev;
  91. next = b;
  92. b->prev = this;
  93. a2->next = an;
  94. an->prev = a2;
  95. b2->next = a2;
  96. a2->prev = b2;
  97. bp->next = b2;
  98. b2->prev = bp;
  99. return b2;
  100. }
  101. /**
  102. * Function remove
  103. * Removes the node from the linked list and z-ordered linked list.
  104. */
  105. void remove()
  106. {
  107. next->prev = prev;
  108. prev->next = next;
  109. if( prevZ )
  110. prevZ->nextZ = nextZ;
  111. if( nextZ )
  112. nextZ->prevZ = prevZ;
  113. next = NULL;
  114. prev = NULL;
  115. nextZ = NULL;
  116. prevZ = NULL;
  117. }
  118. void updateOrder()
  119. {
  120. if( !z )
  121. z = parent->zOrder( x, y );
  122. }
  123. /**
  124. * Function updateList
  125. * After inserting or changing nodes, this function should be called to
  126. * remove duplicate vertices and ensure z-ordering is correct
  127. */
  128. void updateList()
  129. {
  130. Vertex* p = next;
  131. while( p != this )
  132. {
  133. /**
  134. * Remove duplicates
  135. */
  136. if( *p == *p->next )
  137. {
  138. p = p->prev;
  139. p->next->remove();
  140. if( p == p->next )
  141. break;
  142. }
  143. p->updateOrder();
  144. p = p->next;
  145. };
  146. updateOrder();
  147. zSort();
  148. }
  149. /**
  150. * Sort all vertices in this vertex's list by their Morton code
  151. */
  152. void zSort()
  153. {
  154. std::deque<Vertex*> queue;
  155. queue.push_back( this );
  156. for( auto p = next; p && p != this; p = p->next )
  157. queue.push_back( p );
  158. std::sort( queue.begin(), queue.end(), []( const Vertex* a, const Vertex* b)
  159. {
  160. return a->z < b->z;
  161. } );
  162. Vertex* prev_elem = nullptr;
  163. for( auto elem : queue )
  164. {
  165. if( prev_elem )
  166. prev_elem->nextZ = elem;
  167. elem->prevZ = prev_elem;
  168. prev_elem = elem;
  169. }
  170. prev_elem->nextZ = nullptr;
  171. }
  172. /**
  173. * Check to see if triangle surrounds our current vertex
  174. */
  175. bool inTriangle( const Vertex& a, const Vertex& b, const Vertex& c )
  176. {
  177. return ( c.x - x ) * ( a.y - y ) - ( a.x - x ) * ( c.y - y ) >= 0
  178. && ( a.x - x ) * ( b.y - y ) - ( b.x - x ) * ( a.y - y ) >= 0
  179. && ( b.x - x ) * ( c.y - y ) - ( c.x - x ) * ( b.y - y ) >= 0;
  180. }
  181. const size_t i;
  182. const double x;
  183. const double y;
  184. PolygonTriangulation* parent;
  185. // previous and next vertices nodes in a polygon ring
  186. Vertex* prev = nullptr;
  187. Vertex* next = nullptr;
  188. // z-order curve value
  189. int32_t z = 0;
  190. // previous and next nodes in z-order
  191. Vertex* prevZ = nullptr;
  192. Vertex* nextZ = nullptr;
  193. };
  194. BOX2I m_bbox;
  195. std::deque<Vertex> m_vertices;
  196. SHAPE_POLY_SET::TRIANGULATED_POLYGON& m_result;
  197. /**
  198. * Calculate the Morton code of the Vertex
  199. * http://www.graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN
  200. *
  201. */
  202. int32_t zOrder( const double aX, const double aY ) const
  203. {
  204. int32_t x = static_cast<int32_t>( 32767.0 * ( aX - m_bbox.GetX() ) / m_bbox.GetWidth() );
  205. int32_t y = static_cast<int32_t>( 32767.0 * ( aY - m_bbox.GetY() ) / m_bbox.GetHeight() );
  206. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  207. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  208. x = ( x | ( x << 2 ) ) & 0x33333333;
  209. x = ( x | ( x << 1 ) ) & 0x55555555;
  210. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  211. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  212. y = ( y | ( y << 2 ) ) & 0x33333333;
  213. y = ( y | ( y << 1 ) ) & 0x55555555;
  214. return x | ( y << 1 );
  215. }
  216. /**
  217. * Function removeNullTriangles
  218. * Iterates through the list to remove NULL triangles if they exist.
  219. * This should only be called as a last resort when tesselation fails
  220. * as the NULL triangles are inserted as Steiner points to improve the
  221. * triangulation regularity of polygons
  222. */
  223. bool removeNullTriangles( Vertex* aStart )
  224. {
  225. bool retval = false;
  226. Vertex* p = aStart->next;
  227. while( p != aStart )
  228. {
  229. if( area( p->prev, p, p->next ) == 0.0 )
  230. {
  231. p = p->prev;
  232. p->next->remove();
  233. retval = true;
  234. if( p == p->next )
  235. break;
  236. }
  237. p = p->next;
  238. };
  239. // We needed an end point above that wouldn't be removed, so
  240. // here we do the final check for this as a Steiner point
  241. if( area( aStart->prev, aStart, aStart->next ) == 0.0 )
  242. {
  243. p->remove();
  244. retval = true;
  245. }
  246. return retval;
  247. }
  248. /**
  249. * Function createList
  250. * Takes a Clipper path and converts it into a circular, doubly-linked
  251. * list for triangulation
  252. */
  253. Vertex* createList( const ClipperLib::Path& aPath )
  254. {
  255. Vertex* tail = nullptr;
  256. for( auto point : aPath )
  257. tail = insertVertex( VECTOR2I( point.X, point.Y ), tail );
  258. if( tail && ( *tail == *tail->next ) )
  259. {
  260. tail->next->remove();
  261. }
  262. return tail;
  263. }
  264. /**
  265. * Function createList
  266. * Takes the SHAPE_LINE_CHAIN and links each point into a
  267. * circular, doubly-linked list
  268. */
  269. Vertex* createList( const SHAPE_LINE_CHAIN& points )
  270. {
  271. Vertex* tail = nullptr;
  272. for( int i = 0; i < points.PointCount(); i++ )
  273. tail = insertVertex( points.CPoint( i ), tail );
  274. if( tail && ( *tail == *tail->next ) )
  275. {
  276. tail->next->remove();
  277. }
  278. return tail;
  279. }
  280. /**
  281. * Function: earcutList
  282. * Walks through a circular linked list starting at aPoint. For each point,
  283. * test to see if the adjacent points form a triangle that is completely enclosed
  284. * by the remaining polygon (an "ear" sticking off the polygon). If the three points
  285. * form an ear, we log the ear's location and remove the center point from the linked list.
  286. *
  287. * This function can be called recursively in the case of difficult polygons. In cases where
  288. * there is an intersection (not technically allowed by KiCad, but could exist in an edited file),
  289. * we create a single triangle and remove both vertices before attempting to
  290. */
  291. bool earcutList( Vertex* aPoint, int pass = 0 )
  292. {
  293. if( !aPoint )
  294. return true;
  295. Vertex* stop = aPoint;
  296. Vertex* prev;
  297. Vertex* next;
  298. while( aPoint->prev != aPoint->next )
  299. {
  300. prev = aPoint->prev;
  301. next = aPoint->next;
  302. if( isEar( aPoint ) )
  303. {
  304. m_result.AddTriangle( prev->i, aPoint->i, next->i );
  305. aPoint->remove();
  306. // Skip one vertex as the triangle will account for the prev node
  307. aPoint = next->next;
  308. stop = next->next;
  309. continue;
  310. }
  311. Vertex* nextNext = next->next;
  312. if( *prev != *nextNext && intersects( prev, aPoint, next, nextNext ) &&
  313. locallyInside( prev, nextNext ) &&
  314. locallyInside( nextNext, prev ) )
  315. {
  316. m_result.AddTriangle( prev->i, aPoint->i, nextNext->i );
  317. // remove two nodes involved
  318. next->remove();
  319. aPoint->remove();
  320. aPoint = nextNext;
  321. continue;
  322. }
  323. aPoint = next;
  324. /**
  325. * We've searched the entire polygon for available ears and there are still un-sliced nodes
  326. * remaining
  327. */
  328. if( aPoint == stop )
  329. {
  330. // First, try to remove the remaining steiner points
  331. if( removeNullTriangles( aPoint ) )
  332. continue;
  333. // If we don't have any NULL triangles left, cut the polygon in two and try again
  334. splitPolygon( aPoint );
  335. break;
  336. }
  337. }
  338. /**
  339. * At this point, our polygon should be fully tesselated.
  340. */
  341. return( aPoint->prev == aPoint->next );
  342. }
  343. /**
  344. * Function isEar
  345. * Checks whether the given vertex is in the middle of an ear.
  346. * This works by walking forward and backward in zOrder to the limits
  347. * of the minimal bounding box formed around the triangle, checking whether
  348. * any points are located inside the given triangle.
  349. *
  350. * Returns true if aEar is the apex point of a ear in the polygon
  351. */
  352. bool isEar( Vertex* aEar ) const
  353. {
  354. const Vertex* a = aEar->prev;
  355. const Vertex* b = aEar;
  356. const Vertex* c = aEar->next;
  357. // If the area >=0, then the three points for a concave sequence
  358. // with b as the reflex point
  359. if( area( a, b, c ) >= 0 )
  360. return false;
  361. // triangle bbox
  362. const double minTX = std::min( a->x, std::min( b->x, c->x ) );
  363. const double minTY = std::min( a->y, std::min( b->y, c->y ) );
  364. const double maxTX = std::max( a->x, std::max( b->x, c->x ) );
  365. const double maxTY = std::max( a->y, std::max( b->y, c->y ) );
  366. // z-order range for the current triangle bounding box
  367. const int32_t minZ = zOrder( minTX, minTY );
  368. const int32_t maxZ = zOrder( maxTX, maxTY );
  369. // first look for points inside the triangle in increasing z-order
  370. Vertex* p = aEar->nextZ;
  371. while( p && p->z <= maxZ )
  372. {
  373. if( p != a && p != c
  374. && p->inTriangle( *a, *b, *c )
  375. && area( p->prev, p, p->next ) >= 0 )
  376. return false;
  377. p = p->nextZ;
  378. }
  379. // then look for points in decreasing z-order
  380. p = aEar->prevZ;
  381. while( p && p->z >= minZ )
  382. {
  383. if( p != a && p != c
  384. && p->inTriangle( *a, *b, *c )
  385. && area( p->prev, p, p->next ) >= 0 )
  386. return false;
  387. p = p->prevZ;
  388. }
  389. return true;
  390. }
  391. /**
  392. * Function splitPolygon
  393. * If we cannot find an ear to slice in the current polygon list, we
  394. * use this to split the polygon into two separate lists and slice them each
  395. * independently. This is assured to generate at least one new ear if the
  396. * split is successful
  397. */
  398. void splitPolygon( Vertex* start )
  399. {
  400. Vertex* origPoly = start;
  401. do
  402. {
  403. Vertex* marker = origPoly->next->next;
  404. while( marker != origPoly->prev )
  405. {
  406. // Find a diagonal line that is wholly enclosed by the polygon interior
  407. if( origPoly->i != marker->i && goodSplit( origPoly, marker ) )
  408. {
  409. Vertex* newPoly = origPoly->split( marker );
  410. origPoly->updateList();
  411. newPoly->updateList();
  412. earcutList( origPoly );
  413. earcutList( newPoly );
  414. return;
  415. }
  416. marker = marker->next;
  417. }
  418. origPoly = origPoly->next;
  419. } while( origPoly != start );
  420. }
  421. /**
  422. * Check if a segment joining two vertices lies fully inside the polygon.
  423. * To do this, we first ensure that the line isn't along the polygon edge.
  424. * Next, we know that if the line doesn't intersect the polygon, then it is
  425. * either fully inside or fully outside the polygon. Finally, by checking whether
  426. * the segment is enclosed by the local triangles, we distinguish between
  427. * these two cases and no further checks are needed.
  428. */
  429. bool goodSplit( const Vertex* a, const Vertex* b ) const
  430. {
  431. return a->next->i != b->i &&
  432. a->prev->i != b->i &&
  433. !intersectsPolygon( a, b ) &&
  434. locallyInside( a, b );
  435. }
  436. /**
  437. * Function area
  438. * Returns the twice the signed area of the triangle formed by vertices
  439. * p, q, r.
  440. */
  441. double area( const Vertex* p, const Vertex* q, const Vertex* r ) const
  442. {
  443. return ( q->y - p->y ) * ( r->x - q->x ) - ( q->x - p->x ) * ( r->y - q->y );
  444. }
  445. /**
  446. * Function intersects
  447. * Checks for intersection between two segments, end points included.
  448. * Returns true if p1-p2 intersects q1-q2
  449. */
  450. bool intersects( const Vertex* p1, const Vertex* q1, const Vertex* p2, const Vertex* q2 ) const
  451. {
  452. if( ( *p1 == *q1 && *p2 == *q2 ) || ( *p1 == *q2 && *p2 == *q1 ) )
  453. return true;
  454. return ( area( p1, q1, p2 ) > 0 ) != ( area( p1, q1, q2 ) > 0 )
  455. && ( area( p2, q2, p1 ) > 0 ) != ( area( p2, q2, q1 ) > 0 );
  456. }
  457. /**
  458. * Function intersectsPolygon
  459. * Checks whether the segment from vertex a -> vertex b crosses any of the segments
  460. * of the polygon of which vertex a is a member.
  461. * Return true if the segment intersects the edge of the polygon
  462. */
  463. bool intersectsPolygon( const Vertex* a, const Vertex* b ) const
  464. {
  465. const Vertex* p = a->next;
  466. do
  467. {
  468. if( p->i != a->i &&
  469. p->next->i != a->i &&
  470. p->i != b->i &&
  471. p->next->i != b->i && intersects( p, p->next, a, b ) )
  472. return true;
  473. p = p->next;
  474. } while( p != a );
  475. return false;
  476. }
  477. /**
  478. * Function locallyInside
  479. * Checks whether the segment from vertex a -> vertex b is inside the polygon
  480. * around the immediate area of vertex a. We don't define the exact area
  481. * over which the segment is inside but it is guaranteed to be inside the polygon
  482. * immediately adjacent to vertex a.
  483. * Returns true if the segment from a->b is inside a's polygon next to vertex a
  484. */
  485. bool locallyInside( const Vertex* a, const Vertex* b ) const
  486. {
  487. if( area( a->prev, a, a->next ) < 0 )
  488. return area( a, b, a->next ) >= 0 && area( a, a->prev, b ) >= 0;
  489. else
  490. return area( a, b, a->prev ) < 0 || area( a, a->next, b ) < 0;
  491. }
  492. /**
  493. * Function insertVertex
  494. * Creates an entry in the vertices lookup and optionally inserts the newly
  495. * created vertex into an existing linked list.
  496. * Returns a pointer to the newly created vertex
  497. */
  498. Vertex* insertVertex( const VECTOR2I& pt, Vertex* last )
  499. {
  500. m_result.AddVertex( pt );
  501. m_vertices.emplace_back( m_result.GetVertexCount() - 1, pt.x, pt.y, this );
  502. Vertex* p = &m_vertices.back();
  503. if( !last )
  504. {
  505. p->prev = p;
  506. p->next = p;
  507. }
  508. else
  509. {
  510. p->next = last->next;
  511. p->prev = last;
  512. last->next->prev = p;
  513. last->next = p;
  514. }
  515. return p;
  516. }
  517. public:
  518. void TesselatePolygon( const SHAPE_LINE_CHAIN& aPoly )
  519. {
  520. ClipperLib::Clipper c;
  521. m_bbox = aPoly.BBox();
  522. if( !m_bbox.GetWidth() || !m_bbox.GetHeight() )
  523. return;
  524. Vertex* outerNode = createList( aPoly );
  525. if( !outerNode )
  526. return;
  527. outerNode->updateList();
  528. if( !earcutList( outerNode ) )
  529. {
  530. m_vertices.clear();
  531. m_result.Clear();
  532. ClipperLib::Paths simplified;
  533. ClipperLib::SimplifyPolygon( aPoly.convertToClipper( true ), simplified );
  534. for( auto path : simplified )
  535. {
  536. outerNode = createList( path );
  537. if( !outerNode )
  538. return;
  539. earcutList( outerNode );
  540. }
  541. }
  542. m_vertices.clear();
  543. }
  544. };
  545. #endif //__POLYGON_TRIANGULATION_H