KiCad PCB EDA Suite
Loading...
Searching...
No Matches
multichannel_tool.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) Kicad Developers, see change_log.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, you may find one here:
18 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
19 * or you may search the http://www.gnu.org website for the version 2 license,
20 * or you may write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 */
23
24
25#include <board_commit.h>
26#include <tools/pcb_actions.h>
27
30
31#include "multichannel_tool.h"
32
33#include <pcbexpr_evaluator.h>
34
35#include <zone.h>
38#include <pcb_group.h>
41#include <optional>
42#include <algorithm>
44#include <pcb_track.h>
45#include <tool/tool_manager.h>
47#include <random>
48#include <core/profile.h>
49#include <wx/log.h>
50#include <pgm_base.h>
51
52
53#define MULTICHANNEL_EXTRA_DEBUG
54
55static const wxString traceMultichannelTool = wxT( "MULTICHANNEL_TOOL" );
56
57
59{
60}
61
62
64{
65
66}
67
68
70{
73}
74
75
77 std::set<FOOTPRINT*>& aComponents )
78{
80 PCBEXPR_UCODE ucode;
81 PCBEXPR_CONTEXT ctx, preflightCtx;
82
83 auto reportError = [&]( const wxString& aMessage, int aOffset )
84 {
85 wxLogTrace( traceMultichannelTool, wxT( "ERROR: %s"), aMessage );
86 };
87
88 ctx.SetErrorCallback( reportError );
89 preflightCtx.SetErrorCallback( reportError );
90 compiler.SetErrorCallback( reportError );
91 //compiler.SetDebugReporter( m_reporter );
92
93 wxLogTrace( traceMultichannelTool, wxT( "rule area '%s'"), aRuleArea->GetZoneName() );
94
95 wxString ruleText;
96
97 switch( aRuleArea->GetRuleAreaPlacementSourceType() )
98 {
99 case RULE_AREA_PLACEMENT_SOURCE_TYPE::SHEETNAME:
100 {
101 ruleText =
102 wxT( "A.memberOfSheet('" ) + aRuleArea->GetRuleAreaPlacementSource() + wxT( "')" );
103 break;
104 }
105 case RULE_AREA_PLACEMENT_SOURCE_TYPE::COMPONENT_CLASS:
106 ruleText = wxT( "A.hasComponentClass('" ) + aRuleArea->GetRuleAreaPlacementSource()
107 + wxT( "')" );
108 break;
109 }
110
111 auto ok = compiler.Compile( ruleText, &ucode, &preflightCtx );
112
113 if( !ok )
114 {
115 return false;
116 }
117
118 for( FOOTPRINT* fp : board()->Footprints() )
119 {
120 ctx.SetItems( fp, fp );
121 auto val = ucode.Run( &ctx );
122 if( val->AsDouble() != 0.0 )
123 {
124 wxLogTrace( traceMultichannelTool, wxT( " - %s [sheet %s]" ), fp->GetReference(),
125 fp->GetSheetname() );
126
127 aComponents.insert( fp );
128 }
129 }
130
131 return true;
132}
133
134
135bool MULTICHANNEL_TOOL::findOtherItemsInRuleArea( ZONE* aRuleArea, std::set<BOARD_ITEM*>& aItems )
136{
137 std::vector<BOARD_ITEM*> result;
138
140 PCBEXPR_UCODE ucode;
141 PCBEXPR_CONTEXT ctx, preflightCtx;
142
143 auto reportError = [&]( const wxString& aMessage, int aOffset )
144 {
145 wxLogTrace( traceMultichannelTool, wxT( "ERROR: %s"), aMessage );
146 };
147
148 ctx.SetErrorCallback( reportError );
149 preflightCtx.SetErrorCallback( reportError );
150 compiler.SetErrorCallback( reportError );
151
152 bool restoreBlankName = false;
153
154 if( aRuleArea->GetZoneName().IsEmpty() )
155 {
156 restoreBlankName = true;
157 aRuleArea->SetZoneName( aRuleArea->m_Uuid.AsString() );
158 }
159
160 wxString ruleText = wxString::Format( wxT( "A.enclosedByArea('%s')" ), aRuleArea->GetZoneName() );
161
162 if( !compiler.Compile( ruleText, &ucode, &preflightCtx ) )
163 {
164 if( restoreBlankName )
165 aRuleArea->SetZoneName( wxEmptyString );
166
167 return false;
168 }
169
170 auto testAndAdd =
171 [&]( BOARD_ITEM* aItem )
172 {
173 ctx.SetItems( aItem, aItem );
174 auto val = ucode.Run( &ctx );
175
176 if( val->AsDouble() != 0.0 )
177 aItems.insert( aItem );
178 };
179
180 for( ZONE* zone : board()->Zones() )
181 {
182 if( zone == aRuleArea )
183 continue;
184
185 testAndAdd( zone );
186 }
187
188 for( BOARD_ITEM* drawing : board()->Drawings() )
189 testAndAdd( drawing );
190
191 for( PCB_GROUP* group : board()->Groups() )
192 {
193 // A group is cloned in its entirety if *all* children are contained
194 bool addGroup = true;
195
196 group->RunOnDescendants(
197 [&]( BOARD_ITEM* aItem )
198 {
199 if( aItem->IsType( { PCB_ZONE_T, PCB_SHAPE_T, PCB_DIMENSION_T } ) )
200 {
201 ctx.SetItems( aItem, aItem );
202 auto val = ucode.Run( &ctx );
203
204 if( val->AsDouble() == 0.0 )
205 addGroup = false;
206 }
207 } );
208
209 if( addGroup )
210 aItems.insert( group );
211 }
212
213 if( restoreBlankName )
214 aRuleArea->SetZoneName( wxEmptyString );
215
216 return true;
217}
218
219
220std::set<FOOTPRINT*> MULTICHANNEL_TOOL::queryComponentsInSheet( wxString aSheetName ) const
221{
222 std::set<FOOTPRINT*> rv;
223 if( aSheetName.EndsWith( wxT( "/" ) ) )
224 aSheetName.RemoveLast();
225
226 for( auto& fp : board()->Footprints() )
227 {
228 auto sn = fp->GetSheetname();
229 if( sn.EndsWith( wxT( "/" ) ) )
230 sn.RemoveLast();
231
232 if( sn == aSheetName )
233 {
234 rv.insert( fp );
235 }
236 }
237
238 return rv;
239}
240
241
242std::set<FOOTPRINT*>
243MULTICHANNEL_TOOL::queryComponentsInComponentClass( const wxString& aComponentClassName ) const
244{
245 std::set<FOOTPRINT*> rv;
246
247 for( auto& fp : board()->Footprints() )
248 {
249 if( fp->GetComponentClass()->ContainsClassName( aComponentClassName ) )
250 rv.insert( fp );
251 }
252
253 return rv;
254}
255
256
257const SHAPE_LINE_CHAIN MULTICHANNEL_TOOL::buildRAOutline( std::set<FOOTPRINT*>& aFootprints,
258 int aMargin )
259{
260 std::vector<VECTOR2I> bbCorners;
261 bbCorners.reserve( aFootprints.size() * 4 );
262
263 for( auto fp : aFootprints )
264 {
265 const BOX2I bb = fp->GetBoundingBox( false ).GetInflated( aMargin );
266 KIGEOM::CollectBoxCorners( bb, bbCorners );
267 }
268
269 std::vector<VECTOR2I> hullVertices;
270 BuildConvexHull( hullVertices, bbCorners );
271
272 SHAPE_LINE_CHAIN hull( hullVertices );
273
274 // Make the newly computed convex hull use only 90 degree segments
275 return KIGEOM::RectifyPolygon( hull );
276}
277
278
280{
281 using PathAndName = std::pair<wxString, wxString>;
282 std::set<PathAndName> uniqueSheets;
283 std::set<wxString> uniqueComponentClasses;
284
285 m_areas.m_areas.clear();
286
287 for( const FOOTPRINT* fp : board()->Footprints() )
288 {
289 uniqueSheets.insert( PathAndName( fp->GetSheetname(), fp->GetSheetfile() ) );
290
291 const COMPONENT_CLASS* compClass = fp->GetComponentClass();
292
293 for( const COMPONENT_CLASS* singleClass : compClass->GetConstituentClasses() )
294 uniqueComponentClasses.insert( singleClass->GetName() );
295 }
296
297 for( const PathAndName& sheet : uniqueSheets )
298 {
299 RULE_AREA ent;
300
301 ent.m_sourceType = RULE_AREA_PLACEMENT_SOURCE_TYPE::SHEETNAME;
302 ent.m_generateEnabled = false;
303 ent.m_sheetPath = sheet.first;
304 ent.m_sheetName = sheet.second;
306 m_areas.m_areas.push_back( ent );
307
308 wxLogTrace( traceMultichannelTool, wxT("found sheet '%s' @ '%s' s %d\n"),
309 ent.m_sheetName, ent.m_sheetPath, (int)m_areas.m_areas.size() );
310 }
311
312 for( const wxString& compClass : uniqueComponentClasses )
313 {
314 RULE_AREA ent;
315
316 ent.m_sourceType = RULE_AREA_PLACEMENT_SOURCE_TYPE::COMPONENT_CLASS;
317 ent.m_generateEnabled = false;
318 ent.m_componentClass = compClass;
320 m_areas.m_areas.push_back( ent );
321
322 wxLogTrace( traceMultichannelTool, wxT( "found component class '%s' s %d\n" ),
323 ent.m_componentClass, static_cast<int>( m_areas.m_areas.size() ) );
324 }
325}
326
327
329{
330 m_areas.m_areas.clear();
331
332 for( ZONE* zone : board()->Zones() )
333 {
334 if( !zone->GetIsRuleArea() )
335 continue;
336 if( !zone->GetRuleAreaPlacementEnabled() )
337 continue;
338
339 RULE_AREA area;
340
341 area.m_existsAlready = true;
342 area.m_area = zone;
343
345
346 area.m_ruleName = zone->GetZoneName();
347 area.m_center = zone->Outline()->COutline( 0 ).Centre();
348 m_areas.m_areas.push_back( area );
349
350 wxLogTrace( traceMultichannelTool, wxT("RA '%s', %d footprints\n"), area.m_ruleName, (int) area.m_raFootprints.size() );
351 }
352
353 wxLogTrace( traceMultichannelTool, wxT("Total RAs found: %d\n"), (int) m_areas.m_areas.size() );
354}
355
356
358{
359 for( RULE_AREA& ra : m_areas.m_areas )
360 {
361 if( ra.m_ruleName == aName )
362 return &ra;
363 }
364
365 return nullptr;
366}
367
368
370{
372}
373
374
376{
377 std::vector<ZONE*> refRAs;
378
379 auto isSelectedItemAnRA = []( EDA_ITEM* aItem ) -> ZONE*
380 {
381 if( !aItem || aItem->Type() != PCB_ZONE_T )
382 return nullptr;
383
384 ZONE* zone = static_cast<ZONE*>( aItem );
385
386 if( !zone->GetIsRuleArea() )
387 return nullptr;
388
389 if( !zone->GetRuleAreaPlacementEnabled() )
390 return nullptr;
391
392 return zone;
393 };
394
395 for( EDA_ITEM* item : selection() )
396 {
397 if( auto zone = isSelectedItemAnRA( item ) )
398 {
399 refRAs.push_back(zone);
400 }
401 else if ( item->Type() == PCB_GROUP_T )
402 {
403 PCB_GROUP *group = static_cast<PCB_GROUP*>( item );
404
405 for( BOARD_ITEM* grpItem : group->GetItems() )
406 {
407 if( auto grpZone = isSelectedItemAnRA( grpItem ) )
408 {
409 refRAs.push_back( grpZone );
410 }
411 }
412 }
413 }
414
415 if( refRAs.size() != 1 )
416 {
419 this,
420 _( "Select a reference Rule Area to copy from..." ),
421 [&]( EDA_ITEM* aItem )
422 {
423 return isSelectedItemAnRA( aItem ) != nullptr;
424 }
425 } );
426
427 return 0;
428 }
429
431
432 int status = CheckRACompatibility( refRAs.front() );
433
434 if( status < 0 )
435 return status;
436
437 if( m_areas.m_areas.size() <= 1 )
438 {
439 frame()->ShowInfoBarError( _( "No Rule Areas to repeat layout to have been found." ),
440 true );
441 return 0;
442 }
443
445 int ret = dialog.ShowModal();
446
447 if( ret != wxID_OK )
448 return 0;
449
450 return RepeatLayout( aEvent, refRAs.front() );
451}
452
453
455{
456 m_areas.m_refRA = nullptr;
457
458 for( RULE_AREA& ra : m_areas.m_areas )
459 {
460 if( ra.m_area == aRefZone )
461 {
462 m_areas.m_refRA = &ra;
463 break;
464 }
465 }
466
467 if( !m_areas.m_refRA )
468 return -1;
469
470 m_areas.m_compatMap.clear();
471
472 for( RULE_AREA& ra : m_areas.m_areas )
473 {
474 if( ra.m_area == m_areas.m_refRA->m_area )
475 continue;
476
478
480 }
481
482 return 0;
483}
484
485
486int MULTICHANNEL_TOOL::RepeatLayout( const TOOL_EVENT& aEvent, ZONE* aRefZone )
487{
488 int totalCopied = 0;
489
490 BOARD_COMMIT commit( GetManager(), true );
491
492 for( auto& targetArea : m_areas.m_compatMap )
493 {
494 if( !targetArea.second.m_doCopy )
495 {
496 wxLogTrace( traceMultichannelTool, wxT("skipping copy to RA '%s' (disabled in dialog)\n"),
497 targetArea.first->m_ruleName );
498 continue;
499 }
500
501 if( !targetArea.second.m_isOk )
502 continue;
503
504 std::unordered_set<BOARD_ITEM*> affectedItems;
505 std::unordered_set<BOARD_ITEM*> groupableItems;
506
507 if( !copyRuleAreaContents( targetArea.second.m_matchingComponents, &commit, m_areas.m_refRA,
508 targetArea.first, m_areas.m_options, affectedItems,
509 groupableItems ) )
510 {
511 auto errMsg = wxString::Format(
512 _( "Copy Rule Area contents failed between rule areas '%s' and '%s'." ),
514 targetArea.first->m_area->GetZoneName() );
515
516 commit.Revert();
517
518 if( Pgm().IsGUI() )
519 {
520 frame()->ShowInfoBarError( errMsg, true );
521 }
522
523 return -1;
524 }
525
527 {
528 pruneExistingGroups( commit, affectedItems );
529
530 PCB_GROUP* grp = new PCB_GROUP( board() );
531
532 commit.Add( grp );
533
534 for( BOARD_ITEM* item : groupableItems )
535 {
536 commit.Stage( item, CHT_GROUP );
537 }
538 }
539
540 totalCopied++;
541 }
542
543 commit.Push( _( "Repeat layout" ) );
544
545 if( Pgm().IsGUI() )
546 {
547 frame()->ShowInfoBarMsg( wxString::Format( _( "Copied to %d Rule Areas." ), totalCopied ),
548 true );
549 }
550 return 0;
551}
552
553
554wxString MULTICHANNEL_TOOL::stripComponentIndex( const wxString& aRef ) const
555{
556 wxString rv;
557
558 // fixme: i'm pretty sure this can be written in a simpler way, but I really suck at figuring
559 // out which wx's built in functions would do it for me. And I hate regexps :-)
560 for( auto k : aRef )
561 {
562 if( !k.IsAscii() )
563 break;
564 char c;
565 k.GetAsChar( &c );
566
567 if( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || ( c == '_' ) )
568 rv.Append( k );
569 else
570 break;
571 }
572
573 return rv;
574}
575
576
577int MULTICHANNEL_TOOL::findRoutedConnections( std::set<BOARD_ITEM*>& aOutput,
578 std::shared_ptr<CONNECTIVITY_DATA> aConnectivity,
579 const SHAPE_POLY_SET& aRAPoly, RULE_AREA* aRA,
580 FOOTPRINT* aFp,
581 const REPEAT_LAYOUT_OPTIONS& aOpts ) const
582{
583 std::set<BOARD_ITEM*> conns;
584
585 for( PAD* pad : aFp->Pads() )
586 {
587 const std::vector<BOARD_CONNECTED_ITEM*> connItems = aConnectivity->GetConnectedItems(
589
590 for( BOARD_CONNECTED_ITEM* item : connItems )
591 conns.insert( item );
592 }
593
594 int count = 0;
595
596 for( BOARD_ITEM* item : conns )
597 {
598 // fixme: respect layer sets assigned to each RA
599
600 if( item->Type() == PCB_PAD_T )
601 continue;
602
603 std::shared_ptr<SHAPE> effShape = item->GetEffectiveShape( item->GetLayer() );
604
605 if( effShape->Collide( &aRAPoly, 0 ) )
606 {
607 aOutput.insert( item );
608 count++;
609 }
610 }
611
612 // The user also will consider tracks and vias that are inside the source area but
613 // not connected to any of the source pads to count as "routing" (e.g. stitching vias)
614
616 PCBEXPR_UCODE ucode;
617 PCBEXPR_CONTEXT ctx, preflightCtx;
618
619 auto reportError = [&]( const wxString& aMessage, int aOffset )
620 {
621 wxLogTrace( traceMultichannelTool, wxT( "ERROR: %s"), aMessage );
622 };
623
624 ctx.SetErrorCallback( reportError );
625 preflightCtx.SetErrorCallback( reportError );
626 compiler.SetErrorCallback( reportError );
627
628 bool restoreBlankName = false;
629
630 if( aRA->m_area->GetZoneName().IsEmpty() )
631 {
632 restoreBlankName = true;
633 aRA->m_area->SetZoneName( aRA->m_area->m_Uuid.AsString() );
634 }
635
636 wxString ruleText = wxString::Format( wxT( "A.enclosedByArea('%s')" ),
637 aRA->m_area->GetZoneName() );
638
639 auto testAndAdd =
640 [&]( BOARD_ITEM* aItem )
641 {
642 if( aOutput.contains( aItem ) )
643 return;
644
645 ctx.SetItems( aItem, aItem );
646 auto val = ucode.Run( &ctx );
647
648 if( val->AsDouble() != 0.0 )
649 {
650 aOutput.insert( aItem );
651 count++;
652 }
653 };
654
655 if( compiler.Compile( ruleText, &ucode, &preflightCtx ) )
656 {
657 for( PCB_TRACK* track : board()->Tracks() )
658 testAndAdd( track );
659 }
660
661 if( restoreBlankName )
662 aRA->m_area->SetZoneName( wxEmptyString );
663
664 return count;
665}
666
667
669 BOARD_COMMIT* aCommit,
670 RULE_AREA* aRefArea, RULE_AREA* aTargetArea,
672 std::unordered_set<BOARD_ITEM*>& aAffectedItems,
673 std::unordered_set<BOARD_ITEM*>& aGroupableItems )
674{
675 // copy RA shapes first
676 SHAPE_LINE_CHAIN refOutline = aRefArea->m_area->Outline()->COutline( 0 );
677 SHAPE_LINE_CHAIN targetOutline = aTargetArea->m_area->Outline()->COutline( 0 );
678
679 VECTOR2I disp = aTargetArea->m_center - aRefArea->m_center;
680
681 SHAPE_POLY_SET refPoly;
682 refPoly.AddOutline( refOutline );
683 refPoly.CacheTriangulation( false );
684
685 SHAPE_POLY_SET targetPoly;
686
687 SHAPE_LINE_CHAIN newTargetOutline( refOutline );
688 newTargetOutline.Move( disp );
689 targetPoly.AddOutline( newTargetOutline );
690 targetPoly.CacheTriangulation( false );
691
692 auto connectivity = board()->GetConnectivity();
693
694 aCommit->Modify( aTargetArea->m_area );
695
696 aAffectedItems.insert( aTargetArea->m_area );
697 aGroupableItems.insert( aTargetArea->m_area );
698
699 if( aOpts.m_copyRouting )
700 {
701 std::set<BOARD_ITEM*> refRouting;
702 std::set<BOARD_ITEM*> targetRouting;
703
704 wxLogTrace( traceMultichannelTool, wxT("copying routing: %d fps\n"), (int) aMatches.size() );
705
706 for( auto& fpPair : aMatches )
707 {
708 findRoutedConnections( targetRouting, connectivity, targetPoly, aTargetArea,
709 fpPair.second, aOpts );
710 findRoutedConnections( refRouting, connectivity, refPoly, aRefArea, fpPair.first,
711 aOpts );
712
713 wxLogTrace( traceMultichannelTool, wxT("target-routes %d\n"), (int) targetRouting.size() );
714 }
715
716 for( BOARD_ITEM* item : targetRouting )
717 {
718 if( item->IsLocked() && !aOpts.m_includeLockedItems )
719 continue;
720
721 // item already removed
722 if( aCommit->GetStatus( item ) != 0 )
723 continue;
724
725 if( aTargetArea->m_area->GetLayerSet().Contains( item->GetLayer() ) )
726 {
727 aAffectedItems.insert( item );
728 aCommit->Remove( item );
729 }
730 }
731
732 for( BOARD_ITEM* item : refRouting )
733 {
734 if( !aRefArea->m_area->GetLayerSet().Contains( item->GetLayer() ) )
735 continue;
736
737 if( !aTargetArea->m_area->GetLayerSet().Contains( item->GetLayer() ) )
738 continue;
739
740 BOARD_ITEM* copied = static_cast<BOARD_ITEM*>( item->Clone() );
741
742 copied->Move( disp );
743 copied->SetParentGroup( nullptr );
744 aGroupableItems.insert( copied );
745 aCommit->Add( copied );
746 }
747 }
748
749 if( aOpts.m_copyOtherItems )
750 {
751 std::set<BOARD_ITEM*> sourceItems;
752
753 findOtherItemsInRuleArea( aRefArea->m_area, sourceItems );
754
755 for( BOARD_ITEM* item : sourceItems )
756 {
757 if( !aRefArea->m_area->GetLayerSet().Contains( item->GetLayer() ) )
758 continue;
759
760 if( !aTargetArea->m_area->GetLayerSet().Contains( item->GetLayer() ) )
761 continue;
762
763 // Groups that are fully-contained within the area are added themselves; copy their
764 // items as part of DeepClone rather than explicitly
765 if( item->GetParentGroup() && sourceItems.contains( item->GetParentGroup() ) )
766 continue;
767
768 BOARD_ITEM* copied;
769
770 if( item->Type() == PCB_GROUP_T )
771 {
772 copied = static_cast<PCB_GROUP*>( item )->DeepClone();
773 }
774 else
775 {
776 copied = static_cast<BOARD_ITEM*>( item->Clone() );
777 }
778
779 copied->ClearFlags();
780 copied->SetParentGroup( nullptr );
781 copied->Move( disp );
782 aGroupableItems.insert( copied );
783 aCommit->Add( copied );
784
785 getView()->Query( copied->GetBoundingBox(),
786 [&]( KIGFX::VIEW_ITEM* viewItem ) -> bool
787 {
788 BOARD_ITEM* existingItem = static_cast<BOARD_ITEM*>( viewItem );
789
790 if( existingItem && existingItem->Similarity( *copied ) == 1.0 )
791 aCommit->Remove( existingItem );
792
793 return true;
794 } );
795 }
796 }
797
798 aTargetArea->m_area->RemoveAllContours();
799 aTargetArea->m_area->AddPolygon( newTargetOutline );
800 aTargetArea->m_area->UnHatchBorder();
801 aTargetArea->m_area->HatchBorder();
802
803 if( aOpts.m_copyPlacement )
804 {
805 for( auto& fpPair : aMatches )
806 {
807 FOOTPRINT* refFP = fpPair.first;
808 FOOTPRINT* targetFP = fpPair.second;
809
810 if( !aRefArea->m_area->GetLayerSet().Contains( refFP->GetLayer() ) )
811 {
812 wxLogTrace( traceMultichannelTool, wxT( "discard ref:%s (ref layer)\n" ),
813 refFP->GetReference() );
814 continue;
815 }
816 if( !aTargetArea->m_area->GetLayerSet().Contains( refFP->GetLayer() ) )
817 {
818 wxLogTrace( traceMultichannelTool, wxT( "discard ref:%s (target layer)\n" ),
819 refFP->GetReference() );
820 continue;
821 }
822
823 if( targetFP->IsLocked() && !aOpts.m_includeLockedItems )
824 continue;
825
826 aCommit->Modify( targetFP );
827
828 targetFP->SetLayerAndFlip( refFP->GetLayer() );
829 targetFP->SetOrientation( refFP->GetOrientation() );
830 VECTOR2I targetPos = refFP->GetPosition() + disp;
831 targetFP->SetPosition( targetPos );
832
833 for( PCB_FIELD* refField : refFP->Fields() )
834 {
835 if( !refField->IsVisible() )
836 continue;
837
838 PCB_FIELD* targetField = targetFP->GetFieldById( refField->GetId() );
839 wxCHECK2( targetField, continue );
840
841 targetField->SetAttributes( refField->GetAttributes() );
842 targetField->SetPosition( refField->GetPosition() + disp );
843 targetField->SetIsKnockout( refField->IsKnockout() );
844 }
845
846 aAffectedItems.insert( targetFP );
847 aGroupableItems.insert( targetFP );
848 }
849 }
850
851 return true;
852}
853
854
856 RULE_AREA_COMPAT_DATA& aMatches )
857{
858 using namespace TMATCH;
859
860 std::unique_ptr<CONNECTION_GRAPH> cgRef ( CONNECTION_GRAPH::BuildFromFootprintSet( aRefArea->m_raFootprints ) );
861 std::unique_ptr<CONNECTION_GRAPH> cgTarget ( CONNECTION_GRAPH::BuildFromFootprintSet( aTargetArea->m_raFootprints ) );
862
863 auto status = cgRef->FindIsomorphism( cgTarget.get(), aMatches.m_matchingComponents );
864
865 switch( status )
866 {
867 case CONNECTION_GRAPH::ST_OK:
868 aMatches.m_isOk = true;
869 aMatches.m_errorMsg = _("OK");
870 break;
871 case CONNECTION_GRAPH::ST_EMPTY:
872 aMatches.m_isOk = false;
873 aMatches.m_errorMsg = _("One or both of the areas has no components assigned.");
874 break;
875 case CONNECTION_GRAPH::ST_COMPONENT_COUNT_MISMATCH:
876 aMatches.m_isOk = false;
877 aMatches.m_errorMsg = _("Component count mismatch");
878 break;
879 case CONNECTION_GRAPH::ST_ITERATION_COUNT_EXCEEDED:
880 aMatches.m_isOk = false;
881 aMatches.m_errorMsg = _("Iteration count exceeded (timeout)");
882 break;
883 case CONNECTION_GRAPH::ST_TOPOLOGY_MISMATCH:
884 aMatches.m_isOk = false;
885 aMatches.m_errorMsg = _("Topology mismatch");
886 break;
887 default:
888 break;
889 }
890
891 return ( status == TMATCH::CONNECTION_GRAPH::ST_OK );
892}
893
894
896 const std::unordered_set<BOARD_ITEM*>& aItemsToRemove )
897{
898 for( PCB_GROUP* grp : board()->Groups() )
899 {
900 std::unordered_set<BOARD_ITEM*>& grpItems = grp->GetItems();
901 size_t n_erased = 0;
902
903 for( BOARD_ITEM* refItem : grpItems )
904 {
905 //printf("check ref %p [%s]\n", refItem, refItem->GetTypeDesc().c_str().AsChar() );
906 for( BOARD_ITEM* testItem : aItemsToRemove )
907 {
908 if( refItem->m_Uuid == testItem->m_Uuid )
909 {
910 aCommit.Stage( refItem, CHT_UNGROUP );
911 n_erased++;
912 }
913 }
914 }
915
916 if( n_erased == grpItems.size() )
917 {
918 aCommit.Stage( grp, CHT_REMOVE );
919 }
920
921 //printf("Grp %p items %d pruned %d air %d\n", grp,grpItems.size(), (int) n_erased, (int) aItemsToRemove.size() );
922 }
923
924 return false;
925}
926
927
929{
930 if( Pgm().IsGUI() )
931 {
933
934 if( m_areas.m_areas.size() <= 1 )
935 {
936 frame()->ShowInfoBarError( _( "Cannot auto-generate any placement areas because the "
937 "schematic has only one or no hierarchical sheet(s) or "
938 "component classes." ),
939 true );
940 return 0;
941 }
942
944 int ret = dialog.ShowModal();
945
946 if( ret != wxID_OK )
947 return 0;
948 }
949
950 for( ZONE* zone : board()->Zones() )
951 {
952 if( !zone->GetIsRuleArea() )
953 continue;
954 if( !zone->GetRuleAreaPlacementEnabled() )
955 continue;
956
957 std::set<FOOTPRINT*> components;
958 identifyComponentsInRuleArea( zone, components );
959
960 if( components.empty() )
961 continue;
962
963 for( RULE_AREA& ra : m_areas.m_areas )
964 {
965 if( components == ra.m_components )
966 {
967 if( zone->GetRuleAreaPlacementSourceType()
968 == RULE_AREA_PLACEMENT_SOURCE_TYPE::SHEETNAME )
969 {
970 wxLogTrace(
972 wxT( "Placement rule area for sheet '%s' already exists as '%s'\n" ),
973 ra.m_sheetPath, zone->GetZoneName() );
974 }
975 else
976 {
977 wxLogTrace( traceMultichannelTool,
978 wxT( "Placement rule area for component class '%s' already exists "
979 "as '%s'\n" ),
980 ra.m_componentClass, zone->GetZoneName() );
981 }
982
983 ra.m_oldArea = zone;
984 ra.m_existsAlready = true;
985 }
986 }
987 }
988
989 wxLogTrace( traceMultichannelTool,
990 wxT( "%d placement areas found\n" ), (int) m_areas.m_areas.size() );
991
992 BOARD_COMMIT commit( GetManager(), true );
993
994 for( RULE_AREA& ra : m_areas.m_areas )
995 {
996 if( !ra.m_generateEnabled )
997 continue;
998
1000 continue;
1001
1002 SHAPE_LINE_CHAIN raOutline = buildRAOutline( ra.m_components, 100000 );
1003
1004 std::unique_ptr<ZONE> newZone( new ZONE( board() ) );
1005
1006 if( ra.m_sourceType == RULE_AREA_PLACEMENT_SOURCE_TYPE::SHEETNAME )
1007 {
1008 newZone->SetZoneName(
1009 wxString::Format( wxT( "auto-placement-area-%s" ), ra.m_sheetPath ) );
1010 }
1011 else
1012 {
1013 newZone->SetZoneName(
1014 wxString::Format( wxT( "auto-placement-area-%s" ), ra.m_componentClass ) );
1015 }
1016
1017 wxLogTrace( traceMultichannelTool, wxT( "Generated rule area '%s' (%d components)\n" ),
1018 newZone->GetZoneName(), (int) ra.m_components.size() );
1019
1020 newZone->SetIsRuleArea( true );
1021 newZone->SetLayerSet( LSET::AllCuMask() );
1022 newZone->SetRuleAreaPlacementEnabled( true );
1023 newZone->SetDoNotAllowCopperPour( false );
1024 newZone->SetDoNotAllowVias( false );
1025 newZone->SetDoNotAllowTracks( false );
1026 newZone->SetDoNotAllowPads( false );
1027 newZone->SetDoNotAllowFootprints( false );
1028
1029 if( ra.m_sourceType == RULE_AREA_PLACEMENT_SOURCE_TYPE::SHEETNAME )
1030 {
1031 newZone->SetRuleAreaPlacementSourceType( RULE_AREA_PLACEMENT_SOURCE_TYPE::SHEETNAME );
1032 newZone->SetRuleAreaPlacementSource( ra.m_sheetPath );
1033 }
1034 else
1035 {
1036 newZone->SetRuleAreaPlacementSourceType(
1037 RULE_AREA_PLACEMENT_SOURCE_TYPE::COMPONENT_CLASS );
1038 newZone->SetRuleAreaPlacementSource( ra.m_componentClass );
1039 }
1040
1041 newZone->AddPolygon( raOutline );
1042 newZone->SetHatchStyle( ZONE_BORDER_DISPLAY_STYLE::NO_HATCH );
1043
1044 if( ra.m_existsAlready )
1045 {
1046 commit.Remove( ra.m_oldArea );
1047 }
1048
1049 ra.m_area = newZone.get();
1050 commit.Add( newZone.release() );
1051
1052 }
1053
1054 commit.Push( _( "Auto-generate placement rule areas" ) );
1055
1056 // fixme: handle corner cases where the items belonging to a Rule Area already
1057 // belong to other groups.
1058
1060 {
1061 // fixme: sth gets weird when creating new zones & grouping them within a single COMMIT
1062 BOARD_COMMIT grpCommit( GetManager(), true );
1063
1064 for( RULE_AREA& ra : m_areas.m_areas )
1065 {
1066 if( !ra.m_generateEnabled )
1067 continue;
1068
1070 continue;
1071
1072 std::unordered_set<BOARD_ITEM*> toPrune;
1073
1074 std::copy( ra.m_components.begin(), ra.m_components.end(),
1075 std::inserter( toPrune, toPrune.begin() ) );
1076
1077 if( ra.m_existsAlready )
1078 toPrune.insert( ra.m_area );
1079
1080 pruneExistingGroups( grpCommit, toPrune );
1081
1082 PCB_GROUP* grp = new PCB_GROUP( board() );
1083
1084 grpCommit.Add( grp );
1085 grpCommit.Stage( ra.m_area, CHT_GROUP );
1086
1087 for( FOOTPRINT* fp : ra.m_components )
1088 {
1089 grpCommit.Stage( fp, CHT_GROUP );
1090 }
1091 }
1092 grpCommit.Push( _( "Group components with their placement rule areas" ) );
1093 }
1094
1095 return true;
1096}
virtual void Push(const wxString &aMessage=wxEmptyString, int aCommitFlags=0) override
Revert the commit by restoring the modified items state.
COMMIT & Stage(EDA_ITEM *aItem, CHANGE_TYPE aChangeType, BASE_SCREEN *aScreen=nullptr) override
virtual void Revert() override
A base class derived from BOARD_ITEM for items that can be connected and have a net,...
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 Move(const VECTOR2I &aMoveVector)
Move this object.
Definition: board_item.h:342
virtual void SetIsKnockout(bool aKnockout)
Definition: board_item.h:325
const ZONES & Zones() const
Definition: board.h:335
const TRACKS & Tracks() const
Definition: board.h:329
std::shared_ptr< CONNECTIVITY_DATA > GetConnectivity() const
Return a list of missing connections between components/tracks.
Definition: board.h:475
constexpr BOX2< Vec > GetInflated(coord_type aDx, coord_type aDy) const
Get a new rectangle that is this one, inflated by aDx and aDy.
Definition: box2.h:638
Represent a set of changes (additions, deletions or modifications) of a data model (e....
Definition: commit.h:74
COMMIT & Remove(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Notify observers that aItem has been removed.
Definition: commit.h:92
virtual COMMIT & Stage(EDA_ITEM *aItem, CHANGE_TYPE aChangeType, BASE_SCREEN *aScreen=nullptr)
Definition: commit.cpp:48
COMMIT & Modify(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Create an undo entry for an item that has been already modified.
Definition: commit.h:105
COMMIT & Add(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Notify observers that aItem has been added.
Definition: commit.h:80
int GetStatus(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Definition: commit.cpp:130
const std::vector< COMPONENT_CLASS * > & GetConstituentClasses() const
Fetches a vector of the constituent classes for this (effective) class.
int ShowModal() override
A base class for most all the KiCad significant classes used in schematics and boards.
Definition: eda_item.h:89
virtual const BOX2I GetBoundingBox() const
Return the orthogonal bounding box of this object for display purposes.
Definition: eda_item.cpp:77
const KIID m_Uuid
Definition: eda_item.h:489
void ClearFlags(EDA_ITEM_FLAGS aMask=EDA_ITEM_ALL_FLAGS)
Definition: eda_item.h:129
virtual bool IsType(const std::vector< KICAD_T > &aScanTypes) const
Check whether the item is one of the listed types.
Definition: eda_item.h:176
void SetAttributes(const EDA_TEXT &aSrc, bool aSetPosition=true)
Set the text attributes from another instance.
Definition: eda_text.cpp:424
void SetPosition(const VECTOR2I &aPos) override
Definition: footprint.cpp:2388
EDA_ANGLE GetOrientation() const
Definition: footprint.h:227
void SetOrientation(const EDA_ANGLE &aNewAngle)
Definition: footprint.cpp:2458
std::deque< PAD * > & Pads()
Definition: footprint.h:206
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
Definition: footprint.h:236
PCB_FIELD * GetFieldById(int aFieldId)
Return a field in this symbol.
Definition: footprint.cpp:567
bool IsLocked() const override
Definition: footprint.h:411
void SetLayerAndFlip(PCB_LAYER_ID aLayer)
Used as Layer property setter – performs a flip if necessary to set the footprint layer.
Definition: footprint.cpp:2321
PCB_FIELDS & Fields()
Definition: footprint.h:203
const wxString & GetReference() const
Definition: footprint.h:622
VECTOR2I GetPosition() const override
Definition: footprint.h:224
An abstract base class for deriving all objects that can be added to a VIEW.
Definition: view_item.h:84
int Query(const BOX2I &aRect, std::vector< LAYER_ITEM_PAIR > &aResult) const
Find all visible items that touch or are within the rectangle aRect.
Definition: view.cpp:412
wxString AsString() const
Definition: kiid.cpp:238
void SetErrorCallback(std::function< void(const wxString &aMessage, int aOffset)> aCallback)
bool Compile(const wxString &aString, UCODE *aCode, CONTEXT *aPreflightContext)
void SetErrorCallback(std::function< void(const wxString &aMessage, int aOffset)> aCallback)
VALUE * Run(CONTEXT *ctx)
static LSET AllCuMask(int aCuLayerCount=MAX_CU_LAYERS)
Return a mask holding the requested number of Cu PCB_LAYER_IDs.
Definition: lset.cpp:686
bool Contains(PCB_LAYER_ID aLayer) const
See if the layer set contains a PCB layer.
Definition: lset.h:62
int CheckRACompatibility(ZONE *aRefZone)
std::set< FOOTPRINT * > queryComponentsInSheet(wxString aSheetName) const
int findRoutedConnections(std::set< BOARD_ITEM * > &aOutput, std::shared_ptr< CONNECTIVITY_DATA > aConnectivity, const SHAPE_POLY_SET &aRAPoly, RULE_AREA *aRA, FOOTPRINT *aFp, const REPEAT_LAYOUT_OPTIONS &aOpts) const
int repeatLayout(const TOOL_EVENT &aEvent)
void UpdatePickedItem(const EDA_ITEM *aItem) override
void setTransitions() override
This method is meant to be overridden in order to specify handlers for events.
const SHAPE_LINE_CHAIN buildRAOutline(std::set< FOOTPRINT * > &aFootprints, int aMargin)
wxString stripComponentIndex(const wxString &aRef) const
bool resolveConnectionTopology(RULE_AREA *aRefArea, RULE_AREA *aTargetArea, RULE_AREA_COMPAT_DATA &aMatches)
RULE_AREAS_DATA m_areas
bool pruneExistingGroups(COMMIT &aCommit, const std::unordered_set< BOARD_ITEM * > &aItemsToCheck)
int RepeatLayout(const TOOL_EVENT &aEvent, ZONE *aRefZone)
int AutogenerateRuleAreas(const TOOL_EVENT &aEvent)
bool identifyComponentsInRuleArea(ZONE *aRuleArea, std::set< FOOTPRINT * > &aComponents)
std::set< FOOTPRINT * > queryComponentsInComponentClass(const wxString &aComponentClassName) const
RULE_AREA * findRAByName(const wxString &aName)
bool copyRuleAreaContents(TMATCH::COMPONENT_MATCHES &aMatches, BOARD_COMMIT *aCommit, RULE_AREA *aRefArea, RULE_AREA *aTargetArea, REPEAT_LAYOUT_OPTIONS aOpts, std::unordered_set< BOARD_ITEM * > &aAffectedItems, std::unordered_set< BOARD_ITEM * > &aGroupableItems)
bool findOtherItemsInRuleArea(ZONE *aRuleArea, std::set< BOARD_ITEM * > &aItems)
Definition: pad.h:54
void SetItems(BOARD_ITEM *a, BOARD_ITEM *b=nullptr)
static TOOL_ACTION repeatLayout
Definition: pcb_actions.h:592
static TOOL_ACTION generatePlacementRuleAreas
Definition: pcb_actions.h:593
static TOOL_ACTION selectItemInteractively
Selection of reference points/items.
Definition: pcb_actions.h:331
A set of BOARD_ITEMs (i.e., without duplicates).
Definition: pcb_group.h:52
virtual void SetPosition(const VECTOR2I &aPos) override
Definition: pcb_text.h:87
T * frame() const
BOARD * board() const
const PCB_SELECTION & selection() const
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
Represent a set of closed polygons.
int AddOutline(const SHAPE_LINE_CHAIN &aOutline)
Adds a new outline to the set and returns its index.
virtual void CacheTriangulation(bool aPartition=true, bool aSimplify=false)
Build a polygon triangulation, needed to draw a polygon on OpenGL and in some other calculations.
const SHAPE_LINE_CHAIN & COutline(int aIndex) const
TOOL_MANAGER * GetManager() const
Return the instance of TOOL_MANAGER that takes care of the tool.
Definition: tool_base.h:146
TOOL_MANAGER * m_toolMgr
Definition: tool_base.h:218
KIGFX::VIEW * getView() const
Returns the instance of #VIEW object used in the application.
Definition: tool_base.cpp:36
Generic, UI-independent tool event.
Definition: tool_event.h:167
void Go(int(T::*aStateFunc)(const TOOL_EVENT &), const TOOL_EVENT_LIST &aConditions=TOOL_EVENT(TC_ANY, TA_ANY))
Define which state (aStateFunc) to go when a certain event arrives (aConditions).
bool RunAction(const std::string &aActionName, T aParam)
Run the specified action immediately, pausing the current action to run the new one.
Definition: tool_manager.h:150
Handle a list of polygons defining a copper zone.
Definition: zone.h:73
bool GetIsRuleArea() const
Accessors to parameters used in Rule Area zones:
Definition: zone.h:724
wxString GetRuleAreaPlacementSource() const
Definition: zone.h:730
void AddPolygon(std::vector< VECTOR2I > &aPolygon)
Add a polygon to the zone outline.
Definition: zone.cpp:1014
void HatchBorder()
Compute the hatch lines depending on the hatch parameters and stores it in the zone's attribute m_bor...
Definition: zone.cpp:1140
bool GetRuleAreaPlacementEnabled() const
Definition: zone.h:725
SHAPE_POLY_SET * Outline()
Definition: zone.h:340
const wxString & GetZoneName() const
Definition: zone.h:135
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition: zone.h:133
RULE_AREA_PLACEMENT_SOURCE_TYPE GetRuleAreaPlacementSourceType() const
Definition: zone.h:726
void SetZoneName(const wxString &aName)
Definition: zone.h:136
void UnHatchBorder()
Clear the zone's hatch.
Definition: zone.cpp:1126
void RemoveAllContours(void)
Definition: zone.h:554
@ CHT_GROUP
Definition: commit.h:45
@ CHT_REMOVE
Definition: commit.h:43
@ CHT_UNGROUP
Definition: commit.h:46
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
#define _(s)
static const wxString traceMultichannelTool
SHAPE_LINE_CHAIN RectifyPolygon(const SHAPE_LINE_CHAIN &aPoly)
void CollectBoxCorners(const BOX2I &aBox, std::vector< VECTOR2I > &aCorners)
Add the 4 corners of a BOX2I to a vector.
Definition: shape_utils.cpp:84
std::map< FOOTPRINT *, FOOTPRINT * > COMPONENT_MATCHES
Definition: topo_match.h:149
Class to handle a set of BOARD_ITEMs.
PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: pgm_base.cpp:1060
see class PGM_BASE
Utility functions for working with shapes.
std::unordered_map< RULE_AREA *, RULE_AREA_COMPAT_DATA > m_compatMap
REPEAT_LAYOUT_OPTIONS m_options
std::vector< RULE_AREA > m_areas
TMATCH::COMPONENT_MATCHES m_matchingComponents
VECTOR2I m_center
RULE_AREA_PLACEMENT_SOURCE_TYPE m_sourceType
wxString m_sheetName
wxString m_componentClass
bool m_existsAlready
std::set< FOOTPRINT * > m_raFootprints
ZONE * m_oldArea
std::set< FOOTPRINT * > m_components
wxString m_ruleName
wxString m_sheetPath
bool m_generateEnabled
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
Definition: typeinfo.h:88
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
Definition: typeinfo.h:97
@ PCB_GROUP_T
class PCB_GROUP, a set of BOARD_ITEMs
Definition: typeinfo.h:110
@ PCB_ZONE_T
class ZONE, a copper pour area
Definition: typeinfo.h:107
@ PCB_PAD_T
class PAD, a pad in a footprint
Definition: typeinfo.h:87
@ PCB_ARC_T
class PCB_ARC, an arc track segment on a copper layer
Definition: typeinfo.h:98
@ PCB_TRACE_T
class PCB_TRACK, a track segment (segment on a copper layer)
Definition: typeinfo.h:96