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 tail->updateList();
93 m_dist = aDist;
94 }
95
96 VERTEX* getPoint( VERTEX* aPt ) const
97 {
98 // z-order range for the current point ± limit bounding box
99 const int32_t maxZ = zOrder( aPt->x + m_dist, aPt->y + m_dist );
100 const int32_t minZ = zOrder( aPt->x - m_dist, aPt->y - m_dist );
101 const SEG::ecoord limit2 = SEG::Square( m_dist );
102
103 // first look for points in increasing z-order
104 SEG::ecoord min_dist = std::numeric_limits<SEG::ecoord>::max();
105 VERTEX* retval = nullptr;
106
107 auto check_pt = [&]( VERTEX* p )
108 {
109 VECTOR2D diff( p->x - aPt->x, p->y - aPt->y );
110 SEG::ecoord dist2 = diff.SquaredEuclideanNorm();
111
112 if( dist2 < limit2 && dist2 < min_dist
113 && p->isEar() )
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 VERTEX* p = m_vertices.front().next;
142 std::set<VERTEX*> visited;
143
144 while( p != &m_vertices.front() )
145 {
146 // Skip points that are concave
147 if( !p->isEar() )
148 {
149 p = p->next;
150 continue;
151 }
152
153 VERTEX* q = nullptr;
154
155 if( ( visited.empty() || !visited.contains( p ) ) && ( q = getPoint( p ) ) )
156 {
157 visited.insert( p );
158
159 if( !visited.contains( q ) &&
160 m_results.emplace( (intptr_t) p->GetUserData(), (intptr_t) q->GetUserData(),
161 p->i, q->i ).second )
162 {
163 // We don't want to connect multiple points in the same vicinity, so skip
164 // 2 points before and after each point and match.
165 visited.insert( p->prev );
166 visited.insert( p->prev->prev );
167 visited.insert( p->next );
168 visited.insert( p->next->next );
169
170 visited.insert( q->prev );
171 visited.insert( q->prev->prev );
172 visited.insert( q->next );
173 visited.insert( q->next->next );
174
175 visited.insert( q );
176 }
177 }
178
179 p = p->next;
180 }
181 }
182
183 std::set<RESULTS> GetResults() const
184 {
185 return m_results;
186 }
187
188private:
189 std::set<RESULTS> m_results;
191};
192
193
195 m_board( aBoard ),
196 m_brdOutlinesValid( false ),
197 m_commit( aCommit ),
198 m_progressReporter( nullptr ),
199 m_maxError( ARC_HIGH_DEF ),
200 m_worstClearance( 0 )
201{
202 // To enable add "DebugZoneFiller=1" to kicad_advanced settings file.
204}
205
206
208{
209}
210
211
213{
214 m_progressReporter = aReporter;
215 wxASSERT_MSG( m_commit, wxT( "ZONE_FILLER must have a valid commit to call "
216 "SetProgressReporter" ) );
217}
218
219
230bool ZONE_FILLER::Fill( const std::vector<ZONE*>& aZones, bool aCheck, wxWindow* aParent )
231{
232 std::lock_guard<KISPINLOCK> lock( m_board->GetConnectivity()->GetLock() );
233
234 std::vector<std::pair<ZONE*, PCB_LAYER_ID>> toFill;
235 std::map<std::pair<ZONE*, PCB_LAYER_ID>, HASH_128> oldFillHashes;
236 std::map<ZONE*, std::map<PCB_LAYER_ID, ISOLATED_ISLANDS>> isolatedIslandsMap;
237
238 std::shared_ptr<CONNECTIVITY_DATA> connectivity = m_board->GetConnectivity();
239
240 // Rebuild (from scratch, ignoring dirty flags) just in case. This really needs to be reliable.
241 connectivity->ClearRatsnest();
242 connectivity->Build( m_board, m_progressReporter );
243
245
247 {
248 m_progressReporter->Report( aCheck ? _( "Checking zone fills..." )
249 : _( "Building zone fills..." ) );
250 m_progressReporter->SetMaxProgress( aZones.size() );
252 }
253
254 // The board outlines is used to clip solid areas inside the board (when outlines are valid)
257
258 // Update and cache zone bounding boxes and pad effective shapes so that we don't have to
259 // make them thread-safe.
260 //
261 for( ZONE* zone : m_board->Zones() )
262 zone->CacheBoundingBox();
263
264 for( FOOTPRINT* footprint : m_board->Footprints() )
265 {
266 for( PAD* pad : footprint->Pads() )
267 {
268 if( pad->IsDirty() )
269 {
270 pad->BuildEffectiveShapes();
271 pad->BuildEffectivePolygon( ERROR_OUTSIDE );
272 }
273 }
274
275 for( ZONE* zone : footprint->Zones() )
276 zone->CacheBoundingBox();
277
278 // Rules may depend on insideCourtyard() or other expressions
279 footprint->BuildCourtyardCaches();
280 }
281
282 LSET boardCuMask = m_board->GetEnabledLayers() & LSET::AllCuMask();
283
284 auto findHighestPriorityZone = [&]( const BOX2I& aBBox, const PCB_LAYER_ID aItemLayer,
285 const int aNetcode,
286 const std::function<bool( const ZONE* )> aTestFn ) -> ZONE*
287 {
288 unsigned highestPriority = 0;
289 ZONE* highestPriorityZone = nullptr;
290
291 for( ZONE* zone : m_board->Zones() )
292 {
293 // Rule areas are not filled
294 if( zone->GetIsRuleArea() )
295 continue;
296
297 if( zone->GetAssignedPriority() < highestPriority )
298 continue;
299
300 if( !zone->IsOnLayer( aItemLayer ) )
301 continue;
302
303 // Degenerate zones will cause trouble; skip them
304 if( zone->GetNumCorners() <= 2 )
305 continue;
306
307 if( !zone->GetBoundingBox().Intersects( aBBox ) )
308 continue;
309
310 if( !aTestFn( zone ) )
311 continue;
312
313 // Prefer highest priority and matching netcode
314 if( zone->GetAssignedPriority() > highestPriority || zone->GetNetCode() == aNetcode )
315 {
316 highestPriority = zone->GetAssignedPriority();
317 highestPriorityZone = zone;
318 }
319 }
320
321 return highestPriorityZone;
322 };
323
324 auto isInPourKeepoutArea = [&]( const BOX2I& aBBox, const PCB_LAYER_ID aItemLayer,
325 const VECTOR2I aTestPoint ) -> bool
326 {
327 for( ZONE* zone : m_board->Zones() )
328 {
329 if( !zone->GetIsRuleArea() )
330 continue;
331
332 if( !zone->HasKeepoutParametersSet() )
333 continue;
334
335 if( !zone->GetDoNotAllowCopperPour() )
336 continue;
337
338 if( !zone->IsOnLayer( aItemLayer ) )
339 continue;
340
341 // Degenerate zones will cause trouble; skip them
342 if( zone->GetNumCorners() <= 2 )
343 continue;
344
345 if( !zone->GetBoundingBox().Intersects( aBBox ) )
346 continue;
347
348 if( zone->Outline()->Contains( aTestPoint ) )
349 return true;
350 }
351
352 return false;
353 };
354
355 // Determine state of conditional via flashing
356 for( PCB_TRACK* track : m_board->Tracks() )
357 {
358 if( track->Type() == PCB_VIA_T )
359 {
360 PCB_VIA* via = static_cast<PCB_VIA*>( track );
361
362 via->ClearZoneLayerOverrides();
363
364 if( !via->GetRemoveUnconnected() )
365 continue;
366
367 BOX2I bbox = via->GetBoundingBox();
368 VECTOR2I center = via->GetPosition();
369 int testRadius = via->GetDrillValue() / 2 + 1;
370 unsigned netcode = via->GetNetCode();
371 LSET layers = via->GetLayerSet() & boardCuMask;
372
373 // Checking if the via hole touches the zone outline
374 auto viaTestFn = [&]( const ZONE* aZone ) -> bool
375 {
376 return aZone->Outline()->Contains( center, -1, testRadius );
377 };
378
379 for( PCB_LAYER_ID layer : layers.Seq() )
380 {
381 if( !via->ConditionallyFlashed( layer ) )
382 continue;
383
384 if( isInPourKeepoutArea( bbox, layer, center ) )
385 {
386 via->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
387 }
388 else
389 {
390 ZONE* zone = findHighestPriorityZone( bbox, layer, netcode, viaTestFn );
391
392 if( zone && zone->GetNetCode() == via->GetNetCode() )
393 via->SetZoneLayerOverride( layer, ZLO_FORCE_FLASHED );
394 else
395 via->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
396 }
397 }
398 }
399 }
400
401 // Determine state of conditional pad flashing
402 for( FOOTPRINT* footprint : m_board->Footprints() )
403 {
404 for( PAD* pad : footprint->Pads() )
405 {
406 pad->ClearZoneLayerOverrides();
407
408 if( !pad->GetRemoveUnconnected() )
409 continue;
410
411 BOX2I bbox = pad->GetBoundingBox();
412 VECTOR2I center = pad->GetPosition();
413 unsigned netcode = pad->GetNetCode();
414 LSET layers = pad->GetLayerSet() & boardCuMask;
415
416 auto padTestFn = [&]( const ZONE* aZone ) -> bool
417 {
418 return aZone->Outline()->Contains( center );
419 };
420
421 for( PCB_LAYER_ID layer : layers.Seq() )
422 {
423 if( !pad->ConditionallyFlashed( layer ) )
424 continue;
425
426 if( isInPourKeepoutArea( bbox, layer, center ) )
427 {
428 pad->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
429 }
430 else
431 {
432 ZONE* zone = findHighestPriorityZone( bbox, layer, netcode, padTestFn );
433
434 if( zone && zone->GetNetCode() == pad->GetNetCode() )
435 pad->SetZoneLayerOverride( layer, ZLO_FORCE_FLASHED );
436 else
437 pad->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
438 }
439 }
440 }
441 }
442
443 for( ZONE* zone : aZones )
444 {
445 // Rule areas are not filled
446 if( zone->GetIsRuleArea() )
447 continue;
448
449 // Degenerate zones will cause trouble; skip them
450 if( zone->GetNumCorners() <= 2 )
451 continue;
452
453 if( m_commit )
454 m_commit->Modify( zone );
455
456 // calculate the hash value for filled areas. it will be used later to know if the
457 // current filled areas are up to date
458 for( PCB_LAYER_ID layer : zone->GetLayerSet().Seq() )
459 {
460 zone->BuildHashValue( layer );
461 oldFillHashes[ { zone, layer } ] = zone->GetHashValue( layer );
462
463 // Add the zone to the list of zones to test or refill
464 toFill.emplace_back( std::make_pair( zone, layer ) );
465
466 isolatedIslandsMap[ zone ][ layer ] = ISOLATED_ISLANDS();
467 }
468
469 // Remove existing fill first to prevent drawing invalid polygons on some platforms
470 zone->UnFill();
471 }
472
473 auto check_fill_dependency =
474 [&]( ZONE* aZone, PCB_LAYER_ID aLayer, ZONE* aOtherZone ) -> bool
475 {
476 // Check to see if we have to knock-out the filled areas of a higher-priority
477 // zone. If so we have to wait until said zone is filled before we can fill.
478
479 // If the other zone is already filled on the requested layer then we're
480 // good-to-go
481 if( aOtherZone->GetFillFlag( aLayer ) )
482 return false;
483
484 // Even if keepouts exclude copper pours, the exclusion is by outline rather than
485 // filled area, so we're good-to-go here too
486 if( aOtherZone->GetIsRuleArea() )
487 return false;
488
489 // If the other zone is never going to be filled then don't wait for it
490 if( aOtherZone->GetNumCorners() <= 2 )
491 return false;
492
493 // If the zones share no common layers
494 if( !aOtherZone->GetLayerSet().test( aLayer ) )
495 return false;
496
497 if( aZone->HigherPriority( aOtherZone ) )
498 return false;
499
500 // Same-net zones always use outlines to produce determinate results
501 if( aOtherZone->SameNet( aZone ) )
502 return false;
503
504 // A higher priority zone is found: if we intersect and it's not filled yet
505 // then we have to wait.
506 BOX2I inflatedBBox = aZone->GetBoundingBox();
507 inflatedBBox.Inflate( m_worstClearance );
508
509 if( !inflatedBBox.Intersects( aOtherZone->GetBoundingBox() ) )
510 return false;
511
512 return aZone->Outline()->Collide( aOtherZone->Outline(), m_worstClearance );
513 };
514
515 auto fill_lambda =
516 [&]( std::pair<ZONE*, PCB_LAYER_ID> aFillItem ) -> int
517 {
518 PCB_LAYER_ID layer = aFillItem.second;
519 ZONE* zone = aFillItem.first;
520 bool canFill = true;
521
522 // Check for any fill dependencies. If our zone needs to be clipped by
523 // another zone then we can't fill until that zone is filled.
524 for( ZONE* otherZone : aZones )
525 {
526 if( otherZone == zone )
527 continue;
528
529 if( check_fill_dependency( zone, layer, otherZone ) )
530 {
531 canFill = false;
532 break;
533 }
534 }
535
537 return 0;
538
539 if( !canFill )
540 return 0;
541
542 // Now we're ready to fill.
543 {
544 std::unique_lock<std::mutex> zoneLock( zone->GetLock(), std::try_to_lock );
545
546 if( !zoneLock.owns_lock() )
547 return 0;
548
549 SHAPE_POLY_SET fillPolys;
550
551 if( !fillSingleZone( zone, layer, fillPolys ) )
552 return 0;
553
554 zone->SetFilledPolysList( layer, fillPolys );
555 }
556
559
560 return 1;
561 };
562
563 auto tesselate_lambda =
564 [&]( std::pair<ZONE*, PCB_LAYER_ID> aFillItem ) -> int
565 {
567 return 0;
568
569 PCB_LAYER_ID layer = aFillItem.second;
570 ZONE* zone = aFillItem.first;
571
572 {
573 std::unique_lock<std::mutex> zoneLock( zone->GetLock(), std::try_to_lock );
574
575 if( !zoneLock.owns_lock() )
576 return 0;
577
578 zone->CacheTriangulation( layer );
579 zone->SetFillFlag( layer, true );
580 }
581
582 return 1;
583 };
584
585 // Calculate the copper fills (NB: this is multi-threaded)
586 //
587 std::vector<std::pair<std::future<int>, int>> returns;
588 returns.reserve( toFill.size() );
589 size_t finished = 0;
590 bool cancelled = false;
591
593
594 for( const std::pair<ZONE*, PCB_LAYER_ID>& fillItem : toFill )
595 returns.emplace_back( std::make_pair( tp.submit( fill_lambda, fillItem ), 0 ) );
596
597 while( !cancelled && finished != 2 * toFill.size() )
598 {
599 for( size_t ii = 0; ii < returns.size(); ++ii )
600 {
601 auto& ret = returns[ii];
602
603 if( ret.second > 1 )
604 continue;
605
606 std::future_status status = ret.first.wait_for( std::chrono::seconds( 0 ) );
607
608 if( status == std::future_status::ready )
609 {
610 if( ret.first.get() ) // lambda completed
611 {
612 ++finished;
613 ret.second++; // go to next step
614 }
615
616 if( !cancelled )
617 {
618 // Queue the next step (will re-queue the existing step if it didn't complete)
619 if( ret.second == 0 )
620 returns[ii].first = tp.submit( fill_lambda, toFill[ii] );
621 else if( ret.second == 1 )
622 returns[ii].first = tp.submit( tesselate_lambda, toFill[ii] );
623 }
624 }
625 }
626
627 std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) );
628
629
631 {
633
635 cancelled = true;
636 }
637 }
638
639 // Make sure that all futures have finished.
640 // This can happen when the user cancels the above operation
641 for( auto& ret : returns )
642 {
643 if( ret.first.valid() )
644 {
645 std::future_status status = ret.first.wait_for( std::chrono::seconds( 0 ) );
646
647 while( status != std::future_status::ready )
648 {
651
652 status = ret.first.wait_for( std::chrono::milliseconds( 100 ) );
653 }
654 }
655 }
656
657 // Now update the connectivity to check for isolated copper islands
658 // (NB: FindIsolatedCopperIslands() is multi-threaded)
659 //
661 {
663 return false;
664
666 m_progressReporter->Report( _( "Removing isolated copper islands..." ) );
668 }
669
670 connectivity->SetProgressReporter( m_progressReporter );
671 connectivity->FillIsolatedIslandsMap( isolatedIslandsMap );
672 connectivity->SetProgressReporter( nullptr );
673
675 return false;
676
677 for( ZONE* zone : aZones )
678 {
679 // Keepout zones are not filled
680 if( zone->GetIsRuleArea() )
681 continue;
682
683 zone->SetIsFilled( true );
684 }
685
686 // Now remove isolated copper islands according to the isolated islands strategy assigned
687 // by the user (always, never, below-certain-size).
688 //
689 for( const auto& [ zone, zoneIslands ] : isolatedIslandsMap )
690 {
691 // If *all* the polygons are islands, do not remove any of them
692 bool allIslands = true;
693
694 for( const auto& [ layer, layerIslands ] : zoneIslands )
695 {
696 if( layerIslands.m_IsolatedOutlines.size()
697 != static_cast<size_t>( zone->GetFilledPolysList( layer )->OutlineCount() ) )
698 {
699 allIslands = false;
700 break;
701 }
702 }
703
704 if( allIslands )
705 continue;
706
707 for( const auto& [ layer, layerIslands ] : zoneIslands )
708 {
709 if( m_debugZoneFiller && LSET::InternalCuMask().Contains( layer ) )
710 continue;
711
712 if( layerIslands.m_IsolatedOutlines.empty() )
713 continue;
714
715 std::vector<int> islands = layerIslands.m_IsolatedOutlines;
716
717 // The list of polygons to delete must be explored from last to first in list,
718 // to allow deleting a polygon from list without breaking the remaining of the list
719 std::sort( islands.begin(), islands.end(), std::greater<int>() );
720
721 std::shared_ptr<SHAPE_POLY_SET> poly = zone->GetFilledPolysList( layer );
722 long long int minArea = zone->GetMinIslandArea();
723 ISLAND_REMOVAL_MODE mode = zone->GetIslandRemovalMode();
724
725 for( int idx : islands )
726 {
727 SHAPE_LINE_CHAIN& outline = poly->Outline( idx );
728
729 if( mode == ISLAND_REMOVAL_MODE::ALWAYS )
730 poly->DeletePolygonAndTriangulationData( idx, false );
731 else if ( mode == ISLAND_REMOVAL_MODE::AREA && outline.Area( true ) < minArea )
732 poly->DeletePolygonAndTriangulationData( idx, false );
733 else
734 zone->SetIsIsland( layer, idx );
735 }
736
737 poly->UpdateTriangulationDataHash();
738 zone->CalculateFilledArea();
739
741 return false;
742 }
743 }
744
745 // Now remove islands which are either outside the board edge or fail to meet the minimum
746 // area requirements
747 using island_check_return = std::vector<std::pair<std::shared_ptr<SHAPE_POLY_SET>, int>>;
748
749 std::vector<std::pair<std::shared_ptr<SHAPE_POLY_SET>, double>> polys_to_check;
750
751 // rough estimate to save re-allocation time
752 polys_to_check.reserve( m_board->GetCopperLayerCount() * aZones.size() );
753
754 for( ZONE* zone : aZones )
755 {
756 // Don't check for connections on layers that only exist in the zone but
757 // were disabled in the board
758 BOARD* board = zone->GetBoard();
759 LSET zoneCopperLayers = zone->GetLayerSet() & LSET::AllCuMask() & board->GetEnabledLayers();
760
761 // Min-thickness is the web thickness. On the other hand, a blob min-thickness by
762 // min-thickness is not useful. Since there's no obvious definition of web vs. blob, we
763 // arbitrarily choose "at least 3X the area".
764 double minArea = (double) zone->GetMinThickness() * zone->GetMinThickness() * 3;
765
766 for( PCB_LAYER_ID layer : zoneCopperLayers.Seq() )
767 {
769 continue;
770
771 polys_to_check.emplace_back( zone->GetFilledPolysList( layer ), minArea );
772 }
773 }
774
775 auto island_lambda =
776 [&]( int aStart, int aEnd ) -> island_check_return
777 {
778 island_check_return retval;
779
780 for( int ii = aStart; ii < aEnd && !cancelled; ++ii )
781 {
782 auto [poly, minArea] = polys_to_check[ii];
783
784 for( int jj = poly->OutlineCount() - 1; jj >= 0; jj-- )
785 {
786 SHAPE_POLY_SET island;
787 SHAPE_POLY_SET intersection;
788 const SHAPE_LINE_CHAIN& test_poly = poly->Polygon( jj ).front();
789 double island_area = test_poly.Area();
790
791 if( island_area < minArea )
792 continue;
793
794
795 island.AddOutline( test_poly );
796 intersection.BooleanIntersection( m_boardOutline, island,
798
799 // Nominally, all of these areas should be either inside or outside the
800 // board outline. So this test should be able to just compare areas (if
801 // they are equal, you are inside). But in practice, we sometimes have
802 // slight overlap at the edges, so testing against half-size area acts as
803 // a fail-safe.
804 if( intersection.Area() < island_area / 2.0 )
805 retval.emplace_back( poly, jj );
806 }
807 }
808
809 return retval;
810 };
811
812 auto island_returns = tp.parallelize_loop( 0, polys_to_check.size(), island_lambda );
813 cancelled = false;
814
815 // Allow island removal threads to finish
816 for( size_t ii = 0; ii < island_returns.size(); ++ii )
817 {
818 std::future<island_check_return>& ret = island_returns[ii];
819
820 if( ret.valid() )
821 {
822 std::future_status status = ret.wait_for( std::chrono::seconds( 0 ) );
823
824 while( status != std::future_status::ready )
825 {
827 {
829
831 cancelled = true;
832 }
833
834 status = ret.wait_for( std::chrono::milliseconds( 100 ) );
835 }
836 }
837 }
838
839 if( cancelled )
840 return false;
841
842 for( size_t ii = 0; ii < island_returns.size(); ++ii )
843 {
844 std::future<island_check_return>& ret = island_returns[ii];
845
846 if( ret.valid() )
847 {
848 for( auto& action_item : ret.get() )
849 action_item.first->DeletePolygonAndTriangulationData( action_item.second, true );
850 }
851 }
852
853 for( ZONE* zone : aZones )
854 zone->CalculateFilledArea();
855
856
857 if( aCheck )
858 {
859 bool outOfDate = false;
860
861 for( ZONE* zone : aZones )
862 {
863 // Keepout zones are not filled
864 if( zone->GetIsRuleArea() )
865 continue;
866
867 for( PCB_LAYER_ID layer : zone->GetLayerSet().Seq() )
868 {
869 zone->BuildHashValue( layer );
870
871 if( oldFillHashes[ { zone, layer } ] != zone->GetHashValue( layer ) )
872 outOfDate = true;
873 }
874 }
875
876 if( outOfDate )
877 {
878 KIDIALOG dlg( aParent, _( "Zone fills are out-of-date. Refill?" ),
879 _( "Confirmation" ), wxOK | wxCANCEL | wxICON_WARNING );
880 dlg.SetOKCancelLabels( _( "Refill" ), _( "Continue without Refill" ) );
881 dlg.DoNotShowCheckbox( __FILE__, __LINE__ );
882
883 if( dlg.ShowModal() == wxID_CANCEL )
884 return false;
885 }
886 else
887 {
888 // No need to commit something that hasn't changed (and committing will set
889 // the modified flag).
890 return false;
891 }
892 }
893
895 {
897 return false;
898
901 }
902
903 return true;
904}
905
906
911void ZONE_FILLER::addKnockout( PAD* aPad, PCB_LAYER_ID aLayer, int aGap, SHAPE_POLY_SET& aHoles )
912{
913 if( aPad->GetShape( aLayer ) == PAD_SHAPE::CUSTOM )
914 {
915 SHAPE_POLY_SET poly;
916 aPad->TransformShapeToPolygon( poly, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
917
918 // the pad shape in zone can be its convex hull or the shape itself
920 {
921 std::vector<VECTOR2I> convex_hull;
922 BuildConvexHull( convex_hull, poly );
923
924 aHoles.NewOutline();
925
926 for( const VECTOR2I& pt : convex_hull )
927 aHoles.Append( pt );
928 }
929 else
930 aHoles.Append( poly );
931 }
932 else
933 {
934 aPad->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
935 }
936}
937
938
942void ZONE_FILLER::addHoleKnockout( PAD* aPad, int aGap, SHAPE_POLY_SET& aHoles )
943{
944 aPad->TransformHoleToPolygon( aHoles, aGap, m_maxError, ERROR_OUTSIDE );
945}
946
947
952void ZONE_FILLER::addKnockout( BOARD_ITEM* aItem, PCB_LAYER_ID aLayer, int aGap,
953 bool aIgnoreLineWidth, SHAPE_POLY_SET& aHoles )
954{
955 switch( aItem->Type() )
956 {
957 case PCB_FIELD_T:
958 case PCB_TEXT_T:
959 {
960 PCB_TEXT* text = static_cast<PCB_TEXT*>( aItem );
961
962 if( text->IsVisible() )
963 {
964 if( text->IsKnockout() )
965 {
966 // Knockout text should only leave holes where the text is, not where the copper fill
967 // around it would be.
968 PCB_TEXT textCopy = *text;
969 textCopy.SetIsKnockout( false );
970 textCopy.TransformShapeToPolygon( aHoles, aLayer, 0, m_maxError, ERROR_OUTSIDE );
971 }
972 else
973 {
974 text->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
975 }
976 }
977
978 break;
979 }
980
981 case PCB_TEXTBOX_T:
982 case PCB_TABLE_T:
983 case PCB_SHAPE_T:
984 case PCB_TARGET_T:
985 aItem->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE,
986 aIgnoreLineWidth );
987 break;
988
990 case PCB_DIM_LEADER_T:
991 case PCB_DIM_CENTER_T:
992 case PCB_DIM_RADIAL_T:
994 {
995 PCB_DIMENSION_BASE* dim = static_cast<PCB_DIMENSION_BASE*>( aItem );
996
997 dim->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE, false );
998 dim->PCB_TEXT::TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
999 break;
1000 }
1001
1002 default:
1003 break;
1004 }
1005}
1006
1007
1013 SHAPE_POLY_SET& aFill,
1014 std::vector<PAD*>& aThermalConnectionPads,
1015 std::vector<PAD*>& aNoConnectionPads )
1016{
1018 ZONE_CONNECTION connection;
1019 DRC_CONSTRAINT constraint;
1020 int padClearance;
1021 std::shared_ptr<SHAPE> padShape;
1022 int holeClearance;
1023 SHAPE_POLY_SET holes;
1024
1025 for( FOOTPRINT* footprint : m_board->Footprints() )
1026 {
1027 for( PAD* pad : footprint->Pads() )
1028 {
1029 BOX2I padBBox = pad->GetBoundingBox();
1030 padBBox.Inflate( m_worstClearance );
1031
1032 if( !padBBox.Intersects( aZone->GetBoundingBox() ) )
1033 continue;
1034
1035 bool noConnection = pad->GetNetCode() != aZone->GetNetCode();
1036
1037 if( !aZone->IsTeardropArea() )
1038 {
1039 if( aZone->GetNetCode() == 0
1040 || pad->GetZoneLayerOverride( aLayer ) == ZLO_FORCE_NO_ZONE_CONNECTION )
1041 {
1042 noConnection = true;
1043 }
1044 }
1045
1046 if( noConnection )
1047 {
1048 // collect these for knockout in buildCopperItemClearances()
1049 aNoConnectionPads.push_back( pad );
1050 continue;
1051 }
1052
1053 if( aZone->IsTeardropArea() )
1054 {
1055 connection = ZONE_CONNECTION::FULL;
1056 }
1057 else
1058 {
1059 constraint = bds.m_DRCEngine->EvalZoneConnection( pad, aZone, aLayer );
1060 connection = constraint.m_ZoneConnection;
1061 }
1062
1063 if( connection == ZONE_CONNECTION::THERMAL && !pad->CanFlashLayer( aLayer ) )
1064 connection = ZONE_CONNECTION::NONE;
1065
1066 switch( connection )
1067 {
1068 case ZONE_CONNECTION::THERMAL:
1069 padShape = pad->GetEffectiveShape( aLayer, FLASHING::ALWAYS_FLASHED );
1070
1071 if( aFill.Collide( padShape.get(), 0 ) )
1072 {
1073 constraint = bds.m_DRCEngine->EvalRules( THERMAL_RELIEF_GAP_CONSTRAINT, pad,
1074 aZone, aLayer );
1075 padClearance = constraint.GetValue().Min();
1076
1077 aThermalConnectionPads.push_back( pad );
1078 addKnockout( pad, aLayer, padClearance, holes );
1079 }
1080
1081 break;
1082
1083 case ZONE_CONNECTION::NONE:
1084 constraint = bds.m_DRCEngine->EvalRules( PHYSICAL_CLEARANCE_CONSTRAINT, pad,
1085 aZone, aLayer );
1086
1087 if( constraint.GetValue().Min() > aZone->GetLocalClearance().value() )
1088 padClearance = constraint.GetValue().Min();
1089 else
1090 padClearance = aZone->GetLocalClearance().value();
1091
1092 if( pad->FlashLayer( aLayer ) )
1093 {
1094 addKnockout( pad, aLayer, padClearance, holes );
1095 }
1096 else if( pad->GetDrillSize().x > 0 )
1097 {
1098 constraint = bds.m_DRCEngine->EvalRules( PHYSICAL_HOLE_CLEARANCE_CONSTRAINT,
1099 pad, aZone, aLayer );
1100
1101 if( constraint.GetValue().Min() > padClearance )
1102 holeClearance = constraint.GetValue().Min();
1103 else
1104 holeClearance = padClearance;
1105
1106 pad->TransformHoleToPolygon( holes, holeClearance, m_maxError, ERROR_OUTSIDE );
1107 }
1108
1109 break;
1110
1111 default:
1112 // No knockout
1113 continue;
1114 }
1115 }
1116 }
1117
1119}
1120
1121
1127 const std::vector<PAD*>& aNoConnectionPads,
1128 SHAPE_POLY_SET& aHoles )
1129{
1131 long ticker = 0;
1132
1133 auto checkForCancel =
1134 [&ticker]( PROGRESS_REPORTER* aReporter ) -> bool
1135 {
1136 return aReporter && ( ticker++ % 50 ) == 0 && aReporter->IsCancelled();
1137 };
1138
1139 // A small extra clearance to be sure actual track clearances are not smaller than
1140 // requested clearance due to many approximations in calculations, like arc to segment
1141 // approx, rounding issues, etc.
1142 BOX2I zone_boundingbox = aZone->GetBoundingBox();
1144
1145 // Items outside the zone bounding box are skipped, so it needs to be inflated by the
1146 // largest clearance value found in the netclasses and rules
1147 zone_boundingbox.Inflate( m_worstClearance + extra_margin );
1148
1149 auto evalRulesForItems =
1150 [&bds]( DRC_CONSTRAINT_T aConstraint, const BOARD_ITEM* a, const BOARD_ITEM* b,
1151 PCB_LAYER_ID aEvalLayer ) -> int
1152 {
1153 DRC_CONSTRAINT c = bds.m_DRCEngine->EvalRules( aConstraint, a, b, aEvalLayer );
1154
1155 if( c.IsNull() )
1156 return -1;
1157 else
1158 return c.GetValue().Min();
1159 };
1160
1161 // Add non-connected pad clearances
1162 //
1163 auto knockoutPadClearance =
1164 [&]( PAD* aPad )
1165 {
1166 int init_gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT, aZone, aPad, aLayer );
1167 int gap = init_gap;
1168 bool hasHole = aPad->GetDrillSize().x > 0;
1169 bool flashLayer = aPad->FlashLayer( aLayer );
1170 bool platedHole = hasHole && aPad->GetAttribute() == PAD_ATTRIB::PTH;
1171
1172 if( flashLayer || platedHole )
1173 {
1174 gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
1175 aZone, aPad, aLayer ) );
1176 }
1177
1178 if( flashLayer && gap >= 0 )
1179 addKnockout( aPad, aLayer, gap + extra_margin, aHoles );
1180
1181 if( hasHole )
1182 {
1183 // NPTH do not need copper clearance gaps to their holes
1184 if( aPad->GetAttribute() == PAD_ATTRIB::NPTH )
1185 gap = init_gap;
1186
1187 gap = std::max( gap, evalRulesForItems( PHYSICAL_HOLE_CLEARANCE_CONSTRAINT,
1188 aZone, aPad, aLayer ) );
1189
1190 gap = std::max( gap, evalRulesForItems( HOLE_CLEARANCE_CONSTRAINT,
1191 aZone, aPad, aLayer ) );
1192
1193 if( gap >= 0 )
1194 addHoleKnockout( aPad, gap + extra_margin, aHoles );
1195 }
1196 };
1197
1198 for( PAD* pad : aNoConnectionPads )
1199 {
1200 if( checkForCancel( m_progressReporter ) )
1201 return;
1202
1203 knockoutPadClearance( pad );
1204 }
1205
1206 // Add non-connected track clearances
1207 //
1208 auto knockoutTrackClearance =
1209 [&]( PCB_TRACK* aTrack )
1210 {
1211 if( aTrack->GetBoundingBox().Intersects( zone_boundingbox ) )
1212 {
1213 bool sameNet = aTrack->GetNetCode() == aZone->GetNetCode();
1214
1215 if( !aZone->IsTeardropArea() && aZone->GetNetCode() == 0 )
1216 sameNet = false;
1217
1218 int gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT,
1219 aZone, aTrack, aLayer );
1220
1221 if( aTrack->Type() == PCB_VIA_T )
1222 {
1223 PCB_VIA* via = static_cast<PCB_VIA*>( aTrack );
1224
1225 if( via->GetZoneLayerOverride( aLayer ) == ZLO_FORCE_NO_ZONE_CONNECTION )
1226 sameNet = false;
1227 }
1228
1229 if( !sameNet )
1230 {
1231 gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
1232 aZone, aTrack, aLayer ) );
1233 }
1234
1235 if( aTrack->Type() == PCB_VIA_T )
1236 {
1237 PCB_VIA* via = static_cast<PCB_VIA*>( aTrack );
1238
1239 if( via->FlashLayer( aLayer ) && gap > 0 )
1240 {
1241 via->TransformShapeToPolygon( aHoles, aLayer, gap + extra_margin,
1243 }
1244
1245 gap = std::max( gap, evalRulesForItems( PHYSICAL_HOLE_CLEARANCE_CONSTRAINT,
1246 aZone, via, aLayer ) );
1247
1248 if( !sameNet )
1249 {
1250 gap = std::max( gap, evalRulesForItems( HOLE_CLEARANCE_CONSTRAINT,
1251 aZone, via, aLayer ) );
1252 }
1253
1254 if( gap >= 0 )
1255 {
1256 int radius = via->GetDrillValue() / 2;
1257
1258 TransformCircleToPolygon( aHoles, via->GetPosition(),
1259 radius + gap + extra_margin,
1261 }
1262 }
1263 else
1264 {
1265 if( gap >= 0 )
1266 {
1267 aTrack->TransformShapeToPolygon( aHoles, aLayer, gap + extra_margin,
1269 }
1270 }
1271 }
1272 };
1273
1274 for( PCB_TRACK* track : m_board->Tracks() )
1275 {
1276 if( !track->IsOnLayer( aLayer ) )
1277 continue;
1278
1279 if( checkForCancel( m_progressReporter ) )
1280 return;
1281
1282 knockoutTrackClearance( track );
1283 }
1284
1285 // Add graphic item clearances.
1286 //
1287 auto knockoutGraphicClearance =
1288 [&]( BOARD_ITEM* aItem )
1289 {
1290 int shapeNet = -1;
1291
1292 if( aItem->Type() == PCB_SHAPE_T )
1293 shapeNet = static_cast<PCB_SHAPE*>( aItem )->GetNetCode();
1294
1295 bool sameNet = shapeNet == aZone->GetNetCode();
1296
1297 if( !aZone->IsTeardropArea() && aZone->GetNetCode() == 0 )
1298 sameNet = false;
1299
1300 // A item on the Edge_Cuts or Margin is always seen as on any layer:
1301 if( aItem->IsOnLayer( aLayer )
1302 || aItem->IsOnLayer( Edge_Cuts )
1303 || aItem->IsOnLayer( Margin ) )
1304 {
1305 if( aItem->GetBoundingBox().Intersects( zone_boundingbox ) )
1306 {
1307 bool ignoreLineWidths = false;
1308 int gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT,
1309 aZone, aItem, aLayer );
1310
1311 if( aItem->IsOnLayer( aLayer ) && !sameNet )
1312 {
1313 gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
1314 aZone, aItem, aLayer ) );
1315 }
1316 else if( aItem->IsOnLayer( Edge_Cuts ) )
1317 {
1318 gap = std::max( gap, evalRulesForItems( EDGE_CLEARANCE_CONSTRAINT,
1319 aZone, aItem, aLayer ) );
1320 ignoreLineWidths = true;
1321 }
1322 else if( aItem->IsOnLayer( Margin ) )
1323 {
1324 gap = std::max( gap, evalRulesForItems( EDGE_CLEARANCE_CONSTRAINT,
1325 aZone, aItem, aLayer ) );
1326 }
1327
1328 if( gap >= 0 )
1329 {
1330 gap += extra_margin;
1331 addKnockout( aItem, aLayer, gap, ignoreLineWidths, aHoles );
1332 }
1333 }
1334 }
1335 };
1336
1337 auto knockoutCourtyardClearance =
1338 [&]( FOOTPRINT* aFootprint )
1339 {
1340 if( aFootprint->GetBoundingBox().Intersects( zone_boundingbox ) )
1341 {
1342 int gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT, aZone,
1343 aFootprint, aLayer );
1344
1345 if( gap == 0 )
1346 {
1347 aHoles.Append( aFootprint->GetCourtyard( aLayer ) );
1348 }
1349 else if( gap > 0 )
1350 {
1351 SHAPE_POLY_SET hole = aFootprint->GetCourtyard( aLayer );
1352 hole.Inflate( gap, CORNER_STRATEGY::ROUND_ALL_CORNERS, m_maxError );
1353 aHoles.Append( hole );
1354 }
1355 }
1356 };
1357
1358 for( FOOTPRINT* footprint : m_board->Footprints() )
1359 {
1360 knockoutCourtyardClearance( footprint );
1361 knockoutGraphicClearance( &footprint->Reference() );
1362 knockoutGraphicClearance( &footprint->Value() );
1363
1364 std::set<PAD*> allowedNetTiePads;
1365
1366 // Don't knock out holes for graphic items which implement a net-tie to the zone's net
1367 // on the layer being filled.
1368 if( footprint->IsNetTie() )
1369 {
1370 for( PAD* pad : footprint->Pads() )
1371 {
1372 bool sameNet = pad->GetNetCode() == aZone->GetNetCode();
1373
1374 if( !aZone->IsTeardropArea() && aZone->GetNetCode() == 0 )
1375 sameNet = false;
1376
1377 if( sameNet )
1378 {
1379 if( pad->IsOnLayer( aLayer ) )
1380 allowedNetTiePads.insert( pad );
1381
1382 for( PAD* other : footprint->GetNetTiePads( pad ) )
1383 {
1384 if( other->IsOnLayer( aLayer ) )
1385 allowedNetTiePads.insert( other );
1386 }
1387 }
1388 }
1389 }
1390
1391 for( BOARD_ITEM* item : footprint->GraphicalItems() )
1392 {
1393 if( checkForCancel( m_progressReporter ) )
1394 return;
1395
1396 BOX2I itemBBox = item->GetBoundingBox();
1397
1398 if( !zone_boundingbox.Intersects( itemBBox ) )
1399 continue;
1400
1401 bool skipItem = false;
1402
1403 if( item->IsOnLayer( aLayer ) )
1404 {
1405 std::shared_ptr<SHAPE> itemShape = item->GetEffectiveShape();
1406
1407 for( PAD* pad : allowedNetTiePads )
1408 {
1409 if( pad->GetBoundingBox().Intersects( itemBBox )
1410 && pad->GetEffectiveShape( aLayer )->Collide( itemShape.get() ) )
1411 {
1412 skipItem = true;
1413 break;
1414 }
1415 }
1416 }
1417
1418 if( !skipItem )
1419 knockoutGraphicClearance( item );
1420 }
1421 }
1422
1423 for( BOARD_ITEM* item : m_board->Drawings() )
1424 {
1425 if( checkForCancel( m_progressReporter ) )
1426 return;
1427
1428 knockoutGraphicClearance( item );
1429 }
1430
1431 // Add non-connected zone clearances
1432 //
1433 auto knockoutZoneClearance =
1434 [&]( ZONE* aKnockout )
1435 {
1436 // If the zones share no common layers
1437 if( !aKnockout->GetLayerSet().test( aLayer ) )
1438 return;
1439
1440 if( aKnockout->GetBoundingBox().Intersects( zone_boundingbox ) )
1441 {
1442 if( aKnockout->GetIsRuleArea() )
1443 {
1444 // Keepouts use outline with no clearance
1445 aKnockout->TransformSmoothedOutlineToPolygon( aHoles, 0, m_maxError,
1446 ERROR_OUTSIDE, nullptr );
1447 }
1448 else
1449 {
1450 int gap = std::max( 0, evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT,
1451 aZone, aKnockout, aLayer ) );
1452
1453 gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
1454 aZone, aKnockout, aLayer ) );
1455
1456 SHAPE_POLY_SET poly;
1457 aKnockout->TransformShapeToPolygon( poly, aLayer, gap + extra_margin,
1459 aHoles.Append( poly );
1460 }
1461 }
1462 };
1463
1464 for( ZONE* otherZone : m_board->Zones() )
1465 {
1466 if( checkForCancel( m_progressReporter ) )
1467 return;
1468
1469 // Negative clearance permits zones to short
1470 if( evalRulesForItems( CLEARANCE_CONSTRAINT, aZone, otherZone, aLayer ) < 0 )
1471 continue;
1472
1473 if( otherZone->GetIsRuleArea() )
1474 {
1475 if( otherZone->GetDoNotAllowCopperPour() && !aZone->IsTeardropArea() )
1476 knockoutZoneClearance( otherZone );
1477 }
1478 else if( otherZone->HigherPriority( aZone ) )
1479 {
1480 if( !otherZone->SameNet( aZone ) )
1481 knockoutZoneClearance( otherZone );
1482 }
1483 }
1484
1485 for( FOOTPRINT* footprint : m_board->Footprints() )
1486 {
1487 for( ZONE* otherZone : footprint->Zones() )
1488 {
1489 if( checkForCancel( m_progressReporter ) )
1490 return;
1491
1492 if( otherZone->GetIsRuleArea() )
1493 {
1494 if( otherZone->GetDoNotAllowCopperPour() && !aZone->IsTeardropArea() )
1495 knockoutZoneClearance( otherZone );
1496 }
1497 else if( otherZone->HigherPriority( aZone ) )
1498 {
1499 if( !otherZone->SameNet( aZone ) )
1500 knockoutZoneClearance( otherZone );
1501 }
1502 }
1503 }
1504
1506}
1507
1508
1514 SHAPE_POLY_SET& aRawFill )
1515{
1516 BOX2I zoneBBox = aZone->GetBoundingBox();
1517
1518 auto knockoutZoneOutline =
1519 [&]( ZONE* aKnockout )
1520 {
1521 // If the zones share no common layers
1522 if( !aKnockout->GetLayerSet().test( aLayer ) )
1523 return;
1524
1525 if( aKnockout->GetBoundingBox().Intersects( zoneBBox ) )
1526 {
1527 // Processing of arc shapes in zones is not yet supported because Clipper
1528 // can't do boolean operations on them. The poly outline must be converted to
1529 // segments first.
1530 SHAPE_POLY_SET outline = aKnockout->Outline()->CloneDropTriangulation();
1531 outline.ClearArcs();
1532
1533 aRawFill.BooleanSubtract( outline, SHAPE_POLY_SET::PM_FAST );
1534 }
1535 };
1536
1537 for( ZONE* otherZone : m_board->Zones() )
1538 {
1539 // Don't use the `HigherPriority()` check here because we _only_ want to knock out zones
1540 // with explicitly higher priorities, not those with equal priorities
1541 if( otherZone->SameNet( aZone )
1542 && otherZone->GetAssignedPriority() > aZone->GetAssignedPriority() )
1543 {
1544 // Do not remove teardrop area: it is not useful and not good
1545 if( !otherZone->IsTeardropArea() )
1546 knockoutZoneOutline( otherZone );
1547 }
1548 }
1549
1550 for( FOOTPRINT* footprint : m_board->Footprints() )
1551 {
1552 for( ZONE* otherZone : footprint->Zones() )
1553 {
1554 if( otherZone->SameNet( aZone ) && otherZone->HigherPriority( aZone ) )
1555 {
1556 // Do not remove teardrop area: it is not useful and not good
1557 if( !otherZone->IsTeardropArea() )
1558 knockoutZoneOutline( otherZone );
1559 }
1560 }
1561 }
1562}
1563
1564
1565void ZONE_FILLER::connect_nearby_polys( SHAPE_POLY_SET& aPolys, double aDistance )
1566{
1567 if( aPolys.OutlineCount() < 1 )
1568 return;
1569
1570 VERTEX_CONNECTOR vs( aPolys.BBoxFromCaches(), aPolys, aDistance );
1571
1572 vs.FindResults();
1573
1574 // This cannot be a reference because we need to do the comparison below while
1575 // changing the values
1576 std::map<int, std::vector<std::pair<int, VECTOR2I>>> insertion_points;
1577
1578 for( const RESULTS& result : vs.GetResults() )
1579 {
1580 SHAPE_LINE_CHAIN& line1 = aPolys.Outline( result.m_outline1 );
1581 SHAPE_LINE_CHAIN& line2 = aPolys.Outline( result.m_outline2 );
1582
1583 VECTOR2I pt1 = line1.CPoint( result.m_vertex1 );
1584 VECTOR2I pt2 = line2.CPoint( result.m_vertex2 );
1585
1586 // We want to insert the existing point first so that we can place the new point
1587 // between the two points at the same location.
1588 insertion_points[result.m_outline1].push_back( { result.m_vertex1, pt1 } );
1589 insertion_points[result.m_outline1].push_back( { result.m_vertex1, pt2 } );
1590 }
1591
1592 for( auto& [outline, vertices] : insertion_points )
1593 {
1594 SHAPE_LINE_CHAIN& line = aPolys.Outline( outline );
1595
1596 // Stable sort here because we want to make sure that we are inserting pt1 first and
1597 // pt2 second but still sorting the rest of the indices from highest to lowest.
1598 // This allows us to insert into the existing polygon without modifying the future
1599 // insertion points.
1600 std::stable_sort( vertices.begin(), vertices.end(),
1601 []( const std::pair<int, VECTOR2I>& a, const std::pair<int, VECTOR2I>& b )
1602 { return a.first > b.first; } );
1603
1604 for( const auto& [vertex, pt] : vertices )
1605 line.Insert( vertex + 1, pt ); // +1 here because we want to insert after the existing point
1606 }
1607}
1608
1609
1610#define DUMP_POLYS_TO_COPPER_LAYER( a, b, c ) \
1611 { if( m_debugZoneFiller && aDebugLayer == b ) \
1612 { \
1613 m_board->SetLayerName( b, c ); \
1614 SHAPE_POLY_SET d = a; \
1615 d.Fracture( SHAPE_POLY_SET::PM_STRICTLY_SIMPLE ); \
1616 aFillPolys = d; \
1617 return false; \
1618 } \
1619 }
1620
1621
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 /* -------------------------------------------------------------------------------------
1808 * Process the hatch pattern (note that we do this while deflated)
1809 */
1810
1811 if( aZone->GetFillMode() == ZONE_FILL_MODE::HATCH_PATTERN )
1812 {
1813 if( !addHatchFillTypeOnZone( aZone, aLayer, aDebugLayer, aFillPolys ) )
1814 return false;
1815 }
1816 else
1817 {
1818
1819 /* -------------------------------------------------------------------------------------
1820 * Connect nearby polygons
1821 */
1822 aFillPolys.Fracture( SHAPE_POLY_SET::PM_FAST );
1823 connect_nearby_polys( aFillPolys, aZone->GetMinThickness() );
1824
1825 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In10_Cu, wxT( "connected-nearby-polys" ) );
1826 }
1827
1829 return false;
1830
1831 /* -------------------------------------------------------------------------------------
1832 * Finish minimum-width pruning by re-inflating
1833 */
1834
1835 if( half_min_width - epsilon > epsilon )
1836 aFillPolys.Inflate( half_min_width - epsilon, cornerStrategy, m_maxError, true );
1837
1838 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In15_Cu, wxT( "after-reinflating" ) );
1839
1840 /* -------------------------------------------------------------------------------------
1841 * Ensure additive changes (thermal stubs and inflating acute corners) do not add copper
1842 * outside the zone boundary, inside the clearance holes, or between otherwise isolated
1843 * islands
1844 */
1845
1846 for( PAD* pad : thermalConnectionPads )
1847 addHoleKnockout( pad, 0, clearanceHoles );
1848
1849 aFillPolys.BooleanIntersection( aMaxExtents, SHAPE_POLY_SET::PM_FAST );
1850 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In16_Cu, wxT( "after-trim-to-outline" ) );
1851 aFillPolys.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
1852 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In17_Cu, wxT( "after-trim-to-clearance-holes" ) );
1853
1854 /* -------------------------------------------------------------------------------------
1855 * Lastly give any same-net but higher-priority zones control over their own area.
1856 */
1857
1858 subtractHigherPriorityZones( aZone, aLayer, aFillPolys );
1859 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In18_Cu, wxT( "minus-higher-priority-zones" ) );
1860
1861 aFillPolys.Fracture( SHAPE_POLY_SET::PM_FAST );
1862 return true;
1863}
1864
1865
1867 const SHAPE_POLY_SET& aSmoothedOutline,
1868 SHAPE_POLY_SET& aFillPolys )
1869{
1871 BOX2I zone_boundingbox = aZone->GetBoundingBox();
1872 SHAPE_POLY_SET clearanceHoles;
1873 long ticker = 0;
1874
1875 auto checkForCancel =
1876 [&ticker]( PROGRESS_REPORTER* aReporter ) -> bool
1877 {
1878 return aReporter && ( ticker++ % 50 ) == 0 && aReporter->IsCancelled();
1879 };
1880
1881 auto knockoutGraphicClearance =
1882 [&]( BOARD_ITEM* aItem )
1883 {
1884 if( aItem->IsKnockout() && aItem->IsOnLayer( aLayer )
1885 && aItem->GetBoundingBox().Intersects( zone_boundingbox ) )
1886 {
1888 aZone, aItem, aLayer );
1889
1890 addKnockout( aItem, aLayer, cc.GetValue().Min(), false, clearanceHoles );
1891 }
1892 };
1893
1894 for( FOOTPRINT* footprint : m_board->Footprints() )
1895 {
1896 if( checkForCancel( m_progressReporter ) )
1897 return false;
1898
1899 knockoutGraphicClearance( &footprint->Reference() );
1900 knockoutGraphicClearance( &footprint->Value() );
1901
1902 for( BOARD_ITEM* item : footprint->GraphicalItems() )
1903 knockoutGraphicClearance( item );
1904 }
1905
1906 for( BOARD_ITEM* item : m_board->Drawings() )
1907 {
1908 if( checkForCancel( m_progressReporter ) )
1909 return false;
1910
1911 knockoutGraphicClearance( item );
1912 }
1913
1914 aFillPolys = aSmoothedOutline;
1915 aFillPolys.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
1916
1917 for( ZONE* keepout : m_board->Zones() )
1918 {
1919 if( !keepout->GetIsRuleArea() )
1920 continue;
1921
1922 if( !keepout->HasKeepoutParametersSet() )
1923 continue;
1924
1925 if( keepout->GetDoNotAllowCopperPour() && keepout->IsOnLayer( aLayer ) )
1926 {
1927 if( keepout->GetBoundingBox().Intersects( zone_boundingbox ) )
1928 aFillPolys.BooleanSubtract( *keepout->Outline(), SHAPE_POLY_SET::PM_FAST );
1929 }
1930 }
1931
1932 // Features which are min_width should survive pruning; features that are *less* than
1933 // min_width should not. Therefore we subtract epsilon from the min_width when
1934 // deflating/inflating.
1935 int half_min_width = aZone->GetMinThickness() / 2;
1936 int epsilon = pcbIUScale.mmToIU( 0.001 );
1937
1938 aFillPolys.Deflate( half_min_width - epsilon, CORNER_STRATEGY::CHAMFER_ALL_CORNERS, m_maxError );
1939
1940 // Remove the non filled areas due to the hatch pattern
1941 if( aZone->GetFillMode() == ZONE_FILL_MODE::HATCH_PATTERN )
1942 {
1943 if( !addHatchFillTypeOnZone( aZone, aLayer, aLayer, aFillPolys ) )
1944 return false;
1945 }
1946
1947 // Re-inflate after pruning of areas that don't meet minimum-width criteria
1948 if( half_min_width - epsilon > epsilon )
1949 aFillPolys.Inflate( half_min_width - epsilon, CORNER_STRATEGY::ROUND_ALL_CORNERS, m_maxError );
1950
1952 return true;
1953}
1954
1955
1956/*
1957 * Build the filled solid areas data from real outlines (stored in m_Poly)
1958 * The solid areas can be more than one on copper layers, and do not have holes
1959 * ( holes are linked by overlapping segments to the main outline)
1960 */
1962{
1963 SHAPE_POLY_SET* boardOutline = m_brdOutlinesValid ? &m_boardOutline : nullptr;
1964 SHAPE_POLY_SET maxExtents;
1965 SHAPE_POLY_SET smoothedPoly;
1966 PCB_LAYER_ID debugLayer = UNDEFINED_LAYER;
1967
1968 if( m_debugZoneFiller && LSET::InternalCuMask().Contains( aLayer ) )
1969 {
1970 debugLayer = aLayer;
1971 aLayer = F_Cu;
1972 }
1973
1974 if( !aZone->BuildSmoothedPoly( maxExtents, aLayer, boardOutline, &smoothedPoly ) )
1975 return false;
1976
1978 return false;
1979
1980 if( aZone->IsOnCopperLayer() )
1981 {
1982 if( fillCopperZone( aZone, aLayer, debugLayer, smoothedPoly, maxExtents, aFillPolys ) )
1983 aZone->SetNeedRefill( false );
1984 }
1985 else
1986 {
1987 if( fillNonCopperZone( aZone, aLayer, smoothedPoly, aFillPolys ) )
1988 aZone->SetNeedRefill( false );
1989 }
1990
1991 return true;
1992}
1993
1994
1999 const std::vector<PAD*>& aSpokedPadsList,
2000 std::deque<SHAPE_LINE_CHAIN>& aSpokesList )
2001{
2003 BOX2I zoneBB = aZone->GetBoundingBox();
2004 DRC_CONSTRAINT constraint;
2005 int zone_half_width = aZone->GetMinThickness() / 2;
2006
2007 zoneBB.Inflate( std::max( bds.GetBiggestClearanceValue(), aZone->GetLocalClearance().value() ) );
2008
2009 // Is a point on the boundary of the polygon inside or outside?
2010 // The boundary may be off by MaxError
2011 int epsilon = bds.m_MaxError;
2012
2013 for( PAD* pad : aSpokedPadsList )
2014 {
2015 // We currently only connect to pads, not pad holes
2016 if( !pad->IsOnLayer( aLayer ) )
2017 continue;
2018
2019 constraint = bds.m_DRCEngine->EvalRules( THERMAL_RELIEF_GAP_CONSTRAINT, pad, aZone, aLayer );
2020 int thermalReliefGap = constraint.GetValue().Min();
2021
2022 constraint = bds.m_DRCEngine->EvalRules( THERMAL_SPOKE_WIDTH_CONSTRAINT, pad, aZone, aLayer );
2023 int spoke_w = constraint.GetValue().Opt();
2024
2025 // Spoke width should ideally be smaller than the pad minor axis.
2026 // Otherwise the thermal shape is not really a thermal relief,
2027 // and the algo to count the actual number of spokes can fail
2028 int spoke_max_allowed_w = std::min( pad->GetSize( aLayer ).x, pad->GetSize( aLayer ).y );
2029
2030 spoke_w = std::clamp( spoke_w, constraint.Value().Min(), constraint.Value().Max() );
2031
2032 // ensure the spoke width is smaller than the pad minor size
2033 spoke_w = std::min( spoke_w, spoke_max_allowed_w );
2034
2035 // Cannot create stubs having a width < zone min thickness
2036 if( spoke_w < aZone->GetMinThickness() )
2037 continue;
2038
2039 int spoke_half_w = spoke_w / 2;
2040
2041 // Quick test here to possibly save us some work
2042 BOX2I itemBB = pad->GetBoundingBox();
2043 itemBB.Inflate( thermalReliefGap + epsilon );
2044
2045 if( !( itemBB.Intersects( zoneBB ) ) )
2046 continue;
2047
2048 bool customSpokes = false;
2049
2050 if( pad->GetShape( aLayer ) == PAD_SHAPE::CUSTOM )
2051 {
2052 for( const std::shared_ptr<PCB_SHAPE>& primitive : pad->GetPrimitives( aLayer ) )
2053 {
2054 if( primitive->IsProxyItem() && primitive->GetShape() == SHAPE_T::SEGMENT )
2055 {
2056 customSpokes = true;
2057 break;
2058 }
2059 }
2060 }
2061
2062 // Thermal spokes consist of square-ended segments from the pad center to points just
2063 // outside the thermal relief. The outside end has an extra center point (which must be
2064 // at idx 3) which is used for testing whether or not the spoke connects to copper in the
2065 // parent zone.
2066
2067 auto buildSpokesFromOrigin =
2068 [&]( const BOX2I& box, EDA_ANGLE angle )
2069 {
2070 VECTOR2I center = box.GetCenter();
2071 VECTOR2I half_size( box.GetWidth() / 2, box.GetHeight() / 2 );
2072
2073 // Function to find intersection of line with box edge
2074 auto intersectLineBox = [&](const VECTOR2D& direction) -> VECTOR2I {
2075 double dx = direction.x;
2076 double dy = direction.y;
2077
2078 // Shortcircuit the axis cases because they will be degenerate in the
2079 // intersection test
2080 if( direction.x == 0 )
2081 {
2082 return VECTOR2I(0, dy * half_size.y );
2083 }
2084 else if( direction.y == 0 )
2085 {
2086 return VECTOR2I(dx * half_size.x, 0);
2087 }
2088
2089 // We are going to intersect with one side or the other. Whichever
2090 // we hit first is the fraction of the spoke length we keep
2091 double tx = std::min( half_size.x / std::abs( dx ),
2092 half_size.y / std::abs( dy ) );
2093 return VECTOR2I( dx * tx, dy * tx );
2094 };
2095
2096 // Precalculate angles for four cardinal directions
2097 const EDA_ANGLE angles[4] = {
2098 EDA_ANGLE( 0.0, DEGREES_T ) + angle, // Right
2099 EDA_ANGLE( 90.0, DEGREES_T ) + angle, // Up
2100 EDA_ANGLE( 180.0, DEGREES_T ) + angle, // Left
2101 EDA_ANGLE( 270.0, DEGREES_T ) + angle // Down
2102 };
2103
2104 // Generate four spokes in cardinal directions
2105 for( const EDA_ANGLE& spokeAngle : angles )
2106 {
2107 VECTOR2D direction( spokeAngle.Cos(), spokeAngle.Sin() );
2108 VECTOR2D perpendicular = direction.Perpendicular();
2109
2110 VECTOR2I intersection = intersectLineBox( direction );
2111 VECTOR2I spoke_side = perpendicular.Resize( spoke_half_w );
2112
2113 SHAPE_LINE_CHAIN spoke;
2114 spoke.Append( center + spoke_side );
2115 spoke.Append( center - spoke_side );
2116 spoke.Append( center + intersection - spoke_side );
2117 spoke.Append( center + intersection ); // test pt
2118 spoke.Append( center + intersection + spoke_side );
2119 spoke.SetClosed( true );
2120 aSpokesList.push_back( std::move( spoke ) );
2121 }
2122 };
2123
2124 if( customSpokes )
2125 {
2126 SHAPE_POLY_SET thermalPoly;
2127 SHAPE_LINE_CHAIN thermalOutline;
2128
2129 pad->TransformShapeToPolygon( thermalPoly, aLayer, thermalReliefGap + epsilon,
2131
2132 if( thermalPoly.OutlineCount() )
2133 thermalOutline = thermalPoly.Outline( 0 );
2134
2135 for( const std::shared_ptr<PCB_SHAPE>& primitive : pad->GetPrimitives( aLayer ) )
2136 {
2137 if( primitive->IsProxyItem() && primitive->GetShape() == SHAPE_T::SEGMENT )
2138 {
2139 SEG seg( primitive->GetStart(), primitive->GetEnd() );
2140 SHAPE_LINE_CHAIN::INTERSECTIONS intersections;
2141
2142 RotatePoint( seg.A, pad->GetOrientation() );
2143 RotatePoint( seg.B, pad->GetOrientation() );
2144 seg.A += pad->ShapePos( aLayer );
2145 seg.B += pad->ShapePos( aLayer );
2146
2147 // Make sure seg.A is the origin
2148 if( !pad->GetEffectivePolygon( aLayer, ERROR_OUTSIDE )->Contains( seg.A ) )
2149 seg.Reverse();
2150
2151 // Trim seg.B to the thermal outline
2152 if( thermalOutline.Intersect( seg, intersections ) )
2153 {
2154 seg.B = intersections.front().p;
2155
2156 VECTOR2I offset = ( seg.B - seg.A ).Perpendicular().Resize( spoke_half_w );
2157 SHAPE_LINE_CHAIN spoke;
2158
2159 spoke.Append( seg.A + offset );
2160 spoke.Append( seg.A - offset );
2161 spoke.Append( seg.B - offset );
2162 spoke.Append( seg.B ); // test pt
2163 spoke.Append( seg.B + offset );
2164
2165 spoke.SetClosed( true );
2166 aSpokesList.push_back( std::move( spoke ) );
2167 }
2168 }
2169 }
2170 }
2171 else
2172 {
2173 // Since the bounding-box needs to be correclty rotated we use a dummy pad to keep
2174 // from dirtying the real pad's cached shapes.
2175 PAD dummy_pad( *pad );
2176 dummy_pad.SetOrientation( ANGLE_0 );
2177
2178 // Spokes are from center of pad shape, not from hole. So the dummy pad has no shape
2179 // offset and is at position 0,0
2180 dummy_pad.SetPosition( VECTOR2I( 0, 0 ) );
2181 dummy_pad.SetOffset( aLayer, VECTOR2I( 0, 0 ) );
2182
2183 BOX2I spokesBox = dummy_pad.GetBoundingBox();
2184
2185 //Add the half width of the zone mininum width to the inflate amount to account for the fact that
2186 //the deflation procedure will shrink the results by half the half the zone min width
2187 spokesBox.Inflate( thermalReliefGap + epsilon + zone_half_width );
2188
2189 // This is a touchy case because the bounding box for circles overshoots the mark
2190 // when rotated at 45 degrees. So we just build spokes at 0 degrees and rotate
2191 // them later.
2192 if( pad->GetShape( aLayer ) == PAD_SHAPE::CIRCLE
2193 || ( pad->GetShape( aLayer ) == PAD_SHAPE::OVAL
2194 && pad->GetSizeX() == pad->GetSizeY() ) )
2195 {
2196 buildSpokesFromOrigin( spokesBox, ANGLE_0 );
2197
2198 if( pad->GetThermalSpokeAngle() != ANGLE_0 )
2199 {
2200 //Rotate the last four elements of aspokeslist
2201 for( auto it = aSpokesList.rbegin(); it != aSpokesList.rbegin() + 4; ++it )
2202 it->Rotate( pad->GetThermalSpokeAngle() );
2203 }
2204 }
2205 else
2206 {
2207 buildSpokesFromOrigin( spokesBox, pad->GetThermalSpokeAngle() );
2208 }
2209
2210 auto spokeIter = aSpokesList.rbegin();
2211
2212 for( int ii = 0; ii < 4; ++ii, ++spokeIter )
2213 {
2214 spokeIter->Rotate( pad->GetOrientation() );
2215 spokeIter->Move( pad->ShapePos( aLayer ) );
2216 }
2217
2218 // Remove group membership from dummy item before deleting
2219 dummy_pad.SetParentGroup( nullptr );
2220 }
2221 }
2222
2223 for( size_t ii = 0; ii < aSpokesList.size(); ++ii )
2224 aSpokesList[ii].GenerateBBoxCache();
2225}
2226
2227
2229 PCB_LAYER_ID aDebugLayer, SHAPE_POLY_SET& aFillPolys )
2230{
2231 // Build grid:
2232
2233 // obviously line thickness must be > zone min thickness.
2234 // It can happens if a board file was edited by hand by a python script
2235 // Use 1 micron margin to be *sure* there is no issue in Gerber files
2236 // (Gbr file unit = 1 or 10 nm) due to some truncation in coordinates or calculations
2237 // This margin also avoid problems due to rounding coordinates in next calculations
2238 // that can create incorrect polygons
2239 int thickness = std::max( aZone->GetHatchThickness(),
2240 aZone->GetMinThickness() + pcbIUScale.mmToIU( 0.001 ) );
2241
2242 int linethickness = thickness - aZone->GetMinThickness();
2243 int gridsize = thickness + aZone->GetHatchGap();
2244 int maxError = m_board->GetDesignSettings().m_MaxError;
2245
2246 SHAPE_POLY_SET filledPolys = aFillPolys.CloneDropTriangulation();
2247 // Use a area that contains the rotated bbox by orientation, and after rotate the result
2248 // by -orientation.
2249 if( !aZone->GetHatchOrientation().IsZero() )
2250 filledPolys.Rotate( - aZone->GetHatchOrientation() );
2251
2252 BOX2I bbox = filledPolys.BBox( 0 );
2253
2254 // Build hole shape
2255 // the hole size is aZone->GetHatchGap(), but because the outline thickness
2256 // is aZone->GetMinThickness(), the hole shape size must be larger
2257 SHAPE_LINE_CHAIN hole_base;
2258 int hole_size = aZone->GetHatchGap() + aZone->GetMinThickness();
2259 VECTOR2I corner( 0, 0 );;
2260 hole_base.Append( corner );
2261 corner.x += hole_size;
2262 hole_base.Append( corner );
2263 corner.y += hole_size;
2264 hole_base.Append( corner );
2265 corner.x = 0;
2266 hole_base.Append( corner );
2267 hole_base.SetClosed( true );
2268
2269 // Calculate minimal area of a grid hole.
2270 // All holes smaller than a threshold will be removed
2271 double minimal_hole_area = hole_base.Area() * aZone->GetHatchHoleMinArea();
2272
2273 // Now convert this hole to a smoothed shape:
2274 if( aZone->GetHatchSmoothingLevel() > 0 )
2275 {
2276 // the actual size of chamfer, or rounded corner radius is the half size
2277 // of the HatchFillTypeGap scaled by aZone->GetHatchSmoothingValue()
2278 // aZone->GetHatchSmoothingValue() = 1.0 is the max value for the chamfer or the
2279 // radius of corner (radius = half size of the hole)
2280 int smooth_value = KiROUND( aZone->GetHatchGap()
2281 * aZone->GetHatchSmoothingValue() / 2 );
2282
2283 // Minimal optimization:
2284 // make smoothing only for reasonable smooth values, to avoid a lot of useless segments
2285 // and if the smooth value is small, use chamfer even if fillet is requested
2286 #define SMOOTH_MIN_VAL_MM 0.02
2287 #define SMOOTH_SMALL_VAL_MM 0.04
2288
2289 if( smooth_value > pcbIUScale.mmToIU( SMOOTH_MIN_VAL_MM ) )
2290 {
2291 SHAPE_POLY_SET smooth_hole;
2292 smooth_hole.AddOutline( hole_base );
2293 int smooth_level = aZone->GetHatchSmoothingLevel();
2294
2295 if( smooth_value < pcbIUScale.mmToIU( SMOOTH_SMALL_VAL_MM ) && smooth_level > 1 )
2296 smooth_level = 1;
2297
2298 // Use a larger smooth_value to compensate the outline tickness
2299 // (chamfer is not visible is smooth value < outline thickess)
2300 smooth_value += aZone->GetMinThickness() / 2;
2301
2302 // smooth_value cannot be bigger than the half size oh the hole:
2303 smooth_value = std::min( smooth_value, aZone->GetHatchGap() / 2 );
2304
2305 // the error to approximate a circle by segments when smoothing corners by a arc
2306 maxError = std::max( maxError * 2, smooth_value / 20 );
2307
2308 switch( smooth_level )
2309 {
2310 case 1:
2311 // Chamfer() uses the distance from a corner to create a end point
2312 // for the chamfer.
2313 hole_base = smooth_hole.Chamfer( smooth_value ).Outline( 0 );
2314 break;
2315
2316 default:
2317 if( aZone->GetHatchSmoothingLevel() > 2 )
2318 maxError /= 2; // Force better smoothing
2319
2320 hole_base = smooth_hole.Fillet( smooth_value, maxError ).Outline( 0 );
2321 break;
2322
2323 case 0:
2324 break;
2325 };
2326 }
2327 }
2328
2329 // Build holes
2330 SHAPE_POLY_SET holes;
2331
2332 for( int xx = 0; ; xx++ )
2333 {
2334 int xpos = xx * gridsize;
2335
2336 if( xpos > bbox.GetWidth() )
2337 break;
2338
2339 for( int yy = 0; ; yy++ )
2340 {
2341 int ypos = yy * gridsize;
2342
2343 if( ypos > bbox.GetHeight() )
2344 break;
2345
2346 // Generate hole
2347 SHAPE_LINE_CHAIN hole( hole_base );
2348 hole.Move( VECTOR2I( xpos, ypos ) );
2349 holes.AddOutline( hole );
2350 }
2351 }
2352
2353 holes.Move( bbox.GetPosition() );
2354
2355 if( !aZone->GetHatchOrientation().IsZero() )
2356 holes.Rotate( aZone->GetHatchOrientation() );
2357
2358 DUMP_POLYS_TO_COPPER_LAYER( holes, In10_Cu, wxT( "hatch-holes" ) );
2359
2360 int outline_margin = aZone->GetMinThickness() * 1.1;
2361
2362 // Using GetHatchThickness() can look more consistent than GetMinThickness().
2363 if( aZone->GetHatchBorderAlgorithm() && aZone->GetHatchThickness() > outline_margin )
2364 outline_margin = aZone->GetHatchThickness();
2365
2366 // The fill has already been deflated to ensure GetMinThickness() so we just have to
2367 // account for anything beyond that.
2368 SHAPE_POLY_SET deflatedFilledPolys = aFillPolys.CloneDropTriangulation();
2369 deflatedFilledPolys.Deflate( outline_margin - aZone->GetMinThickness(),
2370 CORNER_STRATEGY::CHAMFER_ALL_CORNERS, maxError );
2371 holes.BooleanIntersection( deflatedFilledPolys, SHAPE_POLY_SET::PM_FAST );
2372 DUMP_POLYS_TO_COPPER_LAYER( holes, In11_Cu, wxT( "fill-clipped-hatch-holes" ) );
2373
2374 SHAPE_POLY_SET deflatedOutline = aZone->Outline()->CloneDropTriangulation();
2375 deflatedOutline.Deflate( outline_margin, CORNER_STRATEGY::CHAMFER_ALL_CORNERS, maxError );
2376 holes.BooleanIntersection( deflatedOutline, SHAPE_POLY_SET::PM_FAST );
2377 DUMP_POLYS_TO_COPPER_LAYER( holes, In12_Cu, wxT( "outline-clipped-hatch-holes" ) );
2378
2379 if( aZone->GetNetCode() != 0 )
2380 {
2381 // Vias and pads connected to the zone must not be allowed to become isolated inside
2382 // one of the holes. Effectively this means their copper outline needs to be expanded
2383 // to be at least as wide as the gap so that it is guaranteed to touch at least one
2384 // edge.
2385 BOX2I zone_boundingbox = aZone->GetBoundingBox();
2386 SHAPE_POLY_SET aprons;
2387 int min_apron_radius = ( aZone->GetHatchGap() * 10 ) / 19;
2388
2389 for( PCB_TRACK* track : m_board->Tracks() )
2390 {
2391 if( track->Type() == PCB_VIA_T )
2392 {
2393 PCB_VIA* via = static_cast<PCB_VIA*>( track );
2394
2395 if( via->GetNetCode() == aZone->GetNetCode()
2396 && via->IsOnLayer( aLayer )
2397 && via->GetBoundingBox().Intersects( zone_boundingbox ) )
2398 {
2399 int r = std::max( min_apron_radius,
2400 via->GetDrillValue() / 2 + outline_margin );
2401
2402 TransformCircleToPolygon( aprons, via->GetPosition(), r, maxError,
2403 ERROR_OUTSIDE );
2404 }
2405 }
2406 }
2407
2408 for( FOOTPRINT* footprint : m_board->Footprints() )
2409 {
2410 for( PAD* pad : footprint->Pads() )
2411 {
2412 if( pad->GetNetCode() == aZone->GetNetCode()
2413 && pad->IsOnLayer( aLayer )
2414 && pad->GetBoundingBox().Intersects( zone_boundingbox ) )
2415 {
2416 // What we want is to bulk up the pad shape so that the narrowest bit of
2417 // copper between the hole and the apron edge is at least outline_margin
2418 // wide (and that the apron itself meets min_apron_radius. But that would
2419 // take a lot of code and math, and the following approximation is close
2420 // enough.
2421 int pad_width = std::min( pad->GetSize( aLayer ).x, pad->GetSize( aLayer ).y );
2422 int slot_width = std::min( pad->GetDrillSize().x, pad->GetDrillSize().y );
2423 int min_annular_ring_width = ( pad_width - slot_width ) / 2;
2424 int clearance = std::max( min_apron_radius - pad_width / 2,
2425 outline_margin - min_annular_ring_width );
2426
2427 clearance = std::max( 0, clearance - linethickness / 2 );
2428 pad->TransformShapeToPolygon( aprons, aLayer, clearance, maxError,
2429 ERROR_OUTSIDE );
2430 }
2431 }
2432 }
2433
2435 }
2436 DUMP_POLYS_TO_COPPER_LAYER( holes, In13_Cu, wxT( "pad-via-clipped-hatch-holes" ) );
2437
2438 // Now filter truncated holes to avoid small holes in pattern
2439 // It happens for holes near the zone outline
2440 for( int ii = 0; ii < holes.OutlineCount(); )
2441 {
2442 double area = holes.Outline( ii ).Area();
2443
2444 if( area < minimal_hole_area ) // The current hole is too small: remove it
2445 holes.DeletePolygon( ii );
2446 else
2447 ++ii;
2448 }
2449
2450 // create grid. Use SHAPE_POLY_SET::PM_STRICTLY_SIMPLE to
2451 // generate strictly simple polygons needed by Gerber files and Fracture()
2452 aFillPolys.BooleanSubtract( aFillPolys, holes, SHAPE_POLY_SET::PM_STRICTLY_SIMPLE );
2453 DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In14_Cu, wxT( "after-hatching" ) );
2454
2455 return true;
2456}
@ 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:70
@ ZLO_FORCE_FLASHED
Definition: board_item.h:69
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:80
void SetParentGroup(PCB_GROUP *aGroup)
Definition: board_item.h:90
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:256
virtual void SetIsKnockout(bool aKnockout)
Definition: board_item.h:326
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:2491
LSET GetEnabledLayers() const
A proxy function that calls the corresponding function in m_BoardSettings.
Definition: board.cpp:773
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:896
int GetCopperLayerCount() const
Definition: board.cpp:736
const FOOTPRINTS & Footprints() const
Definition: board.h:331
const TRACKS & Tracks() const
Definition: board.h:329
BOARD_DESIGN_SETTINGS & GetDesignSettings() const
Definition: board.cpp:890
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:152
const MINOPTMAX< int > & GetValue() const
Definition: drc_rule.h:151
ZONE_CONNECTION m_ZoneConnection
Definition: drc_rule.h:191
bool IsNull() const
Definition: drc_rule.h:146
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:665
static LSET AllCuMask(int aCuLayerCount=MAX_CU_LAYERS)
Return a mask holding the requested number of Cu PCB_LAYER_IDs.
Definition: lset.cpp:676
LSEQ Seq(const LSEQ &aSequence) const
Return an LSEQ from the union of this LSET and a desired sequence.
Definition: lset.cpp:410
bool Contains(PCB_LAYER_ID aLayer) const
See if the layer set contains a PCB layer.
Definition: lset.h:60
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:797
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:1874
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:862
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:1857
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:622
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:96
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:339
int32_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
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
const double x
Definition: vertex_set.h:231
VERTEX * next
Definition: vertex_set.h:237
VERTEX * prevZ
Definition: vertex_set.h:243
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:244
VERTEX * prev
Definition: vertex_set.h:236
const int i
Definition: vertex_set.h:230
void * GetUserData() const
Definition: vertex_set.h:79
int32_t z
Definition: vertex_set.h:240
bool isEar() const
Check whether the given vertex is in the middle of an ear.
Definition: vertex_set.cpp:241
const double y
Definition: vertex_set.h:232
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:265
int GetHatchBorderAlgorithm() const
Definition: zone.h:303
std::optional< int > GetLocalClearance() const override
Definition: zone.cpp:528
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:1115
const BOX2I GetBoundingBox() const override
Definition: zone.cpp:381
SHAPE_POLY_SET * Outline()
Definition: zone.h:337
void SetFillFlag(PCB_LAYER_ID aLayer, bool aFlag)
Definition: zone.h:259
void SetFilledPolysList(PCB_LAYER_ID aLayer, const SHAPE_POLY_SET &aPolysList)
Set the list of filled polygons.
Definition: zone.h:638
int GetMinThickness() const
Definition: zone.h:270
bool HigherPriority(const ZONE *aOther) const
Definition: zone.cpp:207
int GetHatchThickness() const
Definition: zone.h:285
double GetHatchHoleMinArea() const
Definition: zone.h:300
bool IsTeardropArea() const
Definition: zone.h:696
EDA_ANGLE GetHatchOrientation() const
Definition: zone.h:291
bool BuildSmoothedPoly(SHAPE_POLY_SET &aSmoothedPoly, PCB_LAYER_ID aLayer, SHAPE_POLY_SET *aBoardOutline, SHAPE_POLY_SET *aSmoothedPolyWithApron=nullptr) const
Definition: zone.cpp:1179
ZONE_FILL_MODE GetFillMode() const
Definition: zone.h:193
int GetHatchGap() const
Definition: zone.h:288
double GetHatchSmoothingValue() const
Definition: zone.h:297
int GetHatchSmoothingLevel() const
Definition: zone.h:294
bool IsOnCopperLayer() const override
Definition: zone.cpp:292
std::mutex & GetLock()
Definition: zone.h:249
unsigned GetAssignedPriority() const
Definition: zone.h:120
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