KiCad PCB EDA Suite
Loading...
Searching...
No Matches
constraint_builder.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
21
22#include <algorithm>
23#include <cmath>
24#include <ranges>
25#include <set>
26
27#include <base_units.h>
28#include <board.h>
29#include <core/kicad_algo.h>
30#include <footprint.h>
31#include <geometry/eda_angle.h>
32#include <geometry/seg.h>
35#include <pcb_dimension.h>
36#include <pcb_shape.h>
37
38
39namespace
40{
41bool isSegment( const BOARD_ITEM* aItem )
42{
43 return aItem->Type() == PCB_SHAPE_T
44 && static_cast<const PCB_SHAPE*>( aItem )->GetShape() == SHAPE_T::SEGMENT;
45}
46
47
48bool isCircleOrArc( const BOARD_ITEM* aItem )
49{
50 if( aItem->Type() != PCB_SHAPE_T )
51 return false;
52
53 SHAPE_T shape = static_cast<const PCB_SHAPE*>( aItem )->GetShape();
54 return shape == SHAPE_T::CIRCLE || shape == SHAPE_T::ARC;
55}
56
57
58bool isArc( const BOARD_ITEM* aItem )
59{
60 return aItem->Type() == PCB_SHAPE_T
61 && static_cast<const PCB_SHAPE*>( aItem )->GetShape() == SHAPE_T::ARC;
62}
63
64
65bool isEllipseKind( const BOARD_ITEM* aItem )
66{
67 if( aItem->Type() != PCB_SHAPE_T )
68 return false;
69
70 SHAPE_T shape = static_cast<const PCB_SHAPE*>( aItem )->GetShape();
71 return shape == SHAPE_T::ELLIPSE || shape == SHAPE_T::ELLIPSE_ARC;
72}
73
74
75bool allSegments( const std::vector<BOARD_ITEM*>& aItems )
76{
77 return std::ranges::all_of( aItems, isSegment );
78}
79
80
81// Circles and arcs have a radius the solver can equate or fix.
82bool allRadial( const std::vector<BOARD_ITEM*>& aItems )
83{
84 return std::ranges::all_of( aItems, isCircleOrArc );
85}
86
87
88// Circles, arcs and ellipses all have a centre the solver can make concentric.
89bool allCentered( const std::vector<BOARD_ITEM*>& aItems )
90{
91 return std::ranges::all_of( aItems,
92 []( const BOARD_ITEM* aItem )
93 {
94 return isCircleOrArc( aItem ) || isEllipseKind( aItem );
95 } );
96}
97}
98
99
100EDA_ANGLE MeasureCornerAngle( const SEG& aA, const SEG& aB )
101{
102 const VECTOR2I aEnds[2] = { aA.A, aA.B };
103 const VECTOR2I bEnds[2] = { aB.A, aB.B };
104
105 // The vertex is the closest endpoint pair; the rays run from it toward each other endpoint.
106 int vA = 0, vB = 0;
107 SEG::ecoord best = ( aEnds[0] - bEnds[0] ).SquaredEuclideanNorm();
108
109 for( int i = 0; i < 2; ++i )
110 {
111 for( int j = 0; j < 2; ++j )
112 {
113 SEG::ecoord dist = ( aEnds[i] - bEnds[j] ).SquaredEuclideanNorm();
114
115 if( dist < best )
116 {
117 best = dist;
118 vA = i;
119 vB = j;
120 }
121 }
122 }
123
124 // Orient both segments from the shared vertex outward so SEG::Angle reads the corner the rays
125 // open. It uses each segment's true direction (not a midpoint ray), so a small gap between the
126 // near endpoints does not skew the measurement, and it returns [0, 180] without folding past 90.
127 return SEG( aEnds[vA], aEnds[1 - vA] ).Angle( SEG( bEnds[vB], bEnds[1 - vB] ) );
128}
129
130
131std::unique_ptr<PCB_CONSTRAINT> BuildConstraintFromItems( BOARD_ITEM* aParent,
133 const std::vector<BOARD_ITEM*>& aItems )
134{
135 // Build a constraint of aType with every selected item bound by its WHOLE anchor.
136 auto makeWhole = [&]()
137 {
138 std::unique_ptr<PCB_CONSTRAINT> c = std::make_unique<PCB_CONSTRAINT>( aParent, aType );
139
140 for( BOARD_ITEM* item : aItems )
141 c->AddMember( item->m_Uuid, CONSTRAINT_ANCHOR::WHOLE );
142
143 return c;
144 };
145
146 switch( aType )
147 {
152 {
153 if( aItems.size() != 2 || !allSegments( aItems ) )
154 return nullptr;
155
156 return makeWhole();
157 }
158
161 {
162 if( aItems.size() != 1 || !isSegment( aItems[0] ) )
163 return nullptr;
164
165 return makeWhole();
166 }
167
169 {
170 if( aItems.size() != 1 || !isSegment( aItems[0] ) )
171 return nullptr;
172
173 const PCB_SHAPE* seg = static_cast<const PCB_SHAPE*>( aItems[0] );
174
175 std::unique_ptr<PCB_CONSTRAINT> c = makeWhole();
176 c->SetValue( ( seg->GetEnd() - seg->GetStart() ).EuclideanNorm() );
177 return c;
178 }
179
181 {
182 if( aItems.size() != 2 || !allCentered( aItems ) )
183 return nullptr;
184
185 return makeWhole();
186 }
187
189 {
190 if( aItems.size() != 2 || !allRadial( aItems ) )
191 return nullptr;
192
193 return makeWhole();
194 }
195
197 {
198 if( aItems.size() != 2 || !allSegments( aItems ) )
199 return nullptr;
200
201 const PCB_SHAPE* a = static_cast<const PCB_SHAPE*>( aItems[0] );
202 const PCB_SHAPE* b = static_cast<const PCB_SHAPE*>( aItems[1] );
203
204 // A zero-length segment has no direction, so the corner angle is undefined and the solver's
205 // angle equation is singular.
206 if( a->GetStart() == a->GetEnd() || b->GetStart() == b->GetEnd() )
207 return nullptr;
208
209 std::unique_ptr<PCB_CONSTRAINT> c = makeWhole();
210 c->SetValue( MeasureCornerAngle( SEG( a->GetStart(), a->GetEnd() ),
211 SEG( b->GetStart(), b->GetEnd() ) ).AsDegrees() );
212 return c;
213 }
214
216 {
217 if( aItems.size() != 1 || !isCircleOrArc( aItems[0] ) )
218 return nullptr;
219
220 std::unique_ptr<PCB_CONSTRAINT> c = makeWhole();
221 c->SetValue( static_cast<const PCB_SHAPE*>( aItems[0] )->GetRadius() );
222 return c;
223 }
224
226 {
227 if( aItems.size() != 1 || !isArc( aItems[0] ) )
228 return nullptr;
229
230 std::unique_ptr<PCB_CONSTRAINT> c = makeWhole();
231 c->SetValue( static_cast<const PCB_SHAPE*>( aItems[0] )->GetArcAngle().AsDegrees() );
232 return c;
233 }
234
236 {
237 if( aItems.size() != 2 )
238 return nullptr;
239
240 const BOARD_ITEM* a = aItems[0];
241 const BOARD_ITEM* b = aItems[1];
242
243 auto isCurve = []( const BOARD_ITEM* aItem )
244 {
245 return isCircleOrArc( aItem ) || isEllipseKind( aItem );
246 };
247
248 bool lineCurve = ( isSegment( a ) && isCurve( b ) ) || ( isSegment( b ) && isCurve( a ) );
249 bool curveCurve = isCircleOrArc( a ) && isCircleOrArc( b );
250
251 if( !lineCurve && !curveCurve )
252 return nullptr;
253
254 return makeWhole();
255 }
256
257 default:
258 // Point-anchored families (coincident, midpoint, symmetric, ...) need point selection,
259 // which the whole-shape authoring tool does not yet provide.
260 return nullptr;
261 }
262}
263
264
266{
267 wxString format;
268
269 // No default: an added type must be classified here, or the build fails rather than shipping
270 // a silently hintless constraint. Each arm mirrors the matching BuildConstraintFromItems rule.
271 switch( aType )
272 {
277 format = _( "%s needs two line segments. Click them to constrain." );
278 break;
279
280 // A zero-length segment has no direction, so the corner angle would be singular
282 format = _( "%s needs two line segments of nonzero length. Click them to constrain." );
283 break;
284
287 format = _( "%s needs one line segment, or two anchor points. Click them to constrain." );
288 break;
289
291 format = _( "%s needs one line segment. Click it to constrain." );
292 break;
293
294 // allCentered also accepts ellipses, which have a centre but no single radius
296 format = _( "%s needs two arcs, circles or ellipses. Click them to constrain." );
297 break;
298
300 format = _( "%s needs two arcs or circles. Click them to constrain." );
301 break;
302
304 format = _( "%s needs one arc or circle. Click it to constrain." );
305 break;
306
308 format = _( "%s needs one arc. Click it to constrain." );
309 break;
310
311 // Two curves must both be arcs or circles; an ellipse pairs only with a line
313 format = _( "%s needs a line and a curve, or two arcs or circles. Click them to constrain." );
314 break;
315
316 // Authored by clicking anchors, so there is never a selection to reject
323 return wxEmptyString;
324 }
325
326 return wxString::Format( format, ConstraintTypeLabel( aType ) );
327}
328
329
330std::vector<CONSTRAINT_ANCHOR_POINT> ConstraintShapeAnchors( const PCB_SHAPE* aShape )
331{
332 std::vector<CONSTRAINT_ANCHOR_POINT> anchors;
333
334 if( !aShape )
335 return anchors;
336
337 switch( aShape->GetShape() )
338 {
339 case SHAPE_T::SEGMENT:
340 case SHAPE_T::BEZIER:
341 return { { CONSTRAINT_ANCHOR::START, aShape->GetStart() },
342 { CONSTRAINT_ANCHOR::END, aShape->GetEnd() } };
343
344 case SHAPE_T::ARC:
346 return { { CONSTRAINT_ANCHOR::START, aShape->GetStart() },
347 { CONSTRAINT_ANCHOR::END, aShape->GetEnd() },
348 { CONSTRAINT_ANCHOR::CENTER, aShape->GetCenter() } };
349
350 case SHAPE_T::CIRCLE:
351 case SHAPE_T::ELLIPSE:
352 return { { CONSTRAINT_ANCHOR::CENTER, aShape->GetCenter() } };
353
355 {
356 // TL TR BR BL order must match frozen corner roles of adapter
357 VECTOR2I s = aShape->GetStart();
358 VECTOR2I e = aShape->GetEnd();
359 VECTOR2I tl( std::min( s.x, e.x ), std::min( s.y, e.y ) );
360 VECTOR2I br( std::max( s.x, e.x ), std::max( s.y, e.y ) );
361
362 return { { CONSTRAINT_ANCHOR::VERTEX, tl, 0 },
363 { CONSTRAINT_ANCHOR::VERTEX, VECTOR2I( br.x, tl.y ), 1 },
364 { CONSTRAINT_ANCHOR::VERTEX, br, 2 },
365 { CONSTRAINT_ANCHOR::VERTEX, VECTOR2I( tl.x, br.y ), 3 } };
366 }
367
368 case SHAPE_T::POLY:
369 {
370 // Same eligibility gate as adapter ingestion so picker never offers unmappable anchor
371 if( !ConstraintPolygonIsModelable( aShape ) )
372 return anchors;
373
374 const SHAPE_LINE_CHAIN& outline = aShape->GetPolyShape().COutline( 0 );
375
376 for( int i = 0; i < outline.PointCount(); ++i )
377 anchors.push_back( { CONSTRAINT_ANCHOR::VERTEX, outline.CPoint( i ), i } );
378
379 return anchors;
380 }
381
382 default:
383 return anchors;
384 }
385}
386
387
389{
390 if( !aShape || aShape->GetShape() != SHAPE_T::POLY )
391 return false;
392
393 const SHAPE_POLY_SET& polySet = aShape->GetPolyShape();
394
395 if( polySet.OutlineCount() != 1 || polySet.HoleCount( 0 ) > 0 )
396 return false;
397
398 const SHAPE_LINE_CHAIN& outline = polySet.COutline( 0 );
399
400 return outline.PointCount() > 0 && outline.ArcCount() == 0;
401}
402
403
404std::optional<CONSTRAINT_ANCHOR_POINT> ConstraintShapeVertex( const PCB_SHAPE* aShape, int aIndex )
405{
406 if( !aShape || aIndex < 0 )
407 return std::nullopt;
408
409 if( aShape->GetShape() != SHAPE_T::RECTANGLE && aShape->GetShape() != SHAPE_T::POLY )
410 return std::nullopt;
411
412 std::vector<CONSTRAINT_ANCHOR_POINT> anchors = ConstraintShapeAnchors( aShape );
413
414 if( aIndex >= (int) anchors.size() )
415 return std::nullopt;
416
417 return anchors[aIndex];
418}
419
420
421std::optional<CONSTRAINT_MEMBER> NearestAnchorAmong( const std::vector<PCB_SHAPE*>& aShapes,
422 const VECTOR2I& aPos, double aMaxDist )
423{
424 double best = aMaxDist;
425 std::optional<CONSTRAINT_MEMBER> result;
426
427 for( const PCB_SHAPE* shape : aShapes )
428 {
429 for( const CONSTRAINT_ANCHOR_POINT& a : ConstraintShapeAnchors( shape ) )
430 {
431 double dist = ( a.pos - aPos ).EuclideanNorm();
432
433 if( dist <= best )
434 {
435 best = dist;
436 result = CONSTRAINT_MEMBER( shape->m_Uuid, a.anchor, a.index );
437 }
438 }
439 }
440
441 return result;
442}
443
444
445std::vector<PCB_SHAPE*> CollectConstraintShapes( BOARD* aBoard )
446{
447 std::vector<PCB_SHAPE*> shapes;
448
449 if( !aBoard )
450 return shapes;
451
452 for( BOARD_ITEM* item : aBoard->Drawings() )
453 {
454 if( PCB_SHAPE* shape = dynamic_cast<PCB_SHAPE*>( item ) )
455 shapes.push_back( shape );
456 }
457
458 for( FOOTPRINT* footprint : aBoard->Footprints() )
459 {
460 for( BOARD_ITEM* item : footprint->GraphicalItems() )
461 {
462 if( PCB_SHAPE* shape = dynamic_cast<PCB_SHAPE*>( item ) )
463 shapes.push_back( shape );
464 }
465 }
466
467 return shapes;
468}
469
470
471std::vector<BOARD_ITEM*> CollectConstrainableItems( BOARD* aBoard )
472{
473 std::vector<BOARD_ITEM*> items;
474
475 if( !aBoard )
476 return items;
477
478 auto collect =
479 [&]( const auto& aContainer )
480 {
481 for( BOARD_ITEM* item : aContainer )
482 {
483 if( item->Type() == PCB_SHAPE_T || dynamic_cast<PCB_DIMENSION_BASE*>( item ) )
484 items.push_back( item );
485 }
486 };
487
488 collect( aBoard->Drawings() );
489
490 for( FOOTPRINT* footprint : aBoard->Footprints() )
491 collect( footprint->GraphicalItems() );
492
493 return items;
494}
495
496
497std::optional<CONSTRAINT_MEMBER> NearestConstraintAnchor( BOARD* aBoard, const VECTOR2I& aPos,
498 double aMaxDist,
499 const std::vector<CONSTRAINT_MEMBER>& aExclude )
500{
501 double best = aMaxDist;
502 std::optional<CONSTRAINT_MEMBER> result;
503
504 for( BOARD_ITEM* item : CollectConstrainableItems( aBoard ) )
505 {
506 for( const CONSTRAINT_ANCHOR_POINT& a : ConstraintItemAnchors( item ) )
507 {
508 CONSTRAINT_MEMBER candidate( item->m_Uuid, a.anchor, a.index );
509
510 // Skip already picked handle so distinct coincident endpoint stays reachable
511 if( alg::contains( aExclude, candidate ) )
512 continue;
513
514 double dist = ( a.pos - aPos ).EuclideanNorm();
515
516 if( dist <= best )
517 {
518 best = dist;
519 result = candidate;
520 }
521 }
522 }
523
524 return result;
525}
526
527
528std::vector<ENDPOINT_BINDING> SelectEndpointBindings( BOARD* aBoard, const KIID& aItem, const VECTOR2I& aStart,
529 const std::optional<VECTOR2I>& aEnd, double aMaxDist )
530{
531 std::vector<ENDPOINT_BINDING> bindings;
532
533 if( !aBoard )
534 return bindings;
535
536 // Best pair of distinct anchors on one item within aMaxDist minimizing summed distance
537 // Distinct anchors required or endpoints merge and pairs judged jointly not per end nearest
538 using ANCHOR_PAIR = std::pair<CONSTRAINT_MEMBER, CONSTRAINT_MEMBER>;
539
540 auto bestPairOn = [&]( BOARD_ITEM* aCandidate ) -> std::optional<std::pair<ANCHOR_PAIR, double>>
541 {
542 std::vector<CONSTRAINT_ANCHOR_POINT> anchors = ConstraintItemAnchors( aCandidate );
543
544 // Sum decomposes per endpoint best and runner up END anchors computed once serve every
545 // START candidate keeps a dense polygon linear in vertex count instead of quadratic
546 const size_t none = anchors.size();
547 size_t bestEnd = none;
548 size_t secondEnd = none;
549 std::vector<double> dEnd( anchors.size(), 0.0 );
550
551 for( size_t j = 0; j < anchors.size(); ++j )
552 {
553 dEnd[j] = ( anchors[j].pos - *aEnd ).EuclideanNorm();
554
555 if( dEnd[j] > aMaxDist )
556 continue;
557
558 if( bestEnd == none || dEnd[j] < dEnd[bestEnd] )
559 {
560 secondEnd = bestEnd;
561 bestEnd = j;
562 }
563 else if( secondEnd == none || dEnd[j] < dEnd[secondEnd] )
564 {
565 secondEnd = j;
566 }
567 }
568
569 if( bestEnd == none )
570 return std::nullopt;
571
572 std::optional<std::pair<ANCHOR_PAIR, double>> best;
573
574 for( size_t i = 0; i < anchors.size(); ++i )
575 {
576 double dStart = ( anchors[i].pos - aStart ).EuclideanNorm();
577
578 if( dStart > aMaxDist )
579 continue;
580
581 size_t j = ( i == bestEnd ) ? secondEnd : bestEnd;
582
583 if( j == none )
584 continue;
585
586 double sum = dStart + dEnd[j];
587
588 if( !best || sum < best->second )
589 {
590 best = std::make_pair(
591 ANCHOR_PAIR{ CONSTRAINT_MEMBER( aCandidate->m_Uuid, anchors[i].anchor, anchors[i].index ),
592 CONSTRAINT_MEMBER( aCandidate->m_Uuid, anchors[j].anchor, anchors[j].index ) },
593 sum );
594 }
595 }
596
597 return best;
598 };
599
600 // Prefer single object reaching both endpoints so a single feature dimension stays bound at
601 // both ends
602 if( aEnd )
603 {
604 std::optional<ANCHOR_PAIR> bestPair;
605 double bestSum = 0.0;
606
607 for( BOARD_ITEM* item : CollectConstrainableItems( aBoard ) )
608 {
609 if( item->m_Uuid == aItem )
610 continue;
611
612 auto pair = bestPairOn( item );
613
614 if( !pair )
615 continue;
616
617 if( !bestPair || pair->second < bestSum )
618 {
619 bestSum = pair->second;
620 bestPair = pair->first;
621 }
622 }
623
624 if( bestPair )
625 {
626 bindings.push_back( { CONSTRAINT_ANCHOR::START, bestPair->first } );
627 bindings.push_back( { CONSTRAINT_ANCHOR::END, bestPair->second } );
628 return bindings;
629 }
630 }
631
632 // Else bind each endpoint to its own nearest anchor the two may land on different objects
633 // and either may find nothing
634 std::vector<CONSTRAINT_MEMBER> exclude{ { aItem, CONSTRAINT_ANCHOR::START }, { aItem, CONSTRAINT_ANCHOR::END } };
635
636 if( auto startTarget = NearestConstraintAnchor( aBoard, aStart, aMaxDist, exclude ) )
637 {
638 bindings.push_back( { CONSTRAINT_ANCHOR::START, *startTarget } );
639 exclude.push_back( *startTarget );
640 }
641
642 if( aEnd )
643 {
644 if( auto endTarget = NearestConstraintAnchor( aBoard, *aEnd, aMaxDist, exclude ) )
645 bindings.push_back( { CONSTRAINT_ANCHOR::END, *endTarget } );
646 }
647
648 return bindings;
649}
650
651
653{
654 if( !aBoard )
655 return nullptr;
656
657 BOARD_ITEM* item = aBoard->ResolveItem( aId, true );
658
659 return item && ( item->Type() == PCB_SHAPE_T || dynamic_cast<PCB_DIMENSION_BASE*>( item ) )
660 ? item
661 : nullptr;
662}
663
664
665std::optional<KIID> NearestOutlineShape( BOARD* aBoard, const VECTOR2I& aPos, double aMaxDist, bool aAllowCircle )
666{
667 double best = aMaxDist;
668 std::optional<KIID> result;
669
670 for( PCB_SHAPE* shape : CollectConstraintShapes( aBoard ) )
671 {
672 const SHAPE_T shapeType = shape->GetShape();
673 double dist = 0;
674
675 if( shapeType == SHAPE_T::SEGMENT )
676 {
677 dist = SEG( shape->GetStart(), shape->GetEnd() ).Distance( aPos );
678 }
679 else if( aAllowCircle && ( shapeType == SHAPE_T::CIRCLE || shapeType == SHAPE_T::ARC ) )
680 {
681 dist = std::abs( ( aPos - shape->GetCenter() ).EuclideanNorm() - shape->GetRadius() );
682 }
683 else if( aAllowCircle && ( shapeType == SHAPE_T::ELLIPSE || shapeType == SHAPE_T::ELLIPSE_ARC ) )
684 {
685 // Radial distance to the outline at the click's polar angle in the ellipse frame.
686 // Not the exact outline distance, but exact on the outline, which is all a snap needs.
687 double a = shape->GetEllipseMajorRadius();
688 double b = shape->GetEllipseMinorRadius();
689 double phi = shape->GetEllipseRotation().AsRadians();
690 VECTOR2D d = VECTOR2D( aPos - shape->GetEllipseCenter() );
691 double lx = d.x * std::cos( phi ) + d.y * std::sin( phi );
692 double ly = -d.x * std::sin( phi ) + d.y * std::cos( phi );
693 double r = std::hypot( lx, ly );
694
695 if( a <= 0 || b <= 0 )
696 continue;
697
698 double theta = std::atan2( ly, lx );
699 double re = a * b / std::hypot( b * std::cos( theta ), a * std::sin( theta ) );
700
701 dist = std::abs( r - re );
702 }
703 else
704 {
705 continue;
706 }
707
708 if( dist <= best )
709 {
710 best = dist;
711 result = shape->m_Uuid;
712 }
713 }
714
715 return result;
716}
717
718
719std::vector<CONSTRAINT_ANCHOR_POINT> ConstraintItemAnchors( const BOARD_ITEM* aItem )
720{
721 if( !aItem )
722 return {};
723
724 if( aItem->Type() == PCB_SHAPE_T )
725 return ConstraintShapeAnchors( static_cast<const PCB_SHAPE*>( aItem ) );
726
727 if( const PCB_DIMENSION_BASE* dim = dynamic_cast<const PCB_DIMENSION_BASE*>( aItem ) )
728 {
729 std::vector<CONSTRAINT_ANCHOR_POINT> anchors;
730 anchors.push_back( { CONSTRAINT_ANCHOR::START, dim->GetStart() } );
731
732 // Only aligned/orthogonal/radial dimensions have a second measured feature point; a leader
733 // or centre mark's second point is a control point.
734 switch( aItem->Type() )
735 {
738 case PCB_DIM_RADIAL_T:
739 anchors.push_back( { CONSTRAINT_ANCHOR::END, dim->GetEnd() } );
740 break;
741
742 default:
743 break;
744 }
745
746 return anchors;
747 }
748
749 return {};
750}
751
752
753std::optional<VECTOR2I> ConstraintAnchorPosition( BOARD* aBoard, const CONSTRAINT_MEMBER& aMember )
754{
756 {
757 // VERTEX anchor needs its ordinal too else every vertex member resolves to vertex 0
758 if( a.anchor == aMember.m_anchor
759 && ( a.anchor != CONSTRAINT_ANCHOR::VERTEX || a.index == aMember.m_index ) )
760 {
761 return a.pos;
762 }
763 }
764
765 return std::nullopt;
766}
767
768
769double InitialConstraintValue( PCB_CONSTRAINT_TYPE aType, double aMeasured,
770 const std::map<PCB_CONSTRAINT_TYPE, double>& aRemembered )
771{
772 auto it = aRemembered.find( aType );
773
774 return it != aRemembered.end() ? it->second : aMeasured;
775}
776
777
778std::optional<KIID> NearestConstrainedShape( const std::vector<PCB_SHAPE*>& aCandidates,
779 const VECTOR2I& aPos, int aMaxDist )
780{
781 auto it = std::ranges::find_if( aCandidates,
782 [&]( const PCB_SHAPE* aShape )
783 {
784 return aShape && aShape->HitTest( aPos, aMaxDist );
785 } );
786
787 return it == aCandidates.end() ? std::nullopt : std::optional<KIID>( ( *it )->m_Uuid );
788}
789
790
791std::optional<KIID> SelectRadialDimensionTarget( BOARD* aBoard, const KIID& aDimension,
792 const VECTOR2I& aCenter, const VECTOR2I& aRim,
793 double aMaxDist )
794{
795 if( !aBoard )
796 return std::nullopt;
797
798 std::optional<KIID> best;
799 double bestErr = 0.0;
800
801 for( PCB_SHAPE* shape : CollectConstraintShapes( aBoard ) )
802 {
803 if( shape->m_Uuid == aDimension || !isCircleOrArc( shape ) )
804 continue;
805
806 // Centre and rim must land on the same circle or arc centre and circumference or else a
807 // radial dimension over unrelated geometry would bind spuriously
808 std::optional<VECTOR2I> centerPos;
809
810 for( const CONSTRAINT_ANCHOR_POINT& a : ConstraintShapeAnchors( shape ) )
811 {
812 if( a.anchor == CONSTRAINT_ANCHOR::CENTER )
813 centerPos = a.pos;
814 }
815
816 if( !centerPos )
817 continue;
818
819 double centerErr = ( *centerPos - aCenter ).EuclideanNorm();
820
821 if( centerErr > aMaxDist )
822 continue;
823
824 double rimErr = std::abs( ( aRim - *centerPos ).EuclideanNorm() - shape->GetRadius() );
825
826 if( rimErr > aMaxDist )
827 continue;
828
829 // Arc outline is swept portion only not the whole circle so a rim point off the arc must
830 // not bind
831 if( shape->GetShape() == SHAPE_T::ARC && !shape->HitTest( aRim, KiROUND( aMaxDist ) ) )
832 continue;
833
834 double err = centerErr + rimErr;
835
836 if( !best || err < bestErr )
837 {
838 bestErr = err;
839 best = shape->m_Uuid;
840 }
841 }
842
843 return best;
844}
845
846
847bool DimensionEndpointsBound( BOARD* aBoard, const PCB_DIMENSION_BASE* aDimension )
848{
849 if( !aBoard || !aDimension )
850 return false;
851
852 const CONSTRAINT_MEMBER startMember( aDimension->m_Uuid, CONSTRAINT_ANCHOR::START );
853 const CONSTRAINT_MEMBER endMember( aDimension->m_Uuid, CONSTRAINT_ANCHOR::END );
854
855 auto anyConstraint = [&]( const auto& aMatch )
856 {
857 if( std::ranges::any_of( aBoard->Constraints(), aMatch ) )
858 return true;
859
860 // Bindings are parented to the owning dimension footprint not necessarily the first so
861 // every footprint must be scanned to match the write path
862 return std::ranges::any_of( aBoard->Footprints(),
863 [&]( const FOOTPRINT* aFootprint )
864 { return std::ranges::any_of( aFootprint->Constraints(), aMatch ); } );
865 };
866
867 // Radial dimension binds centre coincident plus rim on outline of one circle or arc
868 // Legs on different objects or an object that cannot play the radius role never offer Driving
869 if( aDimension->Type() == PCB_DIM_RADIAL_T )
870 {
871 auto rimOnItem = [&]( const KIID& aItem )
872 {
873 return anyConstraint(
874 [&]( const PCB_CONSTRAINT* aConstraint )
875 {
877 return false;
878
879 // Point on line binding is asymmetric the dimension rim point is member 0
880 // and the object outline WHOLE anchor is member 1
881 const std::vector<CONSTRAINT_MEMBER>& members = aConstraint->GetMembers();
882
883 return members.size() == 2 && members[0] == endMember
884 && members[1] == CONSTRAINT_MEMBER( aItem, CONSTRAINT_ANCHOR::WHOLE );
885 } );
886 };
887
888 return anyConstraint(
889 [&]( const PCB_CONSTRAINT* aConstraint )
890 {
892 return false;
893
894 const std::vector<CONSTRAINT_MEMBER>& members = aConstraint->GetMembers();
895
896 if( members.size() != 2 )
897 return false;
898
899 // Authored dimension first but coincident is symmetric so accept either order
900 const CONSTRAINT_MEMBER* target = nullptr;
901
902 if( members[0] == startMember )
903 target = &members[1];
904 else if( members[1] == startMember )
905 target = &members[0];
906
907 if( !target || target->m_anchor != CONSTRAINT_ANCHOR::CENTER )
908 return false;
909
910 BOARD_ITEM* item = ResolveConstrainableItem( aBoard, target->m_item );
911
912 return item && isCircleOrArc( item ) && rimOnItem( target->m_item );
913 } );
914 }
915
916 // Aligned or orthogonal needs a coincident per endpoint whose target still resolves a target
917 // pointing at a deleted item or a stale vertex index does not count
918 auto hasCoincident = [&]( const CONSTRAINT_MEMBER& aMember )
919 {
920 return anyConstraint(
921 [&]( const PCB_CONSTRAINT* aConstraint )
922 {
924 return false;
925
926 const std::vector<CONSTRAINT_MEMBER>& members = aConstraint->GetMembers();
927
928 // Must pair with a distinct target not itself
929 if( members.size() != 2 || members[0].m_item == members[1].m_item )
930 return false;
931
932 if( members[0] == aMember )
933 return ConstraintAnchorPosition( aBoard, members[1] ).has_value();
934
935 return members[1] == aMember
936 && ConstraintAnchorPosition( aBoard, members[0] ).has_value();
937 } );
938 };
939
940 return hasCoincident( startMember ) && hasCoincident( endMember );
941}
942
943
945{
946 if( !aDimension )
947 return false;
948
949 switch( aDimension->Type() )
950 {
953 case PCB_DIM_RADIAL_T:
954 return true;
955
956 default:
957 return false;
958 }
959}
960
961
963{
964 if( !aBoard || !aDimension )
965 return nullptr;
966
967 const CONSTRAINT_MEMBER startMember( aDimension->m_Uuid, CONSTRAINT_ANCHOR::START );
968 const CONSTRAINT_MEMBER endMember( aDimension->m_Uuid, CONSTRAINT_ANCHOR::END );
969
970 auto matches = [&]( const PCB_CONSTRAINT* aConstraint )
971 {
972 if( aConstraint->GetConstraintType() != PCB_CONSTRAINT_TYPE::FIXED_LENGTH )
973 return false;
974
975 const std::vector<CONSTRAINT_MEMBER>& members = aConstraint->GetMembers();
976
977 return members.size() == 2
978 && ( ( members[0] == startMember && members[1] == endMember )
979 || ( members[0] == endMember && members[1] == startMember ) );
980 };
981
982 auto scan = [&]( const CONSTRAINTS& aList ) -> PCB_CONSTRAINT*
983 {
984 auto it = std::ranges::find_if( aList, matches );
985 return it != aList.end() ? *it : nullptr;
986 };
987
988 if( PCB_CONSTRAINT* c = scan( aBoard->Constraints() ) )
989 return c;
990
991 // Driving length is parented to the owning dimension footprint not necessarily the first so
992 // scan every footprint to match the write
993 for( FOOTPRINT* footprint : aBoard->Footprints() )
994 {
995 if( PCB_CONSTRAINT* c = scan( footprint->Constraints() ) )
996 return c;
997 }
998
999 return nullptr;
1000}
1001
1002
1003bool DimensionCanDrive( BOARD* aBoard, const PCB_DIMENSION_BASE* aDimension )
1004{
1005 if( !DimensionHasValueMode( aDimension ) )
1006 return false;
1007
1008 if( DimensionEndpointsBound( aBoard, aDimension ) )
1009 return true;
1010
1011 PCB_CONSTRAINT* existing = FindDimensionLengthConstraint( aBoard, aDimension );
1012
1013 return existing && existing->IsDriving();
1014}
1015
1016
1018{
1019 PCB_CONSTRAINT* lengthConstraint = FindDimensionLengthConstraint( aBoard, aDimension );
1020
1021 if( lengthConstraint && lengthConstraint->IsDriving() )
1023
1024 if( aDimension && aDimension->GetOverrideTextEnabled() )
1026
1028}
1029
1030
1032 std::optional<int> aDrivingLengthIU,
1033 const std::optional<wxString>& aOverrideText,
1034 const std::function<void( BOARD_ITEM* )>& aBeforeModify,
1035 const std::function<void( BOARD_ITEM* )>& aStageAdd,
1036 const std::function<void( BOARD_ITEM* )>& aBeforeRemove )
1037{
1038 if( !aBoard || !DimensionHasValueMode( aDimension ) )
1039 return nullptr;
1040
1041 PCB_CONSTRAINT* existing = FindDimensionLengthConstraint( aBoard, aDimension );
1042
1043 if( aMode == DIM_VALUE_MODE::DRIVING )
1044 {
1045 // Unbound dimension has no geometry to drive and a non positive length would collapse the
1046 // constraint so the transition rejects with the board untouched
1047 if( !aDrivingLengthIU || *aDrivingLengthIU <= 0 || !DimensionCanDrive( aBoard, aDimension ) )
1048 return nullptr;
1049
1050 aBeforeModify( aDimension );
1051 aDimension->SetOverrideTextEnabled( false );
1052 aDimension->Update();
1053
1054 if( existing )
1055 {
1056 aBeforeModify( existing );
1057 existing->SetValue( *aDrivingLengthIU );
1058 existing->SetDriving( true );
1059 return existing;
1060 }
1061
1062 BOARD_ITEM* parent = aDimension->GetParentFootprint()
1063 ? static_cast<BOARD_ITEM*>( aDimension->GetParentFootprint() )
1064 : static_cast<BOARD_ITEM*>( aBoard );
1065
1066 auto constraint = std::make_unique<PCB_CONSTRAINT>( parent, PCB_CONSTRAINT_TYPE::FIXED_LENGTH );
1067 constraint->AddMember( aDimension->m_Uuid, CONSTRAINT_ANCHOR::START );
1068 constraint->AddMember( aDimension->m_Uuid, CONSTRAINT_ANCHOR::END );
1069 constraint->SetValue( *aDrivingLengthIU );
1070 constraint->SetDriving( true );
1071
1072 PCB_CONSTRAINT* added = constraint.get();
1073 aStageAdd( constraint.release() );
1074 return added;
1075 }
1076
1077 aBeforeModify( aDimension );
1078 aDimension->SetOverrideTextEnabled( aMode == DIM_VALUE_MODE::ARBITRARY );
1079
1080 if( aMode == DIM_VALUE_MODE::ARBITRARY && aOverrideText )
1081 aDimension->SetOverrideText( *aOverrideText );
1082
1083 aDimension->Update();
1084
1085 // Driven and Arbitrary both measure geometry natively so any driving length is dropped
1086 if( existing )
1087 aBeforeRemove( existing );
1088
1089 return nullptr;
1090}
1091
1092
1093void RemapPolygonVertexMembers( BOARD* aBoard, const KIID& aPoly, int aChangedIndex, int aDelta,
1094 const std::function<void( BOARD_ITEM* )>& aBeforeModify,
1095 const std::function<void( BOARD_ITEM* )>& aBeforeRemove )
1096{
1097 if( !aBoard || aDelta == 0 )
1098 return;
1099
1100 auto remapIn = [&]( const CONSTRAINTS& aConstraints )
1101 {
1102 for( PCB_CONSTRAINT* constraint : aConstraints )
1103 {
1104 bool shifts = false;
1105 bool doomed = false;
1106
1107 for( const CONSTRAINT_MEMBER& member : constraint->GetMembers() )
1108 {
1109 if( member.m_item != aPoly || member.m_anchor != CONSTRAINT_ANCHOR::VERTEX )
1110 continue;
1111
1112 if( aDelta < 0 && member.m_index == aChangedIndex )
1113 doomed = true;
1114 else if( member.m_index >= aChangedIndex )
1115 shifts = true;
1116 }
1117
1118 // Deleted vertex drags its bound member down and no fixed arity solver form survives
1119 // losing one so the whole constraint retires left unedited the staged removal image
1120 // keeps the authored members for undo
1121 if( doomed )
1122 {
1123 aBeforeRemove( constraint );
1124 continue;
1125 }
1126
1127 if( !shifts )
1128 continue;
1129
1130 aBeforeModify( constraint );
1131
1132 for( CONSTRAINT_MEMBER& member : constraint->Members() )
1133 {
1134 if( member.m_item == aPoly && member.m_anchor == CONSTRAINT_ANCHOR::VERTEX
1135 && member.m_index >= aChangedIndex )
1136 {
1137 member.m_index += aDelta;
1138 }
1139 }
1140 }
1141 };
1142
1143 remapIn( aBoard->Constraints() );
1144
1145 for( FOOTPRINT* footprint : aBoard->Footprints() )
1146 remapIn( footprint->Constraints() );
1147}
1148
1149
1150bool ConstraintIsDuplicateOnBoard( BOARD* aBoard, const PCB_CONSTRAINT* aConstraint )
1151{
1152 auto scan = [&]( const CONSTRAINTS& aList )
1153 {
1154 return std::ranges::any_of( aList,
1155 [&]( const PCB_CONSTRAINT* aExisting )
1156 {
1157 return ConstraintsAreDuplicate( *aExisting, *aConstraint );
1158 } );
1159 };
1160
1161 if( scan( aBoard->Constraints() ) )
1162 return true;
1163
1164 return std::ranges::any_of( aBoard->Footprints(),
1165 [&]( FOOTPRINT* aFootprint )
1166 {
1167 return scan( aFootprint->Constraints() );
1168 } );
1169}
1170
1171
1172namespace
1173{
1174// Tuning knobs for draw time auto constraints
1175// The bind tolerance accepts only exact landings while the corridor also captures near misses
1176constexpr double AUTO_BIND_TOL_MM = 0.01;
1177constexpr double AUTO_CORRIDOR_MM = 0.25;
1178constexpr double AUTO_TANGENT_TOL_DEG = 10.0;
1179
1180
1181// Tangent direction of a segment or circular shape at aPos or nullopt for other kinds
1182std::optional<double> tangentDirAt( const PCB_SHAPE* aShape, const VECTOR2I& aPos )
1183{
1184 switch( aShape->GetShape() )
1185 {
1186 case SHAPE_T::SEGMENT:
1187 {
1188 VECTOR2D dir( aShape->GetEnd() - aShape->GetStart() );
1189
1190 if( dir.EuclideanNorm() == 0 )
1191 return std::nullopt;
1192
1193 return std::atan2( dir.y, dir.x );
1194 }
1195
1196 case SHAPE_T::ARC:
1197 case SHAPE_T::CIRCLE:
1198 {
1199 VECTOR2D radial( aPos - aShape->GetCenter() );
1200
1201 if( radial.EuclideanNorm() == 0 )
1202 return std::nullopt;
1203
1204 return std::atan2( radial.y, radial.x ) + M_PI / 2;
1205 }
1206
1207 default: return std::nullopt;
1208 }
1209}
1210
1211
1212// A drawn shape meeting aTarget within a few degrees of tangency gets a tangent constraint
1213// The target is the first member so the snap solve moves the drawn shape not the board
1214std::unique_ptr<PCB_CONSTRAINT> makeTangent( const PCB_SHAPE* aShape, const PCB_SHAPE* aTarget, const VECTOR2I& aPos,
1215 BOARD_ITEM* aParent )
1216{
1217 const double tangentTol = AUTO_TANGENT_TOL_DEG * M_PI / 180.0;
1218
1219 bool curveInvolved = aShape->GetShape() == SHAPE_T::ARC || aTarget->GetShape() == SHAPE_T::ARC
1220 || aTarget->GetShape() == SHAPE_T::CIRCLE;
1221
1222 if( !curveInvolved )
1223 return nullptr;
1224
1225 std::optional<double> myDir = tangentDirAt( aShape, aPos );
1226 std::optional<double> otherDir = tangentDirAt( aTarget, aPos );
1227
1228 if( !myDir || !otherDir )
1229 return nullptr;
1230
1231 double diff = std::fabs( std::fmod( *myDir - *otherDir, M_PI ) );
1232 diff = std::min( diff, M_PI - diff );
1233
1234 if( diff > tangentTol )
1235 return nullptr;
1236
1237 auto constraint = std::make_unique<PCB_CONSTRAINT>( aParent, PCB_CONSTRAINT_TYPE::TANGENT );
1238 constraint->AddMember( aTarget->m_Uuid, CONSTRAINT_ANCHOR::WHOLE );
1239 constraint->AddMember( aShape->m_Uuid, CONSTRAINT_ANCHOR::WHOLE );
1240
1241 return constraint;
1242}
1243
1244
1245// Append unless an equal constraint exists on the board or already in this batch
1246// One draw can touch the same target twice so the batch check matters
1247void addUnlessDuplicate( BOARD* aBoard, std::vector<AUTO_CONSTRAINT>& aResult,
1248 std::unique_ptr<PCB_CONSTRAINT> aConstraint, bool aNeedsSolve )
1249{
1250 if( ConstraintIsDuplicateOnBoard( aBoard, aConstraint.get() ) )
1251 return;
1252
1253 if( std::ranges::any_of( aResult,
1254 [&]( const AUTO_CONSTRAINT& aEntry )
1255 {
1256 return ConstraintsAreDuplicate( *aEntry.constraint, *aConstraint );
1257 } ) )
1258 {
1259 return;
1260 }
1261
1262 aResult.push_back( { std::move( aConstraint ), aNeedsSolve } );
1263}
1264
1265
1266// A circle or closed ellipse has no endpoints so only its centre binds
1267// Another curve centre reads as concentric an anchor coincides and an outline holds the centre
1268std::vector<AUTO_CONSTRAINT> selectCenterBindings( BOARD* aBoard, const PCB_SHAPE* aShape, BOARD_ITEM* aParent )
1269{
1270 std::vector<AUTO_CONSTRAINT> result;
1271
1272 const double tol = pcbIUScale.mmToIU( AUTO_BIND_TOL_MM );
1273 VECTOR2I center = aShape->GetCenter();
1274
1275 std::vector<CONSTRAINT_MEMBER> exclude = { { aShape->m_Uuid, CONSTRAINT_ANCHOR::CENTER } };
1276
1277 if( std::optional<CONSTRAINT_MEMBER> target = NearestConstraintAnchor( aBoard, center, tol, exclude ) )
1278 {
1279 std::unique_ptr<PCB_CONSTRAINT> constraint;
1280
1281 if( target->m_anchor == CONSTRAINT_ANCHOR::CENTER )
1282 {
1283 constraint = std::make_unique<PCB_CONSTRAINT>( aParent, PCB_CONSTRAINT_TYPE::CONCENTRIC );
1284 constraint->AddMember( target->m_item, CONSTRAINT_ANCHOR::WHOLE );
1285 constraint->AddMember( aShape->m_Uuid, CONSTRAINT_ANCHOR::WHOLE );
1286 }
1287 else
1288 {
1289 constraint = std::make_unique<PCB_CONSTRAINT>( aParent, PCB_CONSTRAINT_TYPE::COINCIDENT );
1290 constraint->AddMember( aShape->m_Uuid, CONSTRAINT_ANCHOR::CENTER );
1291 constraint->AddMember( target->m_item, target->m_anchor, target->m_index );
1292 }
1293
1294 addUnlessDuplicate( aBoard, result, std::move( constraint ), false );
1295 }
1296 else if( std::optional<KIID> outline = NearestOutlineShape( aBoard, center, tol, true ) )
1297 {
1298 if( *outline != aShape->m_Uuid )
1299 {
1300 auto constraint = std::make_unique<PCB_CONSTRAINT>( aParent, PCB_CONSTRAINT_TYPE::POINT_ON_LINE );
1301 constraint->AddMember( aShape->m_Uuid, CONSTRAINT_ANCHOR::CENTER );
1302 constraint->AddMember( *outline, CONSTRAINT_ANCHOR::WHOLE );
1303
1304 addUnlessDuplicate( aBoard, result, std::move( constraint ), false );
1305 }
1306 }
1307
1308 return result;
1309}
1310
1311
1312// Endpoints landing on existing anchors bind coincident
1313void selectEndpointCoincidents( BOARD* aBoard, const PCB_SHAPE* aShape, BOARD_ITEM* aParent,
1314 std::vector<AUTO_CONSTRAINT>& aResult, std::set<CONSTRAINT_ANCHOR>& aBound,
1315 std::vector<std::pair<VECTOR2I, KIID>>& aTouches )
1316{
1317 const double tol = pcbIUScale.mmToIU( AUTO_BIND_TOL_MM );
1318
1319 std::vector<ENDPOINT_BINDING> bindings =
1320 SelectEndpointBindings( aBoard, aShape->m_Uuid, aShape->GetStart(), aShape->GetEnd(), tol );
1321
1322 for( const ENDPOINT_BINDING& binding : bindings )
1323 {
1324 auto constraint = std::make_unique<PCB_CONSTRAINT>( aParent, PCB_CONSTRAINT_TYPE::COINCIDENT );
1325 constraint->AddMember( aShape->m_Uuid, binding.sourceAnchor );
1326 constraint->AddMember( binding.target.m_item, binding.target.m_anchor, binding.target.m_index );
1327
1328 aBound.insert( binding.sourceAnchor );
1329
1330 VECTOR2I pos = binding.sourceAnchor == CONSTRAINT_ANCHOR::START ? aShape->GetStart() : aShape->GetEnd();
1331 aTouches.emplace_back( pos, binding.target.m_item );
1332
1333 addUnlessDuplicate( aBoard, aResult, std::move( constraint ), false );
1334 }
1335}
1336
1337
1338// An endpoint with no anchor to coincide with but sitting on an outline binds point on line
1339// Landing on a segment midpoint means the midpoint snap was used so bind midpoint instead
1340void selectOutlineFallbacks( BOARD* aBoard, const PCB_SHAPE* aShape, BOARD_ITEM* aParent,
1341 std::vector<AUTO_CONSTRAINT>& aResult, const std::set<CONSTRAINT_ANCHOR>& aBound,
1342 std::vector<std::pair<VECTOR2I, KIID>>& aTouches )
1343{
1344 const double tol = pcbIUScale.mmToIU( AUTO_BIND_TOL_MM );
1345
1347 {
1348 if( aBound.contains( anchor ) )
1349 continue;
1350
1351 VECTOR2I pos = anchor == CONSTRAINT_ANCHOR::START ? aShape->GetStart() : aShape->GetEnd();
1352 std::optional<KIID> target = NearestOutlineShape( aBoard, pos, tol, true );
1353
1354 if( !target || *target == aShape->m_Uuid )
1355 continue;
1356
1358 PCB_SHAPE* targetShape = dynamic_cast<PCB_SHAPE*>( aBoard->ResolveItem( *target, true ) );
1359
1360 if( targetShape && targetShape->GetShape() == SHAPE_T::SEGMENT )
1361 {
1362 VECTOR2I mid = targetShape->GetStart() + ( targetShape->GetEnd() - targetShape->GetStart() ) / 2;
1363
1364 if( ( pos - mid ).EuclideanNorm() <= tol )
1366 }
1367
1368 auto constraint = std::make_unique<PCB_CONSTRAINT>( aParent, type );
1369 constraint->AddMember( aShape->m_Uuid, anchor );
1370 constraint->AddMember( *target, CONSTRAINT_ANCHOR::WHOLE );
1371
1372 aTouches.emplace_back( pos, *target );
1373
1374 addUnlessDuplicate( aBoard, aResult, std::move( constraint ), false );
1375 }
1376}
1377
1378
1379// A segment drawn through or near an existing shape anchor pins that point on the new segment
1380// Near misses within the corridor bind too and the post push solve pulls the line onto them
1381void selectCorridorPins( BOARD* aBoard, const PCB_SHAPE* aShape, BOARD_ITEM* aParent,
1382 std::vector<AUTO_CONSTRAINT>& aResult )
1383{
1384 if( aShape->GetShape() != SHAPE_T::SEGMENT || aShape->GetStart() == aShape->GetEnd() )
1385 return;
1386
1387 const double tol = pcbIUScale.mmToIU( AUTO_BIND_TOL_MM );
1388 const double corridor = pcbIUScale.mmToIU( AUTO_CORRIDOR_MM );
1389
1390 SEG span( aShape->GetStart(), aShape->GetEnd() );
1391 std::vector<VECTOR2I> boundPos;
1392
1393 for( BOARD_ITEM* item : CollectConstrainableItems( aBoard ) )
1394 {
1395 if( item->m_Uuid == aShape->m_Uuid || item->Type() != PCB_SHAPE_T )
1396 continue;
1397
1399 {
1400 if( span.Distance( anchor.pos ) > corridor )
1401 continue;
1402
1403 // The drawn endpoints already bound above so only true mid span hits count
1404 if( ( anchor.pos - aShape->GetStart() ).EuclideanNorm() <= corridor
1405 || ( anchor.pos - aShape->GetEnd() ).EuclideanNorm() <= corridor )
1406 {
1407 continue;
1408 }
1409
1410 // Chained corners stack two anchors on one spot and one binding is enough
1411 if( std::ranges::any_of( boundPos,
1412 [&]( const VECTOR2I& aP )
1413 {
1414 return ( anchor.pos - aP ).EuclideanNorm() <= tol;
1415 } ) )
1416 {
1417 continue;
1418 }
1419
1420 boundPos.push_back( anchor.pos );
1421
1422 auto constraint = std::make_unique<PCB_CONSTRAINT>( aParent, PCB_CONSTRAINT_TYPE::POINT_ON_LINE );
1423 constraint->AddMember( item->m_Uuid, anchor.anchor, anchor.index );
1424 constraint->AddMember( aShape->m_Uuid, CONSTRAINT_ANCHOR::WHOLE );
1425
1426 addUnlessDuplicate( aBoard, aResult, std::move( constraint ), true );
1427 }
1428 }
1429}
1430
1431
1432// Tangents where the drawn shape touched another shape near tangency
1433void selectTangents( BOARD* aBoard, const PCB_SHAPE* aShape, BOARD_ITEM* aParent, std::vector<AUTO_CONSTRAINT>& aResult,
1434 const std::vector<std::pair<VECTOR2I, KIID>>& aTouches )
1435{
1436 for( const auto& [pos, id] : aTouches )
1437 {
1438 PCB_SHAPE* target = dynamic_cast<PCB_SHAPE*>( aBoard->ResolveItem( id, true ) );
1439
1440 if( target && target != aShape )
1441 {
1442 if( std::unique_ptr<PCB_CONSTRAINT> tangent = makeTangent( aShape, target, pos, aParent ) )
1443 addUnlessDuplicate( aBoard, aResult, std::move( tangent ), true );
1444 }
1445 }
1446}
1447
1448
1449// A segment drawn in a constrained line mode keeps its axis
1450void selectAxisConstraint( BOARD* aBoard, const PCB_SHAPE* aShape, BOARD_ITEM* aParent,
1451 std::vector<AUTO_CONSTRAINT>& aResult )
1452{
1453 if( aShape->GetShape() != SHAPE_T::SEGMENT || aShape->GetStart() == aShape->GetEnd() )
1454 return;
1455
1456 bool horizontal = aShape->GetStart().y == aShape->GetEnd().y;
1457 bool vertical = aShape->GetStart().x == aShape->GetEnd().x;
1458
1459 if( !horizontal && !vertical )
1460 return;
1461
1462 auto constraint = std::make_unique<PCB_CONSTRAINT>( aParent, horizontal ? PCB_CONSTRAINT_TYPE::HORIZONTAL
1464 constraint->AddMember( aShape->m_Uuid, CONSTRAINT_ANCHOR::WHOLE );
1465
1466 addUnlessDuplicate( aBoard, aResult, std::move( constraint ), false );
1467}
1468} // namespace
1469
1470
1471std::vector<AUTO_CONSTRAINT> SelectShapeAutoConstraints( BOARD* aBoard, const PCB_SHAPE* aShape, BOARD_ITEM* aParent,
1472 bool aAxisConstraint )
1473{
1474 std::vector<AUTO_CONSTRAINT> result;
1475
1476 if( !aBoard || !aShape )
1477 return result;
1478
1479 if( aShape->GetShape() == SHAPE_T::CIRCLE || aShape->GetShape() == SHAPE_T::ELLIPSE )
1480 return selectCenterBindings( aBoard, aShape, aParent );
1481
1482 std::set<CONSTRAINT_ANCHOR> bound;
1483 std::vector<std::pair<VECTOR2I, KIID>> touches;
1484
1485 selectEndpointCoincidents( aBoard, aShape, aParent, result, bound, touches );
1486 selectOutlineFallbacks( aBoard, aShape, aParent, result, bound, touches );
1487 selectCorridorPins( aBoard, aShape, aParent, result );
1488 selectTangents( aBoard, aShape, aParent, result, touches );
1489
1490 if( aAxisConstraint )
1491 selectAxisConstraint( aBoard, aShape, aParent, result );
1492
1493 return result;
1494}
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:121
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:986
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:83
FOOTPRINT * GetParentFootprint() const
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:373
const FOOTPRINTS & Footprints() const
Definition board.h:421
const CONSTRAINTS & Constraints() const
Geometric constraints (#2329) owned by this board.
Definition board.h:465
BOARD_ITEM * ResolveItem(const KIID &aID, bool aAllowNullptrReturn=false) const
Definition board.cpp:1928
const DRAWINGS & Drawings() const
Definition board.h:423
double AsDegrees() const
Definition eda_angle.h:116
const KIID m_Uuid
Definition eda_item.h:531
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:108
SHAPE_POLY_SET & GetPolyShape()
SHAPE_T GetShape() const
Definition eda_shape.h:185
const VECTOR2I & GetEnd() const
Return the ending point of the graphic.
Definition eda_shape.h:240
const VECTOR2I & GetStart() const
Return the starting point of the graphic.
Definition eda_shape.h:190
Definition kiid.h:46
A geometric constraint between board items (issue #2329).
const std::vector< CONSTRAINT_MEMBER > & GetMembers() const
bool IsDriving() const
A driving constraint forces its value; a reference (non-driving) one only measures it.
PCB_CONSTRAINT_TYPE GetConstraintType() const
void SetValue(std::optional< double > aValue)
void SetDriving(bool aDriving)
Abstract dimension API.
void Update()
Update the dimension's cached text and geometry.
void SetOverrideTextEnabled(bool aOverride)
void SetOverrideText(const wxString &aValue)
bool GetOverrideTextEnabled() const
VECTOR2I GetCenter() const override
This defaults to the center of the bounding box if not overridden.
Definition pcb_shape.h:78
bool HitTest(const VECTOR2I &aPosition, int aAccuracy=0) const override
Test if aPosition is inside or on the boundary of this item.
Definition pcb_shape.h:153
Definition seg.h:38
VECTOR2I A
Definition seg.h:45
VECTOR2I::extended_type ecoord
Definition seg.h:40
VECTOR2I B
Definition seg.h:46
int Distance(const SEG &aSeg) const
Compute minimum Euclidean distance to segment aSeg.
Definition seg.cpp:698
EDA_ANGLE Angle(const SEG &aOther) const
Determine the smallest angle between two segments.
Definition seg.cpp:107
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
int PointCount() const
Return the number of points (vertices) in this line chain.
size_t ArcCount() const
Represent a set of closed polygons.
int HoleCount(int aOutline) const
Returns the number of holes in a given outline.
int OutlineCount() const
Return the number of outlines in the set.
const SHAPE_LINE_CHAIN & COutline(int aIndex) const
DIM_VALUE_MODE DimensionValueMode(BOARD *aBoard, const PCB_DIMENSION_BASE *aDimension)
The value mode aDimension is in, derived from state: a self driving length means Driving,...
void RemapPolygonVertexMembers(BOARD *aBoard, const KIID &aPoly, int aChangedIndex, int aDelta, const std::function< void(BOARD_ITEM *)> &aBeforeModify, const std::function< void(BOARD_ITEM *)> &aBeforeRemove)
Repoint persisted VERTEX constraint members after an outline edit of polygon aPoly inserts or removes...
std::vector< PCB_SHAPE * > CollectConstraintShapes(BOARD *aBoard)
Every PCB_SHAPE on the board (drawings plus footprint graphics) – the candidates constraints can refe...
std::vector< AUTO_CONSTRAINT > SelectShapeAutoConstraints(BOARD *aBoard, const PCB_SHAPE *aShape, BOARD_ITEM *aParent, bool aAxisConstraint)
Choose the constraints a freshly drawn shape should get from what its features landed on.
std::vector< ENDPOINT_BINDING > SelectEndpointBindings(BOARD *aBoard, const KIID &aItem, const VECTOR2I &aStart, const std::optional< VECTOR2I > &aEnd, double aMaxDist)
Choose the coincident bindings a freshly drawn item endpoints should take so it tracks the geometry i...
double InitialConstraintValue(PCB_CONSTRAINT_TYPE aType, double aMeasured, const std::map< PCB_CONSTRAINT_TYPE, double > &aRemembered)
Value a freshly authored constraint dialog should open with.
EDA_ANGLE MeasureCornerAngle(const SEG &aA, const SEG &aB)
The corner angle between two segments, in the closed range [0, 180] degrees.
bool DimensionHasValueMode(const PCB_DIMENSION_BASE *aDimension)
True for dimension types with a measured value aligned orthogonal or radial offering the Driven Drivi...
PCB_CONSTRAINT * FindDimensionLengthConstraint(BOARD *aBoard, const PCB_DIMENSION_BASE *aDimension)
Self FIXED_LENGTH constraint whose members are exactly aDimension START and END or nullptr the drivin...
std::vector< CONSTRAINT_ANCHOR_POINT > ConstraintItemAnchors(const BOARD_ITEM *aItem)
The constraint anchors an item exposes.
std::optional< KIID > NearestConstrainedShape(const std::vector< PCB_SHAPE * > &aCandidates, const VECTOR2I &aPos, int aMaxDist)
The candidate shape whose outline aPos hits within aMaxDist, or std::nullopt.
std::optional< CONSTRAINT_ANCHOR_POINT > ConstraintShapeVertex(const PCB_SHAPE *aShape, int aIndex)
VERTEX anchor at ordinal aIndex of a rectangle or eligible polygon or std::nullopt if the shape has n...
wxString ConstraintSelectionHint(PCB_CONSTRAINT_TYPE aType)
A sentence naming what aType needs selected, for the moment a selection does not fit it and the tool ...
std::unique_ptr< PCB_CONSTRAINT > BuildConstraintFromItems(BOARD_ITEM *aParent, PCB_CONSTRAINT_TYPE aType, const std::vector< BOARD_ITEM * > &aItems)
Build a constraint of aType from a set of selected board items, or nullptr if the selection does not ...
std::vector< CONSTRAINT_ANCHOR_POINT > ConstraintShapeAnchors(const PCB_SHAPE *aShape)
Enumerate a shape constraint anchors with positions segment and arc endpoints arc centre circle centr...
std::optional< KIID > NearestOutlineShape(BOARD *aBoard, const VECTOR2I &aPos, double aMaxDist, bool aAllowCircle)
The shape whose outline is nearest aPos within aMaxDist.
std::optional< KIID > SelectRadialDimensionTarget(BOARD *aBoard, const KIID &aDimension, const VECTOR2I &aCenter, const VECTOR2I &aRim, double aMaxDist)
Single circle or arc a radial dimension binds to or std::nullopt.
std::vector< BOARD_ITEM * > CollectConstrainableItems(BOARD *aBoard)
Every constrainable item on the board – shapes plus dimensions – for board-wide anchor picking.
std::optional< VECTOR2I > ConstraintAnchorPosition(BOARD *aBoard, const CONSTRAINT_MEMBER &aMember)
Current location of a constraint member's anchor (its shape's START/END/CENTER, or a dimension's feat...
std::optional< CONSTRAINT_MEMBER > NearestConstraintAnchor(BOARD *aBoard, const VECTOR2I &aPos, double aMaxDist, const std::vector< CONSTRAINT_MEMBER > &aExclude)
Find the constrainable-item anchor (a shape's segment/arc endpoint or centre, or a dimension's featur...
bool DimensionCanDrive(BOARD *aBoard, const PCB_DIMENSION_BASE *aDimension)
True when Driving mode may be offered for aDimension needs both endpoints bound via DimensionEndpoint...
bool ConstraintPolygonIsModelable(const PCB_SHAPE *aShape)
True when polygon has one non empty hole free arc free outline making it solver eligible Shared by ad...
BOARD_ITEM * ResolveConstrainableItem(BOARD *aBoard, const KIID &aId)
The board item a constraint may reference: a PCB_SHAPE or a dimension, or nullptr for anything else (...
bool ConstraintIsDuplicateOnBoard(BOARD *aBoard, const PCB_CONSTRAINT *aConstraint)
True if the board or one of its footprints already carries an equal constraint.
std::optional< CONSTRAINT_MEMBER > NearestAnchorAmong(const std::vector< PCB_SHAPE * > &aShapes, const VECTOR2I &aPos, double aMaxDist)
The {shape, anchor} member nearest aPos within aMaxDist among aShapes, or std::nullopt.
bool DimensionEndpointsBound(BOARD *aBoard, const PCB_DIMENSION_BASE *aDimension)
True when both of aDimension measured endpoints are bound to anchors that still resolve a coincident ...
PCB_CONSTRAINT * SetDimensionValueMode(BOARD *aBoard, PCB_DIMENSION_BASE *aDimension, DIM_VALUE_MODE aMode, std::optional< int > aDrivingLengthIU, const std::optional< wxString > &aOverrideText, const std::function< void(BOARD_ITEM *)> &aBeforeModify, const std::function< void(BOARD_ITEM *)> &aStageAdd, const std::function< void(BOARD_ITEM *)> &aBeforeRemove)
Apply a value mode transition to aDimension Driving creates or updates the driving length with aDrivi...
DIM_VALUE_MODE
Mode a value bearing dimension value is in Driven mirrors measured geometry Driving forces geometry t...
#define _(s)
SHAPE_T
Definition eda_shape.h:44
@ ELLIPSE
Definition eda_shape.h:52
@ SEGMENT
Definition eda_shape.h:46
@ RECTANGLE
Use RECTANGLE instead of RECT to avoid collision in a Windows header.
Definition eda_shape.h:47
@ ELLIPSE_ARC
Definition eda_shape.h:53
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:96
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:400
bool ConstraintsAreDuplicate(const PCB_CONSTRAINT &aA, const PCB_CONSTRAINT &aB)
True if two constraints express the same relation, meaning the same type and the same members compare...
wxString ConstraintTypeLabel(PCB_CONSTRAINT_TYPE aType)
Human-readable name of a constraint type (e.g. "Parallel"), for menus and lists.
CONSTRAINT_ANCHOR
Which feature of a referenced board item participates in a constraint.
@ VERTEX
An indexed rectangle corner or polygon outline vertex; pairs with CONSTRAINT_MEMBER::m_index.
@ WHOLE
The item as a whole (a segment as a line, a circle).
@ START
First endpoint of a segment or arc.
@ END
Second endpoint of a segment or arc.
@ CENTER
Center of an arc or circle.
PCB_CONSTRAINT_TYPE
The geometric relationship a PCB_CONSTRAINT enforces between its members.
@ CONCENTRIC
Two arcs/circles share a center.
@ SYMMETRIC
Two points are mirror images about an axis.
@ FIXED_POSITION
A point is locked at its current location.
@ VERTICAL
A segment (or two points) is vertical.
@ TANGENT
A line and a curve, or two curves, touch tangentially.
@ COINCIDENT
Two points are made to coincide.
@ PERPENDICULAR
Two segments are perpendicular.
@ FIXED_RADIUS
An arc/circle has a driving radius value.
@ HORIZONTAL
A segment (or two points) is horizontal.
@ EQUAL_RADIUS
Two arcs/circles have equal radius.
@ MIDPOINT
A point is the midpoint of a segment.
@ POINT_ON_LINE
A point lies on a segment's supporting line.
@ FIXED_LENGTH
A segment has a driving length value.
@ ANGULAR_DIMENSION
An angle between members (driving or reference).
@ COLLINEAR
Two segments lie on the same line.
@ ARC_ANGLE
An arc has a driving or reference swept-angle value.
@ PARALLEL
Two segments are parallel.
@ EQUAL_LENGTH
Two segments have equal length.
std::deque< PCB_CONSTRAINT * > CONSTRAINTS
One constraint chosen for a freshly drawn shape.
std::unique_ptr< PCB_CONSTRAINT > constraint
A selectable feature of a shape (a segment endpoint, arc centre, ...) and its location.
One participant in a constraint: a referenced board item plus the feature of that item that participa...
KIID m_item
Referenced board item, usually a PCB_SHAPE.
CONSTRAINT_ANCHOR m_anchor
Which feature of that item participates.
int m_index
Vertex ordinal; only meaningful for the VERTEX anchor.
One of a drawn item feature points bound coincident to an object anchor by draw time auto constrain s...
std::vector< double > vA
VECTOR2I center
wxString result
Test unit parsing edge cases and error handling.
#define M_PI
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
Definition typeinfo.h:81
@ PCB_DIM_ORTHOGONAL_T
class PCB_DIM_ORTHOGONAL, a linear dimension constrained to x/y
Definition typeinfo.h:99
@ PCB_DIM_ALIGNED_T
class PCB_DIM_ALIGNED, a linear dimension (graphic item)
Definition typeinfo.h:95
@ PCB_DIM_RADIAL_T
class PCB_DIM_RADIAL, a radius or diameter dimension
Definition typeinfo.h:98
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:683
VECTOR2< double > VECTOR2D
Definition vector2d.h:682