KiCad PCB EDA Suite
Loading...
Searching...
No Matches
polygon_triangulation.h
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Modifications Copyright (C) 2018-2024 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
46#ifndef __POLYGON_TRIANGULATION_H
47#define __POLYGON_TRIANGULATION_H
48
49#include <algorithm>
50#include <deque>
51#include <cmath>
52
53#include <advanced_config.h>
54#include <clipper.hpp>
57#include <math/box2.h>
58#include <math/vector2d.h>
59
60#include <wx/log.h>
61
62#define TRIANGULATE_TRACE "triangulate"
64{
65public:
67 m_result( aResult )
68 {};
69
72 {
73 m_bbox = aPoly.BBox();
75
76 if( !m_bbox.GetWidth() || !m_bbox.GetHeight() )
77 return false;
78
82 VERTEX* firstVertex = createList( aPoly );
83
84 wxLogTrace( TRIANGULATE_TRACE, "Created list with %f area", firstVertex->area() );
85
86 if( !firstVertex || firstVertex->prev == firstVertex->next )
87 return false;
88
89 firstVertex->updateList();
90
91 if( aHintData )
92 {
93 m_result.Triangles() = aHintData->Triangles();
94 return true;
95 }
96 else
97 {
98 auto retval = earcutList( firstVertex );
99
100 if( !retval )
101 {
102 wxLogTrace( TRIANGULATE_TRACE, "Tesselation failed, logging remaining vertices" );
103 logRemaining();
104 }
105
106 m_vertices.clear();
107 return retval;
108 }
109 }
110
111private:
112 struct VERTEX
113 {
114 VERTEX( size_t aIndex, double aX, double aY, POLYGON_TRIANGULATION* aParent ) :
115 i( aIndex ),
116 x( aX ),
117 y( aY ),
118 parent( aParent )
119 {
120 }
121
122 VERTEX& operator=( const VERTEX& ) = delete;
123 VERTEX& operator=( VERTEX&& ) = delete;
124
125 bool operator==( const VERTEX& rhs ) const
126 {
127 return this->x == rhs.x && this->y == rhs.y;
128 }
129 bool operator!=( const VERTEX& rhs ) const { return !( *this == rhs ); }
130
131
143 {
144 parent->m_vertices.emplace_back( i, x, y, parent );
145 VERTEX* a2 = &parent->m_vertices.back();
146 parent->m_vertices.emplace_back( b->i, b->x, b->y, parent );
147 VERTEX* b2 = &parent->m_vertices.back();
148 VERTEX* an = next;
149 VERTEX* bp = b->prev;
150
151 next = b;
152 b->prev = this;
153
154 a2->next = an;
155 an->prev = a2;
156
157 b2->next = a2;
158 a2->prev = b2;
159
160 bp->next = b2;
161 b2->prev = bp;
162
163 return b2;
164 }
165
169 void remove()
170 {
171 next->prev = prev;
172 prev->next = next;
173
174 if( prevZ )
175 prevZ->nextZ = nextZ;
176
177 if( nextZ )
178 nextZ->prevZ = prevZ;
179
180 next = nullptr;
181 prev = nullptr;
182 nextZ = nullptr;
183 prevZ = nullptr;
184 }
185
187 {
188 if( !z )
189 z = parent->zOrder( x, y );
190 }
191
197 {
198 VERTEX* p = next;
199
200 while( p != this )
201 {
205 if( *p == *p->next )
206 {
207 p = p->prev;
208 p->next->remove();
209
210 if( p == p->next )
211 break;
212 }
213
214 p->updateOrder();
215 p = p->next;
216 };
217
218 updateOrder();
219 zSort();
220 }
221
225 void zSort()
226 {
227 std::deque<VERTEX*> queue;
228
229 queue.push_back( this );
230
231 for( auto p = next; p && p != this; p = p->next )
232 queue.push_back( p );
233
234 std::sort( queue.begin(), queue.end(), []( const VERTEX* a, const VERTEX* b )
235 {
236 if( a->z != b->z )
237 return a->z < b->z;
238
239 if( a->x != b->x )
240 return a->x < b->x;
241
242 if( a->y != b->y )
243 return a->y < b->y;
244
245 return a->i < b->i;
246 } );
247
248 VERTEX* prev_elem = nullptr;
249
250 for( auto elem : queue )
251 {
252 if( prev_elem )
253 prev_elem->nextZ = elem;
254
255 elem->prevZ = prev_elem;
256 prev_elem = elem;
257 }
258
259 prev_elem->nextZ = nullptr;
260 }
261
262
266 bool inTriangle( const VERTEX& a, const VERTEX& b, const VERTEX& c )
267 {
268 return ( c.x - x ) * ( a.y - y ) - ( a.x - x ) * ( c.y - y ) >= 0
269 && ( a.x - x ) * ( b.y - y ) - ( b.x - x ) * ( a.y - y ) >= 0
270 && ( b.x - x ) * ( c.y - y ) - ( c.x - x ) * ( b.y - y ) >= 0;
271 }
272
277 double area( const VERTEX* aEnd = nullptr ) const
278 {
279 const VERTEX* p = this;
280 double a = 0.0;
281
282 do
283 {
284 a += ( p->x + p->next->x ) * ( p->next->y - p->y );
285 p = p->next;
286 } while( p != this && p != aEnd );
287
288 if( p != this )
289 a += ( p->x + aEnd->x ) * ( aEnd->y - p->y );
290
291 return a / 2;
292 }
293
294 const size_t i;
295 double x;
296 double y;
298
299 // previous and next vertices nodes in a polygon ring
300 VERTEX* prev = nullptr;
301 VERTEX* next = nullptr;
302
303 // z-order curve value
304 int32_t z = 0;
305
306 // previous and next nodes in z-order
307 VERTEX* prevZ = nullptr;
308 VERTEX* nextZ = nullptr;
309 };
310
316 int32_t zOrder( const double aX, const double aY ) const
317 {
318 int32_t x = static_cast<int32_t>( 32767.0 * ( aX - m_bbox.GetX() ) / m_bbox.GetWidth() );
319 int32_t y = static_cast<int32_t>( 32767.0 * ( aY - m_bbox.GetY() ) / m_bbox.GetHeight() );
320
321 x = ( x | ( x << 8 ) ) & 0x00FF00FF;
322 x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
323 x = ( x | ( x << 2 ) ) & 0x33333333;
324 x = ( x | ( x << 1 ) ) & 0x55555555;
325
326 y = ( y | ( y << 8 ) ) & 0x00FF00FF;
327 y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
328 y = ( y | ( y << 2 ) ) & 0x33333333;
329 y = ( y | ( y << 1 ) ) & 0x55555555;
330
331 return x | ( y << 1 );
332 }
333
334
339 {
340 std::set<VERTEX*> seen;
341 wxLog::EnableLogging();
342 for( VERTEX& p : m_vertices )
343 {
344 if( !p.next || p.next == &p || seen.find( &p ) != seen.end() )
345 continue;
346
347 logVertices( &p, &seen );
348 }
349 }
350
351 void logVertices( VERTEX* aStart, std::set<VERTEX*>* aSeen )
352 {
353 if( aSeen && aSeen->count( aStart ) )
354 return;
355
356 if( aSeen )
357 aSeen->insert( aStart );
358
359 int count = 1;
360 VERTEX* p = aStart->next;
361 wxString msg = wxString::Format( "Vertices: %d,%d,", static_cast<int>( aStart->x ),
362 static_cast<int>( aStart->y ) );
363
364 do
365 {
366 msg += wxString::Format( "%d,%d,", static_cast<int>( p->x ), static_cast<int>( p->y ) );
367
368 if( aSeen )
369 aSeen->insert( p );
370
371 p = p->next;
372 count++;
373 } while( p != aStart );
374
375 if( count < 3 ) // Don't log anything that only has 2 or fewer points
376 return;
377
378 msg.RemoveLast();
379 wxLogTrace( TRIANGULATE_TRACE, msg );
380 }
381
382
391 {
392 VERTEX* retval = nullptr;
393 VERTEX* p = aStart->next;
394 size_t count = 0;
395
396 while( p != aStart )
397 {
398 // We make a dummy triangle that is actually part of the existing line segment
399 // and measure its area. This will not be exactly zero due to floating point
400 // errors. We then look for areas that are less than 4 times the area of the
401 // dummy triangle. For small triangles, this is a small number
402 VERTEX tmp( 0, 0.5 * ( p->prev->x + p->next->x ), 0.5 * ( p->prev->y + p->next->y ), this );
403 double null_area = 4.0 * std::abs( area( p->prev, &tmp, p->next ) );
404
405 if( *p == *( p->next ) || std::abs( area( p->prev, p, p->next ) ) <= null_area )
406 {
407 // This is a spike, remove it, leaving only one point
408 if( *( p->next ) == *( p->prev ) )
409 p->next->remove();
410
411 p = p->prev;
412 p->next->remove();
413 retval = aStart;
414 ++count;
415
416 if( p == p->next )
417 break;
418
419 continue;
420 }
421
422 p = p->next;
423 };
424
425 // We needed an end point above that wouldn't be removed, so
426 // here we do the final check for this as a Steiner point
427 VERTEX tmp( 0, 0.5 * ( aStart->prev->x + aStart->next->x ),
428 0.5 * ( aStart->prev->y + aStart->next->y ), this );
429 double null_area = 4.0 * std::abs( area( aStart->prev, &tmp, aStart->next ) );
430
431 if( std::abs( area( aStart->prev, aStart, aStart->next ) ) <= null_area )
432 {
433 retval = p->next;
434 p->remove();
435 ++count;
436 }
437
438 wxLogTrace( TRIANGULATE_TRACE, "Removed %zu NULL triangles", count );
439
440 return retval;
441 }
442
447 {
448 wxLogTrace( TRIANGULATE_TRACE, "Creating list from %d points", points.PointCount() );
449
450 VERTEX* tail = nullptr;
451 double sum = 0.0;
452
453 // Check for winding order
454 for( int i = 0; i < points.PointCount(); i++ )
455 {
456 VECTOR2D p1 = points.CPoint( i );
457 VECTOR2D p2 = points.CPoint( i + 1 );
458
459 sum += ( ( p2.x - p1.x ) * ( p2.y + p1.y ) );
460 }
461
462 VECTOR2I last_pt{ std::numeric_limits<int>::max(), std::numeric_limits<int>::max() };
464 sq_dist *= sq_dist;
465
466 auto addVertex = [&]( int i )
467 {
468 const VECTOR2I& pt = points.CPoint( i );
469 VECTOR2I diff = pt - last_pt;
470 if( diff.SquaredEuclideanNorm() > sq_dist )
471 {
472 tail = insertVertex( pt, tail );
473 last_pt = pt;
474 }
475 };
476
477 if( sum > 0.0 )
478 {
479 for( int i = points.PointCount() - 1; i >= 0; i-- )
480 addVertex( i );
481 }
482 else
483 {
484 for( int i = 0; i < points.PointCount(); i++ )
485 addVertex( i );
486 }
487
488 if( tail && ( *tail == *tail->next ) )
489 tail->next->remove();
490
491 return tail;
492 }
493
507 bool earcutList( VERTEX* aPoint, int pass = 0 )
508 {
509 wxLogTrace( TRIANGULATE_TRACE, "earcutList starting at %p for pass %d", aPoint, pass );
510
511 if( !aPoint )
512 return true;
513
514 VERTEX* stop = aPoint;
515 VERTEX* prev;
516 VERTEX* next;
517 int internal_pass = 1;
518
519 while( aPoint->prev != aPoint->next )
520 {
521 prev = aPoint->prev;
522 next = aPoint->next;
523
524 if( isEar( aPoint ) )
525 {
526 // Tiny ears cannot be seen on the screen
527 if( !isTooSmall( aPoint ) )
528 {
529 m_result.AddTriangle( prev->i, aPoint->i, next->i );
530 }
531 else
532 {
533 wxLogTrace( TRIANGULATE_TRACE, "Ignoring tiny ear with area %f",
534 area( prev, aPoint, next ) );
535 }
536
537 aPoint->remove();
538
539 // Skip one vertex as the triangle will account for the prev node
540 aPoint = next->next;
541 stop = next->next;
542
543 continue;
544 }
545
546 VERTEX* nextNext = next->next;
547
548 if( *prev != *nextNext && intersects( prev, aPoint, next, nextNext ) &&
549 locallyInside( prev, nextNext ) &&
550 locallyInside( nextNext, prev ) )
551 {
552 wxLogTrace( TRIANGULATE_TRACE,
553 "Local intersection detected. Merging minor triangle with area %f",
554 area( prev, aPoint, nextNext ) );
555 m_result.AddTriangle( prev->i, aPoint->i, nextNext->i );
556
557 // remove two nodes involved
558 next->remove();
559 aPoint->remove();
560
561 aPoint = nextNext;
562 stop = nextNext;
563
564 continue;
565 }
566
567 aPoint = next;
568
569 /*
570 * We've searched the entire polygon for available ears and there are still
571 * un-sliced nodes remaining.
572 */
573 if( aPoint == stop )
574 {
575 VERTEX* newPoint;
576
577 // Removing null triangles will remove steiner points as well as colinear points
578 // that are three in a row. Because our next step is to subdivide the polygon,
579 // we need to allow it to add the subdivided points first. This is why we only
580 // run the RemoveNullTriangles function after the first pass.
581 if( ( internal_pass == 2 ) && ( newPoint = removeNullTriangles( aPoint ) ) )
582 {
583 aPoint = newPoint;
584 stop = newPoint;
585 continue;
586 }
587
588 ++internal_pass;
589
590 // This will subdivide the polygon 2 times. The first pass will add enough points
591 // such that each edge is less than the average edge length. If this doesn't work
592 // The next pass will remove the null triangles (above) and subdivide the polygon
593 // again, this time adding one point to each long edge (and thereby changing the locations)
594 if( internal_pass < 4 )
595 {
596 wxLogTrace( TRIANGULATE_TRACE, "Subdividing polygon" );
597 subdividePolygon( aPoint, internal_pass );
598 continue;
599 }
600
601 // If we don't have any NULL triangles left, cut the polygon in two and try again
602 wxLogTrace( TRIANGULATE_TRACE, "Splitting polygon" );
603
604 if( !splitPolygon( aPoint ) )
605 return false;
606
607 break;
608 }
609 }
610
611 // Check to see if we are left with only three points in the polygon
612 if( aPoint->next && aPoint->prev == aPoint->next->next )
613 {
614 // Three concave points will never be able to be triangulated because they were
615 // created by an intersecting polygon, so just drop them.
616 if( area( aPoint->prev, aPoint, aPoint->next ) >= 0 )
617 return true;
618 }
619
620 /*
621 * At this point, our polygon should be fully tessellated.
622 */
623 if( aPoint->prev != aPoint->next )
625
626 return true;
627 }
628
629
634 bool isTooSmall( const VERTEX* aPoint ) const
635 {
637 double prev_sq_len = ( aPoint->prev->x - aPoint->x ) * ( aPoint->prev->x - aPoint->x ) +
638 ( aPoint->prev->y - aPoint->y ) * ( aPoint->prev->y - aPoint->y );
639 double next_sq_len = ( aPoint->next->x - aPoint->x ) * ( aPoint->next->x - aPoint->x ) +
640 ( aPoint->next->y - aPoint->y ) * ( aPoint->next->y - aPoint->y );
641 double opp_sq_len = ( aPoint->next->x - aPoint->prev->x ) * ( aPoint->next->x - aPoint->prev->x ) +
642 ( aPoint->next->y - aPoint->prev->y ) * ( aPoint->next->y - aPoint->prev->y );
643
644 return ( prev_sq_len < min_area || next_sq_len < min_area || opp_sq_len < min_area );
645 }
646
647
657 bool isEar( VERTEX* aEar ) const
658 {
659 const VERTEX* a = aEar->prev;
660 const VERTEX* b = aEar;
661 const VERTEX* c = aEar->next;
662
663 // If the area >=0, then the three points for a concave sequence
664 // with b as the reflex point
665 if( area( a, b, c ) >= 0 )
666 return false;
667
668 // triangle bbox
669 const double minTX = std::min( a->x, std::min( b->x, c->x ) );
670 const double minTY = std::min( a->y, std::min( b->y, c->y ) );
671 const double maxTX = std::max( a->x, std::max( b->x, c->x ) );
672 const double maxTY = std::max( a->y, std::max( b->y, c->y ) );
673
674 // z-order range for the current triangle bounding box
675 const int32_t minZ = zOrder( minTX, minTY );
676 const int32_t maxZ = zOrder( maxTX, maxTY );
677
678 // first look for points inside the triangle in increasing z-order
679 VERTEX* p = aEar->nextZ;
680
681 while( p && p->z <= maxZ )
682 {
683 if( p != a && p != c
684 && p->inTriangle( *a, *b, *c )
685 && area( p->prev, p, p->next ) >= 0 )
686 return false;
687
688 p = p->nextZ;
689 }
690
691 // then look for points in decreasing z-order
692 p = aEar->prevZ;
693
694 while( p && p->z >= minZ )
695 {
696 if( p != a && p != c
697 && p->inTriangle( *a, *b, *c )
698 && area( p->prev, p, p->next ) >= 0 )
699 return false;
700
701 p = p->prevZ;
702 }
703
704 return true;
705 }
706
710 void subdividePolygon( VERTEX* aStart, int pass = 0 )
711 {
712 VERTEX* p = aStart;
713
714 struct VertexComparator {
715 bool operator()(const std::pair<VERTEX*,double>& a, const std::pair<VERTEX*,double>& b) const {
716 return a.second > b.second;
717 }
718 };
719
720 std::set<std::pair<VERTEX*,double>, VertexComparator> longest;
721 double avg = 0.0;
722
723 do
724 {
725 double len = ( p->x - p->next->x ) * ( p->x - p->next->x ) +
726 ( p->y - p->next->y ) * ( p->y - p->next->y );
727 longest.emplace( p, len );
728
729 avg += len;
730 p = p->next;
731 } while (p != aStart);
732
733 avg /= longest.size();
734 wxLogTrace( TRIANGULATE_TRACE, "Average length: %f", avg );
735
736 for( auto it = longest.begin(); it != longest.end() && it->second > avg; ++it )
737 {
738 wxLogTrace( TRIANGULATE_TRACE, "Subdividing edge with length %f", it->second );
739 VERTEX* a = it->first;
740 VERTEX* b = a->next;
741 VERTEX* last = a;
742
743 // We adjust the number of divisions based on the pass in order to progressively
744 // subdivide the polygon when triangulation fails
745 int divisions = avg / it->second + 2 + pass;
746 double step = 1.0 / divisions;
747
748 for( int i = 1; i < divisions; i++ )
749 {
750 double x = a->x * ( 1.0 - step * i ) + b->x * ( step * i );
751 double y = a->y * ( 1.0 - step * i ) + b->y * ( step * i );
752 last = insertVertex( VECTOR2I( x, y ), last );
753 }
754 }
755
756 // update z-order of the vertices
757 aStart->updateList();
758 }
759
766 bool splitPolygon( VERTEX* start )
767 {
768 VERTEX* origPoly = start;
769
770 // If we have fewer than 4 points, we cannot split the polygon
771 if( !start || !start->next || start->next == start->prev
772 || start->next->next == start->prev )
773 {
774 return true;
775 }
776
777 // Our first attempts to split the polygon will be at overlapping points.
778 // These are natural split points and we only need to switch the loop directions
779 // to generate two new loops. Since they are overlapping, we are do not
780 // need to create a new segment to disconnect the two loops.
781 do
782 {
783 std::vector<VERTEX*> overlapPoints;
784 VERTEX* z_pt = origPoly;
785
786 while ( z_pt->prevZ && *z_pt->prevZ == *origPoly )
787 z_pt = z_pt->prevZ;
788
789 overlapPoints.push_back( z_pt );
790
791 while( z_pt->nextZ && *z_pt->nextZ == *origPoly )
792 {
793 z_pt = z_pt->nextZ;
794 overlapPoints.push_back( z_pt );
795 }
796
797 if( overlapPoints.size() != 2 || overlapPoints[0]->next == overlapPoints[1]
798 || overlapPoints[0]->prev == overlapPoints[1] )
799 {
800 origPoly = origPoly->next;
801 continue;
802 }
803
804 if( overlapPoints[0]->area( overlapPoints[1] ) < 0 || overlapPoints[1]->area( overlapPoints[0] ) < 0 )
805 {
806 wxLogTrace( TRIANGULATE_TRACE, "Split generated a hole, skipping" );
807 origPoly = origPoly->next;
808 continue;
809 }
810
811 wxLogTrace( TRIANGULATE_TRACE, "Splitting at overlap point %f, %f", overlapPoints[0]->x, overlapPoints[0]->y );
812 std::swap( overlapPoints[0]->next, overlapPoints[1]->next );
813 overlapPoints[0]->next->prev = overlapPoints[0];
814 overlapPoints[1]->next->prev = overlapPoints[1];
815
816 overlapPoints[0]->updateList();
817 overlapPoints[1]->updateList();
818 logVertices( overlapPoints[0], nullptr );
819 logVertices( overlapPoints[1], nullptr );
820 bool retval = earcutList( overlapPoints[0] ) && earcutList( overlapPoints[1] );
821
822 wxLogTrace( TRIANGULATE_TRACE, "%s at first overlap split", retval ? "Success" : "Failed" );
823 return retval;
824
825
826 } while ( origPoly != start );
827
828 // If we've made it through the split algorithm and we still haven't found a
829 // set of overlapping points, we need to create a new segment to split the polygon
830 // into two separate polygons. We do this by finding the two vertices that form
831 // a valid line (does not cross the existing polygon)
832 do
833 {
834 VERTEX* marker = origPoly->next->next;
835
836 while( marker != origPoly->prev )
837 {
838 // Find a diagonal line that is wholly enclosed by the polygon interior
839 if( origPoly->next && origPoly->i != marker->i && goodSplit( origPoly, marker ) )
840 {
841 VERTEX* newPoly = origPoly->split( marker );
842
843 origPoly->updateList();
844 newPoly->updateList();
845
846 bool retval = earcutList( origPoly ) && earcutList( newPoly );
847
848 wxLogTrace( TRIANGULATE_TRACE, "%s at split", retval ? "Success" : "Failed" );
849 return retval;
850 }
851
852 marker = marker->next;
853 }
854
855 origPoly = origPoly->next;
856 } while( origPoly != start );
857
858 wxLogTrace( TRIANGULATE_TRACE, "Could not find a valid split point" );
859 return false;
860 }
861
871 bool goodSplit( const VERTEX* a, const VERTEX* b ) const
872 {
873 bool a_on_edge = ( a->nextZ && *a == *a->nextZ ) || ( a->prevZ && *a == *a->prevZ );
874 bool b_on_edge = ( b->nextZ && *b == *b->nextZ ) || ( b->prevZ && *b == *b->prevZ );
875 bool no_intersect = a->next->i != b->i && a->prev->i != b->i && !intersectsPolygon( a, b );
876 bool local_split = locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b );
877 bool same_dir = area( a->prev, a, b->prev ) != 0.0 || area( a, b->prev, b ) != 0.0;
878 bool has_len = ( *a == *b ) && area( a->prev, a, a->next ) > 0 && area( b->prev, b, b->next ) > 0;
879 bool pos_area = a->area( b ) > 0 && b->area( a ) > 0;
880
881 return no_intersect && local_split && ( same_dir || has_len ) && !a_on_edge && !b_on_edge && pos_area;
882
883 }
884
888 double area( const VERTEX* p, const VERTEX* q, const VERTEX* r ) const
889 {
890 return ( q->y - p->y ) * ( r->x - q->x ) - ( q->x - p->x ) * ( r->y - q->y );
891 }
892
893
894 constexpr int sign( double aVal ) const
895 {
896 return ( aVal > 0 ) - ( aVal < 0 );
897 }
898
902 constexpr bool overlapping( const VERTEX* p, const VERTEX* q, const VERTEX* r ) const
903 {
904 return q->x <= std::max( p->x, r->x ) &&
905 q->x >= std::min( p->x, r->x ) &&
906 q->y <= std::max( p->y, r->y ) &&
907 q->y >= std::min( p->y, r->y );
908 }
909
915 bool intersects( const VERTEX* p1, const VERTEX* q1, const VERTEX* p2, const VERTEX* q2 ) const
916 {
917 int sign1 = sign( area( p1, q1, p2 ) );
918 int sign2 = sign( area( p1, q1, q2 ) );
919 int sign3 = sign( area( p2, q2, p1 ) );
920 int sign4 = sign( area( p2, q2, q1 ) );
921
922 if( sign1 != sign2 && sign3 != sign4 )
923 return true;
924
925 if( sign1 == 0 && overlapping( p1, p2, q1 ) )
926 return true;
927
928 if( sign2 == 0 && overlapping( p1, q2, q1 ) )
929 return true;
930
931 if( sign3 == 0 && overlapping( p2, p1, q2 ) )
932 return true;
933
934 if( sign4 == 0 && overlapping( p2, q1, q2 ) )
935 return true;
936
937
938 return false;
939 }
940
947 bool intersectsPolygon( const VERTEX* a, const VERTEX* b ) const
948 {
949 for( auto it = m_vertices.begin(); it != m_vertices.end(); )
950 {
951 const VERTEX* p = &*it;
952 const VERTEX* q = &*( ++it );
953
954 if( p->i == a->i || p->i == b->i || q->i == a->i || q->i == b->i )
955 continue;
956
957 if( intersects( p, q, a, b ) )
958 return true;
959 }
960
961 if( m_vertices.front().i == a->i || m_vertices.front().i == b->i
962 || m_vertices.back().i == a->i || m_vertices.back().i == b->i )
963 {
964 return false;
965 }
966
967 return intersects( a, b, &m_vertices.back(), &m_vertices.front() );
968 }
969
979 bool locallyInside( const VERTEX* a, const VERTEX* b ) const
980 {
981 if( area( a->prev, a, a->next ) < 0 )
982 return area( a, b, a->next ) >= 0 && area( a, a->prev, b ) >= 0;
983 else
984 return area( a, b, a->prev ) < 0 || area( a, a->next, b ) < 0;
985 }
986
990 bool middleInside( const VERTEX* a, const VERTEX* b ) const
991 {
992 const VERTEX* p = a;
993 bool inside = false;
994 double px = ( a->x + b->x ) / 2;
995 double py = ( a->y + b->y ) / 2;
996
997 do
998 {
999 if( ( ( p->y > py ) != ( p->next->y > py ) )
1000 && ( px < ( p->next->x - p->x ) * ( py - p->y ) / ( p->next->y - p->y ) + p->x ) )
1001 inside = !inside;
1002
1003 p = p->next;
1004 } while( p != a );
1005
1006 return inside;
1007 }
1008
1015 VERTEX* insertVertex( const VECTOR2I& pt, VERTEX* last )
1016 {
1017 m_result.AddVertex( pt );
1018 m_vertices.emplace_back( m_result.GetVertexCount() - 1, pt.x, pt.y, this );
1019
1020 VERTEX* p = &m_vertices.back();
1021
1022 if( !last )
1023 {
1024 p->prev = p;
1025 p->next = p;
1026 }
1027 else
1028 {
1029 p->next = last->next;
1030 p->prev = last;
1031 last->next->prev = p;
1032 last->next = p;
1033 }
1034 return p;
1035 }
1036
1037private:
1039 std::deque<VERTEX> m_vertices;
1041};
1042
1043#endif //__POLYGON_TRIANGULATION_H
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
coord_type GetHeight() const
Definition: box2.h:189
coord_type GetY() const
Definition: box2.h:182
coord_type GetWidth() const
Definition: box2.h:188
coord_type GetX() const
Definition: box2.h:181
SHAPE_POLY_SET::TRIANGULATED_POLYGON & m_result
bool middleInside(const VERTEX *a, const VERTEX *b) const
Check to see if the segment halfway point between a and b is inside the polygon.
bool intersects(const VERTEX *p1, const VERTEX *q1, const VERTEX *p2, const VERTEX *q2) const
Check for intersection between two segments, end points included.
bool splitPolygon(VERTEX *start)
If we cannot find an ear to slice in the current polygon list, we use this to split the polygon into ...
bool isEar(VERTEX *aEar) const
Check whether the given vertex is in the middle of an ear.
constexpr int sign(double aVal) const
int32_t zOrder(const double aX, const double aY) const
Calculate the Morton code of the Vertex http://www.graphics.stanford.edu/~seander/bithacks....
std::deque< VERTEX > m_vertices
void logVertices(VERTEX *aStart, std::set< VERTEX * > *aSeen)
bool goodSplit(const VERTEX *a, const VERTEX *b) const
Check if a segment joining two vertices lies fully inside the polygon.
POLYGON_TRIANGULATION(SHAPE_POLY_SET::TRIANGULATED_POLYGON &aResult)
double area(const VERTEX *p, const VERTEX *q, const VERTEX *r) const
Return the twice the signed area of the triangle formed by vertices p, q, and r.
constexpr bool overlapping(const VERTEX *p, const VERTEX *q, const VERTEX *r) const
If p, q, and r are collinear and r lies between p and q, then return true.
bool locallyInside(const VERTEX *a, const VERTEX *b) const
Check whether the segment from vertex a -> vertex b is inside the polygon around the immediate area o...
VERTEX * insertVertex(const VECTOR2I &pt, VERTEX *last)
Create an entry in the vertices lookup and optionally inserts the newly created vertex into an existi...
void logRemaining()
Outputs a list of vertices that have not yet been triangulated.
VERTEX * removeNullTriangles(VERTEX *aStart)
Iterate through the list to remove NULL triangles if they exist.
bool intersectsPolygon(const VERTEX *a, const VERTEX *b) const
Check whether the segment from vertex a -> vertex b crosses any of the segments of the polygon of whi...
bool isTooSmall(const VERTEX *aPoint) const
Check whether a given vertex is too small to matter.
bool earcutList(VERTEX *aPoint, int pass=0)
Walk through a circular linked list starting at aPoint.
void subdividePolygon(VERTEX *aStart, int pass=0)
Inserts a new vertex halfway between each existing pair of vertices.
bool TesselatePolygon(const SHAPE_LINE_CHAIN &aPoly, SHAPE_POLY_SET::TRIANGULATED_POLYGON *aHintData)
VERTEX * createList(const SHAPE_LINE_CHAIN &points)
Take a SHAPE_LINE_CHAIN and links each point into a circular, doubly-linked list.
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
int PointCount() const
Return the number of points (vertices) in this line chain.
const VECTOR2I & CPoint(int aIndex) const
Return a reference to a given point in the line chain.
const BOX2I BBox(int aClearance=0) const override
Compute a bounding box of the shape, with a margin of aClearance a collision.
void AddVertex(const VECTOR2I &aP)
void AddTriangle(int a, int b, int c)
extended_type SquaredEuclideanNorm() const
Compute the squared euclidean norm of the vector, which is defined as (x ** 2 + y ** 2).
Definition: vector2d.h:272
VECTOR2_TRAITS< int >::extended_type extended_type
Definition: vector2d.h:72
int m_TriangulateSimplificationLevel
The number of internal units that will be allowed to deflect from the base segment when creating a ne...
int m_TriangulateMinimumArea
The minimum area of a polygon that can be left over after triangulation and still consider the triang...
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition: eda_angle.h:424
#define TRIANGULATE_TRACE
CITER next(CITER it)
Definition: ptree.cpp:126
void updateList()
After inserting or changing nodes, this function should be called to remove duplicate vertices and en...
double area(const VERTEX *aEnd=nullptr) const
Returns the signed area of the polygon connected to the current vertex, optionally ending at a specif...
VERTEX * split(VERTEX *b)
Split the referenced polygon between the reference point and vertex b, assuming they are in the same ...
VERTEX(size_t aIndex, double aX, double aY, POLYGON_TRIANGULATION *aParent)
bool operator!=(const VERTEX &rhs) const
VERTEX & operator=(const VERTEX &)=delete
VERTEX & operator=(VERTEX &&)=delete
void zSort()
Sort all vertices in this vertex's list by their Morton code.
bool inTriangle(const VERTEX &a, const VERTEX &b, const VERTEX &c)
Check to see if triangle surrounds our current vertex.
void remove()
Remove the node from the linked list and z-ordered linked list.
bool operator==(const VERTEX &rhs) const
VECTOR2< int > VECTOR2I
Definition: vector2d.h:588