KiCad PCB EDA Suite
Loading...
Searching...
No Matches
zone_filler.cpp
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 * Copyright (C) 2014-2017 CERN
5 * Copyright (C) 2014-2024 KiCad Developers, see AUTHORS.txt for contributors.
6 * @author Tomasz Włostowski <[email protected]>
7 *
8 * This program is free software: you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation, either version 3 of the License, or (at your
11 * option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, you may find one here:
20 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
21 * or you may search the http://www.gnu.org website for the version 2 license,
22 * or you may write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 */
25
26#include <future>
27#include <core/kicad_algo.h>
28#include <advanced_config.h>
29#include <board.h>
31#include <zone.h>
32#include <footprint.h>
33#include <pad.h>
34#include <pcb_target.h>
35#include <pcb_track.h>
36#include <pcb_text.h>
37#include <pcb_textbox.h>
38#include <pcb_tablecell.h>
39#include <pcb_table.h>
40#include <pcb_dimension.h>
43#include <board_commit.h>
44#include <progress_reporter.h>
48#include <geometry/vertex_set.h>
49#include <kidialog.h>
50#include <core/thread_pool.h>
51#include <math/util.h> // for KiROUND
52#include "zone_filler.h"
53
54// Helper classes for connect_nearby_polys
56{
57public:
58 RESULTS( int aOutline1, int aOutline2, int aVertex1, int aVertex2 ) :
59 m_outline1( aOutline1 ), m_outline2( aOutline2 ),
60 m_vertex1( aVertex1 ), m_vertex2( aVertex2 )
61 {
62 }
63
64 bool operator<( const RESULTS& aOther ) const
65 {
66 if( m_outline1 != aOther.m_outline1 )
67 return m_outline1 < aOther.m_outline1;
68 if( m_outline2 != aOther.m_outline2 )
69 return m_outline2 < aOther.m_outline2;
70 if( m_vertex1 != aOther.m_vertex1 )
71 return m_vertex1 < aOther.m_vertex1;
72 return m_vertex2 < aOther.m_vertex2;
73 }
74
79};
80
82{
83public:
84 VERTEX_CONNECTOR( const BOX2I& aBBox, const SHAPE_POLY_SET& aPolys, int aDist ) : VERTEX_SET( 0 )
85 {
86 SetBoundingBox( aBBox );
87 VERTEX* tail = nullptr;
88
89 for( int i = 0; i < aPolys.OutlineCount(); i++ )
90 tail = createList( aPolys.Outline( i ), tail, (void*)( intptr_t )( i ) );
91
92 if( tail )
93 tail->updateList();
94 m_dist = aDist;
95 }
96
97 VERTEX* getPoint( VERTEX* aPt ) const
98 {
99 // z-order range for the current point ± limit bounding box
100 const uint32_t maxZ = zOrder( aPt->x + m_dist, aPt->y + m_dist );
101 const uint32_t minZ = zOrder( aPt->x - m_dist, aPt->y - m_dist );
102 const SEG::ecoord limit2 = SEG::Square( m_dist );
103
104 // first look for points in increasing z-order
105 SEG::ecoord min_dist = std::numeric_limits<SEG::ecoord>::max();
106 VERTEX* retval = nullptr;
107
108 auto check_pt = [&]( VERTEX* p )
109 {
110 VECTOR2D diff( p->x - aPt->x, p->y - aPt->y );
111 SEG::ecoord dist2 = diff.SquaredEuclideanNorm();
112
113 if( dist2 > 0 && dist2 < limit2 && dist2 < min_dist && p->isEar( true ) )
114 {
115 min_dist = dist2;
116 retval = p;
117 }
118 };
119
120 VERTEX* p = aPt->nextZ;
121
122 while( p && p->z <= maxZ )
123 {
124 check_pt( p );
125 p = p->nextZ;
126 }
127
128 p = aPt->prevZ;
129
130 while( p && p->z >= minZ )
131 {
132 check_pt( p );
133 p = p->prevZ;
134 }
135
136 return retval;
137 }
138
140 {
141 if( m_vertices.empty() )
142 return;
143
144 VERTEX* p = m_vertices.front().next;
145 std::set<VERTEX*> visited;
146
147 while( p != &m_vertices.front() )
148 {
149 // Skip points that are concave
150 if( !p->isEar() )
151 {
152 p = p->next;
153 continue;
154 }
155
156 VERTEX* q = nullptr;
157
158 if( ( visited.empty() || !visited.contains( p ) ) && ( q = getPoint( p ) ) )
159 {
160 visited.insert( p );
161
162 if( !visited.contains( q ) &&
163 m_results.emplace( (intptr_t) p->GetUserData(), (intptr_t) q->GetUserData(),
164 p->i, q->i ).second )
165 {
166 // We don't want to connect multiple points in the same vicinity, so skip
167 // 2 points before and after each point and match.
168 visited.insert( p->prev );
169 visited.insert( p->prev->prev );
170 visited.insert( p->next );
171 visited.insert( p->next->next );
172
173 visited.insert( q->prev );
174 visited.insert( q->prev->prev );
175 visited.insert( q->next );
176 visited.insert( q->next->next );
177
178 visited.insert( q );
179 }
180 }
181
182 p = p->next;
183 }
184 }
185
186 std::set<RESULTS> GetResults() const
187 {
188 return m_results;
189 }
190
191private:
192 std::set<RESULTS> m_results;
194};
195
196
198 m_board( aBoard ),
199 m_brdOutlinesValid( false ),
200 m_commit( aCommit ),
201 m_progressReporter( nullptr ),
202 m_maxError( ARC_HIGH_DEF ),
203 m_worstClearance( 0 )
204{
205 // To enable add "DebugZoneFiller=1" to kicad_advanced settings file.
207}
208
209
211{
212}
213
214
216{
217 m_progressReporter = aReporter;
218 wxASSERT_MSG( m_commit, wxT( "ZONE_FILLER must have a valid commit to call "
219 "SetProgressReporter" ) );
220}
221
222
233bool ZONE_FILLER::Fill( const std::vector<ZONE*>& aZones, bool aCheck, wxWindow* aParent )
234{
235 std::lock_guard<KISPINLOCK> lock( m_board->GetConnectivity()->GetLock() );
236
237 std::vector<std::pair<ZONE*, PCB_LAYER_ID>> toFill;
238 std::map<std::pair<ZONE*, PCB_LAYER_ID>, HASH_128> oldFillHashes;
239 std::map<ZONE*, std::map<PCB_LAYER_ID, ISOLATED_ISLANDS>> isolatedIslandsMap;
240
241 std::shared_ptr<CONNECTIVITY_DATA> connectivity = m_board->GetConnectivity();
242
243 // Rebuild (from scratch, ignoring dirty flags) just in case. This really needs to be reliable.
244 connectivity->ClearRatsnest();
245 connectivity->Build( m_board, m_progressReporter );
246
248
250 {
251 m_progressReporter->Report( aCheck ? _( "Checking zone fills..." )
252 : _( "Building zone fills..." ) );
253 m_progressReporter->SetMaxProgress( aZones.size() );
255 }
256
257 // The board outlines is used to clip solid areas inside the board (when outlines are valid)
260
261 // Update and cache zone bounding boxes and pad effective shapes so that we don't have to
262 // make them thread-safe.
263 //
264 for( ZONE* zone : m_board->Zones() )
265 zone->CacheBoundingBox();
266
267 for( FOOTPRINT* footprint : m_board->Footprints() )
268 {
269 for( PAD* pad : footprint->Pads() )
270 {
271 if( pad->IsDirty() )
272 {
273 pad->BuildEffectiveShapes();
274 pad->BuildEffectivePolygon( ERROR_OUTSIDE );
275 }
276 }
277
278 for( ZONE* zone : footprint->Zones() )
279 zone->CacheBoundingBox();
280
281 // Rules may depend on insideCourtyard() or other expressions
282 footprint->BuildCourtyardCaches();
283 }
284
285 LSET boardCuMask = m_board->GetEnabledLayers() & LSET::AllCuMask();
286
287 auto findHighestPriorityZone = [&]( const BOX2I& aBBox, const PCB_LAYER_ID aItemLayer,
288 const int aNetcode,
289 const std::function<bool( const ZONE* )> aTestFn ) -> ZONE*
290 {
291 unsigned highestPriority = 0;
292 ZONE* highestPriorityZone = nullptr;
293
294 for( ZONE* zone : m_board->Zones() )
295 {
296 // Rule areas are not filled
297 if( zone->GetIsRuleArea() )
298 continue;
299
300 if( zone->GetAssignedPriority() < highestPriority )
301 continue;
302
303 if( !zone->IsOnLayer( aItemLayer ) )
304 continue;
305
306 // Degenerate zones will cause trouble; skip them
307 if( zone->GetNumCorners() <= 2 )
308 continue;
309
310 if( !zone->GetBoundingBox().Intersects( aBBox ) )
311 continue;
312
313 if( !aTestFn( zone ) )
314 continue;
315
316 // Prefer highest priority and matching netcode
317 if( zone->GetAssignedPriority() > highestPriority || zone->GetNetCode() == aNetcode )
318 {
319 highestPriority = zone->GetAssignedPriority();
320 highestPriorityZone = zone;
321 }
322 }
323
324 return highestPriorityZone;
325 };
326
327 auto isInPourKeepoutArea = [&]( const BOX2I& aBBox, const PCB_LAYER_ID aItemLayer,
328 const VECTOR2I aTestPoint ) -> bool
329 {
330 for( ZONE* zone : m_board->Zones() )
331 {
332 if( !zone->GetIsRuleArea() )
333 continue;
334
335 if( !zone->HasKeepoutParametersSet() )
336 continue;
337
338 if( !zone->GetDoNotAllowCopperPour() )
339 continue;
340
341 if( !zone->IsOnLayer( aItemLayer ) )
342 continue;
343
344 // Degenerate zones will cause trouble; skip them
345 if( zone->GetNumCorners() <= 2 )
346 continue;
347
348 if( !zone->GetBoundingBox().Intersects( aBBox ) )
349 continue;
350
351 if( zone->Outline()->Contains( aTestPoint ) )
352 return true;
353 }
354
355 return false;
356 };
357
358 // Determine state of conditional via flashing
359 for( PCB_TRACK* track : m_board->Tracks() )
360 {
361 if( track->Type() == PCB_VIA_T )
362 {
363 PCB_VIA* via = static_cast<PCB_VIA*>( track );
364
365 via->ClearZoneLayerOverrides();
366
367 if( !via->GetRemoveUnconnected() )
368 continue;
369
370 BOX2I bbox = via->GetBoundingBox();
371 VECTOR2I center = via->GetPosition();
372 int testRadius = via->GetDrillValue() / 2 + 1;
373 unsigned netcode = via->GetNetCode();
374 LSET layers = via->GetLayerSet() & boardCuMask;
375
376 // Checking if the via hole touches the zone outline
377 auto viaTestFn = [&]( const ZONE* aZone ) -> bool
378 {
379 return aZone->Outline()->Contains( center, -1, testRadius );
380 };
381
382 for( PCB_LAYER_ID layer : layers.Seq() )
383 {
384 if( !via->ConditionallyFlashed( layer ) )
385 continue;
386
387 if( isInPourKeepoutArea( bbox, layer, center ) )
388 {
389 via->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
390 }
391 else
392 {
393 ZONE* zone = findHighestPriorityZone( bbox, layer, netcode, viaTestFn );
394
395 if( zone && zone->GetNetCode() == via->GetNetCode() )
396 via->SetZoneLayerOverride( layer, ZLO_FORCE_FLASHED );
397 else
398 via->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
399 }
400 }
401 }
402 }
403
404 // Determine state of conditional pad flashing
405 for( FOOTPRINT* footprint : m_board->Footprints() )
406 {
407 for( PAD* pad : footprint->Pads() )
408 {
409 pad->ClearZoneLayerOverrides();
410
411 if( !pad->GetRemoveUnconnected() )
412 continue;
413
414 BOX2I bbox = pad->GetBoundingBox();
415 VECTOR2I center = pad->GetPosition();
416 unsigned netcode = pad->GetNetCode();
417 LSET layers = pad->GetLayerSet() & boardCuMask;
418
419 auto padTestFn = [&]( const ZONE* aZone ) -> bool
420 {
421 return aZone->Outline()->Contains( center );
422 };
423
424 for( PCB_LAYER_ID layer : layers.Seq() )
425 {
426 if( !pad->ConditionallyFlashed( layer ) )
427 continue;
428
429 if( isInPourKeepoutArea( bbox, layer, center ) )
430 {
431 pad->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
432 }
433 else
434 {
435 ZONE* zone = findHighestPriorityZone( bbox, layer, netcode, padTestFn );
436
437 if( zone && zone->GetNetCode() == pad->GetNetCode() )
438 pad->SetZoneLayerOverride( layer, ZLO_FORCE_FLASHED );
439 else
440 pad->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
441 }
442 }
443 }
444 }
445
446 for( ZONE* zone : aZones )
447 {
448 // Rule areas are not filled
449 if( zone->GetIsRuleArea() )
450 continue;
451
452 // Degenerate zones will cause trouble; skip them
453 if( zone->GetNumCorners() <= 2 )
454 continue;
455
456 if( m_commit )
457 m_commit->Modify( zone );
458
459 // calculate the hash value for filled areas. it will be used later to know if the
460 // current filled areas are up to date
461 for( PCB_LAYER_ID layer : zone->GetLayerSet().Seq() )
462 {
463 zone->BuildHashValue( layer );
464 oldFillHashes[ { zone, layer } ] = zone->GetHashValue( layer );
465
466 // Add the zone to the list of zones to test or refill
467 toFill.emplace_back( std::make_pair( zone, layer ) );
468
469 isolatedIslandsMap[ zone ][ layer ] = ISOLATED_ISLANDS();
470 }
471
472 // Remove existing fill first to prevent drawing invalid polygons on some platforms
473 zone->UnFill();
474 }
475
476 auto check_fill_dependency =
477 [&]( ZONE* aZone, PCB_LAYER_ID aLayer, ZONE* aOtherZone ) -> bool
478 {
479 // Check to see if we have to knock-out the filled areas of a higher-priority
480 // zone. If so we have to wait until said zone is filled before we can fill.
481
482 // If the other zone is already filled on the requested layer then we're
483 // good-to-go
484 if( aOtherZone->GetFillFlag( aLayer ) )
485 return false;
486
487 // Even if keepouts exclude copper pours, the exclusion is by outline rather than
488 // filled area, so we're good-to-go here too
489 if( aOtherZone->GetIsRuleArea() )
490 return false;
491
492 // If the other zone is never going to be filled then don't wait for it
493 if( aOtherZone->GetNumCorners() <= 2 )
494 return false;
495
496 // If the zones share no common layers
497 if( !aOtherZone->GetLayerSet().test( aLayer ) )
498 return false;
499
500 if( aZone->HigherPriority( aOtherZone ) )
501 return false;
502
503 // Same-net zones always use outlines to produce determinate results
504 if( aOtherZone->SameNet( aZone ) )
505 return false;
506
507 // A higher priority zone is found: if we intersect and it's not filled yet
508 // then we have to wait.
509 BOX2I inflatedBBox = aZone->GetBoundingBox();
510 inflatedBBox.Inflate( m_worstClearance );
511
512 if( !inflatedBBox.Intersects( aOtherZone->GetBoundingBox() ) )
513 return false;
514
515 return aZone->Outline()->Collide( aOtherZone->Outline(), m_worstClearance );
516 };
517
518 auto fill_lambda =
519 [&]( std::pair<ZONE*, PCB_LAYER_ID> aFillItem ) -> int
520 {
521 PCB_LAYER_ID layer = aFillItem.second;
522 ZONE* zone = aFillItem.first;
523 bool canFill = true;
524
525 // Check for any fill dependencies. If our zone needs to be clipped by
526 // another zone then we can't fill until that zone is filled.
527 for( ZONE* otherZone : aZones )
528 {
529 if( otherZone == zone )
530 continue;
531
532 if( check_fill_dependency( zone, layer, otherZone ) )
533 {
534 canFill = false;
535 break;
536 }
537 }
538
540 return 0;
541
542 if( !canFill )
543 return 0;
544
545 // Now we're ready to fill.
546 {
547 std::unique_lock<std::mutex> zoneLock( zone->GetLock(), std::try_to_lock );
548
549 if( !zoneLock.owns_lock() )
550 return 0;
551
552 SHAPE_POLY_SET fillPolys;
553
554 if( !fillSingleZone( zone, layer, fillPolys ) )
555 return 0;
556
557 zone->SetFilledPolysList( layer, fillPolys );
558 }
559
562
563 return 1;
564 };
565
566 auto tesselate_lambda =
567 [&]( std::pair<ZONE*, PCB_LAYER_ID> aFillItem ) -> int
568 {
570 return 0;
571
572 PCB_LAYER_ID layer = aFillItem.second;
573 ZONE* zone = aFillItem.first;
574
575 {
576 std::unique_lock<std::mutex> zoneLock( zone->GetLock(), std::try_to_lock );
577
578 if( !zoneLock.owns_lock() )
579 return 0;
580
581 zone->CacheTriangulation( layer );
582 zone->SetFillFlag( layer, true );
583 }
584
585 return 1;
586 };
587
588 // Calculate the copper fills (NB: this is multi-threaded)
589 //
590 std::vector<std::pair<std::future<int>, int>> returns;
591 returns.reserve( toFill.size() );
592 size_t finished = 0;
593 bool cancelled = false;
594
596
597 for( const std::pair<ZONE*, PCB_LAYER_ID>& fillItem : toFill )
598 returns.emplace_back( std::make_pair( tp.submit( fill_lambda, fillItem ), 0 ) );
599
600 while( !cancelled && finished != 2 * toFill.size() )
601 {
602 for( size_t ii = 0; ii < returns.size(); ++ii )
603 {
604 auto& ret = returns[ii];
605
606 if( ret.second > 1 )
607 continue;
608
609 std::future_status status = ret.first.wait_for( std::chrono::seconds( 0 ) );
610
611 if( status == std::future_status::ready )
612 {
613 if( ret.first.get() ) // lambda completed
614 {
615 ++finished;
616 ret.second++; // go to next step
617 }
618
619 if( !cancelled )
620 {
621 // Queue the next step (will re-queue the existing step if it didn't complete)
622 if( ret.second == 0 )
623 returns[ii].first = tp.submit( fill_lambda, toFill[ii] );
624 else if( ret.second == 1 )
625 returns[ii].first = tp.submit( tesselate_lambda, toFill[ii] );
626 }
627 }
628 }
629
630 std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) );
631
632
634 {
636
638 cancelled = true;
639 }
640 }
641
642 // Make sure that all futures have finished.
643 // This can happen when the user cancels the above operation
644 for( auto& ret : returns )
645 {
646 if( ret.first.valid() )
647 {
648 std::future_status status = ret.first.wait_for( std::chrono::seconds( 0 ) );
649
650 while( status != std::future_status::ready )
651 {
654
655 status = ret.first.wait_for( std::chrono::milliseconds( 100 ) );
656 }
657 }
658 }
659
660 // Now update the connectivity to check for isolated copper islands
661 // (NB: FindIsolatedCopperIslands() is multi-threaded)
662 //
664 {
666 return false;
667
669 m_progressReporter->Report( _( "Removing isolated copper islands..." ) );
671 }
672
673 connectivity->SetProgressReporter( m_progressReporter );
674 connectivity->FillIsolatedIslandsMap( isolatedIslandsMap );
675 connectivity->SetProgressReporter( nullptr );
676
678 return false;
679
680 for( ZONE* zone : aZones )
681 {
682 // Keepout zones are not filled
683 if( zone->GetIsRuleArea() )
684 continue;
685
686 zone->SetIsFilled( true );
687 }
688
689 // Now remove isolated copper islands according to the isolated islands strategy assigned
690 // by the user (always, never, below-certain-size).
691 //
692 for( const auto& [ zone, zoneIslands ] : isolatedIslandsMap )
693 {
694 // If *all* the polygons are islands, do not remove any of them
695 bool allIslands = true;
696
697 for( const auto& [ layer, layerIslands ] : zoneIslands )
698 {
699 if( layerIslands.m_IsolatedOutlines.size()
700 != static_cast<size_t>( zone->GetFilledPolysList( layer )->OutlineCount() ) )
701 {
702 allIslands = false;
703 break;
704 }
705 }
706
707 if( allIslands )
708 continue;
709
710 for( const auto& [ layer, layerIslands ] : zoneIslands )
711 {
712 if( m_debugZoneFiller && LSET::InternalCuMask().Contains( layer ) )
713 continue;
714
715 if( layerIslands.m_IsolatedOutlines.empty() )
716 continue;
717
718 std::vector<int> islands = layerIslands.m_IsolatedOutlines;
719
720 // The list of polygons to delete must be explored from last to first in list,
721 // to allow deleting a polygon from list without breaking the remaining of the list
722 std::sort( islands.begin(), islands.end(), std::greater<int>() );
723
724 std::shared_ptr<SHAPE_POLY_SET> poly = zone->GetFilledPolysList( layer );
725 long long int minArea = zone->GetMinIslandArea();
726 ISLAND_REMOVAL_MODE mode = zone->GetIslandRemovalMode();
727
728 for( int idx : islands )
729 {
730 SHAPE_LINE_CHAIN& outline = poly->Outline( idx );
731
732 if( mode == ISLAND_REMOVAL_MODE::ALWAYS )
733 poly->DeletePolygonAndTriangulationData( idx, false );
734 else if ( mode == ISLAND_REMOVAL_MODE::AREA && outline.Area( true ) < minArea )
735 poly->DeletePolygonAndTriangulationData( idx, false );
736 else
737 zone->SetIsIsland( layer, idx );
738 }
739
740 poly->UpdateTriangulationDataHash();
741 zone->CalculateFilledArea();
742
744 return false;
745 }
746 }
747
748 // Now remove islands which are either outside the board edge or fail to meet the minimum
749 // area requirements
750 using island_check_return = std::vector<std::pair<std::shared_ptr<SHAPE_POLY_SET>, int>>;
751
752 std::vector<std::pair<std::shared_ptr<SHAPE_POLY_SET>, double>> polys_to_check;
753
754 // rough estimate to save re-allocation time
755 polys_to_check.reserve( m_board->GetCopperLayerCount() * aZones.size() );
756
757 for( ZONE* zone : aZones )
758 {
759 // Don't check for connections on layers that only exist in the zone but
760 // were disabled in the board
761 BOARD* board = zone->GetBoard();
762 LSET zoneCopperLayers = zone->GetLayerSet() & LSET::AllCuMask() & board->GetEnabledLayers();
763
764 // Min-thickness is the web thickness. On the other hand, a blob min-thickness by
765 // min-thickness is not useful. Since there's no obvious definition of web vs. blob, we
766 // arbitrarily choose "at least 3X the area".
767 double minArea = (double) zone->GetMinThickness() * zone->GetMinThickness() * 3;
768
769 for( PCB_LAYER_ID layer : zoneCopperLayers.Seq() )
770 {
772 continue;
773
774 polys_to_check.emplace_back( zone->GetFilledPolysList( layer ), minArea );
775 }
776 }
777
778 auto island_lambda =
779 [&]( int aStart, int aEnd ) -> island_check_return
780 {
781 island_check_return retval;
782
783 for( int ii = aStart; ii < aEnd && !cancelled; ++ii )
784 {
785 auto [poly, minArea] = polys_to_check[ii];
786
787 for( int jj = poly->OutlineCount() - 1; jj >= 0; jj-- )
788 {
789 SHAPE_POLY_SET island;
790 SHAPE_POLY_SET intersection;
791 const SHAPE_LINE_CHAIN& test_poly = poly->Polygon( jj ).front();
792 double island_area = test_poly.Area();
793
794 if( island_area < minArea )
795 continue;
796
797
798 island.AddOutline( test_poly );
799 intersection.BooleanIntersection( m_boardOutline, island,
801
802 // Nominally, all of these areas should be either inside or outside the
803 // board outline. So this test should be able to just compare areas (if
804 // they are equal, you are inside). But in practice, we sometimes have
805 // slight overlap at the edges, so testing against half-size area acts as
806 // a fail-safe.
807 if( intersection.Area() < island_area / 2.0 )
808 retval.emplace_back( poly, jj );
809 }
810 }
811
812 return retval;
813 };
814
815 auto island_returns = tp.parallelize_loop( 0, polys_to_check.size(), island_lambda );
816 cancelled = false;
817
818 // Allow island removal threads to finish
819 for( size_t ii = 0; ii < island_returns.size(); ++ii )
820 {
821 std::future<island_check_return>& ret = island_returns[ii];
822
823 if( ret.valid() )
824 {
825 std::future_status status = ret.wait_for( std::chrono::seconds( 0 ) );
826
827 while( status != std::future_status::ready )
828 {
830 {
832
834 cancelled = true;
835 }
836
837 status = ret.wait_for( std::chrono::milliseconds( 100 ) );
838 }
839 }
840 }
841
842 if( cancelled )
843 return false;
844
845 for( size_t ii = 0; ii < island_returns.size(); ++ii )
846 {
847 std::future<island_check_return>& ret = island_returns[ii];
848
849 if( ret.valid() )
850 {
851 for( auto& action_item : ret.get() )
852 action_item.first->DeletePolygonAndTriangulationData( action_item.second, true );
853 }
854 }
855
856 for( ZONE* zone : aZones )
857 zone->CalculateFilledArea();
858
859
860 if( aCheck )
861 {
862 bool outOfDate = false;
863
864 for( ZONE* zone : aZones )
865 {
866 // Keepout zones are not filled
867 if( zone->GetIsRuleArea() )
868 continue;
869
870 for( PCB_LAYER_ID layer : zone->GetLayerSet().Seq() )
871 {
872 zone->BuildHashValue( layer );
873
874 if( oldFillHashes[ { zone, layer } ] != zone->GetHashValue( layer ) )
875 outOfDate = true;
876 }
877 }
878
879 if( outOfDate )
880 {
881 KIDIALOG dlg( aParent, _( "Zone fills are out-of-date. Refill?" ),
882 _( "Confirmation" ), wxOK | wxCANCEL | wxICON_WARNING );
883 dlg.SetOKCancelLabels( _( "Refill" ), _( "Continue without Refill" ) );
884 dlg.DoNotShowCheckbox( __FILE__, __LINE__ );
885
886 if( dlg.ShowModal() == wxID_CANCEL )
887 return false;
888 }
889 else
890 {
891 // No need to commit something that hasn't changed (and committing will set
892 // the modified flag).
893 return false;
894 }
895 }
896
898 {
900 return false;
901
904 }
905
906 return true;
907}
908
909
914void ZONE_FILLER::addKnockout( PAD* aPad, PCB_LAYER_ID aLayer, int aGap, SHAPE_POLY_SET& aHoles )
915{
916 if( aPad->GetShape( aLayer ) == PAD_SHAPE::CUSTOM )
917 {
918 SHAPE_POLY_SET poly;
919 aPad->TransformShapeToPolygon( poly, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
920
921 // the pad shape in zone can be its convex hull or the shape itself
923 {
924 std::vector<VECTOR2I> convex_hull;
925 BuildConvexHull( convex_hull, poly );
926
927 aHoles.NewOutline();
928
929 for( const VECTOR2I& pt : convex_hull )
930 aHoles.Append( pt );
931 }
932 else
933 aHoles.Append( poly );
934 }
935 else
936 {
937 aPad->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
938 }
939}
940
941
945void ZONE_FILLER::addHoleKnockout( PAD* aPad, int aGap, SHAPE_POLY_SET& aHoles )
946{
947 aPad->TransformHoleToPolygon( aHoles, aGap, m_maxError, ERROR_OUTSIDE );
948}
949
950
955void ZONE_FILLER::addKnockout( BOARD_ITEM* aItem, PCB_LAYER_ID aLayer, int aGap,
956 bool aIgnoreLineWidth, SHAPE_POLY_SET& aHoles )
957{
958 switch( aItem->Type() )
959 {
960 case PCB_FIELD_T:
961 case PCB_TEXT_T:
962 {
963 PCB_TEXT* text = static_cast<PCB_TEXT*>( aItem );
964
965 if( text->IsVisible() )
966 {
967 if( text->IsKnockout() )
968 {
969 // Knockout text should only leave holes where the text is, not where the copper fill
970 // around it would be.
971 PCB_TEXT textCopy = *text;
972 textCopy.SetIsKnockout( false );
973 textCopy.TransformShapeToPolygon( aHoles, aLayer, 0, m_maxError, ERROR_OUTSIDE );
974 }
975 else
976 {
977 text->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
978 }
979 }
980
981 break;
982 }
983
984 case PCB_TEXTBOX_T:
985 case PCB_TABLE_T:
986 case PCB_SHAPE_T:
987 case PCB_TARGET_T:
988 aItem->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE,
989 aIgnoreLineWidth );
990 break;
991
993 case PCB_DIM_LEADER_T:
994 case PCB_DIM_CENTER_T:
995 case PCB_DIM_RADIAL_T:
997 {
998 PCB_DIMENSION_BASE* dim = static_cast<PCB_DIMENSION_BASE*>( aItem );
999
1000 dim->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE, false );
1001 dim->PCB_TEXT::TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
1002 break;
1003 }
1004
1005 default:
1006 break;
1007 }
1008}
1009
1010
1016 SHAPE_POLY_SET& aFill,
1017 std::vector<PAD*>& aThermalConnectionPads,
1018 std::vector<PAD*>& aNoConnectionPads )
1019{
1021 ZONE_CONNECTION connection;
1022 DRC_CONSTRAINT constraint;
1023 int padClearance;
1024 std::shared_ptr<SHAPE> padShape;
1025 int holeClearance;
1026 SHAPE_POLY_SET holes;
1027
1028 for( FOOTPRINT* footprint : m_board->Footprints() )
1029 {
1030 for( PAD* pad : footprint->Pads() )
1031 {
1032 BOX2I padBBox = pad->GetBoundingBox();
1033 padBBox.Inflate( m_worstClearance );
1034
1035 if( !padBBox.Intersects( aZone->GetBoundingBox() ) )
1036 continue;
1037
1038 bool noConnection = pad->GetNetCode() != aZone->GetNetCode();
1039
1040 if( !aZone->IsTeardropArea() )
1041 {
1042 if( aZone->GetNetCode() == 0
1043 || pad->GetZoneLayerOverride( aLayer ) == ZLO_FORCE_NO_ZONE_CONNECTION )
1044 {
1045 noConnection = true;
1046 }
1047 }
1048
1049 if( noConnection )
1050 {
1051 // collect these for knockout in buildCopperItemClearances()
1052 aNoConnectionPads.push_back( pad );
1053 continue;
1054 }
1055
1056 if( aZone->IsTeardropArea() )
1057 {
1058 connection = ZONE_CONNECTION::FULL;
1059 }
1060 else
1061 {
1062 constraint = bds.m_DRCEngine->EvalZoneConnection( pad, aZone, aLayer );
1063 connection = constraint.m_ZoneConnection;
1064 }
1065
1066 if( connection == ZONE_CONNECTION::THERMAL && !pad->CanFlashLayer( aLayer ) )
1067 connection = ZONE_CONNECTION::NONE;
1068
1069 switch( connection )
1070 {
1071 case ZONE_CONNECTION::THERMAL:
1072 padShape = pad->GetEffectiveShape( aLayer, FLASHING::ALWAYS_FLASHED );
1073
1074 if( aFill.Collide( padShape.get(), 0 ) )
1075 {
1076 constraint = bds.m_DRCEngine->EvalRules( THERMAL_RELIEF_GAP_CONSTRAINT, pad,
1077 aZone, aLayer );
1078 padClearance = constraint.GetValue().Min();
1079
1080 aThermalConnectionPads.push_back( pad );
1081 addKnockout( pad, aLayer, padClearance, holes );
1082 }
1083
1084 break;
1085
1086 case ZONE_CONNECTION::NONE:
1087 constraint = bds.m_DRCEngine->EvalRules( PHYSICAL_CLEARANCE_CONSTRAINT, pad,
1088 aZone, aLayer );
1089
1090 if( constraint.GetValue().Min() > aZone->GetLocalClearance().value() )
1091 padClearance = constraint.GetValue().Min();
1092 else
1093 padClearance = aZone->GetLocalClearance().value();
1094
1095 if( pad->FlashLayer( aLayer ) )
1096 {
1097 addKnockout( pad, aLayer, padClearance, holes );
1098 }
1099 else if( pad->GetDrillSize().x > 0 )
1100 {
1101 constraint = bds.m_DRCEngine->EvalRules( PHYSICAL_HOLE_CLEARANCE_CONSTRAINT,
1102 pad, aZone, aLayer );
1103
1104 if( constraint.GetValue().Min() > padClearance )
1105 holeClearance = constraint.GetValue().Min();
1106 else
1107 holeClearance = padClearance;
1108
1109 pad->TransformHoleToPolygon( holes, holeClearance, m_maxError, ERROR_OUTSIDE );
1110 }
1111
1112 break;
1113
1114 default:
1115 // No knockout
1116 continue;
1117 }
1118 }
1119 }
1120
1122}
1123
1124
1130 const std::vector<PAD*>& aNoConnectionPads,
1131 SHAPE_POLY_SET& aHoles )
1132{
1134 long ticker = 0;
1135
1136 auto checkForCancel =
1137 [&ticker]( PROGRESS_REPORTER* aReporter ) -> bool
1138 {
1139 return aReporter && ( ticker++ % 50 ) == 0 && aReporter->IsCancelled();
1140 };
1141
1142 // A small extra clearance to be sure actual track clearances are not smaller than
1143 // requested clearance due to many approximations in calculations, like arc to segment
1144 // approx, rounding issues, etc.
1145 BOX2I zone_boundingbox = aZone->GetBoundingBox();
1147
1148 // Items outside the zone bounding box are skipped, so it needs to be inflated by the
1149 // largest clearance value found in the netclasses and rules
1150 zone_boundingbox.Inflate( m_worstClearance + extra_margin );
1151
1152 auto evalRulesForItems =
1153 [&bds]( DRC_CONSTRAINT_T aConstraint, const BOARD_ITEM* a, const BOARD_ITEM* b,
1154 PCB_LAYER_ID aEvalLayer ) -> int
1155 {
1156 DRC_CONSTRAINT c = bds.m_DRCEngine->EvalRules( aConstraint, a, b, aEvalLayer );
1157
1158 if( c.IsNull() )
1159 return -1;
1160 else
1161 return c.GetValue().Min();
1162 };
1163
1164 // Add non-connected pad clearances
1165 //
1166 auto knockoutPadClearance =
1167 [&]( PAD* aPad )
1168 {
1169 int init_gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT, aZone, aPad, aLayer );
1170 int gap = init_gap;
1171 bool hasHole = aPad->GetDrillSize().x > 0;
1172 bool flashLayer = aPad->FlashLayer( aLayer );
1173 bool platedHole = hasHole && aPad->GetAttribute() == PAD_ATTRIB::PTH;
1174
1175 if( flashLayer || platedHole )
1176 {
1177 gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
1178 aZone, aPad, aLayer ) );
1179 }
1180
1181 if( flashLayer && gap >= 0 )
1182 addKnockout( aPad, aLayer, gap + extra_margin, aHoles );
1183
1184 if( hasHole )
1185 {
1186 // NPTH do not need copper clearance gaps to their holes
1187 if( aPad->GetAttribute() == PAD_ATTRIB::NPTH )
1188 gap = init_gap;
1189
1190 gap = std::max( gap, evalRulesForItems( PHYSICAL_HOLE_CLEARANCE_CONSTRAINT,
1191 aZone, aPad, aLayer ) );
1192
1193 gap = std::max( gap, evalRulesForItems( HOLE_CLEARANCE_CONSTRAINT,
1194 aZone, aPad, aLayer ) );
1195
1196 if( gap >= 0 )
1197 addHoleKnockout( aPad, gap + extra_margin, aHoles );
1198 }
1199 };
1200
1201 for( PAD* pad : aNoConnectionPads )
1202 {
1203 if( checkForCancel( m_progressReporter ) )
1204 return;
1205
1206 knockoutPadClearance( pad );
1207 }
1208
1209 // Add non-connected track clearances
1210 //
1211 auto knockoutTrackClearance =
1212 [&]( PCB_TRACK* aTrack )
1213 {
1214 if( aTrack->GetBoundingBox().Intersects( zone_boundingbox ) )
1215 {
1216 bool sameNet = aTrack->GetNetCode() == aZone->GetNetCode();
1217
1218 if( !aZone->IsTeardropArea() && aZone->GetNetCode() == 0 )
1219 sameNet = false;
1220
1221 int gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT,
1222 aZone, aTrack, aLayer );
1223
1224 if( aTrack->Type() == PCB_VIA_T )
1225 {
1226 PCB_VIA* via = static_cast<PCB_VIA*>( aTrack );
1227
1228 if( via->GetZoneLayerOverride( aLayer ) == ZLO_FORCE_NO_ZONE_CONNECTION )
1229 sameNet = false;
1230 }
1231
1232 if( !sameNet )
1233 {
1234 gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
1235 aZone, aTrack, aLayer ) );
1236 }
1237
1238 if( aTrack->Type() == PCB_VIA_T )
1239 {
1240 PCB_VIA* via = static_cast<PCB_VIA*>( aTrack );
1241
1242 if( via->FlashLayer( aLayer ) && gap > 0 )
1243 {
1244 via->TransformShapeToPolygon( aHoles, aLayer, gap + extra_margin,
1246 }
1247
1248 gap = std::max( gap, evalRulesForItems( PHYSICAL_HOLE_CLEARANCE_CONSTRAINT,
1249 aZone, via, aLayer ) );
1250
1251 if( !sameNet )
1252 {
1253 gap = std::max( gap, evalRulesForItems( HOLE_CLEARANCE_CONSTRAINT,
1254 aZone, via, aLayer ) );
1255 }
1256
1257 if( gap >= 0 )
1258 {
1259 int radius = via->GetDrillValue() / 2;
1260
1261 TransformCircleToPolygon( aHoles, via->GetPosition(),
1262 radius + gap + extra_margin,
1264 }
1265 }
1266 else
1267 {
1268 if( gap >= 0 )
1269 {
1270 aTrack->TransformShapeToPolygon( aHoles, aLayer, gap + extra_margin,
1272 }
1273 }
1274 }
1275 };
1276
1277 for( PCB_TRACK* track : m_board->Tracks() )
1278 {
1279 if( !track->IsOnLayer( aLayer ) )
1280 continue;
1281
1282 if( checkForCancel( m_progressReporter ) )
1283 return;
1284
1285 knockoutTrackClearance( track );
1286 }
1287
1288 // Add graphic item clearances.
1289 //
1290 auto knockoutGraphicClearance =
1291 [&]( BOARD_ITEM* aItem )
1292 {
1293 int shapeNet = -1;
1294
1295 if( aItem->Type() == PCB_SHAPE_T )
1296 shapeNet = static_cast<PCB_SHAPE*>( aItem )->GetNetCode();
1297
1298 bool sameNet = shapeNet == aZone->GetNetCode();
1299
1300 if( !aZone->IsTeardropArea() && aZone->GetNetCode() == 0 )
1301 sameNet = false;
1302
1303 // A item on the Edge_Cuts or Margin is always seen as on any layer:
1304 if( aItem->IsOnLayer( aLayer )
1305 || aItem->IsOnLayer( Edge_Cuts )
1306 || aItem->IsOnLayer( Margin ) )
1307 {
1308 if( aItem->GetBoundingBox().Intersects( zone_boundingbox ) )
1309 {
1310 bool ignoreLineWidths = false;
1311 int gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT,
1312 aZone, aItem, aLayer );
1313
1314 if( aItem->IsOnLayer( aLayer ) && !sameNet )
1315 {
1316 gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
1317 aZone, aItem, aLayer ) );
1318 }
1319 else if( aItem->IsOnLayer( Edge_Cuts ) )
1320 {
1321 gap = std::max( gap, evalRulesForItems( EDGE_CLEARANCE_CONSTRAINT,
1322 aZone, aItem, aLayer ) );
1323 ignoreLineWidths = true;
1324 }
1325 else if( aItem->IsOnLayer( Margin ) )
1326 {
1327 gap = std::max( gap, evalRulesForItems( EDGE_CLEARANCE_CONSTRAINT,
1328 aZone, aItem, aLayer ) );
1329 }
1330
1331 if( gap >= 0 )
1332 {
1333 gap += extra_margin;
1334 addKnockout( aItem, aLayer, gap, ignoreLineWidths, aHoles );
1335 }
1336 }
1337 }
1338 };
1339
1340 auto knockoutCourtyardClearance =
1341 [&]( FOOTPRINT* aFootprint )
1342 {
1343 if( aFootprint->GetBoundingBox().Intersects( zone_boundingbox ) )
1344 {
1345 int gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT, aZone,
1346 aFootprint, aLayer );
1347
1348 if( gap == 0 )
1349 {
1350 aHoles.Append( aFootprint->GetCourtyard( aLayer ) );
1351 }
1352 else if( gap > 0 )
1353 {
1354 SHAPE_POLY_SET hole = aFootprint->GetCourtyard( aLayer );
1355 hole.Inflate( gap, CORNER_STRATEGY::ROUND_ALL_CORNERS, m_maxError );
1356 aHoles.Append( hole );
1357 }
1358 }
1359 };
1360
1361 for( FOOTPRINT* footprint : m_board->Footprints() )
1362 {
1363 knockoutCourtyardClearance( footprint );
1364 knockoutGraphicClearance( &footprint->Reference() );
1365 knockoutGraphicClearance( &footprint->Value() );
1366
1367 std::set<PAD*> allowedNetTiePads;
1368
1369 // Don't knock out holes for graphic items which implement a net-tie to the zone's net
1370 // on the layer being filled.
1371 if( footprint->IsNetTie() )
1372 {
1373 for( PAD* pad : footprint->Pads() )
1374 {
1375 bool sameNet = pad->GetNetCode() == aZone->GetNetCode();
1376
1377 if( !aZone->IsTeardropArea() && aZone->GetNetCode() == 0 )
1378 sameNet = false;
1379
1380 if( sameNet )
1381 {
1382 if( pad->IsOnLayer( aLayer ) )
1383 allowedNetTiePads.insert( pad );
1384
1385 for( PAD* other : footprint->GetNetTiePads( pad ) )
1386 {
1387 if( other->IsOnLayer( aLayer ) )
1388 allowedNetTiePads.insert( other );
1389 }
1390 }
1391 }
1392 }
1393
1394 for( BOARD_ITEM* item : footprint->GraphicalItems() )
1395 {
1396 if( checkForCancel( m_progressReporter ) )
1397 return;
1398
1399 BOX2I itemBBox = item->GetBoundingBox();
1400
1401 if( !zone_boundingbox.Intersects( itemBBox ) )
1402 continue;
1403
1404 bool skipItem = false;
1405
1406 if( item->IsOnLayer( aLayer ) )
1407 {
1408 std::shared_ptr<SHAPE> itemShape = item->GetEffectiveShape();
1409
1410 for( PAD* pad : allowedNetTiePads )
1411 {
1412 if( pad->GetBoundingBox().Intersects( itemBBox )
1413 && pad->GetEffectiveShape( aLayer )->Collide( itemShape.get() ) )
1414 {
1415 skipItem = true;
1416 break;
1417 }
1418 }
1419 }
1420
1421 if( !skipItem )
1422 knockoutGraphicClearance( item );
1423 }
1424 }
1425
1426 for( BOARD_ITEM* item : m_board->Drawings() )
1427 {
1428 if( checkForCancel( m_progressReporter ) )
1429 return;
1430
1431 knockoutGraphicClearance( item );
1432 }
1433
1434 // Add non-connected zone clearances
1435 //
1436 auto knockoutZoneClearance =
1437 [&]( ZONE* aKnockout )
1438 {
1439 // If the zones share no common layers
1440 if( !aKnockout->GetLayerSet().test( aLayer ) )
1441 return;
1442
1443 if( aKnockout->GetBoundingBox().Intersects( zone_boundingbox ) )
1444 {
1445 if( aKnockout->GetIsRuleArea() )
1446 {
1447 // Keepouts use outline with no clearance
1448 aKnockout->TransformSmoothedOutlineToPolygon( aHoles, 0, m_maxError,
1449 ERROR_OUTSIDE, nullptr );
1450 }
1451 else
1452 {
1453 int gap = std::max( 0, evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT,
1454 aZone, aKnockout, aLayer ) );
1455
1456 gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
1457 aZone, aKnockout, aLayer ) );
1458
1459 SHAPE_POLY_SET poly;
1460 aKnockout->TransformShapeToPolygon( poly, aLayer, gap + extra_margin,
1462 aHoles.Append( poly );
1463 }
1464 }
1465 };
1466
1467 for( ZONE* otherZone : m_board->Zones() )
1468 {
1469 if( checkForCancel( m_progressReporter ) )
1470 return;
1471
1472 // Negative clearance permits zones to short
1473 if( evalRulesForItems( CLEARANCE_CONSTRAINT, aZone, otherZone, aLayer ) < 0 )
1474 continue;
1475
1476 if( otherZone->GetIsRuleArea() )
1477 {
1478 if( otherZone->GetDoNotAllowCopperPour() && !aZone->IsTeardropArea() )
1479 knockoutZoneClearance( otherZone );
1480 }
1481 else if( otherZone->HigherPriority( aZone ) )
1482 {
1483 if( !otherZone->SameNet( aZone ) )
1484 knockoutZoneClearance( otherZone );
1485 }
1486 }
1487
1488 for( FOOTPRINT* footprint : m_board->Footprints() )
1489 {
1490 for( ZONE* otherZone : footprint->Zones() )
1491 {
1492 if( checkForCancel( m_progressReporter ) )
1493 return;
1494
1495 if( otherZone->GetIsRuleArea() )
1496 {
1497 if( otherZone->GetDoNotAllowCopperPour() && !aZone->IsTeardropArea() )
1498 knockoutZoneClearance( otherZone );
1499 }
1500 else if( otherZone->HigherPriority( aZone ) )
1501 {
1502 if( !otherZone->SameNet( aZone ) )
1503 knockoutZoneClearance( otherZone );
1504 }
1505 }
1506 }
1507
1509}
1510
1511
1517 SHAPE_POLY_SET& aRawFill )
1518{
1519 BOX2I zoneBBox = aZone->GetBoundingBox();
1520
1521 auto knockoutZoneOutline =
1522 [&]( ZONE* aKnockout )
1523 {
1524 // If the zones share no common layers
1525 if( !aKnockout->GetLayerSet().test( aLayer ) )
1526 return;
1527
1528 if( aKnockout->GetBoundingBox().Intersects( zoneBBox ) )
1529 {
1530 // Processing of arc shapes in zones is not yet supported because Clipper
1531 // can't do boolean operations on them. The poly outline must be converted to
1532 // segments first.
1533 SHAPE_POLY_SET outline = aKnockout->Outline()->CloneDropTriangulation();
1534 outline.ClearArcs();
1535
1536 aRawFill.BooleanSubtract( outline, SHAPE_POLY_SET::PM_FAST );
1537 }
1538 };
1539
1540 for( ZONE* otherZone : m_board->Zones() )
1541 {
1542 // Don't use the `HigherPriority()` check here because we _only_ want to knock out zones
1543 // with explicitly higher priorities, not those with equal priorities
1544 if( otherZone->SameNet( aZone )
1545 && otherZone->GetAssignedPriority() > aZone->GetAssignedPriority() )
1546 {
1547 // Do not remove teardrop area: it is not useful and not good
1548 if( !otherZone->IsTeardropArea() )
1549 knockoutZoneOutline( otherZone );
1550 }
1551 }
1552
1553 for( FOOTPRINT* footprint : m_board->Footprints() )
1554 {
1555 for( ZONE* otherZone : footprint->Zones() )
1556 {
1557 if( otherZone->SameNet( aZone ) && otherZone->HigherPriority( aZone ) )
1558 {
1559 // Do not remove teardrop area: it is not useful and not good
1560 if( !otherZone->IsTeardropArea() )
1561 knockoutZoneOutline( otherZone );
1562 }
1563 }
1564 }
1565}
1566
1567
1568void ZONE_FILLER::connect_nearby_polys( SHAPE_POLY_SET& aPolys, double aDistance )
1569{
1570 if( aPolys.OutlineCount() < 1 )
1571 return;
1572
1573 VERTEX_CONNECTOR vs( aPolys.BBoxFromCaches(), aPolys, aDistance );
1574
1575 vs.FindResults();
1576
1577 // This cannot be a reference because we need to do the comparison below while
1578 // changing the values
1579 std::map<int, std::vector<std::pair<int, VECTOR2I>>> insertion_points;
1580
1581 for( const RESULTS& result : vs.GetResults() )
1582 {
1583 SHAPE_LINE_CHAIN& line1 = aPolys.Outline( result.m_outline1 );
1584 SHAPE_LINE_CHAIN& line2 = aPolys.Outline( result.m_outline2 );
1585
1586 VECTOR2I pt1 = line1.CPoint( result.m_vertex1 );
1587 VECTOR2I pt2 = line2.CPoint( result.m_vertex2 );
1588
1589 // We want to insert the existing point first so that we can place the new point
1590 // between the two points at the same location.
1591 insertion_points[result.m_outline1].push_back( { result.m_vertex1, pt1 } );
1592 insertion_points[result.m_outline1].push_back( { result.m_vertex1, pt2 } );
1593 }
1594
1595 for( auto& [outline, vertices] : insertion_points )
1596 {
1597 SHAPE_LINE_CHAIN& line = aPolys.Outline( outline );
1598
1599 // Stable sort here because we want to make sure that we are inserting pt1 first and
1600 // pt2 second but still sorting the rest of the indices from highest to lowest.
1601 // This allows us to insert into the existing polygon without modifying the future
1602 // insertion points.
1603 std::stable_sort( vertices.begin(), vertices.end(),
1604 []( const std::pair<int, VECTOR2I>& a, const std::pair<int, VECTOR2I>& b )
1605 {
1606 return a.first > b.first;
1607 } );
1608
1609 for( const auto& [vertex, pt] : vertices )
1610 line.Insert( vertex + 1, pt ); // +1 here because we want to insert after the existing point
1611 }
1612}
1613
1614
1615#define DUMP_POLYS_TO_COPPER_LAYER( a, b, c ) \
1616 { if( m_debugZoneFiller && aDebugLayer == b ) \
1617 { \
1618 m_board->SetLayerName( b, c ); \
1619 SHAPE_POLY_SET d = a; \
1620 d.Fracture( SHAPE_POLY_SET::PM_STRICTLY_SIMPLE ); \
1621 aFillPolys = d; \
1622 return false; \
1623 } \
1624 }
1625
1626
1627/*
1628 * Note that aSmoothedOutline is larger than the zone where it intersects with other, same-net
1629 * zones. This is to prevent the re-inflation post min-width trimming from createing divots
1630 * between adjacent zones. The final aMaxExtents trimming will remove these areas from the final
1631 * fill.
1632 */
1633bool ZONE_FILLER::fillCopperZone( const ZONE* aZone, PCB_LAYER_ID aLayer, PCB_LAYER_ID aDebugLayer,
1634 const SHAPE_POLY_SET& aSmoothedOutline,
1635 const SHAPE_POLY_SET& aMaxExtents, SHAPE_POLY_SET& aFillPolys )
1636{
1638
1639 // Features which are min_width should survive pruning; features that are *less* than
1640 // min_width should not. Therefore we subtract epsilon from the min_width when
1641 // deflating/inflating.
1642 int half_min_width = aZone->GetMinThickness() / 2;
1643 int epsilon = pcbIUScale.mmToIU( 0.001 );
1644
1645 // Solid polygons are deflated and inflated during calculations. Deflating doesn't cause
1646 // issues, but inflate is tricky as it can create excessively long and narrow spikes for
1647 // acute angles.
1648 // ALLOW_ACUTE_CORNERS cannot be used due to the spike problem.
1649 // CHAMFER_ACUTE_CORNERS is tempting, but can still produce spikes in some unusual
1650 // circumstances (https://gitlab.com/kicad/code/kicad/-/issues/5581).
1651 // It's unclear if ROUND_ACUTE_CORNERS would have the same issues, but is currently avoided
1652 // as a "less-safe" option.
1653 // ROUND_ALL_CORNERS produces the uniformly nicest shapes, but also a lot of segments.
1654 // CHAMFER_ALL_CORNERS improves the segment count.
1655 CORNER_STRATEGY fastCornerStrategy = CORNER_STRATEGY::CHAMFER_ALL_CORNERS;
1656 CORNER_STRATEGY cornerStrategy = CORNER_STRATEGY::ROUND_ALL_CORNERS;
1657
1658 std::vector<PAD*> thermalConnectionPads;
1659 std::vector<PAD*> noConnectionPads;
1660 std::deque<SHAPE_LINE_CHAIN> thermalSpokes;
1661 SHAPE_POLY_SET clearanceHoles;
1662
1663 aFillPolys = aSmoothedOutline;
1664 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In1_Cu, wxT( "smoothed-outline" ) );
1665
1667 return false;
1668
1669 /* -------------------------------------------------------------------------------------
1670 * Knockout thermal reliefs.
1671 */
1672
1673 knockoutThermalReliefs( aZone, aLayer, aFillPolys, thermalConnectionPads, noConnectionPads );
1674 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In2_Cu, wxT( "minus-thermal-reliefs" ) );
1675
1677 return false;
1678
1679 /* -------------------------------------------------------------------------------------
1680 * Knockout electrical clearances.
1681 */
1682
1683 buildCopperItemClearances( aZone, aLayer, noConnectionPads, clearanceHoles );
1684 DUMP_POLYS_TO_COPPER_LAYER( clearanceHoles, In3_Cu, wxT( "clearance-holes" ) );
1685
1687 return false;
1688
1689 /* -------------------------------------------------------------------------------------
1690 * Add thermal relief spokes.
1691 */
1692
1693 buildThermalSpokes( aZone, aLayer, thermalConnectionPads, thermalSpokes );
1694
1696 return false;
1697
1698 // Create a temporary zone that we can hit-test spoke-ends against. It's only temporary
1699 // because the "real" subtract-clearance-holes has to be done after the spokes are added.
1700 static const bool USE_BBOX_CACHES = true;
1701 SHAPE_POLY_SET testAreas = aFillPolys.CloneDropTriangulation();
1702 testAreas.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
1703 DUMP_POLYS_TO_COPPER_LAYER( testAreas, In4_Cu, wxT( "minus-clearance-holes" ) );
1704
1705 // Prune features that don't meet minimum-width criteria
1706 if( half_min_width - epsilon > epsilon )
1707 {
1708 testAreas.Deflate( half_min_width - epsilon, fastCornerStrategy, m_maxError );
1709 DUMP_POLYS_TO_COPPER_LAYER( testAreas, In5_Cu, wxT( "spoke-test-deflated" ) );
1710
1711 testAreas.Inflate( half_min_width - epsilon, fastCornerStrategy, m_maxError );
1712 DUMP_POLYS_TO_COPPER_LAYER( testAreas, In6_Cu, wxT( "spoke-test-reinflated" ) );
1713 }
1714
1716 return false;
1717
1718 // Spoke-end-testing is hugely expensive so we generate cached bounding-boxes to speed
1719 // things up a bit.
1720 testAreas.BuildBBoxCaches();
1721 int interval = 0;
1722
1723 SHAPE_POLY_SET debugSpokes;
1724
1725 for( const SHAPE_LINE_CHAIN& spoke : thermalSpokes )
1726 {
1727 const VECTOR2I& testPt = spoke.CPoint( 3 );
1728
1729 // Hit-test against zone body
1730 if( testAreas.Contains( testPt, -1, 1, USE_BBOX_CACHES ) )
1731 {
1732 if( m_debugZoneFiller )
1733 debugSpokes.AddOutline( spoke );
1734
1735 aFillPolys.AddOutline( spoke );
1736 continue;
1737 }
1738
1739 if( interval++ > 400 )
1740 {
1742 return false;
1743
1744 interval = 0;
1745 }
1746
1747 // Hit-test against other spokes
1748 for( const SHAPE_LINE_CHAIN& other : thermalSpokes )
1749 {
1750 // Hit test in both directions to avoid interactions with round-off errors.
1751 // (See https://gitlab.com/kicad/code/kicad/-/issues/13316.)
1752 if( &other != &spoke
1753 && other.PointInside( testPt, 1, USE_BBOX_CACHES )
1754 && spoke.PointInside( other.CPoint( 3 ), 1, USE_BBOX_CACHES ) )
1755 {
1756 if( m_debugZoneFiller )
1757 debugSpokes.AddOutline( spoke );
1758
1759 aFillPolys.AddOutline( spoke );
1760 break;
1761 }
1762 }
1763 }
1764
1765 DUMP_POLYS_TO_COPPER_LAYER( debugSpokes, In7_Cu, wxT( "spokes" ) );
1766
1768 return false;
1769
1770 aFillPolys.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
1771 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In8_Cu, wxT( "after-spoke-trimming" ) );
1772
1773 /* -------------------------------------------------------------------------------------
1774 * Prune features that don't meet minimum-width criteria
1775 */
1776
1777 if( half_min_width - epsilon > epsilon )
1778 aFillPolys.Deflate( half_min_width - epsilon, fastCornerStrategy, m_maxError );
1779
1780 // Min-thickness is the web thickness. On the other hand, a blob min-thickness by
1781 // min-thickness is not useful. Since there's no obvious definition of web vs. blob, we
1782 // arbitrarily choose "at least 2X min-thickness on one axis". (Since we're doing this
1783 // during the deflated state, that means we test for "at least min-thickness".)
1784 for( int ii = aFillPolys.OutlineCount() - 1; ii >= 0; ii-- )
1785 {
1786 std::vector<SHAPE_LINE_CHAIN>& island = aFillPolys.Polygon( ii );
1787 BOX2I islandExtents;
1788
1789 for( const VECTOR2I& pt : island.front().CPoints() )
1790 {
1791 islandExtents.Merge( pt );
1792
1793 if( islandExtents.GetSizeMax() > aZone->GetMinThickness() )
1794 break;
1795 }
1796
1797 if( islandExtents.GetSizeMax() < aZone->GetMinThickness() )
1798 aFillPolys.DeletePolygon( ii );
1799 }
1800
1801 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In9_Cu, wxT( "deflated" ) );
1802
1804 return false;
1805
1806 /* -------------------------------------------------------------------------------------
1807 * Process the hatch pattern (note that we do this while deflated)
1808 */
1809
1810 if( aZone->GetFillMode() == ZONE_FILL_MODE::HATCH_PATTERN )
1811 {
1812 if( !addHatchFillTypeOnZone( aZone, aLayer, aDebugLayer, aFillPolys ) )
1813 return false;
1814 }
1815 else
1816 {
1817 /* ---------------------------------------------------------------------------------
1818 * Connect nearby polygons with zero-width lines in order to ensure correct
1819 * re-inflation.
1820 */
1821 aFillPolys.Fracture( SHAPE_POLY_SET::PM_FAST );
1822 connect_nearby_polys( aFillPolys, aZone->GetMinThickness() );
1823
1824 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In10_Cu, wxT( "connected-nearby-polys" ) );
1825 }
1826
1828 return false;
1829
1830 /* -------------------------------------------------------------------------------------
1831 * Finish minimum-width pruning by re-inflating
1832 */
1833
1834 if( half_min_width - epsilon > epsilon )
1835 aFillPolys.Inflate( half_min_width - epsilon, cornerStrategy, m_maxError, true );
1836
1837 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In15_Cu, wxT( "after-reinflating" ) );
1838
1839 /* -------------------------------------------------------------------------------------
1840 * Ensure additive changes (thermal stubs and inflating acute corners) do not add copper
1841 * outside the zone boundary, inside the clearance holes, or between otherwise isolated
1842 * islands
1843 */
1844
1845 for( PAD* pad : thermalConnectionPads )
1846 addHoleKnockout( pad, 0, clearanceHoles );
1847
1848 aFillPolys.BooleanIntersection( aMaxExtents, SHAPE_POLY_SET::PM_FAST );
1849 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In16_Cu, wxT( "after-trim-to-outline" ) );
1850 aFillPolys.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
1851 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In17_Cu, wxT( "after-trim-to-clearance-holes" ) );
1852
1853 /* -------------------------------------------------------------------------------------
1854 * Lastly give any same-net but higher-priority zones control over their own area.
1855 */
1856
1857 subtractHigherPriorityZones( aZone, aLayer, aFillPolys );
1858 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In18_Cu, wxT( "minus-higher-priority-zones" ) );
1859
1860 aFillPolys.Fracture( SHAPE_POLY_SET::PM_FAST );
1861 return true;
1862}
1863
1864
1866 const SHAPE_POLY_SET& aSmoothedOutline,
1867 SHAPE_POLY_SET& aFillPolys )
1868{
1870 BOX2I zone_boundingbox = aZone->GetBoundingBox();
1871 SHAPE_POLY_SET clearanceHoles;
1872 long ticker = 0;
1873
1874 auto checkForCancel =
1875 [&ticker]( PROGRESS_REPORTER* aReporter ) -> bool
1876 {
1877 return aReporter && ( ticker++ % 50 ) == 0 && aReporter->IsCancelled();
1878 };
1879
1880 auto knockoutGraphicClearance =
1881 [&]( BOARD_ITEM* aItem )
1882 {
1883 if( aItem->IsKnockout() && aItem->IsOnLayer( aLayer )
1884 && aItem->GetBoundingBox().Intersects( zone_boundingbox ) )
1885 {
1887 aZone, aItem, aLayer );
1888
1889 addKnockout( aItem, aLayer, cc.GetValue().Min(), false, clearanceHoles );
1890 }
1891 };
1892
1893 for( FOOTPRINT* footprint : m_board->Footprints() )
1894 {
1895 if( checkForCancel( m_progressReporter ) )
1896 return false;
1897
1898 knockoutGraphicClearance( &footprint->Reference() );
1899 knockoutGraphicClearance( &footprint->Value() );
1900
1901 for( BOARD_ITEM* item : footprint->GraphicalItems() )
1902 knockoutGraphicClearance( item );
1903 }
1904
1905 for( BOARD_ITEM* item : m_board->Drawings() )
1906 {
1907 if( checkForCancel( m_progressReporter ) )
1908 return false;
1909
1910 knockoutGraphicClearance( item );
1911 }
1912
1913 aFillPolys = aSmoothedOutline;
1914 aFillPolys.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
1915
1916 for( ZONE* keepout : m_board->Zones() )
1917 {
1918 if( !keepout->GetIsRuleArea() )
1919 continue;
1920
1921 if( !keepout->HasKeepoutParametersSet() )
1922 continue;
1923
1924 if( keepout->GetDoNotAllowCopperPour() && keepout->IsOnLayer( aLayer ) )
1925 {
1926 if( keepout->GetBoundingBox().Intersects( zone_boundingbox ) )
1927 {
1928 if( keepout->Outline()->ArcCount() == 0 )
1929 {
1930 aFillPolys.BooleanSubtract( *keepout->Outline(), SHAPE_POLY_SET::PM_FAST );
1931 }
1932 else
1933 {
1934 SHAPE_POLY_SET keepoutOutline( *keepout->Outline() );
1935 keepoutOutline.ClearArcs();
1936 aFillPolys.BooleanSubtract( keepoutOutline, SHAPE_POLY_SET::PM_FAST );
1937 }
1938 }
1939 }
1940 }
1941
1942 // Features which are min_width should survive pruning; features that are *less* than
1943 // min_width should not. Therefore we subtract epsilon from the min_width when
1944 // deflating/inflating.
1945 int half_min_width = aZone->GetMinThickness() / 2;
1946 int epsilon = pcbIUScale.mmToIU( 0.001 );
1947
1948 aFillPolys.Deflate( half_min_width - epsilon, CORNER_STRATEGY::CHAMFER_ALL_CORNERS, m_maxError );
1949
1950 // Remove the non filled areas due to the hatch pattern
1951 if( aZone->GetFillMode() == ZONE_FILL_MODE::HATCH_PATTERN )
1952 {
1953 if( !addHatchFillTypeOnZone( aZone, aLayer, aLayer, aFillPolys ) )
1954 return false;
1955 }
1956
1957 // Re-inflate after pruning of areas that don't meet minimum-width criteria
1958 if( half_min_width - epsilon > epsilon )
1959 aFillPolys.Inflate( half_min_width - epsilon, CORNER_STRATEGY::ROUND_ALL_CORNERS, m_maxError );
1960
1962 return true;
1963}
1964
1965
1966/*
1967 * Build the filled solid areas data from real outlines (stored in m_Poly)
1968 * The solid areas can be more than one on copper layers, and do not have holes
1969 * ( holes are linked by overlapping segments to the main outline)
1970 */
1972{
1973 SHAPE_POLY_SET* boardOutline = m_brdOutlinesValid ? &m_boardOutline : nullptr;
1974 SHAPE_POLY_SET maxExtents;
1975 SHAPE_POLY_SET smoothedPoly;
1976 PCB_LAYER_ID debugLayer = UNDEFINED_LAYER;
1977
1978 if( m_debugZoneFiller && LSET::InternalCuMask().Contains( aLayer ) )
1979 {
1980 debugLayer = aLayer;
1981 aLayer = F_Cu;
1982 }
1983
1984 if( !aZone->BuildSmoothedPoly( maxExtents, aLayer, boardOutline, &smoothedPoly ) )
1985 return false;
1986
1988 return false;
1989
1990 if( aZone->IsOnCopperLayer() )
1991 {
1992 if( fillCopperZone( aZone, aLayer, debugLayer, smoothedPoly, maxExtents, aFillPolys ) )
1993 aZone->SetNeedRefill( false );
1994 }
1995 else
1996 {
1997 if( fillNonCopperZone( aZone, aLayer, smoothedPoly, aFillPolys ) )
1998 aZone->SetNeedRefill( false );
1999 }
2000
2001 return true;
2002}
2003
2004
2009 const std::vector<PAD*>& aSpokedPadsList,
2010 std::deque<SHAPE_LINE_CHAIN>& aSpokesList )
2011{
2013 BOX2I zoneBB = aZone->GetBoundingBox();
2014 DRC_CONSTRAINT constraint;
2015 int zone_half_width = aZone->GetMinThickness() / 2;
2016
2017 zoneBB.Inflate( std::max( bds.GetBiggestClearanceValue(), aZone->GetLocalClearance().value() ) );
2018
2019 // Is a point on the boundary of the polygon inside or outside?
2020 // The boundary may be off by MaxError
2021 int epsilon = bds.m_MaxError;
2022
2023 for( PAD* pad : aSpokedPadsList )
2024 {
2025 // We currently only connect to pads, not pad holes
2026 if( !pad->IsOnLayer( aLayer ) )
2027 continue;
2028
2029 constraint = bds.m_DRCEngine->EvalRules( THERMAL_RELIEF_GAP_CONSTRAINT, pad, aZone, aLayer );
2030 int thermalReliefGap = constraint.GetValue().Min();
2031
2032 constraint = bds.m_DRCEngine->EvalRules( THERMAL_SPOKE_WIDTH_CONSTRAINT, pad, aZone, aLayer );
2033 int spoke_w = constraint.GetValue().Opt();
2034
2035 // Spoke width should ideally be smaller than the pad minor axis.
2036 // Otherwise the thermal shape is not really a thermal relief,
2037 // and the algo to count the actual number of spokes can fail
2038 int spoke_max_allowed_w = std::min( pad->GetSize( aLayer ).x, pad->GetSize( aLayer ).y );
2039
2040 spoke_w = std::clamp( spoke_w, constraint.Value().Min(), constraint.Value().Max() );
2041
2042 // ensure the spoke width is smaller than the pad minor size
2043 spoke_w = std::min( spoke_w, spoke_max_allowed_w );
2044
2045 // Cannot create stubs having a width < zone min thickness
2046 if( spoke_w < aZone->GetMinThickness() )
2047 continue;
2048
2049 int spoke_half_w = spoke_w / 2;
2050
2051 // Quick test here to possibly save us some work
2052 BOX2I itemBB = pad->GetBoundingBox();
2053 itemBB.Inflate( thermalReliefGap + epsilon );
2054
2055 if( !( itemBB.Intersects( zoneBB ) ) )
2056 continue;
2057
2058 bool customSpokes = false;
2059
2060 if( pad->GetShape( aLayer ) == PAD_SHAPE::CUSTOM )
2061 {
2062 for( const std::shared_ptr<PCB_SHAPE>& primitive : pad->GetPrimitives( aLayer ) )
2063 {
2064 if( primitive->IsProxyItem() && primitive->GetShape() == SHAPE_T::SEGMENT )
2065 {
2066 customSpokes = true;
2067 break;
2068 }
2069 }
2070 }
2071
2072 // Thermal spokes consist of square-ended segments from the pad center to points just
2073 // outside the thermal relief. The outside end has an extra center point (which must be
2074 // at idx 3) which is used for testing whether or not the spoke connects to copper in the
2075 // parent zone.
2076
2077 auto buildSpokesFromOrigin =
2078 [&]( const BOX2I& box, EDA_ANGLE angle )
2079 {
2080 VECTOR2I center = box.GetCenter();
2081 VECTOR2I half_size( box.GetWidth() / 2, box.GetHeight() / 2 );
2082
2083 // Function to find intersection of line with box edge
2084 auto intersectLineBox = [&](const VECTOR2D& direction) -> VECTOR2I {
2085 double dx = direction.x;
2086 double dy = direction.y;
2087
2088 // Short-circuit the axis cases because they will be degenerate in the
2089 // intersection test
2090 if( direction.x == 0 )
2091 return VECTOR2I( 0, dy * half_size.y );
2092 else if( direction.y == 0 )
2093 return VECTOR2I( dx * half_size.x, 0 );
2094
2095 // We are going to intersect with one side or the other. Whichever
2096 // we hit first is the fraction of the spoke length we keep
2097 double tx = std::min( half_size.x / std::abs( dx ),
2098 half_size.y / std::abs( dy ) );
2099 return VECTOR2I( dx * tx, dy * tx );
2100 };
2101
2102 // Precalculate angles for four cardinal directions
2103 const EDA_ANGLE angles[4] = {
2104 EDA_ANGLE( 0.0, DEGREES_T ) + angle, // Right
2105 EDA_ANGLE( 90.0, DEGREES_T ) + angle, // Up
2106 EDA_ANGLE( 180.0, DEGREES_T ) + angle, // Left
2107 EDA_ANGLE( 270.0, DEGREES_T ) + angle // Down
2108 };
2109
2110 // Generate four spokes in cardinal directions
2111 for( const EDA_ANGLE& spokeAngle : angles )
2112 {
2113 VECTOR2D direction( spokeAngle.Cos(), spokeAngle.Sin() );
2114 VECTOR2D perpendicular = direction.Perpendicular();
2115
2116 VECTOR2I intersection = intersectLineBox( direction );
2117 VECTOR2I spoke_side = perpendicular.Resize( spoke_half_w );
2118
2119 SHAPE_LINE_CHAIN spoke;
2120 spoke.Append( center + spoke_side );
2121 spoke.Append( center - spoke_side );
2122 spoke.Append( center + intersection - spoke_side );
2123 spoke.Append( center + intersection ); // test pt
2124 spoke.Append( center + intersection + spoke_side );
2125 spoke.SetClosed( true );
2126 aSpokesList.push_back( std::move( spoke ) );
2127 }
2128 };
2129
2130 if( customSpokes )
2131 {
2132 SHAPE_POLY_SET thermalPoly;
2133 SHAPE_LINE_CHAIN thermalOutline;
2134
2135 pad->TransformShapeToPolygon( thermalPoly, aLayer, thermalReliefGap + epsilon,
2137
2138 if( thermalPoly.OutlineCount() )
2139 thermalOutline = thermalPoly.Outline( 0 );
2140
2141 for( const std::shared_ptr<PCB_SHAPE>& primitive : pad->GetPrimitives( aLayer ) )
2142 {
2143 if( primitive->IsProxyItem() && primitive->GetShape() == SHAPE_T::SEGMENT )
2144 {
2145 SEG seg( primitive->GetStart(), primitive->GetEnd() );
2146 SHAPE_LINE_CHAIN::INTERSECTIONS intersections;
2147
2148 RotatePoint( seg.A, pad->GetOrientation() );
2149 RotatePoint( seg.B, pad->GetOrientation() );
2150 seg.A += pad->ShapePos( aLayer );
2151 seg.B += pad->ShapePos( aLayer );
2152
2153 // Make sure seg.A is the origin
2154 if( !pad->GetEffectivePolygon( aLayer, ERROR_OUTSIDE )->Contains( seg.A ) )
2155 seg.Reverse();
2156
2157 // Trim seg.B to the thermal outline
2158 if( thermalOutline.Intersect( seg, intersections ) )
2159 {
2160 seg.B = intersections.front().p;
2161
2162 VECTOR2I offset = ( seg.B - seg.A ).Perpendicular().Resize( spoke_half_w );
2163 SHAPE_LINE_CHAIN spoke;
2164
2165 spoke.Append( seg.A + offset );
2166 spoke.Append( seg.A - offset );
2167 spoke.Append( seg.B - offset );
2168 spoke.Append( seg.B ); // test pt
2169 spoke.Append( seg.B + offset );
2170
2171 spoke.SetClosed( true );
2172 aSpokesList.push_back( std::move( spoke ) );
2173 }
2174 }
2175 }
2176 }
2177 else
2178 {
2179 // Since the bounding-box needs to be correclty rotated we use a dummy pad to keep
2180 // from dirtying the real pad's cached shapes.
2181 PAD dummy_pad( *pad );
2182 dummy_pad.SetOrientation( ANGLE_0 );
2183
2184 // Spokes are from center of pad shape, not from hole. So the dummy pad has no shape
2185 // offset and is at position 0,0
2186 dummy_pad.SetPosition( VECTOR2I( 0, 0 ) );
2187 dummy_pad.SetOffset( aLayer, VECTOR2I( 0, 0 ) );
2188
2189 BOX2I spokesBox = dummy_pad.GetBoundingBox();
2190
2191 // Add the half width of the zone mininum width to the inflate amount to account for
2192 // the fact that the deflation procedure will shrink the results by half the half the
2193 // zone min width
2194 spokesBox.Inflate( thermalReliefGap + epsilon + zone_half_width );
2195
2196 // This is a touchy case because the bounding box for circles overshoots the mark
2197 // when rotated at 45 degrees. So we just build spokes at 0 degrees and rotate
2198 // them later.
2199 if( pad->GetShape( aLayer ) == PAD_SHAPE::CIRCLE
2200 || ( pad->GetShape( aLayer ) == PAD_SHAPE::OVAL
2201 && pad->GetSizeX() == pad->GetSizeY() ) )
2202 {
2203 buildSpokesFromOrigin( spokesBox, ANGLE_0 );
2204
2205 if( pad->GetThermalSpokeAngle() != ANGLE_0 )
2206 {
2207 //Rotate the last four elements of aspokeslist
2208 for( auto it = aSpokesList.rbegin(); it != aSpokesList.rbegin() + 4; ++it )
2209 it->Rotate( pad->GetThermalSpokeAngle() );
2210 }
2211 }
2212 else
2213 {
2214 buildSpokesFromOrigin( spokesBox, pad->GetThermalSpokeAngle() );
2215 }
2216
2217 auto spokeIter = aSpokesList.rbegin();
2218
2219 for( int ii = 0; ii < 4; ++ii, ++spokeIter )
2220 {
2221 spokeIter->Rotate( pad->GetOrientation() );
2222 spokeIter->Move( pad->ShapePos( aLayer ) );
2223 }
2224
2225 // Remove group membership from dummy item before deleting
2226 dummy_pad.SetParentGroup( nullptr );
2227 }
2228 }
2229
2230 for( size_t ii = 0; ii < aSpokesList.size(); ++ii )
2231 aSpokesList[ii].GenerateBBoxCache();
2232}
2233
2234
2236 PCB_LAYER_ID aDebugLayer, SHAPE_POLY_SET& aFillPolys )
2237{
2238 // Build grid:
2239
2240 // obviously line thickness must be > zone min thickness.
2241 // It can happens if a board file was edited by hand by a python script
2242 // Use 1 micron margin to be *sure* there is no issue in Gerber files
2243 // (Gbr file unit = 1 or 10 nm) due to some truncation in coordinates or calculations
2244 // This margin also avoid problems due to rounding coordinates in next calculations
2245 // that can create incorrect polygons
2246 int thickness = std::max( aZone->GetHatchThickness(),
2247 aZone->GetMinThickness() + pcbIUScale.mmToIU( 0.001 ) );
2248
2249 int linethickness = thickness - aZone->GetMinThickness();
2250 int gridsize = thickness + aZone->GetHatchGap();
2251 int maxError = m_board->GetDesignSettings().m_MaxError;
2252
2253 SHAPE_POLY_SET filledPolys = aFillPolys.CloneDropTriangulation();
2254 // Use a area that contains the rotated bbox by orientation, and after rotate the result
2255 // by -orientation.
2256 if( !aZone->GetHatchOrientation().IsZero() )
2257 filledPolys.Rotate( - aZone->GetHatchOrientation() );
2258
2259 BOX2I bbox = filledPolys.BBox( 0 );
2260
2261 // Build hole shape
2262 // the hole size is aZone->GetHatchGap(), but because the outline thickness
2263 // is aZone->GetMinThickness(), the hole shape size must be larger
2264 SHAPE_LINE_CHAIN hole_base;
2265 int hole_size = aZone->GetHatchGap() + aZone->GetMinThickness();
2266 VECTOR2I corner( 0, 0 );;
2267 hole_base.Append( corner );
2268 corner.x += hole_size;
2269 hole_base.Append( corner );
2270 corner.y += hole_size;
2271 hole_base.Append( corner );
2272 corner.x = 0;
2273 hole_base.Append( corner );
2274 hole_base.SetClosed( true );
2275
2276 // Calculate minimal area of a grid hole.
2277 // All holes smaller than a threshold will be removed
2278 double minimal_hole_area = hole_base.Area() * aZone->GetHatchHoleMinArea();
2279
2280 // Now convert this hole to a smoothed shape:
2281 if( aZone->GetHatchSmoothingLevel() > 0 )
2282 {
2283 // the actual size of chamfer, or rounded corner radius is the half size
2284 // of the HatchFillTypeGap scaled by aZone->GetHatchSmoothingValue()
2285 // aZone->GetHatchSmoothingValue() = 1.0 is the max value for the chamfer or the
2286 // radius of corner (radius = half size of the hole)
2287 int smooth_value = KiROUND( aZone->GetHatchGap()
2288 * aZone->GetHatchSmoothingValue() / 2 );
2289
2290 // Minimal optimization:
2291 // make smoothing only for reasonable smooth values, to avoid a lot of useless segments
2292 // and if the smooth value is small, use chamfer even if fillet is requested
2293 #define SMOOTH_MIN_VAL_MM 0.02
2294 #define SMOOTH_SMALL_VAL_MM 0.04
2295
2296 if( smooth_value > pcbIUScale.mmToIU( SMOOTH_MIN_VAL_MM ) )
2297 {
2298 SHAPE_POLY_SET smooth_hole;
2299 smooth_hole.AddOutline( hole_base );
2300 int smooth_level = aZone->GetHatchSmoothingLevel();
2301
2302 if( smooth_value < pcbIUScale.mmToIU( SMOOTH_SMALL_VAL_MM ) && smooth_level > 1 )
2303 smooth_level = 1;
2304
2305 // Use a larger smooth_value to compensate the outline tickness
2306 // (chamfer is not visible is smooth value < outline thickess)
2307 smooth_value += aZone->GetMinThickness() / 2;
2308
2309 // smooth_value cannot be bigger than the half size oh the hole:
2310 smooth_value = std::min( smooth_value, aZone->GetHatchGap() / 2 );
2311
2312 // the error to approximate a circle by segments when smoothing corners by a arc
2313 maxError = std::max( maxError * 2, smooth_value / 20 );
2314
2315 switch( smooth_level )
2316 {
2317 case 1:
2318 // Chamfer() uses the distance from a corner to create a end point
2319 // for the chamfer.
2320 hole_base = smooth_hole.Chamfer( smooth_value ).Outline( 0 );
2321 break;
2322
2323 default:
2324 if( aZone->GetHatchSmoothingLevel() > 2 )
2325 maxError /= 2; // Force better smoothing
2326
2327 hole_base = smooth_hole.Fillet( smooth_value, maxError ).Outline( 0 );
2328 break;
2329
2330 case 0:
2331 break;
2332 };
2333 }
2334 }
2335
2336 // Build holes
2337 SHAPE_POLY_SET holes;
2338
2339 for( int xx = 0; ; xx++ )
2340 {
2341 int xpos = xx * gridsize;
2342
2343 if( xpos > bbox.GetWidth() )
2344 break;
2345
2346 for( int yy = 0; ; yy++ )
2347 {
2348 int ypos = yy * gridsize;
2349
2350 if( ypos > bbox.GetHeight() )
2351 break;
2352
2353 // Generate hole
2354 SHAPE_LINE_CHAIN hole( hole_base );
2355 hole.Move( VECTOR2I( xpos, ypos ) );
2356 holes.AddOutline( hole );
2357 }
2358 }
2359
2360 holes.Move( bbox.GetPosition() );
2361
2362 if( !aZone->GetHatchOrientation().IsZero() )
2363 holes.Rotate( aZone->GetHatchOrientation() );
2364
2365 DUMP_POLYS_TO_COPPER_LAYER( holes, In10_Cu, wxT( "hatch-holes" ) );
2366
2367 int outline_margin = aZone->GetMinThickness() * 1.1;
2368
2369 // Using GetHatchThickness() can look more consistent than GetMinThickness().
2370 if( aZone->GetHatchBorderAlgorithm() && aZone->GetHatchThickness() > outline_margin )
2371 outline_margin = aZone->GetHatchThickness();
2372
2373 // The fill has already been deflated to ensure GetMinThickness() so we just have to
2374 // account for anything beyond that.
2375 SHAPE_POLY_SET deflatedFilledPolys = aFillPolys.CloneDropTriangulation();
2376 deflatedFilledPolys.Deflate( outline_margin - aZone->GetMinThickness(),
2377 CORNER_STRATEGY::CHAMFER_ALL_CORNERS, maxError );
2378 holes.BooleanIntersection( deflatedFilledPolys, SHAPE_POLY_SET::PM_FAST );
2379 DUMP_POLYS_TO_COPPER_LAYER( holes, In11_Cu, wxT( "fill-clipped-hatch-holes" ) );
2380
2381 SHAPE_POLY_SET deflatedOutline = aZone->Outline()->CloneDropTriangulation();
2382 deflatedOutline.Deflate( outline_margin, CORNER_STRATEGY::CHAMFER_ALL_CORNERS, maxError );
2383 holes.BooleanIntersection( deflatedOutline, SHAPE_POLY_SET::PM_FAST );
2384 DUMP_POLYS_TO_COPPER_LAYER( holes, In12_Cu, wxT( "outline-clipped-hatch-holes" ) );
2385
2386 if( aZone->GetNetCode() != 0 )
2387 {
2388 // Vias and pads connected to the zone must not be allowed to become isolated inside
2389 // one of the holes. Effectively this means their copper outline needs to be expanded
2390 // to be at least as wide as the gap so that it is guaranteed to touch at least one
2391 // edge.
2392 BOX2I zone_boundingbox = aZone->GetBoundingBox();
2393 SHAPE_POLY_SET aprons;
2394 int min_apron_radius = ( aZone->GetHatchGap() * 10 ) / 19;
2395
2396 for( PCB_TRACK* track : m_board->Tracks() )
2397 {
2398 if( track->Type() == PCB_VIA_T )
2399 {
2400 PCB_VIA* via = static_cast<PCB_VIA*>( track );
2401
2402 if( via->GetNetCode() == aZone->GetNetCode()
2403 && via->IsOnLayer( aLayer )
2404 && via->GetBoundingBox().Intersects( zone_boundingbox ) )
2405 {
2406 int r = std::max( min_apron_radius,
2407 via->GetDrillValue() / 2 + outline_margin );
2408
2409 TransformCircleToPolygon( aprons, via->GetPosition(), r, maxError,
2410 ERROR_OUTSIDE );
2411 }
2412 }
2413 }
2414
2415 for( FOOTPRINT* footprint : m_board->Footprints() )
2416 {
2417 for( PAD* pad : footprint->Pads() )
2418 {
2419 if( pad->GetNetCode() == aZone->GetNetCode()
2420 && pad->IsOnLayer( aLayer )
2421 && pad->GetBoundingBox().Intersects( zone_boundingbox ) )
2422 {
2423 // What we want is to bulk up the pad shape so that the narrowest bit of
2424 // copper between the hole and the apron edge is at least outline_margin
2425 // wide (and that the apron itself meets min_apron_radius. But that would
2426 // take a lot of code and math, and the following approximation is close
2427 // enough.
2428 int pad_width = std::min( pad->GetSize( aLayer ).x, pad->GetSize( aLayer ).y );
2429 int slot_width = std::min( pad->GetDrillSize().x, pad->GetDrillSize().y );
2430 int min_annular_ring_width = ( pad_width - slot_width ) / 2;
2431 int clearance = std::max( min_apron_radius - pad_width / 2,
2432 outline_margin - min_annular_ring_width );
2433
2434 clearance = std::max( 0, clearance - linethickness / 2 );
2435 pad->TransformShapeToPolygon( aprons, aLayer, clearance, maxError,
2436 ERROR_OUTSIDE );
2437 }
2438 }
2439 }
2440
2442 }
2443 DUMP_POLYS_TO_COPPER_LAYER( holes, In13_Cu, wxT( "pad-via-clipped-hatch-holes" ) );
2444
2445 // Now filter truncated holes to avoid small holes in pattern
2446 // It happens for holes near the zone outline
2447 for( int ii = 0; ii < holes.OutlineCount(); )
2448 {
2449 double area = holes.Outline( ii ).Area();
2450
2451 if( area < minimal_hole_area ) // The current hole is too small: remove it
2452 holes.DeletePolygon( ii );
2453 else
2454 ++ii;
2455 }
2456
2457 // create grid. Use SHAPE_POLY_SET::PM_STRICTLY_SIMPLE to
2458 // generate strictly simple polygons needed by Gerber files and Fracture()
2459 aFillPolys.BooleanSubtract( aFillPolys, holes, SHAPE_POLY_SET::PM_STRICTLY_SIMPLE );
2460 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In14_Cu, wxT( "after-hatching" ) );
2461
2462 return true;
2463}
@ ERROR_OUTSIDE
Definition: approximation.h:33
constexpr int ARC_HIGH_DEF
Definition: base_units.h:120
constexpr EDA_IU_SCALE pcbIUScale
Definition: base_units.h:108
@ ZLO_FORCE_NO_ZONE_CONNECTION
Definition: board_item.h:69
@ ZLO_FORCE_FLASHED
Definition: board_item.h:68
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition: box2.h:990
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
Container for design settings for a BOARD object.
std::shared_ptr< DRC_ENGINE > m_DRCEngine
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition: board_item.h:79
void SetParentGroup(PCB_GROUP *aGroup)
Definition: board_item.h:89
virtual void TransformShapeToPolygon(SHAPE_POLY_SET &aBuffer, PCB_LAYER_ID aLayer, int aClearance, int aError, ERROR_LOC aErrorLoc, bool ignoreLineWidth=false) const
Convert the item shape to a closed polygon.
Definition: board_item.cpp:255
virtual void SetIsKnockout(bool aKnockout)
Definition: board_item.h:325
virtual const BOARD * GetBoard() const
Return the BOARD in which this BOARD_ITEM resides, or NULL if none.
Definition: board_item.cpp:47
Information pertinent to a Pcbnew printed circuit board.
Definition: board.h:290
bool GetBoardPolygonOutlines(SHAPE_POLY_SET &aOutlines, OUTLINE_ERROR_HANDLER *aErrorHandler=nullptr, bool aAllowUseArcsInPolygons=false, bool aIncludeNPTHAsOutlines=false)
Extract the board outlines and build a closed polygon from lines, arcs and circle items on edge cut l...
Definition: board.cpp:2497
LSET GetEnabledLayers() const
A proxy function that calls the corresponding function in m_BoardSettings.
Definition: board.cpp:778
const ZONES & Zones() const
Definition: board.h:335
int GetMaxClearanceValue() const
Returns the maximum clearance value for any object on the board.
Definition: board.cpp:901
int GetCopperLayerCount() const
Definition: board.cpp:741
const FOOTPRINTS & Footprints() const
Definition: board.h:331
const TRACKS & Tracks() const
Definition: board.h:329
BOARD_DESIGN_SETTINGS & GetDesignSettings() const
Definition: board.cpp:895
std::shared_ptr< CONNECTIVITY_DATA > GetConnectivity() const
Return a list of missing connections between components/tracks.
Definition: board.h:475
const DRAWINGS & Drawings() const
Definition: board.h:333
constexpr const Vec & GetPosition() const
Definition: box2.h:211
constexpr int GetSizeMax() const
Definition: box2.h:235
constexpr BOX2< Vec > & Inflate(coord_type dx, coord_type dy)
Inflates the rectangle horizontally by dx and vertically by dy.
Definition: box2.h:558
constexpr size_type GetWidth() const
Definition: box2.h:214
constexpr BOX2< Vec > & Merge(const BOX2< Vec > &aRect)
Modify the position and size of the rectangle in order to contain aRect.
Definition: box2.h:658
constexpr const Vec GetCenter() const
Definition: box2.h:230
constexpr size_type GetHeight() const
Definition: box2.h:215
constexpr bool Intersects(const BOX2< Vec > &aRect) const
Definition: box2.h:311
Represent a set of changes (additions, deletions or modifications) of a data model (e....
Definition: commit.h:74
COMMIT & Modify(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Create an undo entry for an item that has been already modified.
Definition: commit.h:105
MINOPTMAX< int > & Value()
Definition: drc_rule.h:153
const MINOPTMAX< int > & GetValue() const
Definition: drc_rule.h:152
ZONE_CONNECTION m_ZoneConnection
Definition: drc_rule.h:192
bool IsNull() const
Definition: drc_rule.h:147
bool IsZero() const
Definition: eda_angle.h:133
KICAD_T Type() const
Returns the type of object.
Definition: eda_item.h:101
Helper class to create more flexible dialogs, including 'do not show again' checkbox handling.
Definition: kidialog.h:43
void DoNotShowCheckbox(wxString file, int line)
Checks the 'do not show again' setting for the dialog.
Definition: kidialog.cpp:51
bool SetOKCancelLabels(const ButtonLabel &ok, const ButtonLabel &cancel) override
Shows the 'do not show again' checkbox.
Definition: kidialog.h:53
int ShowModal() override
Definition: kidialog.cpp:95
LSET is a set of PCB_LAYER_IDs.
Definition: lset.h:36
static LSET InternalCuMask()
Return a complete set of internal copper layers which is all Cu layers except F_Cu and B_Cu.
Definition: lset.cpp:675
static LSET AllCuMask(int aCuLayerCount=MAX_CU_LAYERS)
Return a mask holding the requested number of Cu PCB_LAYER_IDs.
Definition: lset.cpp:686
LSEQ Seq(const LSEQ &aSequence) const
Return an LSEQ from the union of this LSET and a desired sequence.
Definition: lset.cpp:420
bool Contains(PCB_LAYER_ID aLayer) const
See if the layer set contains a PCB layer.
Definition: lset.h:62
T Min() const
Definition: minoptmax.h:33
T Max() const
Definition: minoptmax.h:34
T Opt() const
Definition: minoptmax.h:35
Definition: pad.h:54
const BOX2I GetBoundingBox() const override
The bounding box is cached, so this will be efficient most of the time.
Definition: pad.cpp:802
PAD_SHAPE GetShape(PCB_LAYER_ID aLayer) const
Definition: pad.h:193
void TransformShapeToPolygon(SHAPE_POLY_SET &aBuffer, PCB_LAYER_ID aLayer, int aClearance, int aMaxError, ERROR_LOC aErrorLoc=ERROR_INSIDE, bool ignoreLineWidth=false) const override
Convert the pad shape to a closed polygon.
Definition: pad.cpp:1876
void SetOffset(PCB_LAYER_ID aLayer, const VECTOR2I &aOffset)
Definition: pad.h:313
void SetPosition(const VECTOR2I &aPos) override
Definition: pad.h:204
PADSTACK::CUSTOM_SHAPE_ZONE_MODE GetCustomShapeInZoneOpt() const
Definition: pad.h:223
void SetOrientation(const EDA_ANGLE &aAngle)
Set the rotation angle of the pad.
Definition: pad.cpp:867
bool TransformHoleToPolygon(SHAPE_POLY_SET &aBuffer, int aClearance, int aError, ERROR_LOC aErrorLoc=ERROR_INSIDE) const
Build the corner list of the polygonal drill shape in the board coordinate system.
Definition: pad.cpp:1859
Abstract dimension API.
void TransformShapeToPolygon(SHAPE_POLY_SET &aBuffer, PCB_LAYER_ID aLayer, int aClearance, int aError, ERROR_LOC aErrorLoc, bool aIgnoreLineWidth=false) const override
Convert the item shape to a closed polygon.
void TransformShapeToPolygon(SHAPE_POLY_SET &aBuffer, PCB_LAYER_ID aLayer, int aClearance, int aMaxError, ERROR_LOC aErrorLoc, bool aIgnoreLineWidth=false) const override
Convert the item shape to a closed polygon.
Definition: pcb_text.cpp:568
A progress reporter interface for use in multi-threaded environments.
virtual bool IsCancelled() const =0
virtual bool KeepRefreshing(bool aWait=false)=0
Update the UI (if any).
virtual void Report(const wxString &aMessage)=0
Display aMessage in the progress bar dialog.
virtual void AdvancePhase()=0
Use the next available virtual zone of the dialog progress bar.
virtual void AdvanceProgress()=0
Increment the progress bar length (inside the current virtual zone).
virtual void SetMaxProgress(int aMaxProgress)=0
Fix the value that gives the 100 percent progress bar length (inside the current virtual zone).
int m_vertex2
Definition: zone_filler.cpp:78
RESULTS(int aOutline1, int aOutline2, int aVertex1, int aVertex2)
Definition: zone_filler.cpp:58
int m_outline2
Definition: zone_filler.cpp:76
int m_outline1
Definition: zone_filler.cpp:75
int m_vertex1
Definition: zone_filler.cpp:77
bool operator<(const RESULTS &aOther) const
Definition: zone_filler.cpp:64
Definition: seg.h:42
VECTOR2I A
Definition: seg.h:49
VECTOR2I::extended_type ecoord
Definition: seg.h:44
VECTOR2I B
Definition: seg.h:50
static SEG::ecoord Square(int a)
Definition: seg.h:123
void Reverse()
Definition: seg.h:358
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
void Move(const VECTOR2I &aVector) override
void SetClosed(bool aClosed)
Mark the line chain as closed (i.e.
int Intersect(const SEG &aSeg, INTERSECTIONS &aIp) const
Find all intersection points between our line chain and the segment aSeg.
double Area(bool aAbsolute=true) const
Return the area of this chain.
void Append(int aX, int aY, bool aAllowDuplication=false)
Append a new point at the end of the line chain.
const VECTOR2I & CPoint(int aIndex) const
Return a reference to a given point in the line chain.
void Insert(size_t aVertex, const VECTOR2I &aP)
std::vector< INTERSECTION > INTERSECTIONS
Represent a set of closed polygons.
void Rotate(const EDA_ANGLE &aAngle, const VECTOR2I &aCenter={ 0, 0 }) override
Rotate all vertices by a given angle.
void RemoveAllContours()
Remove all outlines & holes (clears) the polygon set.
SHAPE_POLY_SET Chamfer(int aDistance)
Return a chamfered version of the polygon set.
void BooleanSubtract(const SHAPE_POLY_SET &b, POLYGON_MODE aFastMode)
Perform boolean polyset difference For aFastMode meaning, see function booleanOp.
void Fracture(POLYGON_MODE aFastMode)
Convert a set of polygons with holes to a single outline with "slits"/"fractures" connecting the oute...
void ClearArcs()
Removes all arc references from all the outlines and holes in the polyset.
int AddOutline(const SHAPE_LINE_CHAIN &aOutline)
Adds a new outline to the set and returns its index.
void DeletePolygon(int aIdx)
Delete aIdx-th polygon from the set.
double Area()
Return the area of this poly set.
bool Collide(const SHAPE *aShape, int aClearance=0, int *aActual=nullptr, VECTOR2I *aLocation=nullptr) const override
Check if the boundary of shape (this) lies closer to the shape aShape than aClearance,...
POLYGON & Polygon(int aIndex)
Return the aIndex-th subpolygon in the set.
void BooleanIntersection(const SHAPE_POLY_SET &b, POLYGON_MODE aFastMode)
Perform boolean polyset intersection For aFastMode meaning, see function booleanOp.
void Inflate(int aAmount, CORNER_STRATEGY aCornerStrategy, int aMaxError, bool aSimplify=false)
Perform outline inflation/deflation.
int Append(int x, int y, int aOutline=-1, int aHole=-1, bool aAllowDuplication=false)
Appends a vertex at the end of the given outline/hole (default: the last outline)
void Simplify(POLYGON_MODE aFastMode)
Simplify the polyset (merges overlapping polys, eliminates degeneracy/self-intersections) For aFastMo...
SHAPE_LINE_CHAIN & Outline(int aIndex)
Return the reference to aIndex-th outline in the set.
int NewOutline()
Creates a new empty polygon in the set and returns its index.
void Deflate(int aAmount, CORNER_STRATEGY aCornerStrategy, int aMaxError)
void BuildBBoxCaches() const
Construct BBoxCaches for Contains(), below.
int OutlineCount() const
Return the number of outlines in the set.
SHAPE_POLY_SET Fillet(int aRadius, int aErrorMax)
Return a filleted version of the polygon set.
void Move(const VECTOR2I &aVector) override
bool Contains(const VECTOR2I &aP, int aSubpolyIndex=-1, int aAccuracy=0, bool aUseBBoxCaches=false) const
Return true if a given subpolygon contains the point aP.
SHAPE_POLY_SET CloneDropTriangulation() const
const BOX2I BBoxFromCaches() const
const BOX2I BBox(int aClearance=0) const override
Compute a bounding box of the shape, with a margin of aClearance a collision.
constexpr extended_type SquaredEuclideanNorm() const
Compute the squared euclidean norm of the vector, which is defined as (x ** 2 + y ** 2).
Definition: vector2d.h:307
constexpr VECTOR2< T > Perpendicular() const
Compute the perpendicular vector.
Definition: vector2d.h:314
VECTOR2< T > Resize(T aNewLength) const
Return a vector of the same direction, but length specified in aNewLength.
Definition: vector2d.h:385
VERTEX * getPoint(VERTEX *aPt) const
Definition: zone_filler.cpp:97
std::set< RESULTS > GetResults() const
VERTEX_CONNECTOR(const BOX2I &aBBox, const SHAPE_POLY_SET &aPolys, int aDist)
Definition: zone_filler.cpp:84
std::set< RESULTS > m_results
std::deque< VERTEX > m_vertices
Definition: vertex_set.h:343
VERTEX * createList(const SHAPE_LINE_CHAIN &points, VERTEX *aTail=nullptr, void *aUserData=nullptr)
Create a list of vertices from a line chain.
Definition: vertex_set.cpp:9
void SetBoundingBox(const BOX2I &aBBox)
Definition: vertex_set.cpp:3
uint32_t zOrder(const double aX, const double aY) const
Note that while the inputs are doubles, these are scaled by the size of the bounding box to fit into ...
Definition: vertex_set.cpp:61
const double x
Definition: vertex_set.h:235
VERTEX * next
Definition: vertex_set.h:241
VERTEX * prevZ
Definition: vertex_set.h:247
void updateList()
After inserting or changing nodes, this function should be called to remove duplicate vertices and en...
Definition: vertex_set.h:121
VERTEX * nextZ
Definition: vertex_set.h:248
VERTEX * prev
Definition: vertex_set.h:240
const int i
Definition: vertex_set.h:234
void * GetUserData() const
Definition: vertex_set.h:79
uint32_t z
Definition: vertex_set.h:244
bool isEar(bool aMatchUserData=false) const
Check whether the given vertex is in the middle of an ear.
Definition: vertex_set.cpp:244
const double y
Definition: vertex_set.h:236
COMMIT * m_commit
Definition: zone_filler.h:141
int m_worstClearance
Definition: zone_filler.h:145
void buildCopperItemClearances(const ZONE *aZone, PCB_LAYER_ID aLayer, const std::vector< PAD * > &aNoConnectionPads, SHAPE_POLY_SET &aHoles)
Removes clearance from the shape for copper items which share the zone's layer but are not connected ...
void addKnockout(PAD *aPad, PCB_LAYER_ID aLayer, int aGap, SHAPE_POLY_SET &aHoles)
Add a knockout for a pad.
bool m_debugZoneFiller
Definition: zone_filler.h:147
void connect_nearby_polys(SHAPE_POLY_SET &aPolys, double aDistance)
Create strands of zero-width between elements of SHAPE_POLY_SET that are within aDistance of each oth...
ZONE_FILLER(BOARD *aBoard, COMMIT *aCommit)
void buildThermalSpokes(const ZONE *box, PCB_LAYER_ID aLayer, const std::vector< PAD * > &aSpokedPadsList, std::deque< SHAPE_LINE_CHAIN > &aSpokes)
Function buildThermalSpokes Constructs a list of all thermal spokes for the given zone.
void subtractHigherPriorityZones(const ZONE *aZone, PCB_LAYER_ID aLayer, SHAPE_POLY_SET &aRawFill)
Removes the outlines of higher-proirity zones with the same net.
SHAPE_POLY_SET m_boardOutline
Definition: zone_filler.h:139
bool m_brdOutlinesValid
Definition: zone_filler.h:140
bool addHatchFillTypeOnZone(const ZONE *aZone, PCB_LAYER_ID aLayer, PCB_LAYER_ID aDebugLayer, SHAPE_POLY_SET &aFillPolys)
for zones having the ZONE_FILL_MODE::ZONE_FILL_MODE::HATCH_PATTERN, create a grid pattern in filled a...
void SetProgressReporter(PROGRESS_REPORTER *aReporter)
BOARD * m_board
Definition: zone_filler.h:138
void knockoutThermalReliefs(const ZONE *aZone, PCB_LAYER_ID aLayer, SHAPE_POLY_SET &aFill, std::vector< PAD * > &aThermalConnectionPads, std::vector< PAD * > &aNoConnectionPads)
Removes thermal reliefs from the shape for any pads connected to the zone.
PROGRESS_REPORTER * m_progressReporter
Definition: zone_filler.h:142
bool fillCopperZone(const ZONE *aZone, PCB_LAYER_ID aLayer, PCB_LAYER_ID aDebugLayer, const SHAPE_POLY_SET &aSmoothedOutline, const SHAPE_POLY_SET &aMaxExtents, SHAPE_POLY_SET &aFillPolys)
Function fillCopperZone Add non copper areas polygons (pads and tracks with clearance) to a filled co...
void addHoleKnockout(PAD *aPad, int aGap, SHAPE_POLY_SET &aHoles)
Add a knockout for a pad's hole.
bool fillNonCopperZone(const ZONE *aZone, PCB_LAYER_ID aLayer, const SHAPE_POLY_SET &aSmoothedOutline, SHAPE_POLY_SET &aFillPolys)
bool fillSingleZone(ZONE *aZone, PCB_LAYER_ID aLayer, SHAPE_POLY_SET &aFillPolys)
Build the filled solid areas polygons from zone outlines (stored in m_Poly) The solid areas can be mo...
bool Fill(const std::vector< ZONE * > &aZones, bool aCheck=false, wxWindow *aParent=nullptr)
Fills the given list of zones.
Handle a list of polygons defining a copper zone.
Definition: zone.h:73
void SetNeedRefill(bool aNeedRefill)
Definition: zone.h:268
int GetHatchBorderAlgorithm() const
Definition: zone.h:306
std::optional< int > GetLocalClearance() const override
Definition: zone.cpp:714
void CacheTriangulation(PCB_LAYER_ID aLayer=UNDEFINED_LAYER)
Create a list of triangles that "fill" the solid areas used for instance to draw these solid areas on...
Definition: zone.cpp:1301
const BOX2I GetBoundingBox() const override
Definition: zone.cpp:567
SHAPE_POLY_SET * Outline()
Definition: zone.h:340
void SetFillFlag(PCB_LAYER_ID aLayer, bool aFlag)
Definition: zone.h:262
void SetFilledPolysList(PCB_LAYER_ID aLayer, const SHAPE_POLY_SET &aPolysList)
Set the list of filled polygons.
Definition: zone.h:641
int GetMinThickness() const
Definition: zone.h:273
bool HigherPriority(const ZONE *aOther) const
Definition: zone.cpp:390
int GetHatchThickness() const
Definition: zone.h:288
double GetHatchHoleMinArea() const
Definition: zone.h:303
bool IsTeardropArea() const
Definition: zone.h:699
EDA_ANGLE GetHatchOrientation() const
Definition: zone.h:294
bool BuildSmoothedPoly(SHAPE_POLY_SET &aSmoothedPoly, PCB_LAYER_ID aLayer, SHAPE_POLY_SET *aBoardOutline, SHAPE_POLY_SET *aSmoothedPolyWithApron=nullptr) const
Definition: zone.cpp:1365
ZONE_FILL_MODE GetFillMode() const
Definition: zone.h:196
int GetHatchGap() const
Definition: zone.h:291
double GetHatchSmoothingValue() const
Definition: zone.h:300
int GetHatchSmoothingLevel() const
Definition: zone.h:297
bool IsOnCopperLayer() const override
Definition: zone.cpp:475
std::mutex & GetLock()
Definition: zone.h:252
unsigned GetAssignedPriority() const
Definition: zone.h:123
void TransformCircleToPolygon(SHAPE_LINE_CHAIN &aBuffer, const VECTOR2I &aCenter, int aRadius, int aError, ERROR_LOC aErrorLoc, int aMinSegCount=0)
Convert a circle to a polygon, using multiple straight lines.
void BuildConvexHull(std::vector< VECTOR2I > &aResult, const std::vector< VECTOR2I > &aPoly)
Calculate the convex hull of a list of points in counter-clockwise order.
Definition: convex_hull.cpp:87
CORNER_STRATEGY
define how inflate transform build inflated polygon
DRC_CONSTRAINT_T
Definition: drc_rule.h:47
@ EDGE_CLEARANCE_CONSTRAINT
Definition: drc_rule.h:53
@ PHYSICAL_HOLE_CLEARANCE_CONSTRAINT
Definition: drc_rule.h:75
@ CLEARANCE_CONSTRAINT
Definition: drc_rule.h:49
@ THERMAL_SPOKE_WIDTH_CONSTRAINT
Definition: drc_rule.h:64
@ THERMAL_RELIEF_GAP_CONSTRAINT
Definition: drc_rule.h:63
@ HOLE_CLEARANCE_CONSTRAINT
Definition: drc_rule.h:51
@ PHYSICAL_CLEARANCE_CONSTRAINT
Definition: drc_rule.h:74
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition: eda_angle.h:401
@ DEGREES_T
Definition: eda_angle.h:31
a few functions useful in geometry calculations.
double m_ExtraClearance
When filling zones, we add an extra amount of clearance to each zone to ensure that rounding errors d...
bool m_DebugZoneFiller
A mode that dumps the various stages of a F_Cu fill into In1_Cu through In9_Cu.
This file is part of the common library.
PCB_LAYER_ID
A quick note on layer IDs:
Definition: layer_ids.h:60
@ In11_Cu
Definition: layer_ids.h:76
@ In17_Cu
Definition: layer_ids.h:82
@ Edge_Cuts
Definition: layer_ids.h:112
@ In9_Cu
Definition: layer_ids.h:74
@ In7_Cu
Definition: layer_ids.h:72
@ In15_Cu
Definition: layer_ids.h:80
@ In2_Cu
Definition: layer_ids.h:67
@ In10_Cu
Definition: layer_ids.h:75
@ Margin
Definition: layer_ids.h:113
@ In4_Cu
Definition: layer_ids.h:69
@ UNDEFINED_LAYER
Definition: layer_ids.h:61
@ In16_Cu
Definition: layer_ids.h:81
@ In1_Cu
Definition: layer_ids.h:66
@ In13_Cu
Definition: layer_ids.h:78
@ In8_Cu
Definition: layer_ids.h:73
@ In14_Cu
Definition: layer_ids.h:79
@ In12_Cu
Definition: layer_ids.h:77
@ In6_Cu
Definition: layer_ids.h:71
@ In5_Cu
Definition: layer_ids.h:70
@ In3_Cu
Definition: layer_ids.h:68
@ F_Cu
Definition: layer_ids.h:64
@ In18_Cu
Definition: layer_ids.h:83
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition: eda_angle.h:390
const double epsilon
constexpr int mmToIU(double mm) const
Definition: base_units.h:88
A storage class for 128-bit hash value.
Definition: hash_128.h:36
A struct recording the isolated and single-pad islands within a zone.
Definition: zone.h:60
static thread_pool * tp
Definition: thread_pool.cpp:30
BS::thread_pool thread_pool
Definition: thread_pool.h:30
thread_pool & GetKiCadThreadPool()
Get a reference to the current thread pool.
Definition: thread_pool.cpp:32
void RotatePoint(int *pX, int *pY, const EDA_ANGLE &aAngle)
Calculate the new point of coord coord pX, pY, for a rotation center 0, 0.
Definition: trigo.cpp:229
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
Definition: typeinfo.h:88
@ PCB_DIM_ORTHOGONAL_T
class PCB_DIM_ORTHOGONAL, a linear dimension constrained to x/y
Definition: typeinfo.h:105
@ PCB_DIM_LEADER_T
class PCB_DIM_LEADER, a leader dimension (graphic item)
Definition: typeinfo.h:102
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
Definition: typeinfo.h:97
@ PCB_DIM_CENTER_T
class PCB_DIM_CENTER, a center point marking (graphic item)
Definition: typeinfo.h:103
@ PCB_TEXTBOX_T
class PCB_TEXTBOX, wrapped text on a layer
Definition: typeinfo.h:93
@ PCB_TEXT_T
class PCB_TEXT, text on a layer
Definition: typeinfo.h:92
@ PCB_FIELD_T
class PCB_FIELD, text associated with a footprint property
Definition: typeinfo.h:90
@ PCB_TARGET_T
class PCB_TARGET, a target (graphic item)
Definition: typeinfo.h:106
@ PCB_DIM_ALIGNED_T
class PCB_DIM_ALIGNED, a linear dimension (graphic item)
Definition: typeinfo.h:101
@ PCB_TABLE_T
class PCB_TABLE, table of PCB_TABLECELLs
Definition: typeinfo.h:94
@ PCB_DIM_RADIAL_T
class PCB_DIM_RADIAL, a radius or diameter dimension
Definition: typeinfo.h:104
VECTOR2< int32_t > VECTOR2I
Definition: vector2d.h:691
#define SMOOTH_MIN_VAL_MM
#define DUMP_POLYS_TO_COPPER_LAYER(a, b, c)
#define SMOOTH_SMALL_VAL_MM
ISLAND_REMOVAL_MODE
Whether or not to remove isolated islands from a zone.
Definition: zone_settings.h:59
ZONE_CONNECTION
How pads are covered by copper in zone.
Definition: zones.h:47