KiCad PCB EDA Suite
Loading...
Searching...
No Matches
item_modification_routine.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, you may find one here:
18 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
19 * or you may search the http://www.gnu.org website for the version 2 license,
20 * or you may write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 */
23
25
27#include <geometry/circle.h>
28#include <geometry/oval.h>
29#include <geometry/roundrect.h>
30#include <geometry/shape_rect.h>
33#include <math.h>
34
35#include <pad.h>
36#include <pcb_track.h>
38#include <confirm.h>
39#include <board.h>
40#include <wx/log.h>
41
42namespace
43{
44
48bool SegmentsShareEndpoint( const SEG& aSegA, const SEG& aSegB )
49{
50 return ( aSegA.A == aSegB.A || aSegA.A == aSegB.B || aSegA.B == aSegB.A || aSegA.B == aSegB.B );
51}
52
53
54std::pair<VECTOR2I*, VECTOR2I*> GetSharedEndpoints( SEG& aSegA, SEG& aSegB )
55{
56 std::pair<VECTOR2I*, VECTOR2I*> result = { nullptr, nullptr };
57
58 if( aSegA.A == aSegB.A )
59 {
60 result = { &aSegA.A, &aSegB.A };
61 }
62 else if( aSegA.A == aSegB.B )
63 {
64 result = { &aSegA.A, &aSegB.B };
65 }
66 else if( aSegA.B == aSegB.A )
67 {
68 result = { &aSegA.B, &aSegB.A };
69 }
70 else if( aSegA.B == aSegB.B )
71 {
72 result = { &aSegA.B, &aSegB.B };
73 }
74
75 return result;
76}
77
78} // namespace
79
80
82 const std::optional<SEG>& aSeg )
83{
84 wxASSERT_MSG( aLine.GetShape() == SHAPE_T::SEGMENT, "Can only modify segments" );
85
86 const bool removed = !aSeg.has_value() || aSeg->Length() == 0;
87
88 if( !removed )
89 {
90 // Mark modified, then change it
92 aLine.SetStart( aSeg->A );
93 aLine.SetEnd( aSeg->B );
94 }
95 else
96 {
97 // The line has become zero length - delete it
98 GetHandler().DeleteItem( aLine );
99 }
100
101 return removed;
102}
103
104
106{
107 return _( "Fillet Lines" );
108}
109
110
111std::optional<wxString> LINE_FILLET_ROUTINE::GetStatusMessage( int aSegmentCount ) const
112{
113 if( GetSuccesses() == 0 )
114 return _( "Unable to fillet the selected lines." );
115 else if( GetFailures() > 0 || (int) GetSuccesses() < aSegmentCount - 1 )
116 return _( "Some of the lines could not be filleted." );
117
118 return std::nullopt;
119}
120
121
123{
124 if( aLineA.GetLength() == 0.0 || aLineB.GetLength() == 0.0 )
125 return;
126
127 SEG seg_a( aLineA.GetStart(), aLineA.GetEnd() );
128 SEG seg_b( aLineB.GetStart(), aLineB.GetEnd() );
129
130 auto [a_pt, b_pt] = GetSharedEndpoints( seg_a, seg_b );
131
132 if( !a_pt || !b_pt )
133 {
134 // The lines do not share an endpoint, so we can't fillet them
135 return;
136 }
137
138 if( seg_a.Angle( seg_b ).IsHorizontal() )
139 return;
140
141 SHAPE_ARC sArc( seg_a, seg_b, m_filletRadiusIU );
142 VECTOR2I t1newPoint, t2newPoint;
143
144 auto setIfPointOnSeg =
145 []( VECTOR2I& aPointToSet, SEG aSegment, VECTOR2I aVecToTest )
146 {
147 VECTOR2I segToVec = aSegment.NearestPoint( aVecToTest ) - aVecToTest;
148
149 // Find out if we are on the segment (minimum precision)
151 {
152 aPointToSet.x = aVecToTest.x;
153 aPointToSet.y = aVecToTest.y;
154 return true;
155 }
156
157 return false;
158 };
159
160 //Do not draw a fillet if the end points of the arc are not within the track segments
161 if( !setIfPointOnSeg( t1newPoint, seg_a, sArc.GetP0() )
162 && !setIfPointOnSeg( t2newPoint, seg_b, sArc.GetP0() ) )
163 {
164 AddFailure();
165 return;
166 }
167
168 if( !setIfPointOnSeg( t1newPoint, seg_a, sArc.GetP1() )
169 && !setIfPointOnSeg( t2newPoint, seg_b, sArc.GetP1() ) )
170 {
171 AddFailure();
172 return;
173 }
174
175 auto tArc = std::make_unique<PCB_SHAPE>( GetBoard(), SHAPE_T::ARC );
176
177 tArc->SetArcGeometry( sArc.GetP0(), sArc.GetArcMid(), sArc.GetP1() );
178
179 // Copy properties from one of the source lines
180 tArc->SetWidth( aLineA.GetWidth() );
181 tArc->SetLayer( aLineA.GetLayer() );
182 tArc->SetLocked( aLineA.IsLocked() );
183
184 CHANGE_HANDLER& handler = GetHandler();
185
186 handler.AddNewItem( std::move( tArc ) );
187
188 *a_pt = t1newPoint;
189 *b_pt = t2newPoint;
190
191 ModifyLineOrDeleteIfZeroLength( aLineA, seg_a );
192 ModifyLineOrDeleteIfZeroLength( aLineB, seg_b );
193
194 AddSuccess();
195}
196
198{
199 return _( "Chamfer Lines" );
200}
201
202
203std::optional<wxString> LINE_CHAMFER_ROUTINE::GetStatusMessage( int aSegmentCount ) const
204{
205 if( GetSuccesses() == 0 )
206 return _( "Unable to chamfer the selected lines." );
207 else if( GetFailures() > 0 || (int) GetSuccesses() < aSegmentCount - 1 )
208 return _( "Some of the lines could not be chamfered." );
209
210 return std::nullopt;
211}
212
213
215{
216 if( aLineA.GetLength() == 0.0 || aLineB.GetLength() == 0.0 )
217 return;
218
219 SEG seg_a( aLineA.GetStart(), aLineA.GetEnd() );
220 SEG seg_b( aLineB.GetStart(), aLineB.GetEnd() );
221
222 // If the segments share an endpoint, we won't try to chamfer them
223 // (we could extend to the intersection point, but this gets complicated
224 // and inconsistent when you select more than two lines)
225 if( !SegmentsShareEndpoint( seg_a, seg_b ) )
226 {
227 // not an error, lots of lines in a 2+ line selection will not intersect
228 return;
229 }
230
231 std::optional<CHAMFER_RESULT> chamfer_result =
232 ComputeChamferPoints( seg_a, seg_b, m_chamferParams );
233
234 if( !chamfer_result )
235 {
236 AddFailure();
237 return;
238 }
239
240 auto tSegment = std::make_unique<PCB_SHAPE>( GetBoard(), SHAPE_T::SEGMENT );
241
242 tSegment->SetStart( chamfer_result->m_chamfer.A );
243 tSegment->SetEnd( chamfer_result->m_chamfer.B );
244
245 // Copy properties from one of the source lines
246 tSegment->SetWidth( aLineA.GetWidth() );
247 tSegment->SetLayer( aLineA.GetLayer() );
248 tSegment->SetLocked( aLineA.IsLocked() );
249
250 CHANGE_HANDLER& handler = GetHandler();
251
252 handler.AddNewItem( std::move( tSegment ) );
253
254 ModifyLineOrDeleteIfZeroLength( aLineA, chamfer_result->m_updated_seg_a );
255 ModifyLineOrDeleteIfZeroLength( aLineB, chamfer_result->m_updated_seg_b );
256
257 AddSuccess();
258}
259
260
262{
263 return _( "Dogbone Corners" );
264}
265
266
267std::optional<wxString> DOGBONE_CORNER_ROUTINE::GetStatusMessage( int aSegmentCount ) const
268{
269 wxString msg;
270
271 if( GetSuccesses() == 0 )
272 msg += _( "Unable to add dogbone corners to the selected lines." );
273 else if( GetFailures() > 0 || (int) GetSuccesses() < aSegmentCount - 1 )
274 msg += _( "Some of the lines could not have dogbone corners added." );
275
277 {
278 if( !msg.empty() )
279 msg += " ";
280
281 msg += _( "Some of the dogbone corners are too narrow to fit a "
282 "cutter of the specified radius." );
283
284 if( !m_params.AddSlots )
285 msg += _( " Consider enabling the 'Add Slots' option." );
286 else
287 msg += _( " Slots were added." );
288 }
289
290 if( msg.empty() )
291 return std::nullopt;
292
293 return msg;
294}
295
296
298{
299 if( aLineA.GetLength() == 0.0 || aLineB.GetLength() == 0.0 )
300 {
301 wxLogTrace( "DOGBONE", "Skip: zero-length line(s) (A len=%f, B len=%f)",
302 aLineA.GetLength(), aLineB.GetLength() );
303 return;
304 }
305
306 if( !EnsureBoardOutline() )
307 {
308 wxLogTrace( "DOGBONE", "Skip: board outline unavailable" );
309 return;
310 }
311
312 SEG seg_a( aLineA.GetStart(), aLineA.GetEnd() );
313 SEG seg_b( aLineB.GetStart(), aLineB.GetEnd() );
314
315 auto [a_pt, b_pt] = GetSharedEndpoints( seg_a, seg_b );
316
317 if( !a_pt || !b_pt )
318 {
319 wxLogTrace( "DOGBONE", "Skip: segments do not share endpoint" );
320 return;
321 }
322
323 // Cannot handle parallel lines
324 if( seg_a.Angle( seg_b ).IsHorizontal() )
325 {
326 wxLogTrace( "DOGBONE", "Skip: parallel segments" );
327 AddFailure();
328 return;
329 }
330
331 // Determine if this corner points into the board outline: we construct the bisector
332 // vector (as done in ComputeDogbone) and test a point a small distance in the opposite
333 // direction (i.e. exterior). If that opposite point is INSIDE the board outline, the
334 // corner indentation points inward (needs dogbone). If the opposite test point is
335 // outside, skip.
336
337 const VECTOR2I corner = *a_pt; // shared endpoint
338 // Build vectors from corner toward other ends
339 const VECTOR2I vecA = ( seg_a.A == corner ? seg_a.B - corner : seg_a.A - corner );
340 const VECTOR2I vecB = ( seg_b.A == corner ? seg_b.B - corner : seg_b.A - corner );
341 // Normalize (resize) to common length to form bisector reliably
342 int maxLen = std::max( vecA.EuclideanNorm(), vecB.EuclideanNorm() );
343 if( maxLen == 0 )
344 {
345 wxLogTrace( "DOGBONE", "Skip: degenerate corner (maxLen==0)" );
346 return;
347 }
348 VECTOR2I vecAn = vecA.Resize( maxLen );
349 VECTOR2I vecBn = vecB.Resize( maxLen );
350 VECTOR2I bisectorOutward = vecAn + vecBn; // direction inside angle region
351
352 // If vectors are nearly opposite, no meaningful dogbone
353 if( bisectorOutward.EuclideanNorm() == 0 )
354 {
355 wxLogTrace( "DOGBONE", "Skip: bisector zero (vectors opposite)" );
356 return;
357 }
358
359 // Opposite direction of bisector (points "outside" if angle is convex, or further into
360 // material if reflex). We'll sample a point a small distance along -bisectorOutward.
361 VECTOR2I sampleDir = ( -bisectorOutward ).Resize( std::min( 1000, m_params.DogboneRadiusIU ) );
362 VECTOR2I samplePoint = corner + sampleDir; // test point opposite bisector
363
364 bool oppositeInside = m_boardOutline.Contains( samplePoint );
365
366 if( !oppositeInside )
367 {
368 wxLogTrace( "DOGBONE", "Skip: corner not inward (sample outside polygon)" );
369 return;
370 }
371
372 std::optional<DOGBONE_RESULT> dogbone_result =
373 ComputeDogbone( seg_a, seg_b, m_params.DogboneRadiusIU, m_params.AddSlots );
374
375 if( !dogbone_result )
376 {
377 wxLogTrace( "DOGBONE", "Skip: ComputeDogbone failed (radius=%d slots=%d)",
378 m_params.DogboneRadiusIU, (int) m_params.AddSlots );
379 AddFailure();
380 return;
381 }
382
383 if( dogbone_result->m_small_arc_mouth )
384 {
385 wxLogTrace( "DOGBONE", "Info: small arc mouth (slots %s)",
386 m_params.AddSlots ? "enabled" : "disabled" );
387 // The arc is too small to fit the radius
388 m_haveNarrowMouths = true;
389 }
390
391 CHANGE_HANDLER& handler = GetHandler();
392
393 auto tArc = std::make_unique<PCB_SHAPE>( GetBoard(), SHAPE_T::ARC );
394
395 const auto copyProps = [&]( PCB_SHAPE& aShape )
396 {
397 aShape.SetWidth( aLineA.GetWidth() );
398 aShape.SetLayer( aLineA.GetLayer() );
399 aShape.SetLocked( aLineA.IsLocked() );
400 };
401
402 const auto addSegment = [&]( const SEG& aSeg )
403 {
404 if( aSeg.Length() == 0 )
405 return;
406
407 auto tSegment = std::make_unique<PCB_SHAPE>( GetBoard(), SHAPE_T::SEGMENT );
408 tSegment->SetStart( aSeg.A );
409 tSegment->SetEnd( aSeg.B );
410
411 copyProps( *tSegment );
412 handler.AddNewItem( std::move( tSegment ) );
413 };
414
415 tArc->SetArcGeometry( dogbone_result->m_arc.GetP0(), dogbone_result->m_arc.GetArcMid(),
416 dogbone_result->m_arc.GetP1() );
417
418 // Copy properties from one of the source lines
419 copyProps( *tArc );
420
421 addSegment( SEG{ dogbone_result->m_arc.GetP0(), dogbone_result->m_updated_seg_a->B } );
422 addSegment( SEG{ dogbone_result->m_arc.GetP1(), dogbone_result->m_updated_seg_b->B } );
423
424 handler.AddNewItem( std::move( tArc ) );
425
426 ModifyLineOrDeleteIfZeroLength( aLineA, dogbone_result->m_updated_seg_a );
427 ModifyLineOrDeleteIfZeroLength( aLineB, dogbone_result->m_updated_seg_b );
428
429 wxLogTrace( "DOGBONE", "Success: dogbone added at (%d,%d)", corner.x, corner.y );
430 AddSuccess();
431}
432
434{
436 return !m_boardOutline.IsEmpty();
437
439
440 BOARD* board = dynamic_cast<BOARD*>( GetBoard() );
441 if( !board )
442 {
443 wxLogTrace( "DOGBONE", "EnsureBoardOutline: board cast failed" );
444 return false;
445 }
446
447 // Build outlines; ignore errors and arcs for this classification
449 {
450 wxLogTrace( "DOGBONE", "EnsureBoardOutline: GetBoardPolygonOutlines failed" );
451 return false;
452 }
453
454 bool ok = !m_boardOutline.IsEmpty();
455 wxLogTrace( "DOGBONE", "EnsureBoardOutline: outline %s", ok ? "ready" : "empty" );
456 return ok;
457}
458
459
461{
462 return _( "Extend Lines to Meet" );
463}
464
465
466std::optional<wxString> LINE_EXTENSION_ROUTINE::GetStatusMessage( int aSegmentCount ) const
467{
468 if( GetSuccesses() == 0 )
469 return _( "Unable to extend the selected lines to meet." );
470 else if( GetFailures() > 0 || (int) GetSuccesses() < aSegmentCount - 1 )
471 return _( "Some of the lines could not be extended to meet." );
472
473 return std::nullopt;
474}
475
476
478{
479 if( aLineA.GetLength() == 0.0 || aLineB.GetLength() == 0.0 )
480 return;
481
482 SEG seg_a( aLineA.GetStart(), aLineA.GetEnd() );
483 SEG seg_b( aLineB.GetStart(), aLineB.GetEnd() );
484
485 if( seg_a.Intersects( seg_b ) )
486 {
487 // already intersecting, nothing to do
488 return;
489 }
490
491 OPT_VECTOR2I intersection = seg_a.IntersectLines( seg_b );
492
493 if( !intersection )
494 {
495 // This might be an error, but it's also possible that the lines are
496 // parallel and don't intersect. We'll just ignore this case.
497 return;
498 }
499
500 CHANGE_HANDLER& handler = GetHandler();
501
502 const auto line_extender = [&]( const SEG& aSeg, PCB_SHAPE& aLine )
503 {
504 // If the intersection point is not already n the line, we'll extend to it
505 if( !aSeg.Contains( *intersection ) )
506 {
507 const int dist_start = ( *intersection - aSeg.A ).EuclideanNorm();
508 const int dist_end = ( *intersection - aSeg.B ).EuclideanNorm();
509
510 const VECTOR2I& furthest_pt = ( dist_start < dist_end ) ? aSeg.B : aSeg.A;
511 // Note, the drawing tool has COORDS_PADDING of 20mm, but we need a larger buffer
512 // or we are not able to select the generated segments
513 unsigned int edge_padding = static_cast<unsigned>( pcbIUScale.mmToIU( 200 ) );
514 VECTOR2I new_end = GetClampedCoords( *intersection, edge_padding );
515
516 handler.MarkItemModified( aLine );
517 aLine.SetStart( furthest_pt );
518 aLine.SetEnd( new_end );
519 }
520 };
521
522 line_extender( seg_a, aLineA );
523 line_extender( seg_b, aLineB );
524
525 AddSuccess();
526}
527
528
530{
531 std::unique_ptr<SHAPE_POLY_SET> poly;
532
533 switch( aPcbShape.GetShape() )
534 {
535 case SHAPE_T::POLY:
536 {
537 poly = std::make_unique<SHAPE_POLY_SET>( aPcbShape.GetPolyShape() );
538 // Arcs cannot be handled by polygon boolean transforms
539 poly->ClearArcs();
540 break;
541 }
543 {
544 poly = std::make_unique<SHAPE_POLY_SET>();
545
546 const std::vector<VECTOR2I> rect_pts = aPcbShape.GetRectCorners();
547
548 poly->NewOutline();
549
550 for( const VECTOR2I& pt : rect_pts )
551 {
552 poly->Append( pt );
553 }
554 break;
555 }
556 case SHAPE_T::CIRCLE:
557 {
558 poly = std::make_unique<SHAPE_POLY_SET>();
559 const SHAPE_ARC arc{ aPcbShape.GetCenter(), aPcbShape.GetCenter() + VECTOR2I{ aPcbShape.GetRadius(), 0 },
560 FULL_CIRCLE, 0 };
561
562 poly->NewOutline();
563 poly->Append( arc );
564 break;
565 }
566 default:
567 {
568 break;
569 }
570 }
571
572 if( !poly )
573 {
574 // Not a polygon or rectangle, nothing to do
575 return;
576 }
577
578 if( m_firstPolygon )
579 {
580 m_width = aPcbShape.GetWidth();
581 m_layer = aPcbShape.GetLayer();
582 m_fillMode = aPcbShape.GetFillMode();
583 m_workingPolygons = std::move( *poly );
584 m_firstPolygon = false;
585
586 // Boolean ops work, but assert on arcs
587 m_workingPolygons.ClearArcs();
588
589 GetHandler().DeleteItem( aPcbShape );
590 }
591 else
592 {
593 if( ProcessSubsequentPolygon( *poly ) )
594 {
595 // If we could process the polygon, delete the source
596 GetHandler().DeleteItem( aPcbShape );
597 AddSuccess();
598 }
599 else
600 {
601 AddFailure();
602 }
603 }
604}
605
606
608{
609 if( m_workingPolygons.OutlineCount() == 0 || m_firstPolygon )
610 {
611 // Nothing to do (no polygons handled or nothing left?)
612 return;
613 }
614
615 CHANGE_HANDLER& handler = GetHandler();
616
617 // If we have disjoint polygons, we'll fix that now and create
618 // new PCB_SHAPEs for each outline
619 for( int i = 0; i < m_workingPolygons.OutlineCount(); ++i )
620 {
621 // If we handled any polygons to get any outline,
622 // there must be a layer set by now.
623 wxASSERT( m_layer >= 0 );
624
625 std::unique_ptr<PCB_SHAPE> new_poly_shape =
626 std::make_unique<PCB_SHAPE>( GetBoard(), SHAPE_T::POLY );
627
628 SHAPE_POLY_SET poly_set = m_workingPolygons.UnitSet( i );
629
630 new_poly_shape->SetPolyShape( poly_set );
631
632 // Copy properties from the source polygon
633 new_poly_shape->SetWidth( m_width );
634 new_poly_shape->SetLayer( m_layer );
635 new_poly_shape->SetFillMode( m_fillMode );
636
637 handler.AddNewItem( std::move( new_poly_shape ) );
638 }
639}
640
641
643{
644 return _( "Merge Polygons" );
645}
646
647
648std::optional<wxString> POLYGON_MERGE_ROUTINE::GetStatusMessage() const
649{
650 if( GetSuccesses() == 0 )
651 return _( "Unable to merge the selected polygons." );
652 else if( GetFailures() > 0 )
653 return _( "Some of the polygons could not be merged." );
654
655 return std::nullopt;
656}
657
658
660{
661 SHAPE_POLY_SET no_arcs_poly = aPolygon;
662 no_arcs_poly.ClearArcs();
663
664 GetWorkingPolygons().BooleanAdd( no_arcs_poly );
665 return true;
666}
667
668
670{
671 return _( "Subtract Polygons" );
672}
673
674
675std::optional<wxString> POLYGON_SUBTRACT_ROUTINE::GetStatusMessage() const
676{
677 if( GetSuccesses() == 0 )
678 return _( "Unable to subtract the selected polygons." );
679 else if( GetFailures() > 0 )
680 return _( "Some of the polygons could not be subtracted." );
681
682 return std::nullopt;
683}
684
685
687{
688 SHAPE_POLY_SET& working_polygons = GetWorkingPolygons();
689 SHAPE_POLY_SET working_copy = working_polygons;
690
691 SHAPE_POLY_SET no_arcs_poly = aPolygon;
692 no_arcs_poly.ClearArcs();
693
694 working_copy.BooleanSubtract( no_arcs_poly );
695
696 working_polygons = std::move( working_copy );
697 return true;
698}
699
700
702{
703 return _( "Intersect Polygons" );
704}
705
706
707std::optional<wxString> POLYGON_INTERSECT_ROUTINE::GetStatusMessage() const
708{
709 if( GetSuccesses() == 0 )
710 return _( "Unable to intersect the selected polygons." );
711 else if( GetFailures() > 0 )
712 return _( "Some of the polygons could not be intersected." );
713
714 return std::nullopt;
715}
716
717
719{
720 SHAPE_POLY_SET& working_polygons = GetWorkingPolygons();
721 SHAPE_POLY_SET working_copy = working_polygons;
722
723 SHAPE_POLY_SET no_arcs_poly = aPolygon;
724 no_arcs_poly.ClearArcs();
725
726 working_copy.BooleanIntersection( no_arcs_poly );
727
728 // Is there anything left?
729 if( working_copy.OutlineCount() == 0 )
730 {
731 // There was no intersection. Rather than deleting the working polygon, we'll skip
732 // and report a failure.
733 return false;
734 }
735
736 working_polygons = std::move( working_copy );
737 return true;
738}
739
740
742{
743 return _( "Outset Items" );
744}
745
746std::optional<wxString> OUTSET_ROUTINE::GetStatusMessage() const
747{
748 if( GetSuccesses() == 0 )
749 return _( "Unable to outset the selected items." );
750 else if( GetFailures() > 0 )
751 return _( "Some of the items could not be outset." );
752
753 return std::nullopt;
754}
755
756
757static SHAPE_RECT GetRectRoundedToGridOutwards( const SHAPE_RECT& aRect, int aGridSize )
758{
759 const VECTOR2I newPos = KIGEOM::RoundNW( aRect.GetPosition(), aGridSize );
760 const VECTOR2I newOpposite =
761 KIGEOM::RoundSE( aRect.GetPosition() + aRect.GetSize(), aGridSize );
762 return SHAPE_RECT( newPos, newOpposite );
763}
764
765
767{
768 /*
769 * This attempts to do exact outsetting, rather than punting to Clipper.
770 * So it can't do all shapes, but it can do the most obvious ones, which are probably
771 * the ones you want to outset anyway, most usually when making a courtyard for a footprint.
772 */
773
774 PCB_LAYER_ID layer = m_params.useSourceLayers ? aItem.GetLayer() : m_params.layer;
775
776 // Not all items have a width, even if the parameters want to copy it
777 // So fall back to the given width if we can't get one.
778 int width = m_params.lineWidth;
779
780 if( m_params.useSourceWidths )
781 {
782 std::optional<int> item_width = GetBoardItemWidth( aItem );
783
784 if( item_width.has_value() )
785 width = *item_width;
786 }
787
788 CHANGE_HANDLER& handler = GetHandler();
789
790 const auto addPolygonalChain = [&]( const SHAPE_LINE_CHAIN& aChain )
791 {
792 SHAPE_POLY_SET new_poly( aChain );
793
794 std::unique_ptr<PCB_SHAPE> new_shape =
795 std::make_unique<PCB_SHAPE>( GetBoard(), SHAPE_T::POLY );
796
797 new_shape->SetPolyShape( new_poly );
798 new_shape->SetLayer( layer );
799 new_shape->SetWidth( width );
800
801 handler.AddNewItem( std::move( new_shape ) );
802 };
803
804 // Iterate the SHAPE_LINE_CHAIN in the polygon, pulling out
805 // segments and arcs to create new PCB_SHAPE primitives.
806 const auto addChain = [&]( const SHAPE_LINE_CHAIN& aChain )
807 {
808 // Prefer to add a polygonal chain if there are no arcs
809 // as this permits boolean ops
810 if( aChain.ArcCount() == 0 )
811 {
812 addPolygonalChain( aChain );
813 return;
814 }
815
816 for( size_t si = 0; si < aChain.GetSegmentCount(); ++si )
817 {
818 const SEG seg = aChain.GetSegment( si );
819
820 if( seg.Length() == 0 )
821 continue;
822
823 if( aChain.IsArcSegment( si ) )
824 continue;
825
826 std::unique_ptr<PCB_SHAPE> new_shape =
827 std::make_unique<PCB_SHAPE>( GetBoard(), SHAPE_T::SEGMENT );
828 new_shape->SetStart( seg.A );
829 new_shape->SetEnd( seg.B );
830 new_shape->SetLayer( layer );
831 new_shape->SetWidth( width );
832
833 handler.AddNewItem( std::move( new_shape ) );
834 }
835
836 for( size_t ai = 0; ai < aChain.ArcCount(); ++ai )
837 {
838 const SHAPE_ARC& arc = aChain.Arc( ai );
839
840 if( arc.GetRadius() == 0 || arc.GetP0() == arc.GetP1() )
841 continue;
842
843 std::unique_ptr<PCB_SHAPE> new_shape =
844 std::make_unique<PCB_SHAPE>( GetBoard(), SHAPE_T::ARC );
845 new_shape->SetArcGeometry( arc.GetP0(), arc.GetArcMid(), arc.GetP1() );
846 new_shape->SetLayer( layer );
847 new_shape->SetWidth( width );
848
849 handler.AddNewItem( std::move( new_shape ) );
850 }
851 };
852
853 const auto addPoly = [&]( const SHAPE_POLY_SET& aPoly )
854 {
855 for( int oi = 0; oi < aPoly.OutlineCount(); ++oi )
856 {
857 addChain( aPoly.Outline( oi ) );
858 }
859 };
860
861 const auto addRect = [&]( const SHAPE_RECT& aRect )
862 {
863 std::unique_ptr<PCB_SHAPE> new_shape =
864 std::make_unique<PCB_SHAPE>( GetBoard(), SHAPE_T::RECTANGLE );
865
866 if( !m_params.gridRounding.has_value() )
867 {
868 new_shape->SetPosition( aRect.GetPosition() );
869 new_shape->SetRectangleWidth( aRect.GetWidth() );
870 new_shape->SetRectangleHeight( aRect.GetHeight() );
871 }
872 else
873 {
874 const SHAPE_RECT grid_rect =
875 GetRectRoundedToGridOutwards( aRect, *m_params.gridRounding );
876 new_shape->SetPosition( grid_rect.GetPosition() );
877 new_shape->SetRectangleWidth( grid_rect.GetWidth() );
878 new_shape->SetRectangleHeight( grid_rect.GetHeight() );
879 }
880
881 new_shape->SetLayer( layer );
882 new_shape->SetWidth( width );
883
884 handler.AddNewItem( std::move( new_shape ) );
885 };
886
887 const auto addCircle = [&]( const CIRCLE& aCircle )
888 {
889 std::unique_ptr<PCB_SHAPE> new_shape =
890 std::make_unique<PCB_SHAPE>( GetBoard(), SHAPE_T::CIRCLE );
891 new_shape->SetCenter( aCircle.Center );
892 new_shape->SetRadius( aCircle.Radius );
893 new_shape->SetLayer( layer );
894 new_shape->SetWidth( width );
895
896 handler.AddNewItem( std::move( new_shape ) );
897 };
898
899 const auto addCircleOrRect = [&]( const CIRCLE& aCircle )
900 {
901 if( m_params.roundCorners )
902 {
903 addCircle( aCircle );
904 }
905 else
906 {
907 const VECTOR2I rVec{ aCircle.Radius, aCircle.Radius };
908 const SHAPE_RECT rect{ aCircle.Center - rVec, aCircle.Center + rVec };
909 addRect( rect );
910 }
911 };
912
913 switch( aItem.Type() )
914 {
915 case PCB_PAD_T:
916 {
917 const PAD& pad = static_cast<const PAD&>( aItem );
918
919 // TODO(JE) padstacks
920 const PAD_SHAPE pad_shape = pad.GetShape( PADSTACK::ALL_LAYERS );
921
922 switch( pad_shape )
923 {
926 case PAD_SHAPE::OVAL:
927 {
928 const VECTOR2I pad_size = pad.GetSize( PADSTACK::ALL_LAYERS );
929
930 BOX2I box{ pad.GetPosition() - pad_size / 2, pad_size };
931 box.Inflate( m_params.outsetDistance );
932
933 int radius = m_params.outsetDistance;
934 if( pad_shape == PAD_SHAPE::ROUNDRECT )
935 {
936 radius += pad.GetRoundRectCornerRadius( PADSTACK::ALL_LAYERS );
937 }
938 else if( pad_shape == PAD_SHAPE::OVAL )
939 {
940 radius += std::min( pad_size.x, pad_size.y ) / 2;
941 }
942
943 radius = m_params.roundCorners ? radius : 0;
944
945 // No point doing a SHAPE_RECT as we may need to rotate it
946 ROUNDRECT rrect( box, radius );
947 SHAPE_POLY_SET poly;
948 rrect.TransformToPolygon( poly );
949
950 poly.Rotate( pad.GetOrientation(), pad.GetPosition() );
951 addPoly( poly );
952 AddSuccess();
953 break;
954 }
956 {
957 const int radius = pad.GetSize( PADSTACK::ALL_LAYERS ).x / 2 + m_params.outsetDistance;
958 const CIRCLE circle( pad.GetPosition(), radius );
959 addCircleOrRect( circle );
960 AddSuccess();
961 break;
962 }
964 {
965 // Not handled yet, but could use a generic convex polygon outset method.
966 break;
967 }
968 default:
969 // Other pad shapes are not supported with exact outsets
970 break;
971 }
972 break;
973 }
974 case PCB_SHAPE_T:
975 {
976 const PCB_SHAPE& pcb_shape = static_cast<const PCB_SHAPE&>( aItem );
977
978 switch( pcb_shape.GetShape() )
979 {
981 {
982 BOX2I box{ pcb_shape.GetPosition(),
983 VECTOR2I{ pcb_shape.GetRectangleWidth(), pcb_shape.GetRectangleHeight() } };
984 box.Inflate( m_params.outsetDistance );
985
986 SHAPE_RECT rect( box );
987
988 if( m_params.roundCorners )
989 {
990 try
991 {
992 ROUNDRECT rrect( rect, m_params.outsetDistance );
993 SHAPE_POLY_SET poly;
994 rrect.TransformToPolygon( poly );
995 addPoly( poly );
996 }
997 catch( ... )
998 {
999 DisplayErrorMessage( nullptr, _( "Cannot create rectangle outset" ) );
1000 }
1001 }
1002 else
1003 {
1004 addRect( rect );
1005 }
1006 AddSuccess();
1007 break;
1008 }
1009 case SHAPE_T::CIRCLE:
1010 {
1011 const CIRCLE circle( pcb_shape.GetCenter(),
1012 pcb_shape.GetRadius() + m_params.outsetDistance );
1013 addCircleOrRect( circle );
1014 AddSuccess();
1015 break;
1016 }
1017 case SHAPE_T::SEGMENT:
1018 {
1019 // For now just make the whole stadium shape and let the user delete the unwanted bits
1020 const SEG seg( pcb_shape.GetStart(), pcb_shape.GetEnd() );
1021
1022 if( m_params.roundCorners )
1023 {
1024 const SHAPE_SEGMENT oval( seg, m_params.outsetDistance * 2 );
1025 addChain( KIGEOM::ConvertToChain( oval ) );
1026 }
1027 else
1028 {
1030 const VECTOR2I ext = ( seg.B - seg.A ).Resize( m_params.outsetDistance );
1031 const VECTOR2I perp = GetRotated( ext, ANGLE_90 );
1032
1033 chain.Append( seg.A - ext + perp );
1034 chain.Append( seg.A - ext - perp );
1035 chain.Append( seg.B + ext - perp );
1036 chain.Append( seg.B + ext + perp );
1037 chain.SetClosed( true );
1038 addChain( chain );
1039 }
1040
1041 AddSuccess();
1042 break;
1043 }
1044 case SHAPE_T::ARC:
1045 {
1046 // Not 100% sure what a sensible non-round outset of an arc is!
1047 // (not sure it's that important in practice)
1048
1049 // Gets rather complicated if this isn't true
1050 if( pcb_shape.GetRadius() >= m_params.outsetDistance )
1051 {
1052 // Again, include the endcaps and let the user delete the unwanted bits
1053 const SHAPE_ARC arc{ pcb_shape.GetCenter(), pcb_shape.GetStart(),
1054 pcb_shape.GetArcAngle(), 0 };
1055
1056 const VECTOR2I startNorm =
1057 VECTOR2I( arc.GetP0() - arc.GetCenter() ).Resize( m_params.outsetDistance );
1058
1059 const SHAPE_ARC inner{ arc.GetCenter(), arc.GetP0() - startNorm,
1060 arc.GetCentralAngle(), 0 };
1061 const SHAPE_ARC outer{ arc.GetCenter(), arc.GetP0() + startNorm,
1062 arc.GetCentralAngle(), 0 };
1063
1065 chain.Append( outer );
1066 // End cap at the P1 end
1067 chain.Append( SHAPE_ARC{ arc.GetP1(), outer.GetP1(), ANGLE_180 } );
1068
1069 if( inner.GetRadius() > 0 )
1070 {
1071 chain.Append( inner.Reversed() );
1072 }
1073
1074 // End cap at the P0 end back to the start
1075 chain.Append( SHAPE_ARC{ arc.GetP0(), inner.GetP0(), ANGLE_180 } );
1076 addChain( chain );
1077 AddSuccess();
1078 }
1079
1080 break;
1081 }
1082
1083 default:
1084 // Other shapes are not supported with exact outsets
1085 // (convex) POLY shouldn't be too traumatic and it would bring trapezoids for free.
1086 break;
1087 }
1088
1089 break;
1090 }
1091 default:
1092 // Other item types are not supported with exact outsets
1093 break;
1094 }
1095
1096 if( m_params.deleteSourceItems )
1097 {
1098 handler.DeleteItem( aItem );
1099 }
1100}
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:112
BOX2< VECTOR2I > BOX2I
Definition box2.h:922
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:79
virtual PCB_LAYER_ID GetLayer() const
Return the primary layer this item is on.
Definition board_item.h:232
bool IsLocked() const override
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:317
bool GetBoardPolygonOutlines(SHAPE_POLY_SET &aOutlines, OUTLINE_ERROR_HANDLER *aErrorHandler=nullptr, bool aAllowUseArcsInPolygons=false, bool aIncludeNPTHAsOutlines=false)
Extract the board outlines and build a closed polygon from lines, arcs and circle items on edge cut l...
Definition board.cpp:2657
Represent basic circle geometry with utility geometry functions.
Definition circle.h:33
SHAPE_POLY_SET m_boardOutline
Cached board outline polygons.
std::optional< wxString > GetStatusMessage(int aSegmentCount) const override
Get a status message to show when the routine is complete.
wxString GetCommitDescription() const override
void ProcessLinePair(PCB_SHAPE &aLineA, PCB_SHAPE &aLineB) override
Perform the action on the pair of lines given.
bool IsHorizontal() const
Definition eda_angle.h:142
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
EDA_ANGLE GetArcAngle() const
FILL_T GetFillMode() const
Definition eda_shape.h:142
int GetRectangleWidth() const
SHAPE_POLY_SET & GetPolyShape()
Definition eda_shape.h:337
int GetRadius() const
SHAPE_T GetShape() const
Definition eda_shape.h:168
const VECTOR2I & GetEnd() const
Return the ending point of the graphic.
Definition eda_shape.h:215
void SetStart(const VECTOR2I &aStart)
Definition eda_shape.h:177
const VECTOR2I & GetStart() const
Return the starting point of the graphic.
Definition eda_shape.h:173
std::vector< VECTOR2I > GetRectCorners() const
void SetEnd(const VECTOR2I &aEnd)
Definition eda_shape.h:219
double GetLength() const
int GetRectangleHeight() const
virtual void MarkItemModified(BOARD_ITEM &aItem)=0
Report that the tool has modified an item on the board.
virtual void DeleteItem(BOARD_ITEM &aItem)=0
Report that the tool has deleted an item on the board.
virtual void AddNewItem(std::unique_ptr< BOARD_ITEM > aItem)=0
Report that the tools wants to add a new item to the board.
void AddFailure()
Mark that one of the actions failed.
void AddSuccess()
Mark that one of the actions succeeded.
bool ModifyLineOrDeleteIfZeroLength(PCB_SHAPE &aItem, const std::optional< SEG > &aSeg)
Helper function useful for multiple tools: modify a line or delete it if it has zero length.
BOARD_ITEM * GetBoard() const
The BOARD used when creating new shapes.
CHANGE_HANDLER & GetHandler()
Access the handler for making changes to the board.
std::optional< wxString > GetStatusMessage(int aSegmentCount) const override
Get a status message to show when the routine is complete.
wxString GetCommitDescription() const override
void ProcessLinePair(PCB_SHAPE &aLineA, PCB_SHAPE &aLineB) override
Perform the action on the pair of lines given.
const CHAMFER_PARAMS m_chamferParams
wxString GetCommitDescription() const override
std::optional< wxString > GetStatusMessage(int aSegmentCount) const override
Get a status message to show when the routine is complete.
void ProcessLinePair(PCB_SHAPE &aLineA, PCB_SHAPE &aLineB) override
Perform the action on the pair of lines given.
std::optional< wxString > GetStatusMessage(int aSegmentCount) const override
Get a status message to show when the routine is complete.
wxString GetCommitDescription() const override
void ProcessLinePair(PCB_SHAPE &aLineA, PCB_SHAPE &aLineB) override
Perform the action on the pair of lines given.
void ProcessItem(BOARD_ITEM &aItem)
wxString GetCommitDescription() const override
std::optional< wxString > GetStatusMessage() const
static constexpr PCB_LAYER_ID ALL_LAYERS
! Temporary layer identifier to identify code that is not padstack-aware
Definition padstack.h:145
Definition pad.h:54
VECTOR2I GetCenter() const override
This defaults to the center of the bounding box if not overridden.
Definition pcb_shape.h:81
int GetWidth() const override
VECTOR2I GetPosition() const override
Definition pcb_shape.h:79
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
Definition pcb_shape.h:71
SHAPE_POLY_SET m_workingPolygons
This can be disjoint, which will be fixed at the end.
void Finalize()
Clear up any outstanding work.
void ProcessShape(PCB_SHAPE &aPcbShape)
virtual bool ProcessSubsequentPolygon(const SHAPE_POLY_SET &aPolygon)=0
std::optional< wxString > GetStatusMessage() const override
Get a status message to show when the routine is complete.
wxString GetCommitDescription() const override
bool ProcessSubsequentPolygon(const SHAPE_POLY_SET &aPolygon) override
bool ProcessSubsequentPolygon(const SHAPE_POLY_SET &aPolygon) override
wxString GetCommitDescription() const override
std::optional< wxString > GetStatusMessage() const override
Get a status message to show when the routine is complete.
wxString GetCommitDescription() const override
std::optional< wxString > GetStatusMessage() const override
Get a status message to show when the routine is complete.
bool ProcessSubsequentPolygon(const SHAPE_POLY_SET &aPolygon) override
A round rectangle shape, based on a rectangle and a radius.
Definition roundrect.h:36
void TransformToPolygon(SHAPE_POLY_SET &aBuffer) const
Get the polygonal representation of the roundrect.
Definition roundrect.cpp:81
Definition seg.h:42
VECTOR2I A
Definition seg.h:49
VECTOR2I B
Definition seg.h:50
bool Intersects(const SEG &aSeg) const
Definition seg.cpp:431
int Length() const
Return the length (this).
Definition seg.h:343
OPT_VECTOR2I IntersectLines(const SEG &aSeg) const
Compute the intersection point of lines passing through ends of (this) and aSeg.
Definition seg.h:220
bool Contains(const SEG &aSeg) const
Definition seg.h:324
EDA_ANGLE Angle(const SEG &aOther) const
Determine the smallest angle between two segments.
Definition seg.cpp:102
const VECTOR2I & GetArcMid() const
Definition shape_arc.h:118
const VECTOR2I & GetP1() const
Definition shape_arc.h:117
double GetRadius() const
const VECTOR2I & GetP0() const
Definition shape_arc.h:116
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
Represent a set of closed polygons.
void Rotate(const EDA_ANGLE &aAngle, const VECTOR2I &aCenter={ 0, 0 }) override
Rotate all vertices by a given angle.
void BooleanAdd(const SHAPE_POLY_SET &b)
Perform boolean polyset union.
void ClearArcs()
Removes all arc references from all the outlines and holes in the polyset.
void BooleanIntersection(const SHAPE_POLY_SET &b)
Perform boolean polyset intersection.
int OutlineCount() const
Return the number of outlines in the set.
void BooleanSubtract(const SHAPE_POLY_SET &b)
Perform boolean polyset difference.
int GetWidth() const override
Definition shape_rect.h:185
const VECTOR2I & GetPosition() const
Definition shape_rect.h:169
const VECTOR2I GetSize() const
Definition shape_rect.h:177
int GetHeight() const
Definition shape_rect.h:193
static const int MIN_PRECISION_IU
This is the minimum precision for all the points in a shape.
Definition shape.h:131
T EuclideanNorm() const
Compute the Euclidean norm of the vector, which is defined as sqrt(x ** 2 + y ** 2).
Definition vector2d.h:283
VECTOR2< T > Resize(T aNewLength) const
Return a vector of the same direction, but length specified in aNewLength.
Definition vector2d.h:385
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:194
This file is part of the common library.
std::optional< CHAMFER_RESULT > ComputeChamferPoints(const SEG &aSegA, const SEG &aSegB, const CHAMFER_PARAMS &aChamferParams)
Compute the chamfer points for a given line pair and chamfer parameters.
std::optional< DOGBONE_RESULT > ComputeDogbone(const SEG &aSegA, const SEG &aSegB, int aDogboneRadius, bool aAddSlots)
Compute the dogbone geometry for a given line pair and dogbone parameters.
#define _(s)
static constexpr EDA_ANGLE ANGLE_90
Definition eda_angle.h:413
static constexpr EDA_ANGLE FULL_CIRCLE
Definition eda_angle.h:409
static constexpr EDA_ANGLE ANGLE_180
Definition eda_angle.h:415
@ SEGMENT
Definition eda_shape.h:45
@ RECTANGLE
Use RECTANGLE instead of RECT to avoid collision in a Windows header.
Definition eda_shape.h:46
a few functions useful in geometry calculations.
VECTOR2< ret_type > GetClampedCoords(const VECTOR2< in_type > &aCoords, pad_type aPadding=1u)
Clamps a vector to values that can be negated, respecting numeric limits of coordinates data type wit...
static SHAPE_RECT GetRectRoundedToGridOutwards(const SHAPE_RECT &aRect, int aGridSize)
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:60
SHAPE_LINE_CHAIN ConvertToChain(const SHAPE_SEGMENT &aOval)
Definition oval.cpp:35
VECTOR2I RoundNW(const VECTOR2I &aVec, int aGridSize)
Round a vector to the nearest grid point in the NW direction.
VECTOR2I RoundSE(const VECTOR2I &aVec, int aGridSize)
Round a vector to the nearest grid point in the SE direction.
PAD_SHAPE
The set of pad shapes, used with PAD::{Set,Get}Shape()
Definition padstack.h:52
@ ROUNDRECT
Definition padstack.h:57
@ TRAPEZOID
Definition padstack.h:56
@ RECTANGLE
Definition padstack.h:54
std::optional< int > GetBoardItemWidth(const BOARD_ITEM &aItem)
Gets the width of a BOARD_ITEM, for items that have a meaningful width.
Utility functions that can be shared by PCB tools.
static bool addSegment(VRML_LAYER &model, IDF_SEGMENT *seg, int icont, int iseg)
std::optional< VECTOR2I > OPT_VECTOR2I
Definition seg.h:39
Utility functions for working with shapes.
const SHAPE_LINE_CHAIN chain
int radius
SHAPE_CIRCLE circle(c.m_circle_center, c.m_circle_radius)
wxString result
Test unit parsing edge cases and error handling.
VECTOR2I GetRotated(const VECTOR2I &aVector, const EDA_ANGLE &aAngle)
Return a new VECTOR2I that is the result of rotating aVector by aAngle.
Definition trigo.h:77
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
Definition typeinfo.h:88
@ PCB_PAD_T
class PAD, a pad in a footprint
Definition typeinfo.h:87
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:695
Supplemental functions for working with vectors and simple objects that interact with vectors.