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