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 The KiCad Developers, see AUTHORS.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, see <https://www.gnu.org/licenses/>.
18 */
19
20
21#include <board_commit.h>
22#include <tools/pcb_actions.h>
23#include <tools/pcb_selection.h>
25#include <tool/action_menu.h>
28#include <tool/tool_menu.h>
29#include <bitmaps.h>
30#include <eda_group.h>
31
34
35#include "multichannel_tool.h"
36
37#include <pcbexpr_evaluator.h>
38
39#include <zone.h>
40#include <board.h>
41#include <netinfo.h>
45#include <pcb_group.h>
46#include <pcb_generator.h>
47#include <footprint.h>
48#include <pad.h>
49#include <pcb_text.h>
54#include <algorithm>
55#include <pcb_track.h>
56#include <tool/tool_manager.h>
59#include <router/router_tool.h>
60#include <router/pns_router.h>
61#include <geometry/shape_rect.h>
62#include <scoped_set_reset.h>
63#include <trigo.h>
64#include <chrono>
65#include <future>
66#include <core/profile.h>
67#include <core/raii.h>
69#include <string_utils.h>
70#include <wx/log.h>
71#include <wx/richmsgdlg.h>
72#include <pgm_base.h>
73
74
75#define MULTICHANNEL_EXTRA_DEBUG
76
77static const wxString traceMultichannelTool = wxT( "MULTICHANNEL_TOOL" );
78
79
80static wxString FormatComponentList( const std::set<FOOTPRINT*>& aComponents )
81{
82 std::vector<wxString> refs;
83
84 for( FOOTPRINT* fp : aComponents )
85 {
86 if( !fp )
87 continue;
88
89 refs.push_back( fp->GetReferenceAsString() );
90 }
91
92 std::sort( refs.begin(), refs.end(),
93 []( const wxString& aLhs, const wxString& aRhs )
94 {
95 return aLhs.CmpNoCase( aRhs ) < 0;
96 } );
97
98 if( refs.empty() )
99 return _( "(none)" );
100
101 wxString result;
102 wxString line;
103 size_t componentsOnLine = 0;
104
105 for( const wxString& ref : refs )
106 {
107 if( componentsOnLine == 10 )
108 {
109 if( !result.IsEmpty() )
110 result += wxT( "\n" );
111
112 result += line;
113 line.clear();
114 componentsOnLine = 0;
115 }
116
117 AccumulateDescription( line, ref );
118 componentsOnLine++;
119 }
120
121 if( !line.IsEmpty() )
122 {
123 if( !result.IsEmpty() )
124 result += wxT( "\n" );
125
126 result += line;
127 }
128
129 return result;
130}
131
132
133static wxString JoinMismatchReasons( const std::vector<wxString>& aReasons )
134{
135 wxString text;
136
137 for( const wxString& reason : aReasons )
138 {
139 if( !text.IsEmpty() )
140 text += wxT( "\n" );
141
142 text += reason;
143 }
144
145 return text;
146}
147
148
149static void ShowTopologyMismatchReasons( wxWindow* aParent, const wxString& aSummary,
150 const std::vector<wxString>& aReasons )
151{
152 if( !aParent || aReasons.empty() )
153 return;
154
155 wxRichMessageDialog dlg( aParent, aSummary, _( "Topology mismatch" ), wxICON_ERROR | wxOK );
156 dlg.ShowDetailedText( JoinMismatchReasons( aReasons ) );
157 dlg.ShowModal();
158}
159
160
161static void collectGroupFootprints( EDA_GROUP* aGroup, std::set<FOOTPRINT*>& aOut )
162{
163 for( EDA_ITEM* item : aGroup->GetItems() )
164 {
165 if( item->Type() == PCB_FOOTPRINT_T )
166 aOut.insert( static_cast<FOOTPRINT*>( item ) );
167 else if( item->Type() == PCB_GROUP_T )
168 collectGroupFootprints( static_cast<PCB_GROUP*>( item ), aOut );
169 }
170}
171
172
173static void collectGroupBoardItems( EDA_GROUP* aGroup, std::set<BOARD_ITEM*>& aOut )
174{
175 for( EDA_ITEM* item : aGroup->GetItems() )
176 {
177 // A generator's own bounding box already covers its children (meander arcs).
178 if( item->Type() == PCB_GROUP_T )
179 collectGroupBoardItems( static_cast<PCB_GROUP*>( item ), aOut );
180 else if( item->IsBOARD_ITEM() )
181 aOut.insert( static_cast<BOARD_ITEM*>( item ) );
182 }
183}
184
185
186// A linked channel made with its items grouped is exactly its group, so an update repeats what the first copy did
187static EDA_GROUP* linkedChannelGroup( const BOARD* aBoard, const RULE_AREA* aArea )
188{
189 ZONE* zone = aArea->m_zone;
190
191 if( !zone || aArea->m_sourceType == PLACEMENT_SOURCE_T::DESIGN_BLOCK || zone->GetLinkSet() == niluuid
192 || !zone->GetRepeatOptions().m_groupItems )
193 {
194 return nullptr;
195 }
196
197 // Scratch zones carry the board pointer too, so membership is by the board's own index
198 if( aBoard->ResolveItem( zone->m_Uuid, true ) != zone )
199 return nullptr;
200
201 return zone->GetParentGroup();
202}
203
204
206{
207}
208
209
214
215
217{
218 PCB_TOOL_BASE::Reset( aReason );
219
220 if( aReason == MODEL_RELOAD || aReason == SUPERMODEL_RELOAD || aReason == SHUTDOWN )
222}
223
224static void makePlacementArea( ZONE* aZone, const SHAPE_LINE_CHAIN& aOutline )
225{
226 aZone->SetIsRuleArea( true );
227 aZone->SetLayerSet( LSET::AllCuMask() );
228 aZone->SetPlacementAreaEnabled( true );
229 aZone->SetDoNotAllowZoneFills( false );
230 aZone->SetDoNotAllowVias( false );
231 aZone->SetDoNotAllowTracks( false );
232 aZone->SetDoNotAllowPads( false );
233 aZone->SetDoNotAllowFootprints( false );
234 aZone->AddPolygon( aOutline );
236}
237
238
239// Touching edges do not count, so channels may share a border
240static bool outlinesOverlap( const SHAPE_POLY_SET& aA, const SHAPE_POLY_SET& aB )
241{
242 if( !aA.BBox().Intersects( aB.BBox() ) )
243 return false;
244
245 SHAPE_POLY_SET overlap = aA;
246 overlap.BooleanIntersection( aB );
247 return !overlap.IsEmpty();
248}
249
250
251// The matched pair whose reference part sorts first, so the choice does not follow heap addresses
252static const std::pair<FOOTPRINT* const, FOOTPRINT*>& firstPair( const TMATCH::COMPONENT_MATCHES& aMatches )
253{
254 return *std::ranges::min_element( aMatches,
255 []( const auto& aA, const auto& aB )
256 {
257 FOOTPRINT* a = aA.first;
258 FOOTPRINT* b = aB.first;
259
260 if( int cmp = StrNumCmp( a->GetReference(), b->GetReference() ) )
261 return cmp < 0;
262
263 return std::tuple( a->GetPosition().x, a->GetPosition().y, a->m_Uuid )
264 < std::tuple( b->GetPosition().x, b->GetPosition().y, b->m_Uuid );
265 } );
266}
267
268
269// The matched pair holding the anchor footprint. An anchor outside the reference area falls back to the
270// first pair, so the group is not shifted to center alignment
271static const std::pair<FOOTPRINT* const, FOOTPRINT*>& anchorPair( const TMATCH::COMPONENT_MATCHES& aMatches,
272 const KIID& aAnchor )
273{
274 auto it = std::ranges::find_if( aMatches, [&]( const auto& aPair ) { return aPair.first->m_Uuid == aAnchor; } );
275 return it != aMatches.end() ? *it : firstPair( aMatches );
276}
277
278
279// The outline aTarget takes on when aRef is repeated onto it, and the transform that produces it
280static SHAPE_LINE_CHAIN repeatedOutline( const RULE_AREA* aRef, const RULE_AREA* aTarget, const KIID& aAnchor,
281 const TMATCH::COMPONENT_MATCHES& aMatches, VECTOR2I& aDisp, EDA_ANGLE& aRot )
282{
283 aDisp = aTarget->m_center - aRef->m_center;
284 aRot = ANGLE_0;
285
286 if( aAnchor != niluuid && !aMatches.empty() )
287 {
288 const auto& [refAnchorFp, targetAnchorFp] = anchorPair( aMatches, aAnchor );
289 VECTOR2I oldpos = refAnchorFp->GetPosition();
290
291 aRot = targetAnchorFp->GetOrientation() - refAnchorFp->GetOrientation();
292 RotatePoint( oldpos, aRot );
293 aDisp = targetAnchorFp->GetPosition() - oldpos;
294 }
295
296 SHAPE_LINE_CHAIN outline( aRef->m_zone->Outline()->COutline( 0 ) );
297 outline.Rotate( aRot, VECTOR2I( 0, 0 ) );
298 outline.Move( aDisp );
299 return outline;
300}
301
302
303// The linked rule areas the selection stands for, whether as the area, a group holding it or a part of its channel
304static std::set<ZONE*> linkedAreasIn( const SELECTION& aSelection )
305{
306 std::set<ZONE*> zones;
307
308 auto asLinked = []( EDA_ITEM* aItem ) -> ZONE*
309 {
310 if( aItem->Type() != PCB_ZONE_T )
311 return nullptr;
312
313 ZONE* zone = static_cast<ZONE*>( aItem );
314 return zone->GetIsRuleArea() && zone->GetLinkSet() != niluuid ? zone : nullptr;
315 };
316
317 // True when the group directly holds a linked area
318 auto addFrom = [&]( EDA_GROUP* aGroup )
319 {
320 bool found = false;
321
322 for( EDA_ITEM* child : aGroup->GetItems() )
323 {
324 if( ZONE* zone = asLinked( child ) )
325 {
326 zones.insert( zone );
327 found = true;
328 }
329 }
330
331 return found;
332 };
333
334 for( EDA_ITEM* item : aSelection )
335 {
336 // What is selected by name wins over the channels around it
337 if( ZONE* zone = asLinked( item ) )
338 {
339 zones.insert( zone );
340 continue;
341 }
342
343 EDA_GROUP* group = item->Type() == PCB_GROUP_T ? static_cast<PCB_GROUP*>( item ) : item->GetParentGroup();
344
345 while( group && !addFrom( group ) )
346 group = group->AsEdaItem()->GetParentGroup();
347 }
348
349 return zones;
350}
351
352
354{
355 for( EDA_ITEM* child : aGroup->GetItems() )
356 {
357 if( child->Type() == PCB_ZONE_T )
358 {
359 ZONE* zone = static_cast<ZONE*>( child );
360
361 if( zone->GetIsRuleArea() && zone->GetPlacementAreaEnabled() )
362 return zone;
363 }
364 }
365
366 return nullptr;
367}
368
369
371{
372public:
374 {
376 SetTitle( _( "Multi-Channel" ) );
377
378 // A channel is repeated again through its Properties
379 auto offChannel =
380 []( const SELECTION& aSelection )
381 {
382 for( EDA_ITEM* item : aSelection )
383 {
384 if( item->Type() != PCB_GROUP_T )
385 continue;
386
387 if( MULTICHANNEL_TOOL::ChannelZone( static_cast<PCB_GROUP*>( item ) ) )
388 return false;
389 }
390
391 return true;
392 };
393
394 auto oneLinked = []( const SELECTION& aSelection ) { return linkedAreasIn( aSelection ).size() == 1; };
395 auto anyLinked = []( const SELECTION& aSelection ) { return !linkedAreasIn( aSelection ).empty(); };
396
399 AddItem( PCB_ACTIONS::repeatLayout, offChannel );
402 }
403
404 ACTION_MENU* create() const override { return new MULTICHANNEL_CONTEXT_MENU( m_tool ); }
405};
406
407
408void MULTICHANNEL_TOOL::ShowMismatchDetails( wxWindow* aParent, const wxString& aSummary,
409 const std::vector<wxString>& aReasons ) const
410{
411 wxWindow* parent = aParent ? aParent : frame();
412 ShowTopologyMismatchReasons( parent, aSummary, aReasons );
413}
414
415
417{
418 PCB_SELECTION_TOOL* selTool = m_toolMgr->GetTool<PCB_SELECTION_TOOL>();
419 wxCHECK( selTool, false );
420
421 TOOL_MENU& selToolMenu = selTool->GetToolMenu();
422
423 std::shared_ptr<MULTICHANNEL_CONTEXT_MENU> menu = std::make_shared<MULTICHANNEL_CONTEXT_MENU>( this );
424 selToolMenu.RegisterSubMenu( menu );
425
426 selToolMenu.GetMenu().AddMenu( menu.get(),
427 SELECTION_CONDITIONS::HasTypes( { PCB_FOOTPRINT_T, PCB_GROUP_T, PCB_ZONE_T } ),
428 100 );
429
430 return true;
431}
432
433
443
444
446 std::set<FOOTPRINT*>& aComponents )
447{
448 if( !aRuleArea || !aRuleArea->m_zone )
449 return false;
450
451 // When we're copying the layout of a design block, we are provided an exact list of items
452 // rather than querying the board for items that are inside the area.
454 {
455 // Get all board connected items that are from the design bloc
456 for( EDA_ITEM* item : aRuleArea->m_designBlockItems )
457 {
458 if( item->Type() == PCB_FOOTPRINT_T )
459 aComponents.insert( static_cast<FOOTPRINT*>( item ) );
460 }
461
462 return (int) aComponents.size();
463 }
464
465
467 PCBEXPR_UCODE ucode;
468 PCBEXPR_CONTEXT ctx, preflightCtx;
469
470 auto reportError =
471 [&]( const wxString& aMessage, int aOffset )
472 {
473 wxLogTrace( traceMultichannelTool, wxT( "ERROR: %s"), aMessage );
474 };
475
476 ctx.SetErrorCallback( reportError );
477 preflightCtx.SetErrorCallback( reportError );
478 compiler.SetErrorCallback( reportError );
479 //compiler.SetDebugReporter( m_reporter );
480
481 wxLogTrace( traceMultichannelTool, wxT( "rule area '%s'" ), aRuleArea->m_zone->GetZoneName() );
482
483 wxString sourceName = aRuleArea->m_zone->GetPlacementAreaSource();
484 sourceName.Replace( wxT( "'" ), wxT( "\\'" ) );
485
486 wxString ruleText;
487
488 switch( aRuleArea->m_zone->GetPlacementAreaSourceType() )
489 {
491 ruleText = wxT( "A.memberOfSheetOrChildren('" ) + sourceName + wxT( "')" );
492 break;
494 ruleText = wxT( "A.hasComponentClass('" ) + sourceName + wxT( "')" );
495 break;
497 ruleText = wxT( "A.memberOfGroup('" ) + sourceName + wxT( "')" );
498 break;
500 // For design blocks, handled above outside the rules system
501 break;
502 }
503
504 auto ok = compiler.Compile( ruleText, &ucode, &preflightCtx );
505
506 if( !ok )
507 return false;
508
509 for( FOOTPRINT* fp : board()->Footprints() )
510 {
511 ctx.SetItems( fp, fp );
512 LIBEVAL::VALUE* val = ucode.Run( &ctx );
513
514 if( val->AsDouble() != 0.0 )
515 {
516 wxLogTrace( traceMultichannelTool, wxT( " - %s [sheet %s]" ),
517 fp->GetReference(),
518 fp->GetSheetname() );
519
520 aComponents.insert( fp );
521 }
522 }
523
524 return true;
525}
526
527
528bool MULTICHANNEL_TOOL::findOtherItemsInRuleArea( RULE_AREA* aRuleArea, std::set<BOARD_ITEM*>& aItems )
529{
530 if( !aRuleArea || !aRuleArea->m_zone )
531 return false;
532
533 // When we're copying the layout of a design block, we are provided an exact list of items
534 // rather than querying the board for items that are inside the area.
536 {
537 // Get all board items that aren't footprints. Connected items are usually handled by the
538 // routing path, except zones which are copied via "other items".
539 for( EDA_ITEM* item : aRuleArea->m_designBlockItems )
540 {
541 if( item->Type() == PCB_FOOTPRINT_T )
542 continue;
543
544 // Generators are copied whole by the routing pass. Nested groups are not yet
545 // preserved (TODO) so they are skipped here.
546 if( item->Type() == PCB_GROUP_T || item->Type() == PCB_GENERATOR_T )
547 continue;
548
549 // Cells are copied with their owning PCB_TABLE, not as standalone items.
550 if( item->Type() == PCB_TABLECELL_T )
551 continue;
552
553 if( BOARD_ITEM* boardItem = dynamic_cast<BOARD_ITEM*>( item ) )
554 {
555 if( !boardItem->IsConnected() || boardItem->Type() == PCB_ZONE_T )
556 aItems.insert( boardItem );
557 }
558 }
559
560 if( aRuleArea->m_fromSelection )
561 {
562 const BOX2I areaBox = aRuleArea->m_zone->Outline()->BBox();
563
564 auto inside =
565 [&]( BOARD_ITEM* aItem )
566 {
567 return ( aRuleArea->m_zone->GetLayerSet() & aItem->GetLayerSet() ).any()
568 && areaBox.Contains( aItem->GetBoundingBox() );
569 };
570
571 for( ZONE* zone : board()->Zones() )
572 {
573 if( !zone->GetIsRuleArea() && inside( zone ) )
574 aItems.insert( zone );
575 }
576
577 for( BOARD_ITEM* drawing : board()->Drawings() )
578 {
579 if( !drawing->IsConnected() && !drawing->GetParentGroup() && inside( drawing ) )
580 aItems.insert( drawing );
581 }
582 }
583
584 return aItems.size() > 0;
585 }
586
587 if( EDA_GROUP* group = linkedChannelGroup( board(), aRuleArea ) )
588 {
589 std::set<BOARD_ITEM*> members;
590 collectGroupBoardItems( group, members );
591
592 for( BOARD_ITEM* boardItem : members )
593 {
594 if( boardItem == aRuleArea->m_zone || boardItem->Type() == PCB_FOOTPRINT_T
595 || boardItem->Type() == PCB_GENERATOR_T || boardItem->Type() == PCB_TABLECELL_T )
596 {
597 continue;
598 }
599
600 if( !boardItem->IsConnected() || boardItem->Type() == PCB_ZONE_T )
601 aItems.insert( boardItem );
602 }
603
604 return true;
605 }
606
607 // The design-block apply target uses a scratch zone not on the board, so enclosedByArea()
608 // below finds nothing. Resolve the group's items directly from the group.
610 && ( !aRuleArea->m_components.empty() || aRuleArea->m_group ) )
611 {
612 bool zoneOnBoard = false;
613
614 for( ZONE* zone : board()->Zones() )
615 {
616 if( zone == aRuleArea->m_zone )
617 {
618 zoneOnBoard = true;
619 break;
620 }
621 }
622
623 if( !zoneOnBoard )
624 {
625 EDA_GROUP* group = aRuleArea->m_group;
626
627 if( !group && !aRuleArea->m_components.empty() )
628 group = ( *aRuleArea->m_components.begin() )->GetParentGroup();
629
630 if( group )
631 {
632 std::set<BOARD_ITEM*> members;
633 collectGroupBoardItems( group, members );
634
635 for( BOARD_ITEM* boardItem : members )
636 {
637 if( boardItem->Type() == PCB_FOOTPRINT_T || boardItem->Type() == PCB_GENERATOR_T
638 || boardItem->Type() == PCB_TABLECELL_T )
639 continue;
640
641 if( !boardItem->IsConnected() || boardItem->Type() == PCB_ZONE_T )
642 aItems.insert( boardItem );
643 }
644 }
645
646 return aItems.size() > 0;
647 }
648 }
649
651 PCBEXPR_UCODE ucode;
652 PCBEXPR_CONTEXT ctx, preflightCtx;
653
654 auto reportError =
655 [&]( const wxString& aMessage, int aOffset )
656 {
657 wxLogTrace( traceMultichannelTool, wxT( "ERROR: %s"), aMessage );
658 };
659
660 ctx.SetErrorCallback( reportError );
661 preflightCtx.SetErrorCallback( reportError );
662 compiler.SetErrorCallback( reportError );
663
664 // Use the zone's UUID to identify it uniquely. Using the zone name could match other zones
665 // with the same name (e.g., a copper fill zone with the same name as a rule area).
666 wxString ruleText = wxString::Format( wxT( "A.enclosedByArea('%s')" ),
667 aRuleArea->m_zone->m_Uuid.AsString() );
668
669 if( !compiler.Compile( ruleText, &ucode, &preflightCtx ) )
670 return false;
671
672 auto testAndAdd =
673 [&]( BOARD_ITEM* aItem )
674 {
675 ctx.SetItems( aItem, aItem );
676 auto val = ucode.Run( &ctx );
677
678 if( val->AsDouble() != 0.0 )
679 aItems.insert( aItem );
680 };
681
682 for( ZONE* zone : board()->Zones() )
683 {
684 if( zone == aRuleArea->m_zone )
685 continue;
686
687 testAndAdd( zone );
688 }
689
690 for( BOARD_ITEM* drawing : board()->Drawings() )
691 {
692 if( !drawing->IsConnected() )
693 testAndAdd( drawing );
694 }
695
696 return true;
697}
698
699
700std::set<FOOTPRINT*> MULTICHANNEL_TOOL::queryComponentsInSheet( wxString aSheetName ) const
701{
702 std::set<FOOTPRINT*> rv;
703
704 if( aSheetName.EndsWith( wxT( "/" ) ) )
705 aSheetName.RemoveLast();
706
707 wxString childPrefix = aSheetName + wxT( "/" );
708
709 for( FOOTPRINT* fp : board()->Footprints() )
710 {
711 auto sn = fp->GetSheetname();
712
713 if( sn.EndsWith( wxT( "/" ) ) )
714 sn.RemoveLast();
715
716 if( sn == aSheetName || sn.StartsWith( childPrefix ) )
717 rv.insert( fp );
718 }
719
720 return rv;
721}
722
723
724std::set<FOOTPRINT*>
725MULTICHANNEL_TOOL::queryComponentsInComponentClass( const wxString& aComponentClassName ) const
726{
727 std::set<FOOTPRINT*> rv;
728
729 for( FOOTPRINT* fp : board()->Footprints() )
730 {
731 if( fp->GetComponentClass()->ContainsClassName( aComponentClassName ) )
732 rv.insert( fp );
733 }
734
735 return rv;
736}
737
738
739std::set<FOOTPRINT*> MULTICHANNEL_TOOL::queryComponentsInGroup( const wxString& aGroupName ) const
740{
741 std::set<FOOTPRINT*> rv;
742
743 for( PCB_GROUP* group : board()->Groups() )
744 {
745 if( group->GetName().Matches( aGroupName ) )
747 }
748
749 return rv;
750}
751
752
753PCB_GROUP* MULTICHANNEL_TOOL::findPlacementGroup( const wxString& aGroupName ) const
754{
755 PCB_GROUP* found = nullptr;
756
757 for( PCB_GROUP* group : board()->Groups() )
758 {
759 if( !group->GetName().Matches( aGroupName ) )
760 continue;
761
762 if( found )
763 return nullptr;
764
765 found = group;
766 }
767
768 return found;
769}
770
771
772std::set<BOARD_ITEM*> MULTICHANNEL_TOOL::queryBoardItemsInGroup( const wxString& aGroupName ) const
773{
774 std::set<BOARD_ITEM*> rv;
775
776 for( PCB_GROUP* group : board()->Groups() )
777 {
778 if( !group->GetName().Matches( aGroupName ) )
779 continue;
780
781 for( EDA_ITEM* item : group->GetItems() )
782 {
783 if( item->IsBOARD_ITEM() )
784 rv.insert( static_cast<BOARD_ITEM*>( item ) );
785 }
786 }
787
788 return rv;
789}
790
791
792const SHAPE_LINE_CHAIN MULTICHANNEL_TOOL::buildRAOutline( std::set<FOOTPRINT*>& aFootprints, int aMargin )
793{
794 std::vector<VECTOR2I> bbCorners;
795 bbCorners.reserve( aFootprints.size() * 4 );
796
797 for( FOOTPRINT* fp : aFootprints )
798 {
799 const BOX2I bb = fp->GetBoundingBox( false ).GetInflated( aMargin );
800 KIGEOM::CollectBoxCorners( bb, bbCorners );
801 }
802
803 std::vector<VECTOR2I> hullVertices;
804 BuildConvexHull( hullVertices, bbCorners );
805
806 SHAPE_LINE_CHAIN hull( hullVertices );
807
808 // Make the newly computed convex hull use only 90 degree segments
809 return KIGEOM::RectifyPolygon( hull );
810}
811
812const SHAPE_LINE_CHAIN MULTICHANNEL_TOOL::buildRAOutline( const std::set<BOARD_ITEM*>& aItems, int aMargin )
813{
814 std::vector<VECTOR2I> bbCorners;
815 bbCorners.reserve( aItems.size() * 4 );
816
817 for( BOARD_ITEM* item : aItems )
818 {
819 BOX2I bb = item->GetBoundingBox();
820
821 if( item->Type() == PCB_FOOTPRINT_T )
822 bb = static_cast<FOOTPRINT*>( item )->GetBoundingBox( false );
823
824 KIGEOM::CollectBoxCorners( bb.GetInflated( aMargin ), bbCorners );
825 }
826
827 std::vector<VECTOR2I> hullVertices;
828 BuildConvexHull( hullVertices, bbCorners );
829
830 SHAPE_LINE_CHAIN hull( hullVertices );
831
832 // Make the newly computed convex hull use only 90 degree segments
833 return KIGEOM::RectifyPolygon( hull );
834}
835
836
837// Returns each parent sheet path above aSheetName, e.g. "/A/B/C/" -> { "/A/", "/A/B/" }.
838// The root and the sheet itself are left out.
839static std::vector<wxString> getParentSheetPaths( const wxString& aSheetName )
840{
841 std::vector<wxString> segments;
842 wxString cur;
843
844 for( wxUniChar ch : aSheetName )
845 {
846 if( ch == '/' )
847 {
848 if( !cur.IsEmpty() )
849 segments.push_back( cur );
850
851 cur.clear();
852 }
853 else
854 {
855 cur += ch;
856 }
857 }
858
859 if( !cur.IsEmpty() )
860 segments.push_back( cur );
861
862 std::vector<wxString> rv;
863 wxString prefix = wxT( "/" );
864
865 for( size_t i = 0; i + 1 < segments.size(); ++i )
866 {
867 prefix += segments[i] + wxT( "/" );
868 rv.push_back( prefix );
869 }
870
871 return rv;
872}
873
874
876{
877 // Sheet path -> sheet file. Container sheets that only hold subsheets have no file of
878 // their own, so they map to an empty string.
879 std::map<wxString, wxString> uniqueSheets;
880 std::set<wxString> uniqueComponentClasses;
881 std::set<wxString> uniqueGroups;
882
883 m_areas.m_areas.clear();
884
885 for( const FOOTPRINT* fp : board()->Footprints() )
886 {
887 uniqueSheets[fp->GetSheetname()] = fp->GetSheetfile();
888
889 // Offer the parent sheets as channels too, not just the deepest one.
890 for( const wxString& parent : getParentSheetPaths( fp->GetSheetname() ) )
891 uniqueSheets.emplace( parent, wxString() );
892
893 const COMPONENT_CLASS* compClass = fp->GetComponentClass();
894
895 for( const COMPONENT_CLASS* singleClass : compClass->GetConstituentClasses() )
896 uniqueComponentClasses.insert( singleClass->GetName() );
897
898 // Offer every named group up the chain, not just the immediate parent, so a
899 // channel group wrapping several sub-groups can be picked too.
900 for( EDA_GROUP* grp = fp->GetParentGroup(); grp; grp = grp->AsEdaItem()->GetParentGroup() )
901 {
902 if( !grp->GetName().IsEmpty() )
903 uniqueGroups.insert( grp->GetName() );
904 }
905 }
906
907 for( const auto& [sheetPath, sheetFile] : uniqueSheets )
908 {
909 RULE_AREA ent;
910
912 ent.m_generateEnabled = false;
913 ent.m_sheetPath = sheetPath;
914 ent.m_sheetName = sheetFile;
916 m_areas.m_areas.push_back( ent );
917
918 wxLogTrace( traceMultichannelTool, wxT("found sheet '%s' @ '%s' s %d\n"),
919 ent.m_sheetName,
920 ent.m_sheetPath,
921 (int) m_areas.m_areas.size() );
922 }
923
924 for( const wxString& compClass : uniqueComponentClasses )
925 {
926 RULE_AREA ent;
927
929 ent.m_generateEnabled = false;
930 ent.m_componentClass = compClass;
932 m_areas.m_areas.push_back( ent );
933
934 wxLogTrace( traceMultichannelTool, wxT( "found component class '%s' s %d\n" ),
936 static_cast<int>( m_areas.m_areas.size() ) );
937 }
938
939 for( const wxString& groupName : uniqueGroups )
940 {
941 RULE_AREA ent;
942
944 ent.m_generateEnabled = false;
945 ent.m_groupName = groupName;
947 m_areas.m_areas.push_back( ent );
948
949 wxLogTrace( traceMultichannelTool, wxT( "found group '%s' s %d\n" ),
951 static_cast<int>( m_areas.m_areas.size() ) );
952 }
953}
954
955
957{
958 m_areas.m_areas.clear();
959
960 for( ZONE* zone : board()->Zones() )
961 {
962 if( !zone->GetIsRuleArea() )
963 continue;
964
965 if( !zone->GetPlacementAreaEnabled() )
966 continue;
967
968 RULE_AREA area;
969
970 area.m_zone = zone;
971 area.m_sourceType = zone->GetPlacementAreaSourceType();
972 area.m_ruleName = zone->GetZoneName();
973 area.m_center = zone->Outline()->COutline( 0 ).Centre();
974
975 switch( area.m_sourceType )
976 {
977 case PLACEMENT_SOURCE_T::SHEETNAME: area.m_sheetPath = zone->GetPlacementAreaSource(); break;
978
979 case PLACEMENT_SOURCE_T::COMPONENT_CLASS: area.m_componentClass = zone->GetPlacementAreaSource(); break;
980
982 area.m_groupName = zone->GetPlacementAreaSource();
984 break;
985
987 }
988
990
991 m_areas.m_areas.push_back( area );
992
993 wxLogTrace( traceMultichannelTool, wxT( "RA '%s', %d footprints\n" ), area.m_ruleName,
994 (int) area.m_components.size() );
995 }
996
997 wxLogTrace( traceMultichannelTool, wxT( "Total RAs found: %d\n" ), (int) m_areas.m_areas.size() );
998}
999
1000
1002{
1003 if( aItem )
1005}
1006
1007
1009{
1010 std::vector<ZONE*> refRAs;
1011
1012 auto isSelectedItemAnRA =
1013 []( EDA_ITEM* aItem ) -> ZONE*
1014 {
1015 if( !aItem || aItem->Type() != PCB_ZONE_T )
1016 return nullptr;
1017
1018 ZONE* zone = static_cast<ZONE*>( aItem );
1019
1020 if( !zone->GetIsRuleArea() )
1021 return nullptr;
1022
1023 if( !zone->GetPlacementAreaEnabled() )
1024 return nullptr;
1025
1026 return zone;
1027 };
1028
1029 for( EDA_ITEM* item : selection() )
1030 {
1031 if( ZONE* zone = isSelectedItemAnRA( item ) )
1032 {
1033 refRAs.push_back( zone );
1034 }
1035 else if( item->Type() == PCB_GROUP_T )
1036 {
1037 PCB_GROUP *group = static_cast<PCB_GROUP*>( item );
1038
1039 for( EDA_ITEM* grpItem : group->GetItems() )
1040 {
1041 if( ZONE* grpZone = isSelectedItemAnRA( grpItem ) )
1042 refRAs.push_back( grpZone );
1043 }
1044 }
1045 }
1046
1048
1049 // Plain parts with no rule area are the reference, and the channels repeating them are discovered
1050 if( refRAs.empty() && ( selection().HasType( PCB_FOOTPRINT_T ) || selection().HasType( PCB_GROUP_T ) ) )
1051 {
1052 StartRepeatFromSelection( std::vector<EDA_ITEM*>( selection().begin(), selection().end() ) );
1053
1054 if( !m_areas.m_refRA )
1055 {
1056 frame()->ShowInfoBarMsg( _( "Select the footprints of the circuit to repeat." ), true );
1057 return 0;
1058 }
1059 }
1060 else if( refRAs.size() != 1 )
1061 {
1064 this,
1065 _( "Select a reference Rule Area to copy from..." ),
1066 [&]( EDA_ITEM* aItem )
1067 {
1068 return isSelectedItemAnRA( aItem ) != nullptr;
1069 }
1070 } );
1071
1072 return 0;
1073 }
1074 else
1075 {
1077
1078 int status = CheckRACompatibility( refRAs.front() );
1079
1080 if( status < 0 )
1081 return status;
1082
1083 if( m_areas.m_areas.size() <= 1 )
1084 {
1085 frame()->ShowInfoBarError( _( "No Rule Areas to repeat layout to have been found." ), true );
1086 return 0;
1087 }
1088
1089 const KIID& linkSet = refRAs.front()->GetLinkSet();
1090 m_areas.m_options = refRAs.front()->GetRepeatOptions();
1091 m_areas.m_linkAreas = linkSet != niluuid;
1092
1093 // A linked source's set is the user's previous choice
1094 for( auto& [area, compat] : m_areas.m_compatMap )
1095 compat.m_doCopy = compat.m_isOk && ( linkSet == niluuid || area->m_zone->GetLinkSet() == linkSet );
1096 }
1097
1098 // The view's preview group can be gone since the board loaded, so it is set up again as the router does
1099 getView()->InitPreview();
1100
1101 // Not modal, so the board can be panned and zoomed while the preview shows the result
1103 m_dialog->Bind( wxEVT_CLOSE_WINDOW, &MULTICHANNEL_TOOL::onRepeatDialogClosed, this );
1104 m_dialog->Show( true );
1106 return 0;
1107}
1108
1109
1110// A net that belongs to a channel reaches at most one footprint outside it (a connector or the neighbouring
1111// block). Rails and buses reach many, so they never tie a channel together
1112static bool isChannelNet( const std::vector<FOOTPRINT*>& aOwners, const std::set<FOOTPRINT*>& aChannel )
1113{
1114 return std::ranges::count_if( aOwners, [&]( FOOTPRINT* aFp ) { return !aChannel.contains( aFp ); } ) <= 1;
1115}
1116
1117
1118static std::set<int> channelNets( const std::map<int, std::vector<FOOTPRINT*>>& aNetOwners,
1119 const std::set<FOOTPRINT*>& aChannel )
1120{
1121 std::set<int> nets;
1122
1123 for( const auto& [net, owners] : aNetOwners )
1124 {
1125 if( owners.size() > 1 && isChannelNet( owners, aChannel )
1126 && std::ranges::any_of( owners, [&]( FOOTPRINT* aFp ) { return aChannel.contains( aFp ); } ) )
1127 {
1128 nets.insert( net );
1129 }
1130 }
1131
1132 return nets;
1133}
1134
1135
1136// Moves aItem into aGroup, staging the group it leaves so undo restores that membership too
1137static void stageAddToGroup( BOARD_COMMIT& aCommit, EDA_GROUP* aGroup, BOARD_ITEM* aItem )
1138{
1139 if( EDA_GROUP* old = aItem->GetParentGroup() )
1140 {
1141 if( old == aGroup || old->AsEdaItem()->Type() == PCB_GENERATOR_T )
1142 return;
1143
1144 aCommit.Modify( old->AsEdaItem(), nullptr, RECURSE_MODE::NO_RECURSE );
1145 }
1146
1147 aCommit.Modify( aItem );
1148 aGroup->AddItem( aItem );
1149}
1150
1151
1152static std::set<int> padNets( const FOOTPRINT* aFp, const std::set<int>& aAmong )
1153{
1154 std::set<int> nets;
1155
1156 for( const PAD* pad : aFp->Pads() )
1157 {
1158 if( aAmong.contains( pad->GetNetCode() ) )
1159 nets.insert( pad->GetNetCode() );
1160 }
1161
1162 return nets;
1163}
1164
1165
1166// Repeated sheets give every instance the same symbol UUIDs under its own instance path
1167static std::vector<TMATCH::COMPONENT_MATCHES> matchSheetInstances( BOARD* aBoard, const std::set<FOOTPRINT*>& aRef )
1168{
1169 using PATH = std::vector<KIID>;
1170
1171 std::optional<PATH> refPrefix;
1172
1173 for( FOOTPRINT* fp : aRef )
1174 {
1175 const KIID_PATH& path = fp->GetPath();
1176
1177 if( path.size() < 2 )
1178 return {};
1179
1180 if( !refPrefix )
1181 refPrefix = PATH( path.begin(), path.end() - 1 );
1182
1183 size_t depth = std::min( refPrefix->size(), path.size() - 1 );
1184 auto diff = std::mismatch( refPrefix->begin(), refPrefix->begin() + depth, path.begin() );
1185
1186 refPrefix->resize( diff.first - refPrefix->begin() );
1187 }
1188
1189 if( !refPrefix || refPrefix->empty() )
1190 return {};
1191
1192 const size_t depth = refPrefix->size();
1193
1194 auto rest =
1195 [&]( const KIID_PATH& aPath )
1196 {
1197 return PATH( aPath.begin() + depth, aPath.end() );
1198 };
1199
1200 std::map<PATH, FOOTPRINT*> refByRest;
1201
1202 for( FOOTPRINT* fp : aRef )
1203 refByRest[rest( fp->GetPath() )] = fp;
1204
1205 std::map<PATH, TMATCH::COMPONENT_MATCHES> instances;
1206
1207 for( FOOTPRINT* fp : aBoard->Footprints() )
1208 {
1209 const KIID_PATH& path = fp->GetPath();
1210
1211 if( aRef.contains( fp ) || path.size() <= depth )
1212 continue;
1213
1214 PATH prefix( path.begin(), path.begin() + depth );
1215
1216 if( prefix == *refPrefix )
1217 continue;
1218
1219 if( auto it = refByRest.find( rest( path ) ); it != refByRest.end() && it->second->GetFPID() == fp->GetFPID() )
1220 instances[prefix][it->second] = fp;
1221 }
1222
1223 std::vector<TMATCH::COMPONENT_MATCHES> result;
1224
1225 for( auto& [prefix, matches] : instances )
1226 result.push_back( std::move( matches ) );
1227
1228 return result;
1229}
1230
1231
1232// Pairs the reference footprints, in growth order from the seed, with board footprints that sit on the same
1233// mirrored nets, backtracking on dead ends. With aLoose a leaf may stay unmatched
1235{
1236 const std::map<int, std::vector<FOOTPRINT*>>& m_netOwners;
1237 const std::set<int>& m_internal;
1238 const std::set<FOOTPRINT*>& m_leaves;
1239 const std::set<FOOTPRINT*>& m_claimed;
1240 const std::vector<FOOTPRINT*>& m_order;
1242
1244 std::set<FOOTPRINT*> m_used = {};
1245 std::map<int, int> m_netMap = {};
1246 std::set<int> m_netsTaken = {};
1247 int m_budget = 10000;
1248
1249 bool bind( FOOTPRINT* aRef, FOOTPRINT* aTarget, std::vector<int>& aAdded )
1250 {
1251 for( PAD* pad : aRef->Pads() )
1252 {
1253 int net = pad->GetNetCode();
1254
1255 if( !m_internal.contains( net ) )
1256 continue;
1257
1258 const PAD* peer = aTarget->FindPadByNumber( pad->GetNumber() );
1259
1260 if( !peer )
1261 return false;
1262
1263 int peerNet = peer->GetNetCode();
1264
1265 if( auto it = m_netMap.find( net ); it != m_netMap.end() )
1266 {
1267 if( it->second != peerNet )
1268 return false;
1269 }
1270 else
1271 {
1272 if( peerNet <= 0 || m_netsTaken.contains( peerNet ) )
1273 return false;
1274
1275 m_netMap[net] = peerNet;
1276 m_netsTaken.insert( peerNet );
1277 aAdded.push_back( net );
1278 }
1279 }
1280
1281 return true;
1282 }
1283
1284 // Pairs m_order[aIndex] with aChoice and matches the rest, undoing the pairing on a dead end
1285 bool pair( size_t aIndex, FOOTPRINT* aChoice )
1286 {
1287 FOOTPRINT* ref = m_order[aIndex];
1288 std::vector<int> added;
1289
1290 if( bind( ref, aChoice, added ) )
1291 {
1292 m_map[ref] = aChoice;
1293 m_used.insert( aChoice );
1294
1295 if( extend( aIndex + 1 ) )
1296 return true;
1297
1298 m_map.erase( ref );
1299 m_used.erase( aChoice );
1300 }
1301
1302 for( int net : added )
1303 {
1304 m_netsTaken.erase( m_netMap[net] );
1305 m_netMap.erase( net );
1306 }
1307
1308 return false;
1309 }
1310
1311 bool extend( size_t aIndex )
1312 {
1313 if( aIndex == m_order.size() )
1314 return true;
1315
1316 if( --m_budget < 0 )
1317 return false;
1318
1319 FOOTPRINT* ref = m_order[aIndex];
1320
1321 // One mapped net is enough to bound the choices; bind() checks the rest
1322 auto mapped = std::ranges::find_if( ref->Pads(),
1323 [&]( PAD* aPad ) { return m_netMap.contains( aPad->GetNetCode() ); } );
1324
1325 if( mapped != ref->Pads().end() )
1326 {
1327 for( FOOTPRINT* fp : m_netOwners.at( m_netMap.at( ( *mapped )->GetNetCode() ) ) )
1328 {
1329 if( !m_claimed.contains( fp ) && !m_used.contains( fp ) && fp->GetFPID() == ref->GetFPID()
1330 && pair( aIndex, fp ) )
1331 {
1332 return true;
1333 }
1334
1335 if( m_budget < 0 )
1336 return false;
1337 }
1338 }
1339
1340 // A leaf may stay unmatched; the caller works out which parts were left out
1341 return m_loose && m_leaves.contains( ref ) && extend( aIndex + 1 );
1342 }
1343};
1344
1345
1346void MULTICHANNEL_TOOL::StartRepeatFromSelection( const std::vector<EDA_ITEM*>& aItems )
1347{
1349
1350 // The channels become groups, so copies join them
1351 m_areas.m_options.m_groupItems = true;
1352
1353 for( EDA_ITEM* item : aItems )
1354 {
1355 if( item->Type() == PCB_GROUP_T )
1356 collectGroupBoardItems( static_cast<PCB_GROUP*>( item ), m_areas.m_selectedItems );
1357 else if( item->IsBOARD_ITEM() && !static_cast<BOARD_ITEM*>( item )->GetParentFootprint() )
1358 m_areas.m_selectedItems.insert( static_cast<BOARD_ITEM*>( item ) );
1359 }
1360
1361 for( BOARD_ITEM* item : m_areas.m_selectedItems )
1362 {
1363 if( item->Type() == PCB_FOOTPRINT_T )
1364 m_areas.m_selectedFootprints.insert( static_cast<FOOTPRINT*>( item ) );
1365 }
1366
1367 DiscoverRepeatCandidates( false );
1368
1369 // A session without a reference must not divert later rule area repeats into the selection flow
1370 if( !m_areas.m_refRA )
1372}
1373
1374
1375// The footprints on each net, in board order
1376static std::map<int, std::vector<FOOTPRINT*>> buildNetOwners( const BOARD* aBoard )
1377{
1378 std::map<int, std::vector<FOOTPRINT*>> netOwners;
1379
1380 for( FOOTPRINT* fp : aBoard->Footprints() )
1381 {
1382 for( PAD* pad : fp->Pads() )
1383 {
1384 std::vector<FOOTPRINT*>& owners = netOwners[pad->GetNetCode()];
1385
1386 if( pad->GetNetCode() > 0 && ( owners.empty() || owners.back() != fp ) )
1387 owners.push_back( fp );
1388 }
1389 }
1390
1391 return netOwners;
1392}
1393
1394
1395std::vector<RULE_AREA_COMPAT_DATA> MULTICHANNEL_TOOL::findMatches( const std::set<FOOTPRINT*>& selected,
1396 bool aLoose )
1397{
1398 std::map<int, std::vector<FOOTPRINT*>> netOwners = buildNetOwners( board() );
1399
1400 std::set<int> internal = channelNets( netOwners, selected );
1401 std::set<FOOTPRINT*> leaves;
1402
1403 for( FOOTPRINT* fp : selected )
1404 {
1405 if( padNets( fp, internal ).size() <= 1 )
1406 leaves.insert( fp );
1407 }
1408
1409 std::vector<RULE_AREA_COMPAT_DATA> found;
1410
1411 // Kept when it lacks no selected part, or only leaves under loose matching
1412 auto classify =
1413 [&]( RULE_AREA_COMPAT_DATA& aCandidate )
1414 {
1415 for( FOOTPRINT* fp : selected )
1416 {
1417 if( !aCandidate.m_discovered.contains( fp ) )
1418 aCandidate.m_unmatched.insert( fp );
1419 }
1420
1421 aCandidate.m_doCopy = true;
1422
1423 return aCandidate.m_unmatched.empty()
1424 || ( aLoose && std::ranges::all_of( aCandidate.m_unmatched,
1425 [&]( FOOTPRINT* aFp ) { return leaves.contains( aFp ); } ) );
1426 };
1427
1428 for( TMATCH::COMPONENT_MATCHES& matches : matchSheetInstances( board(), selected ) )
1429 {
1430 RULE_AREA_COMPAT_DATA candidate;
1431 candidate.m_discovered = std::move( matches );
1432
1433 if( classify( candidate ) )
1434 found.push_back( std::move( candidate ) );
1435 }
1436
1437 if( found.empty() )
1438 {
1439 std::map<LIB_ID, int> fpidCount;
1440
1441 for( FOOTPRINT* fp : board()->Footprints() )
1442 fpidCount[fp->GetFPID()]++;
1443
1444 // The rarest part keeps the number of seeds low; a leaf may be the part a channel lacks
1445 FOOTPRINT* seed = *std::ranges::min_element( selected,
1446 [&]( FOOTPRINT* aA, FOOTPRINT* aB )
1447 {
1448 return std::make_pair( leaves.contains( aA ), fpidCount[aA->GetFPID()] )
1449 < std::make_pair( leaves.contains( aB ), fpidCount[aB->GetFPID()] );
1450 } );
1451
1452 std::vector<FOOTPRINT*> order = { seed };
1453
1454 for( size_t i = 0; i < order.size(); ++i )
1455 {
1456 for( int net : padNets( order[i], internal ) )
1457 {
1458 for( FOOTPRINT* fp : netOwners[net] )
1459 {
1460 if( selected.contains( fp ) && std::ranges::find( order, fp ) == order.end() )
1461 order.push_back( fp );
1462 }
1463 }
1464 }
1465
1466 std::set<FOOTPRINT*> claimed = selected;
1467
1468 for( FOOTPRINT* twin : board()->Footprints() )
1469 {
1470 if( claimed.contains( twin ) || twin->GetFPID() != seed->GetFPID() )
1471 continue;
1472
1473 FLAT_MATCHER matcher{ netOwners, internal, leaves, claimed, order, aLoose };
1474 RULE_AREA_COMPAT_DATA candidate;
1475 bool ok = matcher.pair( 0, twin );
1476
1477 if( matcher.m_budget < 0 )
1478 {
1479 candidate.m_discovered = { { seed, twin } };
1480 candidate.m_searchLimit = true;
1481 found.push_back( std::move( candidate ) );
1482 continue;
1483 }
1484
1485 candidate.m_discovered = matcher.m_map;
1486
1487 if( !ok || !classify( candidate ) )
1488 continue;
1489
1490 // Rails are judged against both channels together, whichever channels were found first
1491 RULE_AREA refArea;
1492 RULE_AREA targetArea;
1493 std::set<FOOTPRINT*> both;
1494 std::unordered_set<int> rails;
1495
1496 for( const auto& [ref, target] : candidate.m_discovered )
1497 {
1498 refArea.m_components.insert( ref );
1499 targetArea.m_components.insert( target );
1500 both.insert( { ref, target } );
1501 }
1502
1503 for( FOOTPRINT* fp : both )
1504 {
1505 for( PAD* pad : fp->Pads() )
1506 {
1507 if( pad->GetNetCode() > 0 && !isChannelNet( netOwners[pad->GetNetCode()], both ) )
1508 rails.insert( pad->GetNetCode() );
1509 }
1510 }
1511
1512 // A flat match is only a guess until the topology agrees, so it claims nothing before that
1514
1515 if( !resolveConnectionTopology( &refArea, &targetArea, check, {}, rails ) )
1516 continue;
1517
1518 claimed.insert( targetArea.m_components.begin(), targetArea.m_components.end() );
1519 found.push_back( std::move( candidate ) );
1520 }
1521 }
1522
1523 return found;
1524}
1525
1526
1528{
1529 const std::set<FOOTPRINT*>& selected = m_areas.m_selectedFootprints;
1530 PROF_TIMER timer;
1531
1532 m_areas.m_refRA = nullptr;
1533 m_focusArea = nullptr;
1534 m_areas.m_compatMap.clear();
1535 m_areas.m_areas.clear();
1536 m_areas.m_scratchItems.clear();
1537
1538 if( selected.empty() )
1539 return;
1540
1541 std::vector<RULE_AREA_COMPAT_DATA> found = findMatches( selected, aLoose );
1542
1543 // Filled before any pointer to its elements is taken
1544 m_areas.m_areas.reserve( found.size() + 1 );
1545
1546 auto addArea =
1547 [&]( const SHAPE_LINE_CHAIN& aOutline, const std::set<FOOTPRINT*>& aFootprints,
1548 PLACEMENT_SOURCE_T aSourceType ) -> RULE_AREA&
1549 {
1550 ZONE* zone = new ZONE( board() );
1551 PCB_GROUP* group = new PCB_GROUP( board() );
1552
1553 m_areas.m_scratchItems.emplace_back( zone );
1554 m_areas.m_scratchItems.emplace_back( group );
1555 makePlacementArea( zone, aOutline );
1556
1557 RULE_AREA& area = m_areas.m_areas.emplace_back();
1558 area.m_zone = zone;
1559 area.m_group = group;
1560 area.m_components = aFootprints;
1561 area.m_center = aOutline.Centre();
1562 area.m_sourceType = aSourceType;
1563 return area;
1564 };
1565
1566 // The selection is copied as given, like a design block, rather than by what its area encloses
1567 addArea( buildRAOutline( m_areas.m_selectedItems, 100000 ), selected, PLACEMENT_SOURCE_T::DESIGN_BLOCK )
1568 .m_fromSelection = true;
1569
1570 for( const RULE_AREA_COMPAT_DATA& candidate : found )
1571 {
1572 std::set<FOOTPRINT*> targets;
1573
1574 for( const auto& [ref, target] : candidate.m_discovered )
1575 targets.insert( target );
1576
1577 addArea( buildRAOutline( targets, 100000 ), targets, PLACEMENT_SOURCE_T::GROUP_PLACEMENT );
1578 }
1579
1580 m_areas.m_refRA = &m_areas.m_areas.front();
1581
1582 for( size_t i = 0; i < found.size(); ++i )
1583 m_areas.m_compatMap[&m_areas.m_areas[i + 1]] = std::move( found[i] );
1584
1585 // A candidate that fails on its own starts unticked, so its missing parts do not shrink the others
1586 bool resolved = updateSelectionCore();
1587 bool unticked = false;
1588
1589 for( auto& [area, compat] : m_areas.m_compatMap )
1590 {
1591 unticked |= compat.m_doCopy && !compat.m_isOk;
1592 compat.m_doCopy &= compat.m_isOk;
1593 }
1594
1595 // Cancelled candidates are unticked too, and resolving the rest again would restart the search
1596 if( unticked && resolved )
1598
1599 wxLogTrace( traceMultichannelTool, wxT( "Discovery: %s, %d candidates" ), timer.to_string(),
1600 (int) m_areas.m_compatMap.size() );
1601}
1602
1603
1604std::set<FOOTPRINT*> MULTICHANNEL_TOOL::ExpandToMatchingTopology( const std::set<FOOTPRINT*>& aSeed, bool aLargest )
1605{
1606 // Each trial runs a full discovery, so a large board cannot be searched without limit
1607 int budget = 400;
1608
1609 auto hasTwin =
1610 [&]( const std::set<FOOTPRINT*>& aSet )
1611 {
1612 budget--;
1613
1614 return std::ranges::any_of( findMatches( aSet, false ),
1615 []( const RULE_AREA_COMPAT_DATA& aMatch )
1616 {
1617 return !aMatch.m_searchLimit;
1618 } );
1619 };
1620
1621 std::set<FOOTPRINT*> result = aSeed;
1622
1623 if( result.empty() || !hasTwin( result ) )
1624 return result;
1625
1626 // A sheet instance is the largest set a hierarchical design repeats
1627 const KIID_PATH& path = ( *aSeed.begin() )->GetPath();
1628
1629 if( aLargest && path.size() >= 2 )
1630 {
1631 std::set<FOOTPRINT*> sheet;
1632
1633 for( FOOTPRINT* fp : board()->Footprints() )
1634 {
1635 const KIID_PATH& other = fp->GetPath();
1636
1637 if( other.size() == path.size() && std::equal( path.begin(), path.end() - 1, other.begin() ) )
1638 sheet.insert( fp );
1639 }
1640
1641 bool holdsSeed = std::ranges::all_of( aSeed, [&]( FOOTPRINT* aFp ) { return sheet.contains( aFp ); } );
1642
1643 if( sheet.size() > result.size() && holdsSeed && hasTwin( sheet ) )
1644 {
1645 return sheet;
1646 }
1647 }
1648
1649 std::map<int, std::vector<FOOTPRINT*>> netOwners = buildNetOwners( board() );
1650
1651 // Rails and buses reach too many parts to tie a channel together
1652 constexpr size_t maxOwners = 12;
1653
1654 std::set<FOOTPRINT*> rejected;
1655 bool grew = true;
1656
1657 while( grew && budget > 0 )
1658 {
1659 grew = false;
1660
1661 // A step only reaches the parts next to what the pass started with
1662 const std::set<FOOTPRINT*> frontier = result;
1663
1664 for( const auto& [net, owners] : netOwners )
1665 {
1666 if( owners.size() > maxOwners || !std::ranges::any_of( owners, [&]( FOOTPRINT* aFp )
1667 { return frontier.contains( aFp ); } ) )
1668 {
1669 continue;
1670 }
1671
1672 for( FOOTPRINT* fp : owners )
1673 {
1674 if( budget <= 0 )
1675 break;
1676
1677 if( result.contains( fp ) || rejected.contains( fp ) )
1678 continue;
1679
1680 std::set<FOOTPRINT*> trial = result;
1681 trial.insert( fp );
1682
1683 if( hasTwin( trial ) )
1684 {
1685 result = std::move( trial );
1686 grew = true;
1687 }
1688 else
1689 {
1690 rejected.insert( fp );
1691 }
1692 }
1693 }
1694
1695 // A part refused alone may fit once its neighbours are in
1696 if( grew )
1697 rejected.clear();
1698
1699 if( !aLargest )
1700 break;
1701 }
1702
1703 return result;
1704}
1705
1706
1708{
1709 return expandSelection( false );
1710}
1711
1712
1714{
1715 return expandSelection( true );
1716}
1717
1718
1720{
1721 std::set<FOOTPRINT*> seed;
1722
1723 for( EDA_ITEM* item : selection() )
1724 {
1725 if( item->Type() == PCB_FOOTPRINT_T )
1726 seed.insert( static_cast<FOOTPRINT*>( item ) );
1727 else if( item->Type() == PCB_GROUP_T )
1728 collectGroupFootprints( static_cast<PCB_GROUP*>( item ), seed );
1729 }
1730
1731 if( seed.empty() )
1732 {
1733 frame()->ShowInfoBarMsg( _( "Select a footprint to expand from." ), true );
1734 return 0;
1735 }
1736
1737 std::set<FOOTPRINT*> expanded = ExpandToMatchingTopology( seed, aLargest );
1738
1739 if( expanded.size() == seed.size() )
1740 {
1741 frame()->ShowInfoBarMsg( _( "No larger topology repeats elsewhere on the board." ), true );
1742 return 0;
1743 }
1744
1745 EDA_ITEMS items( expanded.begin(), expanded.end() );
1746
1747 m_toolMgr->RunAction( ACTIONS::selectionClear );
1748 m_toolMgr->RunAction<EDA_ITEMS*>( ACTIONS::selectItems, &items );
1749
1750 frame()->ShowInfoBarMsg( wxString::Format( _( "Selected %d parts that repeat elsewhere." ), (int) expanded.size() ),
1751 true );
1752 return 0;
1753}
1754
1755
1757{
1758 RULE_AREA* ref = m_areas.m_refRA;
1759 std::set<FOOTPRINT*> pruned;
1760
1761 if( !ref )
1762 return true;
1763
1764 // Every channel keeps only the parts all ticked channels share
1765 for( const auto& [area, compat] : m_areas.m_compatMap )
1766 {
1767 if( compat.m_doCopy )
1768 pruned.insert( compat.m_unmatched.begin(), compat.m_unmatched.end() );
1769 }
1770
1771 ref->m_components.clear();
1772 ref->m_designBlockItems.clear();
1773
1774 for( BOARD_ITEM* item : m_areas.m_selectedItems )
1775 {
1776 if( item->Type() == PCB_FOOTPRINT_T && pruned.contains( static_cast<FOOTPRINT*>( item ) ) )
1777 continue;
1778
1779 ref->m_designBlockItems.insert( item );
1780
1781 if( item->Type() == PCB_FOOTPRINT_T )
1782 ref->m_components.insert( static_cast<FOOTPRINT*>( item ) );
1783 }
1784
1785 if( ref->m_components.empty() )
1786 {
1787 for( auto& [area, compat] : m_areas.m_compatMap )
1788 {
1789 compat.m_isOk = false;
1790 compat.m_errorMsg = _( "The ticked channels share no selected part" );
1791 }
1792
1793 return true;
1794 }
1795
1796 // The anchor must be shared by all channels; the biggest part is the one placed first
1797 if( !std::ranges::any_of( ref->m_components,
1798 [&]( FOOTPRINT* aFp ) { return aFp->m_Uuid == m_areas.m_options.m_anchor; } ) )
1799 {
1800 m_areas.m_options.m_anchor = niluuid;
1801 int64_t biggest = -1;
1802
1803 for( FOOTPRINT* fp : ref->m_components )
1804 {
1805 if( int64_t area = fp->GetBoundingBox( false ).GetArea(); area > biggest )
1806 {
1807 biggest = area;
1808 m_areas.m_options.m_anchor = fp->m_Uuid;
1809 }
1810 }
1811 }
1812
1813 std::vector<TOPOLOGY_JOB> jobs;
1814
1815 for( auto& [area, compat] : m_areas.m_compatMap )
1816 {
1817 area->m_components.clear();
1818
1819 for( FOOTPRINT* fp : ref->m_components )
1820 {
1821 if( auto it = compat.m_discovered.find( fp ); it != compat.m_discovered.end() )
1822 area->m_components.insert( it->second );
1823 }
1824
1825 if( compat.m_searchLimit )
1826 {
1827 compat.m_isOk = false;
1828 compat.m_errorMsg = _( "Search limit reached" );
1829 continue;
1830 }
1831
1832 jobs.push_back( { ref, area, &compat } );
1833 }
1834
1835 bool resolved = resolveTopologies( _( "Matching channels..." ), jobs );
1836
1837 for( const TOPOLOGY_JOB& job : jobs )
1838 {
1839 RULE_AREA* area = job.m_target;
1840 RULE_AREA_COMPAT_DATA& compat = *job.m_compat;
1841
1842 if( !compat.m_isOk )
1843 continue;
1844
1845 if( !compat.m_unmatched.empty() )
1846 compat.m_errorMsg = wxString::Format( _( "Loose: prunes %s" ), JoinReferences( compat.m_unmatched ) );
1847
1848 // Copying clears the target by its outline, so it has to be where the copy will land
1849 VECTOR2I disp;
1850 EDA_ANGLE rot;
1851
1852 area->m_zone->RemoveAllContours();
1853 area->m_zone->AddPolygon( repeatedOutline( ref, area, m_areas.m_options.m_anchor, compat.m_matchingComponents,
1854 disp, rot ) );
1855 }
1856
1857 return resolved;
1858}
1859
1860
1862{
1863 RULE_AREA* ref = m_areas.m_refRA;
1864 std::vector<RULE_AREA*> channels = { ref };
1865 BOARD_COMMIT commit( GetManager(), true, false );
1866
1867 for( auto& [area, compat] : m_areas.m_compatMap )
1868 {
1869 if( compat.m_doCopy && compat.m_isOk )
1870 channels.push_back( area );
1871 }
1872
1873 if( channels.size() < 2 )
1874 return 0;
1875
1876 auto addToBoard =
1877 [&]( BOARD_ITEM* aItem )
1878 {
1879 auto it = std::ranges::find_if( m_areas.m_scratchItems,
1880 [&]( const auto& aScratch ) { return aScratch.get() == aItem; } );
1881 commit.Add( it->release() );
1882 };
1883
1884 std::set<wxString> names;
1885
1886 for( PCB_GROUP* group : board()->Groups() )
1887 names.insert( group->GetName() );
1888
1889 for( RULE_AREA* area : channels )
1890 {
1891 // Each channel is named after its counterpart of the anchor
1892 RULE_AREA* matched = area == ref ? channels[1] : area;
1893 const auto& [refAnchor, targetAnchor] =
1894 anchorPair( m_areas.m_compatMap[matched].m_matchingComponents, m_areas.m_options.m_anchor );
1895 FOOTPRINT* anchor = area == ref ? refAnchor : targetAnchor;
1896
1897 wxString name = BOARD::MakeUniqueZoneName( wxString::Format( _( "%s channel" ), anchor->GetReference() ),
1898 [&]( const wxString& aName ) { return names.contains( aName ); } );
1899 names.insert( name );
1900
1901 area->m_group->SetName( name );
1902 area->m_zone->SetZoneName( name );
1903
1904 // A channel that is exactly one sheet instance keeps following the schematic
1905 wxString sheet = anchor->GetSheetname();
1906 bool wholeSheet = queryComponentsInSheet( sheet ) == area->m_components;
1907
1908 area->m_zone->SetPlacementAreaSourceType( wholeSheet ? PLACEMENT_SOURCE_T::SHEETNAME
1910 area->m_zone->SetPlacementAreaSource( wholeSheet ? sheet : area->m_group->GetName() );
1911
1912 addToBoard( area->m_zone );
1913 addToBoard( area->m_group );
1914 stageAddToGroup( commit, area->m_group, area->m_zone );
1915
1916 for( FOOTPRINT* fp : area->m_components )
1917 stageAddToGroup( commit, area->m_group, fp );
1918 }
1919
1920 for( EDA_ITEM* item : ref->m_designBlockItems )
1921 {
1922 if( item->Type() != PCB_FOOTPRINT_T )
1923 stageAddToGroup( commit, ref->m_group, static_cast<BOARD_ITEM*>( item ) );
1924 }
1925
1926 // What the area of the parts brings along is part of the channel, so linked updates repeat it too
1927 std::set<BOARD_ITEM*> found;
1928
1929 if( m_areas.m_options.m_copyRouting )
1930 {
1931 std::set<int> nets;
1932
1933 for( FOOTPRINT* fp : ref->m_components )
1934 {
1935 for( PAD* pad : fp->Pads() )
1936 nets.insert( pad->GetNetCode() );
1937 }
1938
1939 for( BOARD_CONNECTED_ITEM* item : findRepeatRouting( ref, nets, m_areas.m_options ) )
1940 found.insert( item );
1941 }
1942
1943 if( m_areas.m_options.m_copyOtherItems )
1944 findOtherItemsInRuleArea( ref, found );
1945
1946 for( BOARD_ITEM* item : found )
1947 {
1948 if( !item->GetParentGroup() && !ref->m_designBlockItems.contains( item ) )
1949 stageAddToGroup( commit, ref->m_group, item );
1950 }
1951
1952 if( m_areas.m_linkAreas )
1953 {
1954 std::vector<RULE_AREA*> targets;
1955
1956 for( RULE_AREA* area : channels )
1957 {
1958 if( area != ref )
1959 targets.push_back( area );
1960 }
1961
1962 linkAreas( commit, ref->m_zone, targets );
1963 }
1964
1965 applyRepeat( commit );
1966
1967 // Pushing delivers the model change, which ends the session and frees ref
1968 EDA_ITEM* refGroup = ref->m_group->AsEdaItem();
1969 int created = (int) channels.size();
1970
1971 commit.Push( _( "Repeat Layout" ) );
1972
1973 // Editing the old loose selection would leave the reference area behind
1974 m_toolMgr->RunAction( ACTIONS::selectionClear );
1975 m_toolMgr->RunAction( ACTIONS::selectItem, refGroup );
1976
1977 if( Pgm().IsGUI() )
1978 {
1979 frame()->ShowInfoBarMsg( wxString::Format( m_areas.m_linkAreas ? _( "Created %d linked channels." )
1980 : _( "Created %d channels." ),
1981 created ),
1982 true );
1983 }
1984
1985 return 0;
1986}
1987
1988
1989wxString MULTICHANNEL_TOOL::JoinReferences( const std::set<FOOTPRINT*>& aFootprints )
1990{
1991 wxArrayString refs;
1992
1993 for( FOOTPRINT* fp : aFootprints )
1994 refs.push_back( fp->GetReference() );
1995
1996 refs.Sort();
1997 return wxJoin( refs, ',' );
1998}
1999
2000
2002{
2003 if( m_areas.FromSelection() )
2005
2007}
2008
2009
2011{
2013
2014 if( m_areas.FromSelection() )
2015 return applySelectionRepeat();
2016
2017 return RepeatLayout( TOOL_EVENT(), m_areas.m_refRA->m_zone );
2018}
2019
2020
2022{
2024
2026
2027 if( !view || !m_areas.m_refRA )
2028 return;
2029
2030 PROF_TIMER timer;
2031
2032 // The copy is staged and reverted; only clones of its result stay on screen
2033 auto savedCompat = m_areas.m_compatMap;
2034 REPEAT_LAYOUT_OPTIONS savedOptions = m_areas.m_options;
2035 BOARD_COMMIT commit( GetManager(), true, false );
2036
2037 // Grouping changes nothing visible and would stage edits to unrelated groups
2038 m_areas.m_options.m_groupItems = false;
2039 applyRepeat( commit );
2040
2041 auto previewClone =
2042 [&]( BOARD_ITEM* aItem ) -> BOARD_ITEM*
2043 {
2044 BOARD_ITEM* clone = static_cast<BOARD_ITEM*>( aItem->Clone() );
2045
2046 // The revert below deletes groups the copy staged, and drawing asks the parent group for its lock
2047 clone->SetParentGroup( nullptr );
2048 view->AddToPreview( clone, true );
2049 return clone;
2050 };
2051
2052 auto isContainer =
2053 []( const BOARD_ITEM* aItem )
2054 {
2055 return aItem->Type() == PCB_GROUP_T || aItem->Type() == PCB_GENERATOR_T;
2056 };
2057
2058 auto show =
2059 [&]( BOARD_ITEM* aItem )
2060 {
2061 // Group and generator clones share members, so those are shown one member at a time
2062 if( isContainer( aItem ) )
2063 {
2064 aItem->RunOnChildren( [&]( BOARD_ITEM* aChild )
2065 {
2066 if( !isContainer( aChild ) )
2067 previewClone( aChild );
2068 },
2070 return;
2071 }
2072
2073 BOARD_ITEM* clone = previewClone( aItem );
2074 clone->SetBrightened();
2075 clone->RunOnChildren( [&]( BOARD_ITEM* aChild ) { view->AddToPreview( aChild, false ); },
2077 };
2078
2079 for( const auto& [area, compat] : m_areas.m_compatMap )
2080 {
2081 for( BOARD_ITEM* item : compat.m_affectedItems )
2082 m_previewHidden.push_back( item->m_Uuid );
2083
2084 for( BOARD_ITEM* item : compat.m_groupableItems )
2085 show( item );
2086 }
2087
2088 // Marks and ratsnest follow the parts to where the copy puts them
2089 for( const auto& [area, compat] : m_areas.m_compatMap )
2090 {
2091 for( BOARD_ITEM* item : compat.m_affectedItems )
2092 {
2093 if( item->Type() == PCB_FOOTPRINT_T )
2094 {
2095 FOOTPRINT* fp = static_cast<FOOTPRINT*>( item );
2096
2097 m_previewBoxes[fp] = fp->GetBoundingBox( false );
2098 }
2099 }
2100 }
2101
2102 if( !m_previewBoxes.empty() )
2103 {
2104 std::shared_ptr<CONNECTIVITY_DATA> connectivity = board()->GetConnectivity();
2105 std::vector<BOARD_ITEM*> moved;
2106
2107 for( const auto& [fp, box] : m_previewBoxes )
2108 moved.push_back( fp );
2109
2110 for( BOARD_ITEM* fp : moved )
2111 connectivity->Update( fp );
2112
2113 connectivity->RecalculateRatsnest();
2114
2115 auto movedPad =
2116 [&]( const std::shared_ptr<const CN_ANCHOR>& aNode )
2117 {
2118 BOARD_CONNECTED_ITEM* parent = aNode->Parent();
2119
2120 return parent && parent->Type() == PCB_PAD_T
2121 && m_previewBoxes.contains( parent->GetParentFootprint() );
2122 };
2123
2124 for( const CN_EDGE& edge : connectivity->GetRatsnestForItems( moved ) )
2125 {
2126 const std::shared_ptr<const CN_ANCHOR>& a = edge.GetSourceNode();
2127 const std::shared_ptr<const CN_ANCHOR>& b = edge.GetTargetNode();
2128
2129 if( a && b && !a->Dirty() && !b->Dirty() && ( movedPad( a ) || movedPad( b ) ) )
2130 m_previewRatsnest.emplace_back( a->Pos(), b->Pos() );
2131 }
2132 }
2133
2134 // Revert swaps in fresh footprint children, so the originals are hidden only once it is done
2135 commit.Revert();
2136 setPreviewHidden( true );
2138 m_areas.m_compatMap = std::move( savedCompat );
2139 m_areas.m_options = savedOptions;
2140 canvas()->Refresh();
2142 wxLogTrace( traceMultichannelTool, wxT( "Preview: %s" ), timer.to_string() );
2143}
2144
2145
2147{
2148 if( m_previewBoxes.empty() )
2149 return;
2150
2151 // Lines at the old positions would otherwise sit beside the previewed ones
2152 std::vector<BOARD_ITEM*> moved;
2153
2154 for( const auto& [fp, box] : m_previewBoxes )
2155 moved.push_back( fp );
2156
2159}
2160
2161
2162std::set<BOARD_CONNECTED_ITEM*> MULTICHANNEL_TOOL::findRepeatRouting( RULE_AREA* aArea, const std::set<int>& aNets,
2163 const REPEAT_LAYOUT_OPTIONS& aOpts )
2164{
2165 std::shared_ptr<CONNECTIVITY_DATA> connectivity = board()->GetConnectivity();
2166 std::set<BOARD_CONNECTED_ITEM*> scanned;
2167 std::set<BOARD_CONNECTED_ITEM*> routing;
2168
2169 findRoutingInRuleArea( aArea, scanned );
2170
2171 for( BOARD_CONNECTED_ITEM* item : scanned )
2172 {
2173 if( aNets.contains( item->GetNetCode() ) )
2174 routing.insert( item );
2175 }
2176
2177 // A linked channel's group already holds everything it carries
2178 if( aOpts.m_connectedRoutingOnly || linkedChannelGroup( board(), aArea ) )
2179 return routing;
2180
2181 const std::set<BOARD_CONNECTED_ITEM*> inside = routing;
2182
2183 for( BOARD_CONNECTED_ITEM* item : inside )
2184 {
2185 if( item->Type() == PCB_PAD_T )
2186 continue;
2187
2188 for( CN_ITEM* cnItem : connectivity->GetConnectivityAlgo()->ItemEntry( item ).GetItems() )
2189 {
2190 for( CN_ITEM* touching : cnItem->ConnectedItems() )
2191 {
2192 BOARD_CONNECTED_ITEM* next = touching->Valid() ? touching->Parent() : nullptr;
2193
2194 if( !next || ( next->Type() != PCB_TRACE_T && next->Type() != PCB_ARC_T && next->Type() != PCB_VIA_T ) )
2195 continue;
2196
2197 // Tracks of a meander travel with their generator
2198 EDA_GROUP* parent = next->GetParentGroup();
2199
2200 if( parent && parent->AsEdaItem()->Type() == PCB_GENERATOR_T )
2201 continue;
2202
2203 if( next->GetNetCode() == item->GetNetCode() && aNets.contains( next->GetNetCode() ) )
2204 routing.insert( next );
2205 }
2206 }
2207 }
2208
2209 return routing;
2210}
2211
2212
2214{
2216
2217 if( !view )
2218 return;
2219
2220 m_focusArea = aArea;
2221
2222 if( !m_highlight )
2223 m_highlight = view->MakeOverlay();
2224
2225 m_highlight->Clear();
2226
2227 auto mark =
2228 [&]( const RULE_AREA* aMarked, const KIGFX::COLOR4D& aColor )
2229 {
2230 m_highlight->SetIsStroke( true );
2231 m_highlight->SetIsFill( true );
2232 m_highlight->SetStrokeColor( aColor.WithAlpha( 0.9 ) );
2233 m_highlight->SetFillColor( aColor.WithAlpha( 0.08 ) );
2234 m_highlight->SetLineWidth( pcbIUScale.mmToIU( 0.2 ) );
2235
2236 for( FOOTPRINT* fp : aMarked->m_components )
2237 {
2238 auto moved = m_previewBoxes.find( fp );
2239 BOX2I box = moved != m_previewBoxes.end() ? moved->second : fp->GetBoundingBox( false );
2240
2241 m_highlight->Rectangle( box.GetOrigin(), box.GetEnd() );
2242 }
2243 };
2244
2245 if( m_areas.m_refRA )
2246 mark( m_areas.m_refRA, KIGFX::COLOR4D( 0.1, 0.8, 0.3, 1.0 ) );
2247
2248 if( aArea )
2249 mark( aArea, KIGFX::COLOR4D( 1.0, 0.6, 0.1, 1.0 ) );
2250
2251 m_highlight->SetIsFill( false );
2252 m_highlight->SetStrokeColor( KIGFX::COLOR4D( 0.6, 0.8, 1.0, 0.8 ) );
2253 m_highlight->SetLineWidth( pcbIUScale.mmToIU( 0.05 ) );
2254
2255 for( const SEG& line : m_previewRatsnest )
2256 m_highlight->Line( line.A, line.B );
2257
2258 view->Update( m_highlight.get() );
2259 canvas()->Refresh();
2260}
2261
2262
2264{
2266
2267 if( !view )
2268 return;
2269
2270 view->ClearPreview();
2271 setPreviewHidden( false );
2272 m_previewHidden.clear();
2273
2274 if( !m_previewBoxes.empty() )
2275 {
2278 }
2279
2280 m_previewBoxes.clear();
2281 m_previewRatsnest.clear();
2282
2283 if( m_highlight )
2284 {
2285 view->Remove( m_highlight.get() );
2286 m_highlight.reset();
2287 }
2288
2289 canvas()->Refresh();
2290}
2291
2292
2294{
2296
2297 // Hidden items may have been deleted since, so they are found again by UUID
2298 for( const KIID& id : m_previewHidden )
2299 {
2300 BOARD_ITEM* item = board()->ResolveItem( id, true );
2301
2302 if( !item || !view->HasItem( item ) )
2303 continue;
2304
2305 view->Hide( item, aHide );
2306 item->RunOnChildren( [&]( BOARD_ITEM* aChild ) { view->Hide( aChild, aHide ); }, RECURSE_MODE::NO_RECURSE );
2307 }
2308}
2309
2310
2312{
2313 if( m_dialog )
2314 m_dialog->Close( true );
2315}
2316
2317
2319{
2321 m_focusArea = nullptr;
2322
2323 m_dialog->Unbind( wxEVT_CLOSE_WINDOW, &MULTICHANNEL_TOOL::onRepeatDialogClosed, this );
2324 m_dialog->Destroy();
2325 m_dialog = nullptr;
2326
2328}
2329
2330
2332{
2333 m_areas.m_refRA = nullptr;
2334
2335 for( RULE_AREA& ra : m_areas.m_areas )
2336 {
2337 if( ra.m_zone == aRefZone )
2338 {
2339 m_areas.m_refRA = &ra;
2340 break;
2341 }
2342 }
2343
2344 if( !m_areas.m_refRA )
2345 return -1;
2346
2347 m_areas.m_compatMap.clear();
2348
2349 std::vector<TOPOLOGY_JOB> jobs;
2350
2351 for( RULE_AREA& ra : m_areas.m_areas )
2352 {
2353 if( ra.m_zone == m_areas.m_refRA->m_zone )
2354 continue;
2355
2356 jobs.push_back( { m_areas.m_refRA, &ra, &m_areas.m_compatMap[&ra] } );
2357 }
2358
2359 if( !resolveTopologies( _( "Checking Rule Area compatibility..." ), jobs ) )
2360 {
2361 m_areas.m_compatMap.clear();
2362 return -1;
2363 }
2364
2365 return 0;
2366}
2367
2368
2369bool MULTICHANNEL_TOOL::resolveTopologies( const wxString& aTitle, const std::vector<TOPOLOGY_JOB>& aJobs )
2370{
2371 if( aJobs.empty() )
2372 return true;
2373
2374 int total = static_cast<int>( aJobs.size() );
2375 std::atomic<int> completed( 0 );
2376 std::atomic<bool> cancelled( false );
2377 std::atomic<int> matchedComponents( 0 );
2378 std::atomic<int> totalComponents( 0 );
2379
2381 isoParams.m_cancelled = &cancelled;
2382 isoParams.m_matchedComponents = &matchedComponents;
2383 isoParams.m_totalComponents = &totalComponents;
2384
2385 // Process RA resolutions sequentially on a single background thread.
2386 // Each resolveConnectionTopology call internally parallelizes its MRV scan
2387 // across the thread pool, creating many short-lived tasks that fully utilize
2388 // all available cores. Running the outer loop sequentially avoids thread
2389 // pool starvation from nested parallelism.
2390 // The loop waits on those tasks, so it runs outside the pool lest a one-thread pool deadlock
2391 auto future = std::async(
2392 std::launch::async,
2393 [this, &aJobs, &completed, &cancelled, &matchedComponents, &isoParams]()
2394 {
2395 for( const TOPOLOGY_JOB& job : aJobs )
2396 {
2397 if( cancelled.load( std::memory_order_relaxed ) )
2398 break;
2399
2400 matchedComponents.store( 0, std::memory_order_relaxed );
2401 resolveConnectionTopology( job.m_ref, job.m_target, *job.m_compat, isoParams );
2402
2403 if( cancelled.load( std::memory_order_relaxed ) )
2404 break;
2405
2406 completed.fetch_add( 1, std::memory_order_relaxed );
2407 }
2408 } );
2409
2410 if( Pgm().IsGUI() )
2411 {
2412 // Declared first so the windows are enabled again only after the progress dialog is gone, the
2413 // Repeat dialog last so it is raised over the board
2414 std::unique_ptr<WINDOW_DISABLER> dialogDisabler;
2415 std::unique_ptr<WINDOW_DISABLER> frameDisabler;
2416 std::unique_ptr<WX_PROGRESS_REPORTER> reporter;
2417 auto startTime = std::chrono::steady_clock::now();
2418 double highWaterMark = 0.0;
2419
2420 while( future.wait_for( std::chrono::milliseconds( 100 ) ) != std::future_status::ready )
2421 {
2422 if( !reporter )
2423 {
2424 // Short enough to feel immediate, long enough not to flash for a small board
2425 if( std::chrono::steady_clock::now() - startTime > std::chrono::milliseconds( 250 ) )
2426 {
2427 // The progress dialog pumps events from its first Show, and the board and a non-modal
2428 // Repeat dialog must not change while the worker reads them
2429 dialogDisabler = std::make_unique<WINDOW_DISABLER>( m_dialog );
2430 frameDisabler = std::make_unique<WINDOW_DISABLER>( frame() );
2431 reporter = std::make_unique<WX_PROGRESS_REPORTER>( frame(), aTitle, 1, PR_CAN_ABORT );
2432 }
2433 else
2434 {
2435 // Flush background-thread log messages so timing traces appear promptly
2436 wxLog::FlushActive();
2437 }
2438 }
2439
2440 if( reporter )
2441 {
2442 int done = completed.load( std::memory_order_relaxed );
2443 int matched = matchedComponents.load( std::memory_order_relaxed );
2444 int compTotal = totalComponents.load( std::memory_order_relaxed );
2445
2446 double fraction = ( compTotal > 0 )
2447 ? static_cast<double>( matched ) / compTotal
2448 : 0.0;
2449 double progress = static_cast<double>( done + fraction ) / total;
2450
2451 if( progress > highWaterMark )
2452 highWaterMark = progress;
2453
2454 reporter->SetCurrentProgress( highWaterMark );
2455 reporter->Report( wxString::Format(
2456 _( "Resolving topology %d of %d (%d/%d components)" ),
2457 std::min( done + 1, total ), total, matched, compTotal ) );
2458
2459 if( !reporter->KeepRefreshing() )
2460 cancelled.store( true, std::memory_order_relaxed );
2461 }
2462 }
2463 }
2464 else
2465 {
2466 future.wait();
2467 }
2468
2469 if( !cancelled.load( std::memory_order_relaxed ) )
2470 return true;
2471
2472 // A job stopped part way says no more about its topology than one never started
2473 for( size_t i = static_cast<size_t>( completed.load() ); i < aJobs.size(); ++i )
2474 {
2475 aJobs[i].m_compat->m_isOk = false;
2476 aJobs[i].m_compat->m_errorMsg = _( "Cancelled" );
2477 aJobs[i].m_compat->m_mismatchReasons.clear();
2478 }
2479
2480 return false;
2481}
2482
2483
2484int MULTICHANNEL_TOOL::RepeatLayout( const TOOL_EVENT& aEvent, RULE_AREA& aRefArea, RULE_AREA& aTargetArea,
2485 REPEAT_LAYOUT_OPTIONS& aOptions, BOARD_COMMIT* aExternalCommit,
2486 wxString* aErrorOut )
2487{
2488 wxCHECK_MSG( aRefArea.m_zone, -1, wxT( "Reference Rule Area has no zone." ) );
2489 wxCHECK_MSG( aTargetArea.m_zone, -1, wxT( "Target Rule Area has no zone." ) );
2490
2491 const bool silent = aErrorOut != nullptr;
2492
2493 auto reportError = [&]( const wxString& aMsg )
2494 {
2495 if( aErrorOut )
2496 *aErrorOut = aMsg;
2497 else if( Pgm().IsGUI() )
2498 frame()->ShowInfoBarError( aMsg, true );
2499 };
2500
2501 RULE_AREA_COMPAT_DATA compat;
2502
2503 if( !resolveConnectionTopology( &aRefArea, &aTargetArea, compat ) )
2504 {
2505 if( silent )
2506 {
2507 *aErrorOut = compat.m_mismatchReasons.empty() ? compat.m_errorMsg
2509 }
2510 else if( Pgm().IsGUI() )
2511 {
2512 wxString summary = wxString::Format( _( "Rule Area topologies do not match: %s" ), compat.m_errorMsg );
2514 }
2515
2516 return -1;
2517 }
2518
2519 std::optional<BOARD_COMMIT> localCommit;
2520
2521 if( !aExternalCommit )
2522 localCommit.emplace( GetManager(), true, false );
2523
2524 BOARD_COMMIT& commit = aExternalCommit ? *aExternalCommit : *localCommit;
2525
2526 // If no anchor is provided, pick the first matched pair to avoid center-alignment shifting
2527 // the whole group. This keeps Apply Design Block Layout from moving the group to wherever
2528 // the source design block happened to be placed.
2530 && aTargetArea.m_sourceType == PLACEMENT_SOURCE_T::GROUP_PLACEMENT && aOptions.m_anchor == niluuid )
2531 {
2532 if( !compat.m_matchingComponents.empty() )
2533 aOptions.m_anchor = firstPair( compat.m_matchingComponents ).first->m_Uuid;
2534 }
2535
2536 copyRuleAreaContents( &aRefArea, &aTargetArea, &commit, aOptions, compat );
2537
2539 {
2540 EDA_GROUP* group = aTargetArea.m_group;
2541
2542 if( !group && !aTargetArea.m_components.empty() )
2543 group = ( *aTargetArea.m_components.begin() )->GetParentGroup();
2544
2545 if( !group )
2546 {
2547 if( !aExternalCommit )
2548 commit.Revert();
2549
2550 reportError( _( "Target group does not have a group." ) );
2551
2552 return -1;
2553 }
2554
2555 commit.Modify( group->AsEdaItem(), nullptr, RECURSE_MODE::NO_RECURSE );
2556
2557 for( BOARD_ITEM* item : compat.m_groupableItems )
2558 {
2559 // Items already in a nested group stay there so the nesting survives
2560 if( group->ContainsItem( item ) )
2561 continue;
2562
2563 commit.Modify( item );
2564 group->AddItem( item );
2565 }
2566 }
2567
2568 if( !aExternalCommit )
2569 commit.Push( _( "Repeat Layout" ) );
2570
2571 return 0;
2572}
2573
2574
2576{
2577 int totalCopied = 0;
2578
2579 for( auto& [targetArea, compatData] : m_areas.m_compatMap )
2580 {
2581 if( !compatData.m_doCopy )
2582 {
2583 wxLogTrace( traceMultichannelTool, wxT( "skipping copy to RA '%s' (disabled in dialog)\n" ),
2584 targetArea->m_ruleName );
2585 continue;
2586 }
2587
2588 if( !compatData.m_isOk )
2589 continue;
2590
2591 copyRuleAreaContents( m_areas.m_refRA, targetArea, &aCommit, m_areas.m_options, compatData );
2592 totalCopied++;
2593 }
2594
2595 if( m_areas.m_options.m_groupItems )
2596 {
2597 for( const auto& [targetArea, compatData] : m_areas.m_compatMap )
2598 {
2599 if( compatData.m_groupableItems.size() < 2 )
2600 continue;
2601
2602 // A group-driven area already has a group.
2603 EDA_GROUP* group =
2604 targetArea->m_sourceType == PLACEMENT_SOURCE_T::GROUP_PLACEMENT ? targetArea->m_group : nullptr;
2605
2606 if( group )
2607 {
2608 aCommit.Modify( group->AsEdaItem(), nullptr, RECURSE_MODE::NO_RECURSE );
2609 }
2610 else
2611 {
2612 pruneExistingGroups( aCommit, compatData.m_affectedItems );
2613
2614 group = new PCB_GROUP( board() );
2615 aCommit.Add( group->AsEdaItem() );
2616 }
2617
2618 for( BOARD_ITEM* item : compatData.m_groupableItems )
2619 stageAddToGroup( aCommit, group, item );
2620 }
2621 }
2622
2623 return totalCopied;
2624}
2625
2626
2627int MULTICHANNEL_TOOL::RepeatLayout( const TOOL_EVENT& aEvent, ZONE* aRefZone )
2628{
2629 BOARD_COMMIT commit( GetManager(), true, false );
2630 int totalCopied = applyRepeat( commit );
2631
2632 if( m_areas.m_linkAreas )
2633 {
2634 std::vector<RULE_AREA*> targets;
2635
2636 for( const auto& [targetArea, compatData] : m_areas.m_compatMap )
2637 {
2638 if( compatData.m_doCopy && compatData.m_isOk )
2639 targets.push_back( targetArea );
2640 }
2641
2642 linkAreas( commit, aRefZone, targets );
2643 }
2644
2645 commit.Push( _( "Repeat Layout" ) );
2646
2647 if( Pgm().IsGUI() )
2648 frame()->ShowInfoBarMsg( wxString::Format( _( "Copied to %d Rule Areas." ), totalCopied ), true );
2649
2650 return 0;
2651}
2652
2653
2655{
2656 if( aZone->GetBoard() )
2657 aCommit.Modify( aZone );
2658
2659 aZone->SetLinkSet( niluuid );
2661}
2662
2663
2664void MULTICHANNEL_TOOL::linkAreas( BOARD_COMMIT& aCommit, ZONE* aRefZone, const std::vector<RULE_AREA*>& aTargets )
2665{
2666 const REPEAT_LAYOUT_OPTIONS& opts = m_areas.m_options;
2667 const KIID linkSet;
2668 std::set<KIID> oldSets;
2669
2670 // New zones are not on the board yet, so the commit has nothing to snapshot
2671 auto join = [&]( ZONE* aZone, const KIID& aAnchor )
2672 {
2673 if( aZone->GetBoard() )
2674 aCommit.Modify( aZone );
2675
2676 REPEAT_LAYOUT_OPTIONS own = opts;
2677 own.m_anchor = aAnchor;
2678
2679 if( aZone->GetLinkSet() != niluuid )
2680 oldSets.insert( aZone->GetLinkSet() );
2681
2682 aZone->SetLinkSet( linkSet );
2683 aZone->SetRepeatOptions( own );
2684 };
2685
2686 join( aRefZone, opts.m_anchor );
2687
2688 for( RULE_AREA* target : aTargets )
2689 {
2690 const TMATCH::COMPONENT_MATCHES& matches = m_areas.m_compatMap[target].m_matchingComponents;
2692
2693 // Each area keeps its own counterpart of the anchor, so any of them can be the source later
2694 if( opts.m_anchor != niluuid && !matches.empty() )
2695 anchor = anchorPair( matches, opts.m_anchor ).second->m_Uuid;
2696
2697 join( target->m_zone, anchor );
2698 }
2699
2700 // Peers that were left out stay linked to each other unless they are alone
2701 dropLoneLinks( aCommit, oldSets );
2702}
2703
2704
2705void MULTICHANNEL_TOOL::dropLoneLinks( BOARD_COMMIT& aCommit, const std::set<KIID>& aSets )
2706{
2707 std::map<KIID, std::vector<ZONE*>> members;
2708
2709 for( ZONE* zone : board()->Zones() )
2710 {
2711 if( aSets.contains( zone->GetLinkSet() ) )
2712 members[zone->GetLinkSet()].push_back( zone );
2713 }
2714
2715 for( const auto& [linkSet, zones] : members )
2716 {
2717 if( zones.size() < 2 )
2718 detachArea( aCommit, zones.front() );
2719 }
2720}
2721
2722
2724{
2725 // A router keeps its own copy of the board while routing; editing under it leaves it stale
2726 ROUTER_TOOL* router = m_toolMgr->GetTool<ROUTER_TOOL>();
2727 GENERATOR_TOOL* generators = m_toolMgr->GetTool<GENERATOR_TOOL>();
2728
2729 return ( router && router->RoutingInProgress() )
2730 || ( generators && generators->Router() && generators->Router()->RoutingInProgress() );
2731}
2732
2733
2735{
2736 std::set<ZONE*> sources = linkedAreasIn( selection() );
2737
2738 if( sources.size() != 1 )
2739 {
2740 frame()->ShowInfoBarMsg( sources.empty() ? _( "Select a linked Rule Area, or a part of one, to update the "
2741 "others from." )
2742 : _( "Select items from a single linked channel." ),
2743 true );
2744 return 0;
2745 }
2746
2747 if( routerBusy() )
2748 {
2749 frame()->ShowInfoBarWarning( _( "Finish routing before updating linked layouts." ), true );
2750 return 0;
2751 }
2752
2753 UpdateLinkedLayouts( *sources.begin() );
2754 return 0;
2755}
2756
2757
2759{
2760 std::set<ZONE*> members = linkedAreasIn( selection() );
2761
2762 if( members.empty() )
2763 frame()->ShowInfoBarMsg( _( "Select a linked Rule Area, or a part of one, to unlink." ), true );
2764 else
2765 UnlinkAreas( members );
2766
2767 return 0;
2768}
2769
2770
2771void MULTICHANNEL_TOOL::UnlinkAreas( const std::set<ZONE*>& aZones )
2772{
2773 BOARD_COMMIT commit( GetManager(), true, false );
2774 std::set<KIID> oldSets;
2775
2776 for( ZONE* zone : aZones )
2777 {
2778 if( zone->GetLinkSet() != niluuid )
2779 oldSets.insert( zone->GetLinkSet() );
2780
2781 detachArea( commit, zone );
2782 }
2783
2784 dropLoneLinks( commit, oldSets );
2785 commit.Push( _( "Unlink Layout" ) );
2786}
2787
2788
2790{
2791 // The dialog's session lives in the same data this rebuilds
2793
2795
2796 RULE_AREA* ref = nullptr;
2797 std::vector<RULE_AREA*> linked;
2798 std::map<FOOTPRINT*, int> footprintUse;
2799
2800 for( RULE_AREA& area : m_areas.m_areas )
2801 {
2802 if( area.m_zone->GetLinkSet() == niluuid )
2803 continue;
2804
2805 linked.push_back( &area );
2806
2807 if( area.m_zone == aSource )
2808 ref = &area;
2809
2810 for( FOOTPRINT* fp : area.m_components )
2811 footprintUse[fp]++;
2812 }
2813
2814 if( !ref )
2815 return false;
2816
2817 // A target sharing parts with another linked area would overwrite that area's layout
2818 auto sharesParts =
2819 [&]( RULE_AREA* aArea )
2820 {
2821 return std::ranges::any_of( aArea->m_components,
2822 [&]( FOOTPRINT* aFp ) { return footprintUse[aFp] > 1; } );
2823 };
2824
2825 // Copper is cleared and copied by area, unless both ends hold exactly their own group's items
2826 auto overlapsOtherArea =
2827 [&]( RULE_AREA* aArea, const SHAPE_POLY_SET& aOutline )
2828 {
2829 return std::ranges::any_of( linked,
2830 [&]( RULE_AREA* aOther )
2831 {
2832 return aOther != aArea
2833 && outlinesOverlap( aOutline, *aOther->m_zone->Outline() );
2834 } );
2835 };
2836
2837 const bool refGrouped = linkedChannelGroup( board(), ref ) != nullptr;
2838
2839 // A source lying over another linked area would copy that area's contents too
2840 if( sharesParts( ref ) || ( !refGrouped && overlapsOtherArea( ref, *ref->m_zone->Outline() ) ) )
2841 {
2842 if( Pgm().IsGUI() )
2843 {
2844 frame()->ShowInfoBarWarning(
2845 wxString::Format( _( "'%s' overlaps another linked Rule Area." ), ref->m_ruleName ), true );
2846 }
2847
2848 return false;
2849 }
2850
2851 BOARD_COMMIT commit( GetManager(), true, false );
2852 std::vector<wxString> problems;
2853 std::vector<SHAPE_POLY_SET> acceptedOutlines;
2854
2855 m_areas.m_refRA = ref;
2856 m_areas.m_options = aSource->GetRepeatOptions();
2857 m_areas.m_compatMap.clear();
2858
2859 std::vector<RULE_AREA*> targets;
2860 std::vector<TOPOLOGY_JOB> jobs;
2861
2862 for( RULE_AREA* target : linked )
2863 {
2864 if( target == ref || target->m_zone->GetLinkSet() != aSource->GetLinkSet() )
2865 continue;
2866
2867 targets.push_back( target );
2868 jobs.push_back( { ref, target, &m_areas.m_compatMap[target] } );
2869 }
2870
2871 if( !resolveTopologies( _( "Updating linked layouts..." ), jobs ) )
2872 {
2873 m_areas.m_compatMap.clear();
2874 return false;
2875 }
2876
2877 for( RULE_AREA* target : targets )
2878 {
2879 RULE_AREA_COMPAT_DATA& compat = m_areas.m_compatMap[target];
2880
2881 if( !compat.m_isOk )
2882 {
2883 problems.push_back( wxString::Format( wxT( "'%s': %s" ), target->m_ruleName, compat.m_errorMsg ) );
2884 continue;
2885 }
2886
2887 // Unless both ends are grouped, copying clears the target by area, so both its outline now and the
2888 // one the copy gives it must stay clear of every other linked area
2889 VECTOR2I disp;
2890 EDA_ANGLE rot;
2891 SHAPE_POLY_SET repeated( repeatedOutline( ref, target, m_areas.m_options.m_anchor,
2892 compat.m_matchingComponents, disp, rot ) );
2893
2894 bool overlapsAccepted = std::ranges::any_of( acceptedOutlines,
2895 [&]( const SHAPE_POLY_SET& aOther )
2896 {
2897 return outlinesOverlap( repeated, aOther );
2898 } );
2899
2900 bool scoped = refGrouped && linkedChannelGroup( board(), target ) != nullptr;
2901
2902 if( sharesParts( target )
2903 || ( !scoped && ( overlapsAccepted || overlapsOtherArea( target, *target->m_zone->Outline() )
2904 || overlapsOtherArea( target, repeated ) ) ) )
2905 {
2906 problems.push_back(
2907 wxString::Format( _( "'%s' overlaps another linked Rule Area." ), target->m_ruleName ) );
2908 continue;
2909 }
2910
2911 compat.m_doCopy = true;
2912 acceptedOutlines.push_back( std::move( repeated ) );
2913 }
2914
2915 int copied = applyRepeat( commit );
2916
2917 if( !problems.empty() && Pgm().IsGUI() )
2918 {
2919 frame()->ShowInfoBarWarning(
2920 wxString::Format( _( "Some linked Rule Areas were not updated. %s" ), JoinMismatchReasons( problems ) ),
2921 true );
2922 }
2923
2924 if( !copied )
2925 return false;
2926
2927 commit.Push( _( "Update Linked Layouts" ), SKIP_ENTERED_GROUP );
2928 return true;
2929}
2930
2931
2932int MULTICHANNEL_TOOL::findRoutingInRuleArea( RULE_AREA* aRuleArea, std::set<BOARD_CONNECTED_ITEM*>& aOutput ) const
2933{
2934 if( !aRuleArea || !aRuleArea->m_zone )
2935 return 0;
2936
2937 // The user also will consider tracks and vias that are inside the source area but
2938 // not connected to any of the source pads to count as "routing" (e.g. stitching vias)
2939
2940 int count = 0;
2941
2942 // When we're copying the layout of a design block, we are provided an exact list of items
2943 // rather than querying the board for items that are inside the area.
2945 {
2946 // Get all board connected items that are from the design block, except pads,
2947 // which shouldn't be copied
2948 for( EDA_ITEM* item : aRuleArea->m_designBlockItems )
2949 {
2950 // Include any connected items except pads.
2951 if( item->Type() == PCB_PAD_T )
2952 continue;
2953
2954 if( BOARD_CONNECTED_ITEM* bci = dynamic_cast<BOARD_CONNECTED_ITEM*>( item ) )
2955 {
2956 // Zones are handled by the "copy other items" path, we need this check here
2957 // because design blocks explicitly include them as part of the block contents,
2958 // but other RA types grab them by querying the board for items enclosed by the RA polygon
2959 if( bci->Type() == PCB_ZONE_T )
2960 continue;
2961
2962 // Tracks inside a generator (meander) are copied with the generator.
2963 if( EDA_GROUP* parent = bci->GetParentGroup() )
2964 {
2965 if( parent->AsEdaItem()->Type() == PCB_GENERATOR_T )
2966 continue;
2967 }
2968
2969 if( bci->IsConnected() )
2970 aOutput.insert( bci );
2971 }
2972 }
2973
2974 if( !aRuleArea->m_fromSelection )
2975 return (int) aOutput.size();
2976
2977 count = (int) aOutput.size();
2978 }
2979
2980 if( EDA_GROUP* group = linkedChannelGroup( board(), aRuleArea ) )
2981 {
2982 std::set<BOARD_ITEM*> members;
2983 collectGroupBoardItems( group, members );
2984
2985 for( BOARD_ITEM* member : members )
2986 {
2987 BOARD_CONNECTED_ITEM* bci = dynamic_cast<BOARD_CONNECTED_ITEM*>( member );
2988
2989 if( !bci || bci->Type() == PCB_PAD_T || bci->Type() == PCB_ZONE_T || !bci->IsConnected() )
2990 continue;
2991
2992 if( EDA_GROUP* parent = bci->GetParentGroup() )
2993 {
2994 if( parent->AsEdaItem()->Type() == PCB_GENERATOR_T )
2995 continue;
2996 }
2997
2998 aOutput.insert( bci );
2999 count++;
3000 }
3001
3002 return count;
3003 }
3004
3005 // The design-block apply target uses a scratch zone not on the board, so enclosedByArea()
3006 // below finds nothing. Match routing against the zone outline directly.
3007 if( aRuleArea->m_sourceType == PLACEMENT_SOURCE_T::GROUP_PLACEMENT || aRuleArea->m_fromSelection )
3008 {
3009 bool zoneOnBoard = false;
3010
3011 for( ZONE* zone : board()->Zones() )
3012 {
3013 if( zone == aRuleArea->m_zone )
3014 {
3015 zoneOnBoard = true;
3016 break;
3017 }
3018 }
3019
3020 if( !zoneOnBoard )
3021 {
3022 const SHAPE_POLY_SET& areaOutline = *aRuleArea->m_zone->Outline();
3023 const BOX2I areaBox = areaOutline.BBox();
3024 int maxError = board()->GetDesignSettings().m_MaxError;
3025
3026 auto enclosedByZone = [&]( BOARD_CONNECTED_ITEM* aItem )
3027 {
3028 if( aOutput.contains( aItem ) )
3029 return;
3030
3031 // Tracks inside a generator (meander) are removed with the generator.
3032 if( EDA_GROUP* parent = aItem->GetParentGroup() )
3033 {
3034 if( parent->AsEdaItem()->Type() == PCB_GENERATOR_T )
3035 return;
3036 }
3037
3038 if( !( aRuleArea->m_zone->GetLayerSet() & aItem->GetLayerSet() ).any()
3039 || !areaBox.Contains( aItem->GetBoundingBox() ) )
3040 {
3041 return;
3042 }
3043
3044 SHAPE_POLY_SET itemShape;
3045 aItem->TransformShapeToPolygon( itemShape, aItem->GetLayer(), 0, maxError, ERROR_OUTSIDE );
3046
3047 if( itemShape.IsEmpty() )
3048 return;
3049
3050 itemShape.BooleanSubtract( areaOutline );
3051
3052 if( itemShape.IsEmpty() )
3053 {
3054 aOutput.insert( aItem );
3055 count++;
3056 }
3057 };
3058
3059 for( PCB_TRACK* track : board()->Tracks() )
3060 enclosedByZone( track );
3061
3062 for( BOARD_ITEM* drawing : board()->Drawings() )
3063 {
3064 if( drawing->IsConnected() )
3065 enclosedByZone( static_cast<BOARD_CONNECTED_ITEM*>( drawing ) );
3066 }
3067
3068 return count;
3069 }
3070 }
3071
3073 PCBEXPR_UCODE ucode;
3074 PCBEXPR_CONTEXT ctx, preflightCtx;
3075
3076 auto reportError =
3077 [&]( const wxString& aMessage, int aOffset )
3078 {
3079 wxLogTrace( traceMultichannelTool, wxT( "ERROR: %s" ), aMessage );
3080 };
3081
3082 ctx.SetErrorCallback( reportError );
3083 preflightCtx.SetErrorCallback( reportError );
3084 compiler.SetErrorCallback( reportError );
3085
3086 // Use the zone's UUID to identify it uniquely. Using the zone name could match other zones
3087 // with the same name (e.g., a copper fill zone with the same name as a rule area).
3088 wxString ruleText = wxString::Format( wxT( "A.enclosedByArea('%s')" ),
3089 aRuleArea->m_zone->m_Uuid.AsString() );
3090
3091 const BOX2I zoneBox = aRuleArea->m_zone->Outline()->BBox();
3092
3093 auto testAndAdd =
3094 [&]( BOARD_CONNECTED_ITEM* aItem )
3095 {
3096 if( aOutput.contains( aItem ) )
3097 return;
3098
3099 // Tracks inside a generator (meander) are copied with the generator.
3100 if( EDA_GROUP* parent = aItem->GetParentGroup() )
3101 {
3102 if( parent->AsEdaItem()->Type() == PCB_GENERATOR_T )
3103 return;
3104 }
3105
3106 // Items outside the area's box cannot be enclosed, so skip the costly evaluation
3107 if( !( aRuleArea->m_zone->GetLayerSet() & aItem->GetLayerSet() ).any()
3108 || !zoneBox.Intersects( aItem->GetBoundingBox() ) )
3109 {
3110 return;
3111 }
3112
3113 ctx.SetItems( aItem, aItem );
3114 LIBEVAL::VALUE* val = ucode.Run( &ctx );
3115
3116 if( val->AsDouble() != 0.0 )
3117 {
3118 aOutput.insert( aItem );
3119 count++;
3120 }
3121 };
3122
3123 if( compiler.Compile( ruleText, &ucode, &preflightCtx ) )
3124 {
3125 for( PCB_TRACK* track : board()->Tracks() )
3126 testAndAdd( track );
3127
3128 for( BOARD_ITEM* drawing : board()->Drawings() )
3129 {
3130 if( drawing->IsConnected() )
3131 testAndAdd( static_cast<BOARD_CONNECTED_ITEM*>( drawing ) );
3132 }
3133 }
3134
3135 return count;
3136}
3137
3138
3140 REPEAT_LAYOUT_OPTIONS aOpts, RULE_AREA_COMPAT_DATA& aCompatData )
3141{
3142 VECTOR2I disp;
3143 EDA_ANGLE rot;
3144 SHAPE_LINE_CHAIN newTargetOutline =
3145 repeatedOutline( aRefArea, aTargetArea, aOpts.m_anchor, aCompatData.m_matchingComponents, disp, rot );
3146
3147 // Reference net to the net of the first matching target pad, built once for all copied items
3148 const bool hasMatches = !aCompatData.m_matchingComponents.empty();
3149 std::map<int, int> netMap;
3150
3151 for( const auto& [refFP, targetFP] : aCompatData.m_matchingComponents )
3152 {
3153 for( const PAD* refPad : refFP->Pads() )
3154 {
3155 if( refPad->GetNetCode() <= 0 )
3156 continue;
3157
3158 std::vector<const PAD*> targetPads = targetFP->GetPads( refPad->GetNumber() );
3159
3160 if( !targetPads.empty() )
3161 netMap.emplace( refPad->GetNetCode(), targetPads[0]->GetNetCode() );
3162 }
3163 }
3164
3165 SHAPE_POLY_SET refPoly;
3166 refPoly.AddOutline( aRefArea->m_zone->Outline()->COutline( 0 ) );
3167 refPoly.CacheTriangulation();
3168
3169 std::shared_ptr<CONNECTIVITY_DATA> connectivity = board()->GetConnectivity();
3170
3171 // Group placement targets let RepeatLayout() reuse the existing target group, and m_groupItems
3172 // flat-groups every copy into one rule-area group. Reconstructing source groups here in either
3173 // case strands their members and leaves empty phantom clones behind (issue 22316).
3174 const bool preserveGroups = aTargetArea->m_sourceType != PLACEMENT_SOURCE_T::GROUP_PLACEMENT
3175 && !aOpts.m_groupItems;
3176
3177 // Defer reconstruction until every copy is made. Cloning a source group the moment one member
3178 // is copied would duplicate user groups that merely overlap the source area (issue 22316); a
3179 // group is rebuilt only once all of its members have been reproduced.
3180 std::vector<std::pair<BOARD_ITEM*, BOARD_ITEM*>> groupFixupPairs;
3181 std::set<BOARD_ITEM*> reproducedSourceItems;
3182
3183 auto fixupParentGroup =
3184 [&]( BOARD_ITEM* sourceItem, BOARD_ITEM* destItem )
3185 {
3186 // The copy inherits the source's parent-group pointer but is not a member of that
3187 // group; clear the dangling reference.
3188 destItem->SetParentGroup( nullptr );
3189
3190 if( !preserveGroups )
3191 return;
3192
3193 if( sourceItem->GetParentGroup() )
3194 groupFixupPairs.emplace_back( sourceItem, destItem );
3195
3196 reproducedSourceItems.insert( sourceItem );
3197 };
3198
3199 // Only stage changes for a target Rule Area zone if it actually belongs to the board.
3200 // In some workflows (e.g. ApplyDesignBlockLayout), the target area is a temporary zone
3201 // and is not added to the BOARD.
3202 bool targetZoneOnBoard = false;
3203
3204 if( aTargetArea->m_zone )
3205 {
3206 for( ZONE* z : board()->Zones() )
3207 {
3208 if( z == aTargetArea->m_zone )
3209 {
3210 targetZoneOnBoard = true;
3211 break;
3212 }
3213 }
3214 }
3215
3216 if( targetZoneOnBoard )
3217 {
3218 aCommit->Modify( aTargetArea->m_zone );
3219 aCompatData.m_affectedItems.insert( aTargetArea->m_zone );
3220 aCompatData.m_groupableItems.insert( aTargetArea->m_zone );
3221
3222 // The source rule-area zone maps to the target zone; treat it as reproduced so a group
3223 // containing it can still be rebuilt.
3224 if( preserveGroups )
3225 {
3226 if( aRefArea->m_zone->GetParentGroup() )
3227 groupFixupPairs.emplace_back( aRefArea->m_zone, aTargetArea->m_zone );
3228
3229 reproducedSourceItems.insert( aRefArea->m_zone );
3230 }
3231 }
3232
3233 if( aOpts.m_copyRouting )
3234 {
3235 std::set<BOARD_CONNECTED_ITEM*> refRouting;
3236 std::set<BOARD_CONNECTED_ITEM*> targetRouting;
3237
3238 wxLogTrace( traceMultichannelTool, wxT( "copying routing: %d fps\n" ),
3239 (int) aCompatData.m_matchingComponents.size() );
3240
3241 std::set<int> refc;
3242 std::set<int> targc;
3243
3244 for( const auto& [refFP, targetFP] : aCompatData.m_matchingComponents )
3245 {
3246 for( PAD* pad : refFP->Pads() )
3247 refc.insert( pad->GetNetCode() );
3248
3249 for( PAD* pad : targetFP->Pads() )
3250 targc.insert( pad->GetNetCode() );
3251 }
3252
3253 // What is removed from the target spans the same run as what is copied from the reference
3254 if( aRefArea->ScansContents() )
3255 {
3256 targetRouting = findRepeatRouting( aTargetArea, targc, aOpts );
3257 refRouting = findRepeatRouting( aRefArea, refc, aOpts );
3258 }
3259 else
3260 {
3261 findRoutingInRuleArea( aTargetArea, targetRouting );
3262 findRoutingInRuleArea( aRefArea, refRouting );
3263 }
3264
3265 // Nets used by the target group's own items, footprint pads included. Taken from the area's
3266 // footprints too, since a channel created from a selection fills its group only when applied
3267 std::set<int> targetGroupNets;
3268
3269 for( FOOTPRINT* fp : aTargetArea->m_components )
3270 {
3271 for( PAD* pad : fp->Pads() )
3272 targetGroupNets.insert( pad->GetNetCode() );
3273 }
3274
3275 if( aTargetArea->m_group )
3276 {
3277 std::set<BOARD_ITEM*> members;
3278 collectGroupBoardItems( aTargetArea->m_group, members );
3279
3280 for( BOARD_ITEM* member : members )
3281 {
3282 if( BOARD_CONNECTED_ITEM* bci = dynamic_cast<BOARD_CONNECTED_ITEM*>( member ) )
3283 targetGroupNets.insert( bci->GetNetCode() );
3284 }
3285 }
3286
3287 // A channel made from a selection or a link replaces loose routing only on its own nets; buses
3288 // and rails it shares stay. A design block replaces it on every net of the group
3289 const bool channelScope = aRefArea->m_fromSelection || linkedChannelGroup( board(), aTargetArea );
3290 std::set<int> targetChannelNets;
3291
3292 for( int net : targetGroupNets )
3293 {
3294 if( !channelScope )
3295 {
3296 targetChannelNets.insert( net );
3297 continue;
3298 }
3299
3300 std::vector<FOOTPRINT*> owners;
3301
3302 for( BOARD_CONNECTED_ITEM* pad : connectivity->GetNetItems( net, { PCB_PAD_T } ) )
3303 {
3304 if( std::ranges::find( owners, pad->GetParentFootprint() ) == owners.end() )
3305 owners.push_back( pad->GetParentFootprint() );
3306 }
3307
3308 if( isChannelNet( owners, aTargetArea->m_components ) )
3309 targetChannelNets.insert( net );
3310 }
3311
3312 for( BOARD_CONNECTED_ITEM* item : targetRouting )
3313 {
3314 // Never remove pads as part of routing copy.
3315 if( item->Type() == PCB_PAD_T )
3316 continue;
3317
3318 if( aRefArea->m_designBlockItems.count( item ) )
3319 continue;
3320
3321 // Design block apply: replace only the group's own routing, nested groups included, and
3322 // loose routing on the group's nets. Other groups' routing belongs to stacked instances (issue 24767).
3323 // Everything else is unrelated and just sits inside the block's area (issue 24944).
3324 if( aTargetArea->m_group && !aTargetArea->m_group->ContainsItem( item ) )
3325 {
3326 if( item->GetParentGroup() )
3327 continue;
3328
3329 if( item->IsLocked() )
3330 continue;
3331
3332 if( item->GetNetCode() <= 0 || !targetChannelNets.contains( item->GetNetCode() ) )
3333 continue;
3334 }
3335
3336 if( item->IsLocked() && !aOpts.m_includeLockedItems )
3337 continue;
3338
3339 if( ( aOpts.m_connectedRoutingOnly || aRefArea->ScansContents() ) && !targc.contains( item->GetNetCode() ) )
3340 continue;
3341
3342 // item already removed
3343 if( aCommit->GetStatus( item ) != 0 )
3344 continue;
3345
3346 if( !aTargetArea->m_zone->GetLayerSet().Contains( item->GetLayer() ) )
3347 {
3348 continue;
3349 }
3350
3351 aCompatData.m_affectedItems.insert( item );
3352 aCommit->Remove( item );
3353 }
3354
3355 for( BOARD_CONNECTED_ITEM* item : refRouting )
3356 {
3357 // Never copy pads as part of routing copy.
3358 if( item->Type() == PCB_PAD_T )
3359 continue;
3360
3361 if( item->IsLocked() && !aOpts.m_includeLockedItems )
3362 continue;
3363
3364 if( ( aOpts.m_connectedRoutingOnly || aRefArea->ScansContents() ) && !refc.contains( item->GetNetCode() ) )
3365 continue;
3366
3367 if( !aRefArea->m_zone->GetLayerSet().Contains( item->GetLayer() ) )
3368 continue;
3369
3370 if( !aTargetArea->m_zone->GetLayerSet().Contains( item->GetLayer() ) )
3371 continue;
3372
3373 BOARD_CONNECTED_ITEM* copied = static_cast<BOARD_CONNECTED_ITEM*>( item->Duplicate( false ) );
3374
3375 fixupNet( item, copied, hasMatches, netMap );
3376 fixupParentGroup( item, copied );
3377
3378 copied->Rotate( VECTOR2( 0, 0 ), rot );
3379 copied->Move( disp );
3380 aCompatData.m_groupableItems.insert( copied );
3381 aCommit->Add( copied );
3382 }
3383
3384 // Copy generators (meanders) whole so they are not flattened to loose tracks. Design
3385 // block apply has an exact item list, other rule areas resolve them by area.
3386 std::vector<PCB_GENERATOR*> refGenerators;
3387 std::vector<PCB_GENERATOR*> targetGenerators;
3388
3389 auto appendGenerators =
3390 [&]( EDA_GROUP* aGroup, std::vector<PCB_GENERATOR*>& aOut )
3391 {
3392 std::set<BOARD_ITEM*> members;
3393 collectGroupBoardItems( aGroup, members );
3394
3395 for( BOARD_ITEM* member : members )
3396 {
3397 if( member->Type() == PCB_GENERATOR_T )
3398 aOut.push_back( static_cast<PCB_GENERATOR*>( member ) );
3399 }
3400 };
3401
3403 {
3404 for( EDA_ITEM* item : aRefArea->m_designBlockItems )
3405 {
3406 if( item->Type() == PCB_GENERATOR_T )
3407 refGenerators.push_back( static_cast<PCB_GENERATOR*>( item ) );
3408 }
3409
3410 EDA_GROUP* targetGroup = aTargetArea->m_group;
3411
3412 if( !targetGroup && !aTargetArea->m_components.empty() )
3413 targetGroup = ( *aTargetArea->m_components.begin() )->GetParentGroup();
3414
3415 if( targetGroup )
3416 appendGenerators( targetGroup, targetGenerators );
3417 }
3418 else
3419 {
3420 // Each side takes its generators from its group when it is a linked channel, else from its outline
3421 EDA_GROUP* refGroup = linkedChannelGroup( board(), aRefArea );
3422 EDA_GROUP* targetGroup = linkedChannelGroup( board(), aTargetArea );
3423
3424 if( refGroup )
3425 appendGenerators( refGroup, refGenerators );
3426
3427 if( targetGroup )
3428 appendGenerators( targetGroup, targetGenerators );
3429
3430 if( !refGroup || !targetGroup )
3431 {
3432 const SHAPE_LINE_CHAIN& refOut = aRefArea->m_zone->Outline()->COutline( 0 );
3433 const SHAPE_LINE_CHAIN& targetOut = aTargetArea->m_zone->Outline()->COutline( 0 );
3434
3435 for( PCB_GENERATOR* gen : board()->Generators() )
3436 {
3437 if( gen->GetGeneratorType() != wxT( "tuning_pattern" ) )
3438 continue;
3439
3440 if( !refGroup && gen->HitTest( refOut, false ) )
3441 refGenerators.push_back( gen );
3442 else if( !targetGroup && !( refGroup && gen->HitTest( refOut, false ) )
3443 && gen->HitTest( targetOut, false ) )
3444 targetGenerators.push_back( gen );
3445 }
3446 }
3447 }
3448
3449 // Remove the target's existing generators so the copy replaces them.
3450 for( PCB_GENERATOR* gen : targetGenerators )
3451 {
3452 if( gen->IsLocked() && !aOpts.m_includeLockedItems )
3453 continue;
3454
3455 gen->RunOnChildren(
3456 [&]( BOARD_ITEM* child )
3457 {
3458 aCommit->Remove( child );
3459 },
3461 aCommit->Remove( gen );
3462 aCompatData.m_affectedItems.insert( gen );
3463 }
3464
3465 for( PCB_GENERATOR* gen : refGenerators )
3466 {
3467 if( gen->IsLocked() && !aOpts.m_includeLockedItems )
3468 continue;
3469
3470 PCB_GENERATOR* clone = gen->DeepClone();
3471
3472 clone->ResetUuid();
3473 clone->RunOnChildren(
3474 []( BOARD_ITEM* child )
3475 {
3476 child->ResetUuidDirect();
3477 },
3479
3480 clone->ClearFlags();
3481 clone->Rotate( VECTOR2( 0, 0 ), rot );
3482 clone->Move( disp );
3483 aCommit->Add( clone );
3484
3485 clone->RunOnChildren(
3486 [&]( BOARD_ITEM* child )
3487 {
3488 child->ClearFlags();
3489
3490 if( BOARD_CONNECTED_ITEM* bci = dynamic_cast<BOARD_CONNECTED_ITEM*>( child ) )
3491 fixupNet( bci, bci, hasMatches, netMap );
3492
3493 aCommit->Add( child );
3494 },
3496
3497 aCompatData.m_groupableItems.insert( clone );
3498 }
3499 }
3500
3501 if( aOpts.m_copyOtherItems )
3502 {
3503 std::set<BOARD_ITEM*> sourceItems;
3504 std::set<BOARD_ITEM*> targetItems;
3505
3506 findOtherItemsInRuleArea( aRefArea, sourceItems );
3507 findOtherItemsInRuleArea( aTargetArea, targetItems );
3508
3509 // Apply Design Block Layout uses synthetic copper-only rule area zones that don't
3510 // reflect the layers the user actually drew on. The source items were collected by
3511 // explicit enumeration (m_designBlockItems) and the destination is a group bounding
3512 // box, so the per-item layer filter would incorrectly reject silkscreen, fab and
3513 // user drawings. Skip the layer filter only when both halves are the synthetic
3514 // design-block-to-group flow; regular GROUP_PLACEMENT rule areas have user-authored
3515 // layer sets that must still be honored.
3516 const bool skipLayerFilter = aRefArea->m_sourceType == PLACEMENT_SOURCE_T::DESIGN_BLOCK
3517 && aTargetArea->m_sourceType
3519
3520 for( BOARD_ITEM* item : targetItems )
3521 {
3522 if( item->GetParent() && item->GetParent()->Type() == PCB_FOOTPRINT_T )
3523 continue;
3524
3525 // Don't remove the appended source items: this geometric query can pick them up, but
3526 // they're deleted when the temporary append is reverted, leaving dangling pointers.
3527 if( aRefArea->m_designBlockItems.count( item ) )
3528 continue;
3529
3530 if( item->IsLocked() && !aOpts.m_includeLockedItems )
3531 continue;
3532
3533 // item already removed
3534 if( aCommit->GetStatus( item ) != 0 )
3535 continue;
3536
3537 if( item->Type() == PCB_ZONE_T )
3538 {
3539 ZONE* zone = static_cast<ZONE*>( item );
3540
3541 // Check all zone layers are included in the target rule area.
3542 if( skipLayerFilter
3543 || aTargetArea->m_zone->GetLayerSet().ContainsAll( zone->GetLayerSet() ) )
3544 {
3545 aCompatData.m_affectedItems.insert( zone );
3546 aCommit->Remove( zone );
3547 }
3548 }
3549 else
3550 {
3551 if( skipLayerFilter
3552 || aTargetArea->m_zone->GetLayerSet().Contains( item->GetLayer() ) )
3553 {
3554 aCompatData.m_affectedItems.insert( item );
3555 aCommit->Remove( item );
3556 }
3557 }
3558 }
3559
3560 for( BOARD_ITEM* item : sourceItems )
3561 {
3562 if( item->GetParent() && item->GetParent()->Type() == PCB_FOOTPRINT_T )
3563 continue;
3564
3565 if( item->IsLocked() && !aOpts.m_includeLockedItems )
3566 continue;
3567
3568 BOARD_ITEM* copied = nullptr;
3569
3570 if( item->Type() == PCB_ZONE_T )
3571 {
3572 ZONE* zone = static_cast<ZONE*>( item );
3573
3574 if( !skipLayerFilter )
3575 {
3576 LSET allowedLayers =
3577 aRefArea->m_zone->GetLayerSet() & aTargetArea->m_zone->GetLayerSet();
3578
3579 // Check all zone layers are included in both source and target rule areas.
3580 if( !allowedLayers.ContainsAll( zone->GetLayerSet() ) )
3581 continue;
3582 }
3583
3584 ZONE* targetZone = static_cast<ZONE*>( item->Duplicate( false ) );
3585 fixupNet( zone, targetZone, hasMatches, netMap );
3586
3587 copied = targetZone;
3588 }
3589 else
3590 {
3591 if( !skipLayerFilter )
3592 {
3593 if( !aRefArea->m_zone->GetLayerSet().Contains( item->GetLayer() ) )
3594 continue;
3595
3596 if( !aTargetArea->m_zone->GetLayerSet().Contains( item->GetLayer() ) )
3597 continue;
3598 }
3599
3600 copied = static_cast<BOARD_ITEM*>( item->Clone() );
3601 }
3602
3603 if( copied )
3604 {
3605 fixupParentGroup( item, copied );
3606
3607 copied->ClearFlags();
3608 copied->Rotate( VECTOR2( 0, 0 ), rot );
3609 copied->Move( disp );
3610 aCompatData.m_groupableItems.insert( copied );
3611 aCommit->Add( copied );
3612 }
3613 }
3614 }
3615
3616 if( aOpts.m_copyPlacement )
3617 {
3618 for( const auto& [refFP, targetFP] : aCompatData.m_matchingComponents )
3619 {
3620 if( !aRefArea->m_zone->GetLayerSet().Contains( refFP->GetLayer() ) )
3621 {
3622 wxLogTrace( traceMultichannelTool, wxT( "discard ref:%s (ref layer)\n" ),
3623 refFP->GetReference() );
3624 continue;
3625 }
3626 if( !aTargetArea->m_zone->GetLayerSet().Contains( refFP->GetLayer() ) )
3627 {
3628 wxLogTrace( traceMultichannelTool, wxT( "discard ref:%s (target layer)\n" ),
3629 refFP->GetReference() );
3630 continue;
3631 }
3632
3633 // For regular Rule Area repeat, ignore source footprints outside the reference area.
3634 // For Design Block apply, use the exact source item set collected from the block.
3636 && !linkedChannelGroup( board(), aRefArea )
3637 && !refFP->GetEffectiveShape( refFP->GetLayer() )->Collide( &refPoly, 0 ) )
3638 {
3639 continue;
3640 }
3641
3642 if( targetFP->IsLocked() && !aOpts.m_includeLockedItems )
3643 continue;
3644
3645 aCommit->Modify( targetFP );
3646
3647 targetFP->SetLayerAndFlip( refFP->GetLayer() );
3648 targetFP->SetOrientation( refFP->GetOrientation() );
3649 targetFP->SetPosition( refFP->GetPosition() );
3650 targetFP->Rotate( VECTOR2( 0, 0 ), rot );
3651 targetFP->Move( disp );
3652
3653 for( PCB_FIELD* refField : refFP->GetFields() )
3654 {
3655 wxCHECK2( refField, continue );
3656
3657 PCB_FIELD* targetField = targetFP->GetField( refField->GetName() );
3658
3659 if( !targetField )
3660 continue;
3661
3662 targetField->SetLayerSet( refField->GetLayerSet() );
3663 targetField->SetVisible( refField->IsVisible() );
3664 targetField->SetAttributes( refField->GetAttributes() );
3665 targetField->SetPosition( refField->GetPosition() );
3666 targetField->SetTextAngle( refField->GetTextAngle() );
3667 targetField->Rotate( VECTOR2( 0, 0 ), rot );
3668 targetField->Move( disp );
3669 targetField->SetIsKnockout( refField->IsKnockout() );
3670 }
3671
3672 // Copy non-field text items. Texts can share content (e.g. "${REFERENCE}" on both
3673 // F.SilkS and B.SilkS), so match one-to-one and prefer the same layer. Otherwise both
3674 // collapse onto one target item and the other side's text is lost.
3675 std::set<PCB_TEXT*> consumedTargets;
3676
3677 for( BOARD_ITEM* refItem : refFP->GraphicalItems() )
3678 {
3679 if( refItem->Type() != PCB_TEXT_T )
3680 continue;
3681
3682 PCB_TEXT* refText = static_cast<PCB_TEXT*>( refItem );
3683 PCB_TEXT* targetText = nullptr;
3684
3685 for( BOARD_ITEM* targetItem : targetFP->GraphicalItems() )
3686 {
3687 if( targetItem->Type() != PCB_TEXT_T )
3688 continue;
3689
3690 PCB_TEXT* candidate = static_cast<PCB_TEXT*>( targetItem );
3691
3692 if( consumedTargets.contains( candidate ) || candidate->GetText() != refText->GetText() )
3693 {
3694 continue;
3695 }
3696
3697 targetText = candidate;
3698
3699 if( candidate->GetLayer() == refText->GetLayer() )
3700 break;
3701 }
3702
3703 if( !targetText )
3704 continue;
3705
3706 consumedTargets.insert( targetText );
3707
3708 targetText->SetLayer( refText->GetLayer() );
3709 targetText->SetVisible( refText->IsVisible() );
3710 targetText->SetAttributes( refText->GetAttributes() );
3711 targetText->SetPosition( refText->GetPosition() );
3712 targetText->SetTextAngle( refText->GetTextAngle() );
3713 targetText->Rotate( VECTOR2( 0, 0 ), rot );
3714 targetText->Move( disp );
3715 targetText->SetIsKnockout( refText->IsKnockout() );
3716 }
3717
3718 // Copy 3D model settings
3719 targetFP->Models() = refFP->Models();
3720
3721 std::set<PAD*> consumedPads;
3722
3723 for( PAD* refPad : refFP->Pads() )
3724 {
3725 for( PAD* targetPad : targetFP->Pads() )
3726 {
3727 if( consumedPads.contains( targetPad ) || targetPad->GetNumber() != refPad->GetNumber() )
3728 {
3729 continue;
3730 }
3731
3732 consumedPads.insert( targetPad );
3733 targetPad->ImportSettingsFrom( *refPad );
3734 break;
3735 }
3736 }
3737
3738 aCompatData.m_affectedItems.insert( targetFP );
3739 aCompatData.m_groupableItems.insert( targetFP );
3740
3741 // The matched footprint maps to its target; treat it as reproduced so a group
3742 // containing it can be rebuilt.
3743 if( preserveGroups && refFP->GetParentGroup() )
3744 groupFixupPairs.emplace_back( refFP, targetFP );
3745
3746 if( preserveGroups )
3747 reproducedSourceItems.insert( refFP );
3748 }
3749 }
3750
3751 // Rebuild a source group only when all of its members were reproduced. A group that merely
3752 // overlaps the source area keeps uncopied members, so it is left untouched rather than
3753 // partially duplicated (issue 22316).
3754 if( preserveGroups && !groupFixupPairs.empty() )
3755 {
3756 std::map<EDA_GROUP*, EDA_GROUP*> groupMap;
3757 std::map<EDA_GROUP*, bool> fullyReproducedCache;
3758
3759 auto groupFullyReproduced =
3760 [&]( EDA_GROUP* aGroup )
3761 {
3762 if( auto it = fullyReproducedCache.find( aGroup ); it != fullyReproducedCache.end() )
3763 return it->second;
3764
3765 bool reproduced = true;
3766
3767 for( EDA_ITEM* member : aGroup->GetItems() )
3768 {
3769 // Nested groups are not reproduced, so a parent containing one can never
3770 // be fully reproduced.
3771 if( !member->IsBOARD_ITEM()
3772 || !reproducedSourceItems.contains( static_cast<BOARD_ITEM*>( member ) ) )
3773 {
3774 reproduced = false;
3775 break;
3776 }
3777 }
3778
3779 fullyReproducedCache[aGroup] = reproduced;
3780 return reproduced;
3781 };
3782
3783 for( const auto& [sourceItem, destItem] : groupFixupPairs )
3784 {
3785 EDA_GROUP* parentGroup = sourceItem->GetParentGroup();
3786
3787 if( !parentGroup || !groupFullyReproduced( parentGroup ) )
3788 continue;
3789
3790 if( !groupMap.contains( parentGroup ) )
3791 {
3792 PCB_GROUP* newGroup = static_cast<PCB_GROUP*>(
3793 static_cast<PCB_GROUP*>( parentGroup->AsEdaItem() )->Duplicate( false ) );
3794 newGroup->GetItems().clear();
3795 newGroup->SetParentGroup( nullptr );
3796
3797 if( newGroup->Type() == PCB_GENERATOR_T )
3798 {
3799 newGroup->Rotate( VECTOR2( 0, 0 ), rot );
3800 newGroup->Move( disp );
3801 }
3802
3803 groupMap[parentGroup] = newGroup;
3804 aCommit->Add( newGroup );
3805 }
3806
3807 // AddItem reparents the footprint out of any group it already belongs to; stage that
3808 // group so the membership change is captured for undo.
3809 if( EDA_GROUP* oldGroup = destItem->GetParentGroup() )
3810 {
3811 if( oldGroup != groupMap[parentGroup] )
3812 aCommit->Modify( oldGroup->AsEdaItem() );
3813 }
3814
3815 groupMap[parentGroup]->AddItem( destItem );
3816 }
3817 }
3818
3819 aTargetArea->m_zone->RemoveAllContours();
3820 aTargetArea->m_zone->AddPolygon( newTargetOutline );
3821 aTargetArea->m_zone->UnHatchBorder();
3822 aTargetArea->m_zone->HatchBorder();
3823}
3824
3830 bool aHasMatches,
3831 const std::map<int, int>& aNetMap )
3832{
3833 // Copy as no-net.
3834 if( !aHasMatches )
3835 {
3836 aTarget->SetNetCode( 0 );
3837 return;
3838 }
3839
3840 auto it = aNetMap.find( aRef->GetNetCode() );
3841
3842 if( it != aNetMap.end() )
3843 aTarget->SetNetCode( it->second );
3844}
3845
3846
3847std::vector<NETINFO_ITEM*> MULTICHANNEL_TOOL::IsolateDesignBlockAutoNets( BOARD* aBoard,
3848 const std::set<FOOTPRINT*>& aFootprints,
3849 const std::unordered_set<EDA_ITEM*>& aItems )
3850{
3851 std::vector<NETINFO_ITEM*> created;
3852 std::map<int, NETINFO_ITEM*> remap;
3853 int counter = 0;
3854
3855 // Auto-generated names are tied to a reference designator, so a block's Net-(D3-A) collides
3856 // with a different part's Net-(D3-A) on the board. Named/power nets are intentional and left
3857 // alone so the topology matcher keeps excluding real global rails.
3858 auto isAutoName = []( const wxString& aName )
3859 {
3860 return aName.StartsWith( wxT( "Net-(" ) ) || aName.StartsWith( wxT( "unconnected-" ) );
3861 };
3862
3863 auto remapItem = [&]( BOARD_CONNECTED_ITEM* aItem )
3864 {
3865 int code = aItem->GetNetCode();
3866
3867 if( code <= 0 )
3868 return;
3869
3870 NETINFO_ITEM* oldNet = aBoard->FindNet( code );
3871
3872 if( !oldNet || !isAutoName( oldNet->GetNetname() ) )
3873 return;
3874
3875 auto it = remap.find( code );
3876
3877 if( it == remap.end() )
3878 {
3879 wxString name;
3880
3881 do
3882 {
3883 name = wxString::Format( wxT( "__dbapply_%d_%d" ), code, counter++ );
3884 } while( aBoard->FindNet( name ) );
3885
3886 NETINFO_ITEM* newNet = new NETINFO_ITEM( aBoard, name );
3887 aBoard->Add( newNet );
3888 created.push_back( newNet );
3889 it = remap.emplace( code, newNet ).first;
3890 }
3891
3892 aItem->SetNet( it->second );
3893 };
3894
3895 for( FOOTPRINT* fp : aFootprints )
3896 {
3897 for( PAD* pad : fp->Pads() )
3898 remapItem( pad );
3899 }
3900
3901 for( EDA_ITEM* item : aItems )
3902 {
3903 if( BOARD_CONNECTED_ITEM* bci = dynamic_cast<BOARD_CONNECTED_ITEM*>( item ) )
3904 remapItem( bci );
3905 }
3906
3907 return created;
3908}
3909
3910
3911// Pairs footprints by their unique closest symbol instance path, independent of net topology
3912// Leaves aResult untouched unless that gives a full pad compatible bijection
3913static bool matchBySymbolInstancePath( const std::set<FOOTPRINT*>& aRef, const std::set<FOOTPRINT*>& aTarget,
3914 TMATCH::COMPONENT_MATCHES& aResult )
3915{
3916 if( aRef.empty() || aRef.size() != aTarget.size() )
3917 return false;
3918
3920 std::set<FOOTPRINT*> used;
3921
3922 for( FOOTPRINT* refFp : aRef )
3923 {
3924 FOOTPRINT* targetFp = nullptr;
3925 size_t bestLength = 0;
3926 bool tied = false;
3927
3928 for( FOOTPRINT* candidate : aTarget )
3929 {
3930 size_t length = TMATCH::CommonPathTailLength( refFp->GetPath(), candidate->GetPath() );
3931
3932 if( length > bestLength )
3933 {
3934 targetFp = candidate;
3935 bestLength = length;
3936 tied = false;
3937 }
3938 else if( length == bestLength && length > 0 )
3939 {
3940 tied = true;
3941 }
3942 }
3943
3944 // A missing or ambiguous path (copy paste, hand built group) is not a clean instance link
3945 if( !targetFp || tied )
3946 return false;
3947
3948 // Routing and placement copy only makes sense between pad compatible footprints
3949 if( refFp->GetFPID() != targetFp->GetFPID() || refFp->Pads().size() != targetFp->Pads().size() )
3950 return false;
3951
3952 if( !used.insert( targetFp ).second )
3953 return false;
3954
3955 result[refFp] = targetFp;
3956 }
3957
3958 aResult = std::move( result );
3959 return true;
3960}
3961
3962
3964 RULE_AREA_COMPAT_DATA& aMatches,
3965 const TMATCH::ISOMORPHISM_PARAMS& aParams,
3966 const std::unordered_set<int>& aExtraGlobalNets )
3967{
3968 using namespace TMATCH;
3969
3970 // Footprint-free design block has nothing to match to
3971 if( aRefArea->m_sourceType == PLACEMENT_SOURCE_T::DESIGN_BLOCK && aRefArea->m_components.empty()
3972 && aTargetArea->m_components.empty() )
3973 {
3974 aMatches.m_matchingComponents.clear();
3975 aMatches.m_isOk = true;
3976 aMatches.m_errorMsg = _( "OK" );
3977 aMatches.m_mismatchReasons.clear();
3978 return true;
3979 }
3980
3981 // Placement areas resolve their components from their source, so two areas sharing a sheet,
3982 // component class or group resolve to identical footprints. Repeating into such a target would
3983 // move and delete the reference's own items, corrupting the placement rather than copying it.
3984 if( !aRefArea->m_components.empty() )
3985 {
3986 std::set<FOOTPRINT*> shared;
3987 std::set_intersection( aRefArea->m_components.begin(), aRefArea->m_components.end(),
3988 aTargetArea->m_components.begin(), aTargetArea->m_components.end(),
3989 std::inserter( shared, shared.begin() ) );
3990
3991 if( !shared.empty() )
3992 {
3993 aMatches.m_matchingComponents.clear();
3994 aMatches.m_isOk = false;
3995 aMatches.m_errorMsg = _( "Target Rule Area shares components with the reference area" );
3996 aMatches.m_mismatchReasons.clear();
3997 aMatches.m_mismatchReasons.push_back(
3998 _( "This target Rule Area selects the same components as the reference area. "
3999 "Repeat layout cannot copy a Rule Area onto itself. Give each placement Rule "
4000 "Area a distinct sheet, component class or group." ) );
4001 aMatches.m_mismatchReasons.push_back( wxString::Format( _( "Shared components:\n%s" ),
4002 FormatComponentList( shared ) ) );
4003 return false;
4004 }
4005 }
4006
4007 // A global rail connects >=2 pads in more than one channel; find them across all areas so the
4008 // exclusion is the same for every target, not just the one being matched against.
4009 std::unordered_map<int, std::vector<const RULE_AREA*>> netInternalAreas;
4010
4011 for( const RULE_AREA& area : m_areas.m_areas )
4012 {
4013 std::unordered_map<int, int> areaNetPadCounts;
4014
4015 for( const FOOTPRINT* fp : area.m_components )
4016 {
4017 for( const PAD* pad : fp->Pads() )
4018 {
4019 if( pad->GetNetCode() > 0 )
4020 areaNetPadCounts[pad->GetNetCode()]++;
4021 }
4022 }
4023
4024 for( const auto& [netCode, padCount] : areaNetPadCounts )
4025 {
4026 if( padCount >= 2 )
4027 netInternalAreas[netCode].push_back( &area );
4028 }
4029 }
4030
4031 // Require two component-disjoint areas so overlapping rule areas can't make a per-channel net
4032 // look global.
4033 auto disjoint =
4034 []( const RULE_AREA* aA, const RULE_AREA* aB )
4035 {
4036 for( FOOTPRINT* fp : aA->m_components )
4037 {
4038 if( aB->m_components.count( fp ) )
4039 return false;
4040 }
4041
4042 return true;
4043 };
4044
4045 std::unordered_set<int> globalNets = aExtraGlobalNets;
4046
4047 for( const auto& [netCode, areas] : netInternalAreas )
4048 {
4049 for( size_t i = 0; i < areas.size() && !globalNets.count( netCode ); i++ )
4050 {
4051 for( size_t j = i + 1; j < areas.size(); j++ )
4052 {
4053 if( disjoint( areas[i], areas[j] ) )
4054 {
4055 globalNets.insert( netCode );
4056 break;
4057 }
4058 }
4059 }
4060 }
4061
4062 PROF_TIMER timerBuild;
4063 std::unique_ptr<CONNECTION_GRAPH> cgRef( CONNECTION_GRAPH::BuildFromFootprintSet( aRefArea->m_components,
4064 aTargetArea->m_components,
4065 globalNets ) );
4066 std::unique_ptr<CONNECTION_GRAPH> cgTarget( CONNECTION_GRAPH::BuildFromFootprintSet( aTargetArea->m_components,
4067 aRefArea->m_components,
4068 globalNets ) );
4069 timerBuild.Stop();
4070
4071 wxLogTrace( traceMultichannelTool, wxT( "Graph construction: %s (%d + %d components)" ),
4072 timerBuild.to_string(),
4073 (int) aRefArea->m_components.size(),
4074 (int) aTargetArea->m_components.size() );
4075
4076 std::vector<TMATCH::TOPOLOGY_MISMATCH_REASON> mismatchReasons;
4077
4078 PROF_TIMER timerIso;
4079 bool status = cgRef->FindIsomorphism( cgTarget.get(), aMatches.m_matchingComponents,
4080 mismatchReasons, aParams );
4081 timerIso.Stop();
4082
4083 wxLogTrace( traceMultichannelTool, wxT( "FindIsomorphism: %s, result=%d" ),
4084 timerIso.to_string(), status ? 1 : 0 );
4085
4086 // Net topology can legitimately differ between a design block and its placed instance once the
4087 // user edits connectivity on the board (a wire tying two block pads onto one net, etc.). Fall
4088 // back to the symbol instance linkage, which still gives the correct mapping in that case. Skip
4089 // it on a cancelled scan so cancellation is not mistaken for a topology miss.
4090 const bool cancelled = aParams.m_cancelled && aParams.m_cancelled->load( std::memory_order_relaxed );
4091
4092 if( !status && !cancelled
4093 && matchBySymbolInstancePath( aRefArea->m_components, aTargetArea->m_components,
4094 aMatches.m_matchingComponents ) )
4095 {
4096 status = true;
4097 }
4098
4099 aMatches.m_isOk = status;
4100
4101 if( status )
4102 {
4103 aMatches.m_errorMsg = _( "OK" );
4104 aMatches.m_mismatchReasons.clear();
4105 return true;
4106 }
4107
4108 aMatches.m_mismatchReasons.clear();
4109
4110 for( const auto& reason : mismatchReasons )
4111 {
4112 if( reason.m_reason.IsEmpty() )
4113 continue;
4114
4115 if( !reason.m_reference.IsEmpty() && !reason.m_candidate.IsEmpty() )
4116 aMatches.m_mismatchReasons.push_back( reason.m_reason );
4117 else if( !reason.m_reference.IsEmpty() )
4118 {
4119 aMatches.m_mismatchReasons.push_back( wxString::Format( wxT( "%s: %s" ),
4120 reason.m_reference,
4121 reason.m_reason ) );
4122 }
4123 else
4124 aMatches.m_mismatchReasons.push_back( reason.m_reason );
4125 }
4126
4127 if( aMatches.m_mismatchReasons.empty() )
4128 aMatches.m_mismatchReasons.push_back( _( "The components in the two areas could not be paired up." ) );
4129
4130 // The reason above already gives both totals. Only the lists add anything, and only when
4131 // both sides have parts to compare.
4132 if( aRefArea->m_components.size() != aTargetArea->m_components.size() && !aRefArea->m_components.empty()
4133 && !aTargetArea->m_components.empty() )
4134 {
4135 aMatches.m_mismatchReasons.push_back( wxString::Format( _( "Reference area components:\n%s" ),
4136 FormatComponentList( aRefArea->m_components ) ) );
4137 aMatches.m_mismatchReasons.push_back( wxString::Format( _( "Target area components:\n%s" ),
4138 FormatComponentList( aTargetArea->m_components ) ) );
4139 }
4140
4141 aMatches.m_errorMsg = aMatches.m_mismatchReasons.front();
4142
4143 return status;
4144}
4145
4146
4148 const std::unordered_set<BOARD_ITEM*>& aItemsToRemove )
4149{
4150 // Note: groups are only collections, not "real" hierarchy. A group's members are still parented
4151 // by the board (and therefore nested groups are still in the board's list of groups).
4152 for( PCB_GROUP* group : board()->Groups() )
4153 {
4154 std::vector<EDA_ITEM*> pruneList;
4155
4156 for( EDA_ITEM* refItem : group->GetItems() )
4157 {
4158 for( BOARD_ITEM* testItem : aItemsToRemove )
4159 {
4160 if( refItem->m_Uuid == testItem->m_Uuid )
4161 pruneList.push_back( refItem );
4162 }
4163 }
4164
4165 if( !pruneList.empty() )
4166 {
4167 aCommit.Modify( group );
4168
4169 for( EDA_ITEM* item : pruneList )
4170 group->RemoveItem( item );
4171
4172 if( group->GetItems().size() < 2 )
4173 aCommit.Remove( group );
4174 }
4175 }
4176
4177 return false;
4178}
4179
4180
4182{
4184
4185 if( Pgm().IsGUI() )
4186 {
4188
4189 if( m_areas.m_areas.size() <= 1 )
4190 {
4191 frame()->ShowInfoBarError( _( "Cannot auto-generate any placement areas because the "
4192 "schematic has only one or no hierarchical sheets, "
4193 "groups, or component classes." ),
4194 true );
4195 return 0;
4196 }
4197
4199 int ret = dialog.ShowModal();
4200
4201 if( ret != wxID_OK )
4202 return 0;
4203 }
4204
4205 wxLogTrace( traceMultichannelTool, wxT( "%d placement areas found\n" ), (int) m_areas.m_areas.size() );
4206
4207 BOARD_COMMIT commit( GetManager(), true, false );
4208
4209 for( RULE_AREA& ra : m_areas.m_areas )
4210 {
4211 // Clear the result so skipped candidates are not grouped below.
4212 ra.m_zone = nullptr;
4213
4214 if( !ra.m_generateEnabled )
4215 continue;
4216
4217 if( ra.m_components.empty() )
4218 continue;
4219
4220 wxString source;
4221 wxString existingAreaTraceFormat;
4222
4224 {
4225 source = ra.m_sheetPath;
4226 existingAreaTraceFormat = wxT( "Placement rule area for sheet '%s' already exists as '%s'\n" );
4227 }
4229 {
4231 existingAreaTraceFormat = wxT( "Placement rule area for component class '%s' already exists as '%s'\n" );
4232 }
4233 else
4234 {
4235 source = ra.m_groupName;
4236 existingAreaTraceFormat = wxT( "Placement rule area for group '%s' already exists as '%s'\n" );
4237 }
4238
4239 std::unique_ptr<ZONE> newZone( new ZONE( board() ) );
4240 newZone->SetZoneName( wxString::Format( wxT( "auto-placement-area-%s" ), source ) );
4241 newZone->SetPlacementAreaSourceType( ra.m_sourceType );
4242 newZone->SetPlacementAreaSource( source );
4243
4244 std::vector<ZONE*> oldZones;
4245
4246 for( ZONE* zone : board()->Zones() )
4247 {
4248 if( !zone->GetIsRuleArea() || !zone->GetPlacementAreaEnabled() )
4249 continue;
4250
4251 if( zone->GetPlacementAreaSourceType() != newZone->GetPlacementAreaSourceType()
4252 || zone->GetPlacementAreaSource() != newZone->GetPlacementAreaSource() )
4253 {
4254 continue;
4255 }
4256
4257 wxLogTrace( traceMultichannelTool, existingAreaTraceFormat, source, zone->GetZoneName() );
4258
4259 oldZones.push_back( zone );
4260 }
4261
4262 if( !oldZones.empty() && !m_areas.m_replaceExisting )
4263 continue;
4264
4265 SHAPE_LINE_CHAIN raOutline;
4266
4267 // Groups are a way for the user to more explicitly provide a list of items to include in
4268 // the multichannel tool, as opposed to inferring them based on sheet structure or component classes.
4269 // So for group-based RAs, we build the RA outline based everything in the group, not just components.
4271 {
4272 std::set<BOARD_ITEM*> groupItems = queryBoardItemsInGroup( ra.m_groupName );
4273
4274 if( groupItems.empty() )
4275 {
4276 wxLogTrace( traceMultichannelTool,
4277 wxT( "Skipping placement rule area generation for source group '%s': group has no board items." ),
4278 ra.m_groupName );
4279 continue;
4280 }
4281
4282 raOutline = buildRAOutline( groupItems, 100000 );
4283 }
4284 else
4285 {
4286 // Start from the footprints, then also take everything in the design-block groups
4287 // they belong to (recursively) so routing and meanders that extend past the
4288 // footprints land inside the outline. Group membership keeps it bounded to this channel.
4289 std::set<BOARD_ITEM*> outlineItems;
4290 std::set<EDA_GROUP*> groups;
4291 std::set<int> channelNets;
4292
4293 for( FOOTPRINT* fp : ra.m_components )
4294 {
4295 outlineItems.insert( fp );
4296
4297 for( PAD* pad : fp->Pads() )
4298 channelNets.insert( pad->GetNetCode() );
4299
4300 for( EDA_GROUP* g = fp->GetParentGroup(); g; g = g->AsEdaItem()->GetParentGroup() )
4301 groups.insert( g );
4302 }
4303
4304 for( EDA_GROUP* g : groups )
4305 collectGroupBoardItems( g, outlineItems );
4306
4307 // Also include tracks and vias on nets local to this channel (all pads on the net
4308 // belong to the channel), so loose connections between blocks land in the outline.
4309 std::set<int> foreignNets;
4310
4311 for( FOOTPRINT* fp : board()->Footprints() )
4312 {
4313 if( ra.m_components.count( fp ) )
4314 continue;
4315
4316 for( PAD* pad : fp->Pads() )
4317 foreignNets.insert( pad->GetNetCode() );
4318 }
4319
4320 for( PCB_TRACK* track : board()->Tracks() )
4321 {
4322 int net = track->GetNetCode();
4323
4324 if( net > 0 && channelNets.count( net ) && !foreignNets.count( net ) )
4325 outlineItems.insert( track );
4326 }
4327
4328 raOutline = buildRAOutline( outlineItems, 100000 );
4329 }
4330
4331 wxLogTrace( traceMultichannelTool, wxT( "Generated rule area '%s' (%d components)\n" ),
4332 newZone->GetZoneName(),
4333 (int) ra.m_components.size() );
4334
4335 makePlacementArea( newZone.get(), raOutline );
4336
4337 for( ZONE* oldZone : oldZones )
4338 commit.Remove( oldZone );
4339
4340 ra.m_zone = newZone.release();
4341 commit.Add( ra.m_zone );
4342 }
4343
4344 // fixme: handle corner cases where the items belonging to a Rule Area already
4345 // belong to other groups.
4346
4347 if( m_areas.m_options.m_groupItems )
4348 {
4349 for( RULE_AREA& ra : m_areas.m_areas )
4350 {
4351 if( !ra.m_zone )
4352 continue;
4353
4354 std::unordered_set<BOARD_ITEM*> toPrune;
4355
4356 std::copy( ra.m_components.begin(), ra.m_components.end(), std::inserter( toPrune, toPrune.begin() ) );
4357
4358 pruneExistingGroups( commit, toPrune );
4359
4360 PCB_GROUP* group = new PCB_GROUP( board() );
4361
4362 commit.Add( group );
4363
4364 commit.Modify( ra.m_zone );
4365 group->AddItem( ra.m_zone );
4366
4367 for( FOOTPRINT* fp : ra.m_components )
4368 {
4369 commit.Modify( fp );
4370 group->AddItem( fp );
4371 }
4372 }
4373 }
4374
4375 commit.Push( _( "Auto-generate Placement Rule Areas" ) );
4376
4377 return true;
4378}
const char * name
@ ERROR_OUTSIDE
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
#define SKIP_ENTERED_GROUP
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
static TOOL_ACTION selectItem
Select an item (specified as the event parameter).
Definition actions.h:224
static TOOL_ACTION selectionClear
Clear the current selection.
Definition actions.h:221
static TOOL_ACTION selectItems
Select a list of items (specified as the event parameter)
Definition actions.h:229
ACTION_MENU(bool isContextMenu, TOOL_INTERACTIVE *aTool=nullptr)
Default constructor.
void SetTitle(const wxString &aTitle) override
Set title for the menu.
void SetIcon(BITMAPS aIcon)
Assign an icon for the entry.
friend class TOOL_INTERACTIVE
TOOL_INTERACTIVE * m_tool
Creator of the menu.
void Push(const wxString &aMessage=wxEmptyString, int aCommitFlags=0) override
Execute the changes.
void Revert() override
Revert the commit by restoring the modified items state.
A base class derived from BOARD_ITEM for items that can be connected and have a net,...
virtual bool SetNetCode(int aNetCode, bool aNoAssert)
Set net using a net code.
bool IsConnected() const override
Returns information if the object is derived from BOARD_CONNECTED_ITEM.
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
void ResetUuidDirect()
Definition board_item.h:292
virtual void SetLayerSet(const LSET &aLayers)
Definition board_item.h:377
virtual bool IsKnockout() const
Definition board_item.h:437
virtual PCB_LAYER_ID GetLayer() const
Return the primary layer this item is on.
virtual void SetIsKnockout(bool aKnockout)
Definition board_item.h:438
virtual void SetLayer(PCB_LAYER_ID aLayer)
Set the layer this item is on.
Definition board_item.h:397
virtual const BOARD * GetBoard() const
Return the BOARD in which this BOARD_ITEM resides, or NULL if none.
FOOTPRINT * GetParentFootprint() const
virtual void RunOnChildren(const std::function< void(BOARD_ITEM *)> &aFunction, RECURSE_MODE aMode) const
Invoke a function on all children.
Definition board_item.h:279
void ResetUuid()
Definition board_item.h:295
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT, bool aSkipConnectivity=false) override
Removes an item from the container.
Definition board.cpp:1548
NETINFO_ITEM * FindNet(int aNetcode) const
Search for a net with the given netcode.
Definition board.cpp:2833
const FOOTPRINTS & Footprints() const
Definition board.h:465
static wxString MakeUniqueZoneName(const wxString &aBaseName, const std::function< bool(const wxString &)> &aInUse)
Return a name based on aBaseName for which aInUse returns false, adding or incrementing a _<number> s...
Definition board.cpp:1511
BOARD_ITEM * ResolveItem(const KIID &aID, bool aAllowNullptrReturn=false) const
Definition board.cpp:2176
BOARD_DESIGN_SETTINGS & GetDesignSettings()
Definition board.cpp:1318
std::shared_ptr< CONNECTIVITY_DATA > GetConnectivity() const
Return a list of missing connections between components/tracks.
Definition board.h:758
constexpr const Vec GetEnd() const
Definition box2.h:215
constexpr ecoord_type GetArea() const
Return the area of the rectangle.
Definition box2.h:700
constexpr bool Contains(const Vec &aPoint) const
Definition box2.h:171
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:577
constexpr const Vec & GetOrigin() const
Definition box2.h:213
constexpr bool Intersects(const BOX2< Vec > &aRect) const
Definition box2.h:314
CN_EDGE represents a point-to-point connection, whether realized or unrealized (ie: tracks etc.
CN_ITEM represents a BOARD_CONNECTED_ITEM in the connectivity system (ie: a pad, track/arc/via,...
const std::vector< CN_ITEM * > & ConnectedItems() const
Represent a set of changes (additions, deletions or modifications) of a data model (e....
Definition commit.h:68
COMMIT & Remove(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Remove a new item from the model.
Definition commit.h:86
COMMIT & Modify(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr, RECURSE_MODE aRecurse=RECURSE_MODE::NO_RECURSE)
Modify a given item in the model.
Definition commit.h:102
COMMIT & Add(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Add a new item to the model.
Definition commit.h:74
int GetStatus(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Returns status of an item.
Definition commit.cpp:235
A lightweight representation of a component class.
const std::vector< COMPONENT_CLASS * > & GetConstituentClasses() const
Fetches a vector of the constituent classes for this (effective) class.
void AddItem(const TOOL_ACTION &aAction, const SELECTION_CONDITION &aCondition, int aOrder=ANY_ORDER)
Add a menu entry to run a TOOL_ACTION on selected items.
void AddMenu(ACTION_MENU *aMenu, const SELECTION_CONDITION &aCondition=SELECTION_CONDITIONS::ShowAlways, int aOrder=ANY_ORDER)
Add a submenu to the menu.
CONDITIONAL_MENU(TOOL_INTERACTIVE *aTool)
void ClearLocalRatsnest()
Erase the temporary, selection-based ratsnest (i.e.
void BlockRatsnestItems(const std::vector< BOARD_ITEM * > &aItems)
int ShowModal() override
virtual void Refresh(bool aEraseBackground=true, const wxRect *aRect=nullptr) override
A set of EDA_ITEMs (i.e., without duplicates).
Definition eda_group.h:43
std::unordered_set< EDA_ITEM * > & GetItems()
Definition eda_group.h:78
void AddItem(EDA_ITEM *aItem)
Add item to group.
Definition eda_group.cpp:58
bool ContainsItem(const EDA_ITEM *aItem) const
Test if an item is a direct or nested member of this group.
Definition eda_group.cpp:26
virtual EDA_ITEM * AsEdaItem()=0
A base class for most all the KiCad significant classes used in schematics and boards.
Definition eda_item.h:98
const KIID m_Uuid
Definition eda_item.h:599
virtual EDA_GROUP * GetParentGroup() const
Definition eda_item.h:116
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
void ClearFlags(EDA_ITEM_FLAGS aMask=EDA_ITEM_ALL_FLAGS)
Definition eda_item.h:160
virtual void SetParentGroup(EDA_GROUP *aGroup)
Definition eda_item.h:115
void SetBrightened()
Definition eda_item.h:151
virtual const wxString & GetText() const
Return the string associated with the text object.
Definition eda_text.h:118
virtual bool IsVisible() const
Definition eda_text.h:226
void SetAttributes(const EDA_TEXT &aSrc, bool aSetPosition=true)
Set the text attributes from another instance.
Definition eda_text.cpp:395
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:348
const TEXT_ATTRIBUTES & GetAttributes() const
Definition eda_text.h:270
std::deque< PAD * > & Pads()
Definition footprint.h:355
const LIB_ID & GetFPID() const
Definition footprint.h:417
const wxString & GetReference() const
Definition footprint.h:793
VECTOR2I GetPosition() const override
Definition footprint.h:379
PAD * FindPadByNumber(const wxString &aPadNumber, PAD *aSearchAfterMe=nullptr) const
Return a PAD with a matching number.
const BOX2I GetBoundingBox() const override
Return the orthogonal bounding box of this object for display purposes.
Handle actions specific to filling copper zones.
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
Hold a (potentially large) number of VIEW_ITEMs and renders them on a graphics device provided by the...
Definition view.h:68
void InitPreview()
Definition view.cpp:2733
Definition kiid.h:46
wxString AsString() const
Definition kiid.cpp:264
void SetErrorCallback(std::function< void(const wxString &aMessage, int aOffset)> aCallback)
bool Compile(const wxString &aString, UCODE *aCode, CONTEXT *aPreflightContext)
void SetErrorCallback(ERROR_CALLBACK aCallback)
VALUE * Run(CONTEXT *ctx)
virtual double AsDouble() const
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
bool ContainsAll(const LSET &aLayers) const
See if this layer set contains all layers in another set.
Definition lset.h:85
static LSET AllCuMask(int aCuLayerCount)
Return a mask holding the requested number of Cu PCB_LAYER_IDs.
Definition lset.cpp:595
bool Contains(PCB_LAYER_ID aLayer) const
See if the layer set contains a PCB layer.
Definition lset.h:63
ACTION_MENU * create() const override
Return an instance of this class. It has to be overridden in inheriting classes.
MULTICHANNEL_CONTEXT_MENU(TOOL_INTERACTIVE *aTool)
void setPreviewHidden(bool aHide)
int CheckRACompatibility(ZONE *aRefZone)
void detachArea(BOARD_COMMIT &aCommit, ZONE *aZone)
std::set< FOOTPRINT * > queryComponentsInSheet(wxString aSheetName) const
void fixupNet(BOARD_CONNECTED_ITEM *aRef, BOARD_CONNECTED_ITEM *aTarget, bool aHasMatches, const std::map< int, int > &aNetMap)
Attempts to make sure copied items are assigned the right net.
bool findOtherItemsInRuleArea(RULE_AREA *aRuleArea, std::set< BOARD_ITEM * > &aItems)
void dropLoneLinks(BOARD_COMMIT &aCommit, const std::set< KIID > &aSets)
bool resolveConnectionTopology(RULE_AREA *aRefArea, RULE_AREA *aTargetArea, RULE_AREA_COMPAT_DATA &aMatches, const TMATCH::ISOMORPHISM_PARAMS &aParams={}, const std::unordered_set< int > &aExtraGlobalNets={})
void HighlightRepeatAreas(const RULE_AREA *aArea)
Mark the reference parts, and the parts of aArea if given, on the board while the dialog is open.
std::vector< SEG > m_previewRatsnest
bool resolveTopologies(const wxString &aTitle, const std::vector< TOPOLOGY_JOB > &aJobs)
Resolve the topology of each job in turn on a worker thread.
int repeatLayout(const TOOL_EVENT &aEvent)
bool findComponentsInRuleArea(RULE_AREA *aRuleArea, std::set< FOOTPRINT * > &aComponents)
void UpdatePickedItem(const EDA_ITEM *aItem) override
std::map< FOOTPRINT *, BOX2I > m_previewBoxes
int expandToLargestTopology(const TOOL_EVENT &aEvent)
void setTransitions() override
This method is meant to be overridden in order to specify handlers for events.
void UnlinkAreas(const std::set< ZONE * > &aZones)
Remove aZones from their link sets, and any area left alone in one, as one undo step.
static wxString JoinReferences(const std::set< FOOTPRINT * > &aFootprints)
bool Init() override
Init() is called once upon a registration of the tool.
void onRepeatDialogClosed(wxCloseEvent &aEvent)
const SHAPE_LINE_CHAIN buildRAOutline(std::set< FOOTPRINT * > &aFootprints, int aMargin)
int findRoutingInRuleArea(RULE_AREA *aRuleArea, std::set< BOARD_CONNECTED_ITEM * > &aOutput) const
int applyRepeat(BOARD_COMMIT &aCommit)
static ZONE * ChannelZone(const PCB_GROUP *aGroup)
The rule area zone that makes aGroup a repeated channel, or null for any other group.
std::vector< RULE_AREA_COMPAT_DATA > findMatches(const std::set< FOOTPRINT * > &aSelected, bool aLoose)
The channels elsewhere on the board that repeat the topology of aSelected.
void Reset(RESET_REASON aReason) override
Bring the tool to a known, initial state.
std::set< FOOTPRINT * > ExpandToMatchingTopology(const std::set< FOOTPRINT * > &aSeed, bool aLargest)
Grow aSeed with the parts next to it, keeping only sets that still have an exact twin elsewhere on th...
bool UpdateLinkedLayouts(ZONE *aSource)
Copy aSource onto the other areas of its link set, as one undo step.
static std::vector< NETINFO_ITEM * > IsolateDesignBlockAutoNets(BOARD *aBoard, const std::set< FOOTPRINT * > &aFootprints, const std::unordered_set< EDA_ITEM * > &aItems)
Remap auto-generated nets (Net-(...), unconnected-...) of a design block that was appended for layout...
void StartRepeatFromSelection(const std::vector< EDA_ITEM * > &aItems)
Use plain selected items as the reference and discover the channels that repeat them.
int expandToMatchingTopology(const TOOL_EVENT &aEvent)
const RULE_AREA * m_focusArea
std::vector< KIID > m_previewHidden
void copyRuleAreaContents(RULE_AREA *aRefArea, RULE_AREA *aTargetArea, BOARD_COMMIT *aCommit, REPEAT_LAYOUT_OPTIONS aOpts, RULE_AREA_COMPAT_DATA &aCompatData)
RULE_AREAS_DATA m_areas
PCB_GROUP * findPlacementGroup(const wxString &aGroupName) const
bool pruneExistingGroups(COMMIT &aCommit, const std::unordered_set< BOARD_ITEM * > &aItemsToCheck)
std::shared_ptr< KIGFX::VIEW_OVERLAY > m_highlight
int updateLinkedLayouts(const TOOL_EVENT &aEvent)
void ShowMismatchDetails(wxWindow *aParent, const wxString &aSummary, const std::vector< wxString > &aReasons) const
void RefreshRepeat()
Re-derive the channels after a tick or the anchor changed, then redraw the preview.
int RepeatLayout(const TOOL_EVENT &aEvent, ZONE *aRefZone)
int AutogenerateRuleAreas(const TOOL_EVENT &aEvent)
int expandSelection(bool aLargest)
void DiscoverRepeatCandidates(bool aLoose)
std::set< BOARD_CONNECTED_ITEM * > findRepeatRouting(RULE_AREA *aArea, const std::set< int > &aNets, const REPEAT_LAYOUT_OPTIONS &aOpts)
The routing of aArea on aNets, the only nets a repeat ever carries.
DIALOG_MULTICHANNEL_REPEAT_LAYOUT * m_dialog
std::set< FOOTPRINT * > queryComponentsInComponentClass(const wxString &aComponentClassName) const
int ApplyRepeat()
Apply what the Repeat Layout dialog shows.
void linkAreas(BOARD_COMMIT &aCommit, ZONE *aRefZone, const std::vector< RULE_AREA * > &aTargets)
Link aTargets and aRefZone into one set with their own copies of the options.
int unlinkLayout(const TOOL_EVENT &aEvent)
std::set< FOOTPRINT * > queryComponentsInGroup(const wxString &aGroupName) const
std::set< BOARD_ITEM * > queryBoardItemsInGroup(const wxString &aGroupName) const
Handle the data for a net.
Definition netinfo.h:50
const wxString & GetNetname() const
Definition netinfo.h:110
Definition pad.h:61
void SetItems(BOARD_ITEM *a, BOARD_ITEM *b=nullptr)
static TOOL_ACTION unlinkLayout
static TOOL_ACTION repeatLayout
static TOOL_ACTION generatePlacementRuleAreas
static TOOL_ACTION expandToLargestTopology
static TOOL_ACTION updateLinkedLayouts
static TOOL_ACTION expandToMatchingTopology
static TOOL_ACTION selectItemInteractively
Selection of reference points/items.
void RedrawRatsnest()
Force refresh of the ratsnest visual representation.
void Rotate(const VECTOR2I &aRotCentre, const EDA_ANGLE &aAngle) override
Rotate this object.
PCB_GENERATOR * DeepClone() const
void Move(const VECTOR2I &aMoveVector) override
Move this object.
A set of BOARD_ITEMs (i.e., without duplicates).
Definition pcb_group.h:51
void RunOnChildren(const std::function< void(BOARD_ITEM *)> &aFunction, RECURSE_MODE aMode) const override
Invoke a function on all children.
void Rotate(const VECTOR2I &aRotCentre, const EDA_ANGLE &aAngle) override
Rotate this object.
void Move(const VECTOR2I &aMoveVector) override
Move this object.
EDA_ITEM * AsEdaItem() override
Definition pcb_group.h:59
The selection tool: currently supports:
EDA_ANGLE GetTextAngle() const override
Definition pcb_text.cpp:562
VECTOR2I GetPosition() const override
Definition pcb_text.h:101
void SetPosition(const VECTOR2I &aPos) override
Definition pcb_text.h:103
void Move(const VECTOR2I &aMoveVector) override
Move this object.
Definition pcb_text.h:105
void SetTextAngle(const EDA_ANGLE &aAngle) override
Definition pcb_text.cpp:574
void Rotate(const VECTOR2I &aRotCentre, const EDA_ANGLE &aAngle) override
Rotate this object.
Definition pcb_text.cpp:585
T * frame() const
KIGFX::PCB_VIEW * view() const
PCB_TOOL_BASE(TOOL_ID aId, const std::string &aName)
Constructor.
BOARD * board() const
PCB_DRAW_PANEL_GAL * canvas() const
virtual void Reset(RESET_REASON aReason) override
Bring the tool to a known, initial state.
const PCB_SELECTION & selection() const
A small class to help profiling.
Definition profile.h:46
void Stop()
Save the time when this function was called, and set the counter stane to stop.
Definition profile.h:86
std::string to_string()
Definition profile.h:154
bool RoutingInProgress()
Returns whether routing is currently active.
Definition seg.h:38
static SELECTION_CONDITION HasTypes(std::vector< KICAD_T > aTypes)
Create a functor that tests if among the selected items there is at least one of a given types.
static SELECTION_CONDITION HasType(KICAD_T aType)
Create a functor that tests if among the selected items there is at least one of a given type.
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 Rotate(const EDA_ANGLE &aAngle, const VECTOR2I &aCenter={ 0, 0 }) override
Rotate all vertices by a given angle.
Represent a set of closed polygons.
int AddOutline(const SHAPE_LINE_CHAIN &aOutline)
Adds a new outline to the set and returns its index.
bool IsEmpty() const
Return true if the set is empty (no polygons at all)
virtual void CacheTriangulation(bool aSimplify=false, const TASK_SUBMITTER &aSubmitter={}, bool aBuildIndexes=false)
Build a polygon triangulation, needed to draw a polygon on OpenGL and in some other calculations.
void BooleanIntersection(const SHAPE_POLY_SET &b)
Perform boolean polyset intersection.
void BooleanSubtract(const SHAPE_POLY_SET &b)
Perform boolean polyset difference.
const SHAPE_LINE_CHAIN & COutline(int aIndex) const
const BOX2I BBox(int aClearance=0) const override
Compute a bounding box of the shape, with a margin of aClearance a collision.
virtual VECTOR2I Centre() const
Compute a center-of-mass of the shape.
Definition shape.h:242
static std::unique_ptr< CONNECTION_GRAPH > BuildFromFootprintSet(const std::set< FOOTPRINT * > &aFps, const std::set< FOOTPRINT * > &aOtherChannelFps={}, const std::unordered_set< int > &aGlobalNets={})
TOOL_MANAGER * GetManager() const
Return the instance of TOOL_MANAGER that takes care of the tool.
Definition tool_base.h:142
TOOL_MANAGER * m_toolMgr
Definition tool_base.h:220
KIGFX::VIEW * getView() const
Return the instance of KIGFX::VIEW object used in the application.
Definition tool_base.cpp:34
RESET_REASON
Determine the reason of reset for a tool.
Definition tool_base.h:74
@ SHUTDOWN
Tool is being shut down.
Definition tool_base.h:80
@ MODEL_RELOAD
Model changes (the sheet for a schematic)
Definition tool_base.h:76
@ SUPERMODEL_RELOAD
For schematics, the entire schematic changed, not just the sheet.
Definition tool_base.h:77
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).
TOOL_MENU & GetToolMenu()
Manage a CONDITIONAL_MENU and some number of CONTEXT_MENUs as sub-menus.
Definition tool_menu.h:39
CONDITIONAL_MENU & GetMenu()
Definition tool_menu.cpp:40
void RegisterSubMenu(std::shared_ptr< ACTION_MENU > aSubMenu)
Store a submenu of this menu model.
Definition tool_menu.cpp:46
Define a general 2D-vector/point.
Definition vector2d.h:67
Handle a list of polygons defining a copper zone.
Definition zone.h:70
void SetDoNotAllowPads(bool aEnable)
Definition zone.h:860
bool GetIsRuleArea() const
Accessors to parameters used in Rule Area zones:
Definition zone.h:834
const REPEAT_LAYOUT_OPTIONS & GetRepeatOptions() const
Definition zone.h:848
void AddPolygon(std::vector< VECTOR2I > &aPolygon)
Add a polygon to the zone outline.
Definition zone.cpp:1502
wxString GetPlacementAreaSource() const
Definition zone.h:839
void SetRepeatOptions(const REPEAT_LAYOUT_OPTIONS &aOpts)
Definition zone.h:849
void HatchBorder()
Compute the hatch lines depending on the hatch parameters and stores it in the zone's attribute m_bor...
Definition zone.cpp:1637
void SetLinkSet(const KIID &aLinkSet)
Definition zone.h:846
PLACEMENT_SOURCE_T GetPlacementAreaSourceType() const
Definition zone.h:841
SHAPE_POLY_SET * Outline()
Definition zone.h:421
void SetHatchStyle(ZONE_BORDER_DISPLAY_STYLE aStyle)
Definition zone.h:690
void SetIsRuleArea(bool aEnable)
Definition zone.h:835
void SetDoNotAllowTracks(bool aEnable)
Definition zone.h:859
const wxString & GetZoneName() const
Definition zone.h:160
void SetLayerSet(const LSET &aLayerSet) override
Definition zone.cpp:702
bool GetPlacementAreaEnabled() const
Definition zone.h:836
void SetDoNotAllowVias(bool aEnable)
Definition zone.h:858
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition zone.h:133
void SetDoNotAllowFootprints(bool aEnable)
Definition zone.h:861
const KIID & GetLinkSet() const
The set of placement rule areas that share one layout, or niluuid when this one is not linked.
Definition zone.h:845
void SetDoNotAllowZoneFills(bool aEnable)
Definition zone.h:857
void UnHatchBorder()
Clear the zone's hatch.
Definition zone.cpp:1631
void RemoveAllContours(void)
Definition zone.h:654
void SetPlacementAreaEnabled(bool aEnabled)
Definition zone.h:837
void BuildConvexHull(std::vector< VECTOR2I > &aResult, const std::vector< VECTOR2I > &aPoly)
Calculate the convex hull of a list of points in counter-clockwise order.
#define _(s)
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:472
@ RECURSE
Definition eda_item.h:51
@ NO_RECURSE
Definition eda_item.h:52
std::string source
KIID niluuid(0)
static std::map< int, std::vector< FOOTPRINT * > > buildNetOwners(const BOARD *aBoard)
static bool isChannelNet(const std::vector< FOOTPRINT * > &aOwners, const std::set< FOOTPRINT * > &aChannel)
static const std::pair< FOOTPRINT *const, FOOTPRINT * > & firstPair(const TMATCH::COMPONENT_MATCHES &aMatches)
static std::set< int > padNets(const FOOTPRINT *aFp, const std::set< int > &aAmong)
static bool matchBySymbolInstancePath(const std::set< FOOTPRINT * > &aRef, const std::set< FOOTPRINT * > &aTarget, TMATCH::COMPONENT_MATCHES &aResult)
static wxString FormatComponentList(const std::set< FOOTPRINT * > &aComponents)
static const wxString traceMultichannelTool
static wxString JoinMismatchReasons(const std::vector< wxString > &aReasons)
static void stageAddToGroup(BOARD_COMMIT &aCommit, EDA_GROUP *aGroup, BOARD_ITEM *aItem)
static EDA_GROUP * linkedChannelGroup(const BOARD *aBoard, const RULE_AREA *aArea)
static void makePlacementArea(ZONE *aZone, const SHAPE_LINE_CHAIN &aOutline)
static std::vector< TMATCH::COMPONENT_MATCHES > matchSheetInstances(BOARD *aBoard, const std::set< FOOTPRINT * > &aRef)
static bool outlinesOverlap(const SHAPE_POLY_SET &aA, const SHAPE_POLY_SET &aB)
static std::set< ZONE * > linkedAreasIn(const SELECTION &aSelection)
static void collectGroupFootprints(EDA_GROUP *aGroup, std::set< FOOTPRINT * > &aOut)
static const std::pair< FOOTPRINT *const, FOOTPRINT * > & anchorPair(const TMATCH::COMPONENT_MATCHES &aMatches, const KIID &aAnchor)
static void collectGroupBoardItems(EDA_GROUP *aGroup, std::set< BOARD_ITEM * > &aOut)
static void ShowTopologyMismatchReasons(wxWindow *aParent, const wxString &aSummary, const std::vector< wxString > &aReasons)
static SHAPE_LINE_CHAIN repeatedOutline(const RULE_AREA *aRef, const RULE_AREA *aTarget, const KIID &aAnchor, const TMATCH::COMPONENT_MATCHES &aMatches, VECTOR2I &aDisp, EDA_ANGLE &aRot)
static std::vector< wxString > getParentSheetPaths(const wxString &aSheetName)
static std::set< int > channelNets(const std::map< int, std::vector< FOOTPRINT * > > &aNetOwners, const std::set< FOOTPRINT * > &aChannel)
SHAPE_LINE_CHAIN RectifyPolygon(const SHAPE_LINE_CHAIN &aPoly)
Take a polygon and 'rectify' it, so that all sides are H/V.
void CollectBoxCorners(const BOX2I &aBox, std::vector< VECTOR2I > &aCorners)
Add the 4 corners of a BOX2I to a vector.
std::map< FOOTPRINT *, FOOTPRINT * > COMPONENT_MATCHES
Definition topo_match.h:188
size_t CommonPathTailLength(const KIID_PATH &aA, const KIID_PATH &aB)
Count the trailing elements two symbol instance paths share.
Class to handle a set of BOARD_ITEMs.
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
CITER next(CITER it)
Definition ptree.cpp:120
std::vector< EDA_ITEM * > EDA_ITEMS
Utility functions for working with shapes.
int StrNumCmp(const wxString &aString1, const wxString &aString2, CMP_T aCaseSensitivity)
Compare two strings with alphanumerical content.
void AccumulateDescription(wxString &aDesc, const wxString &aItem)
Utility to build comma separated lists in messages.
TMATCH::COMPONENT_MATCHES m_map
bool bind(FOOTPRINT *aRef, FOOTPRINT *aTarget, std::vector< int > &aAdded)
const std::vector< FOOTPRINT * > & m_order
bool extend(size_t aIndex)
const std::set< int > & m_internal
std::set< int > m_netsTaken
const std::map< int, std::vector< FOOTPRINT * > > & m_netOwners
bool pair(size_t aIndex, FOOTPRINT *aChoice)
const std::set< FOOTPRINT * > & m_leaves
std::map< int, int > m_netMap
const std::set< FOOTPRINT * > & m_claimed
std::set< FOOTPRINT * > m_used
Options for copying a placement rule area onto the others linked to it.
KIID m_anchor
This area's own anchor footprint, or niluuid for the area center.
std::vector< wxString > m_mismatchReasons
TMATCH::COMPONENT_MATCHES m_discovered
Pairing found by discovery.
std::unordered_set< BOARD_ITEM * > m_affectedItems
Filled in by copyRuleAreaContents with items that were affected by the copy operation.
TMATCH::COMPONENT_MATCHES m_matchingComponents
std::set< FOOTPRINT * > m_unmatched
Selected footprints the channel lacks.
std::unordered_set< BOARD_ITEM * > m_groupableItems
Filled in by copyRuleAreaContents with affected items that can be grouped together.
VECTOR2I m_center
bool ScansContents() const
True when the contents are scanned from the area rather than taken from an exact item list.
std::unordered_set< EDA_ITEM * > m_designBlockItems
wxString m_sheetName
bool m_fromSelection
The reference of a plain selection, copied as given with its footprint area deciding what else comes ...
PLACEMENT_SOURCE_T m_sourceType
wxString m_componentClass
std::set< FOOTPRINT * > m_components
wxString m_ruleName
PCB_GROUP * m_group
wxString m_groupName
wxString m_sheetPath
std::atomic< bool > * m_cancelled
Definition topo_match.h:47
std::atomic< int > * m_matchedComponents
Definition topo_match.h:48
std::atomic< int > * m_totalComponents
Definition topo_match.h:49
bool copied
bool moved
std::string path
IbisParser parser & reporter
VECTOR2I end
wxString result
Test unit parsing edge cases and error handling.
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:227
@ PCB_GENERATOR_T
class PCB_GENERATOR, generator on a layer
Definition typeinfo.h:83
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
Definition typeinfo.h:89
@ PCB_GROUP_T
class PCB_GROUP, a set of BOARD_ITEMs
Definition typeinfo.h:103
@ PCB_ZONE_T
class ZONE, a copper pour area
Definition typeinfo.h:100
@ PCB_TEXT_T
class PCB_TEXT, text on a layer
Definition typeinfo.h:84
@ PCB_TABLECELL_T
class PCB_TABLECELL, PCB_TEXTBOX for use in tables
Definition typeinfo.h:87
@ PCB_FOOTPRINT_T
class FOOTPRINT, a footprint
Definition typeinfo.h:78
@ PCB_PAD_T
class PAD, a pad in a footprint
Definition typeinfo.h:79
@ PCB_ARC_T
class PCB_ARC, an arc track segment on a copper layer
Definition typeinfo.h:90
@ PCB_TRACE_T
class PCB_TRACK, a track segment (segment on a copper layer)
Definition typeinfo.h:88
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
#define PR_CAN_ABORT
PLACEMENT_SOURCE_T