KiCad PCB EDA Suite
pad_custom_shape_functions.cpp
Go to the documentation of this file.
1 /*
2  * This program source code file is part of KiCad, a free EDA CAD application.
3  *
4  * Copyright (C) 2018 Jean-Pierre Charras, jp.charras at wanadoo.fr
5  * Copyright (C) 1992-2019 KiCad Developers, see AUTHORS.txt for contributors.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, you may find one here:
19  * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20  * or you may search the http://www.gnu.org website for the version 2 license,
21  * or you may write to the Free Software Foundation, Inc.,
22  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24 
30 #include <fctsys.h>
31 #include <trigo.h>
32 
33 #include <pcbnew.h>
34 
35 #include <bezier_curves.h>
36 #include <class_board.h>
37 #include <class_board_item.h>
38 #include <class_drawsegment.h>
39 #include <class_edge_mod.h>
40 #include <class_pad.h>
42 #include <geometry/convex_hull.h>
44 #include <geometry/shape_rect.h>
45 
46 
48 {
49  aTarget->SetShape( m_Shape );
50  aTarget->SetWidth( m_Thickness );
51  aTarget->SetStart( m_Start );
52  aTarget->SetEnd( m_End );
53  aTarget->SetBezControl1( m_Ctrl1 );
54  aTarget->SetBezControl2( m_Ctrl2 );
55 
56  // in a DRAWSEGMENT the radius of a circle is calculated from the
57  // center and one point on the circle outline (stored in m_End)
58  if( m_Shape == S_CIRCLE )
59  {
60  wxPoint end = m_Start;
61  end.x += m_Radius;
62  aTarget->SetEnd( end );
63  }
64 
65  aTarget->SetAngle( m_ArcAngle );
66  aTarget->SetPolyPoints( m_Poly );
67 }
68 
69 
71 {
72  ExportTo( static_cast<DRAWSEGMENT*>( aTarget ) );
73  // Initialize coordinates specific to the EDGE_MODULE (m_Start0 and m_End0)
74  aTarget->SetLocalCoord();
75 }
76 
77 
78 void PAD_CS_PRIMITIVE::Move( wxPoint aMoveVector )
79 {
80  m_Start += aMoveVector;
81  m_End += aMoveVector;
82  m_Ctrl1 += aMoveVector;
83  m_Ctrl2 += aMoveVector;
84 
85  for( auto& corner : m_Poly )
86  {
87  corner += aMoveVector;
88  }
89 }
90 
91 
92 void PAD_CS_PRIMITIVE::Rotate( const wxPoint& aRotCentre, double aAngle )
93 {
94  switch( m_Shape )
95  {
96  case S_ARC:
97  case S_SEGMENT:
98  case S_CIRCLE:
99  // these can all be done by just rotating the start and end points
100  RotatePoint( &m_Start, aRotCentre, aAngle );
101  RotatePoint( &m_End, aRotCentre, aAngle );
102  break;
103 
104  case S_POLYGON:
105  for( auto& pt : m_Poly )
106  RotatePoint( &pt, aRotCentre, aAngle );
107 
108  break;
109 
110  case S_CURVE:
111  RotatePoint( &m_Start, aRotCentre, aAngle );
112  RotatePoint( &m_End, aRotCentre, aAngle );
113  RotatePoint( &m_Ctrl1, aRotCentre, aAngle );
114  RotatePoint( &m_Ctrl2, aRotCentre, aAngle );
115 
116  break;
117 
118  case S_RECT:
119  default:
120  // un-handled edge transform
121  wxASSERT_MSG( false, wxT( "PAD_CS_PRIMITIVE::Rotate not implemented for "
123  break;
124  }
125 }
126 
127 
128 /*
129  * Has meaning only for free shape pads.
130  * add a free shape to the shape list.
131  * the shape is a polygon (can be with thick outline), segment, circle or arc
132  */
133 
134 void D_PAD::AddPrimitivePoly( const SHAPE_POLY_SET& aPoly, int aThickness, bool aMergePrimitives )
135 {
136  std::vector<wxPoint> points;
137 
138  // If aPoly has holes, convert it to a polygon with no holes.
139  SHAPE_POLY_SET poly_no_hole;
140  poly_no_hole.Append( aPoly );
142 
143  for( auto iter = poly_no_hole.CIterate(); iter; iter++ )
144  points.emplace_back( iter->x, iter->y );
145 
146  AddPrimitivePoly( points, aThickness, aMergePrimitives );
147 }
148 
150  const std::vector<wxPoint>& aPoly, int aThickness, bool aMergePrimitives )
151 {
152  PAD_CS_PRIMITIVE shape( S_POLYGON );
153  shape.m_Poly = aPoly;
154  shape.m_Thickness = aThickness;
155  m_basicShapes.push_back( shape );
156 
157  if( aMergePrimitives )
159 }
160 
161 
163  wxPoint aStart, wxPoint aEnd, int aThickness, bool aMergePrimitives )
164 {
165  PAD_CS_PRIMITIVE shape( S_SEGMENT );
166  shape.m_Start = aStart;
167  shape.m_End = aEnd;
168  shape.m_Thickness = aThickness;
169  m_basicShapes.push_back( shape );
170 
171  if( aMergePrimitives )
173 }
174 
175 
177  wxPoint aCenter, wxPoint aStart, int aArcAngle, int aThickness, bool aMergePrimitives )
178 {
179  PAD_CS_PRIMITIVE shape( S_ARC );
180  shape.m_Start = aCenter;
181  shape.m_End = aStart;
182  shape.m_ArcAngle = aArcAngle;
183  shape.m_Thickness = aThickness;
184  m_basicShapes.push_back( shape );
185 
186  if( aMergePrimitives )
188 }
189 
190 
191 void D_PAD::AddPrimitiveCurve( wxPoint aStart, wxPoint aEnd, wxPoint aCtrl1, wxPoint aCtrl2,
192  int aThickness, bool aMergePrimitives )
193 {
194  PAD_CS_PRIMITIVE shape( S_CURVE );
195  shape.m_Start = aStart;
196  shape.m_End = aEnd;
197  shape.m_Ctrl1 = aCtrl1;
198  shape.m_Ctrl2 = aCtrl2;
199  shape.m_Thickness = aThickness;
200  m_basicShapes.push_back( shape );
201 
202  if( aMergePrimitives )
204 }
205 
206 
208  wxPoint aCenter, int aRadius, int aThickness, bool aMergePrimitives )
209 {
210  PAD_CS_PRIMITIVE shape( S_CIRCLE );
211  shape.m_Start = aCenter;
212  shape.m_Radius = aRadius;
213  shape.m_Thickness = aThickness;
214  m_basicShapes.push_back( shape );
215 
216  if( aMergePrimitives )
218 }
219 
220 
221 bool D_PAD::SetPrimitives( const std::vector<PAD_CS_PRIMITIVE>& aPrimitivesList )
222 {
223  // clear old list
224  m_basicShapes.clear();
225 
226  // Import to the basic shape list
227  if( aPrimitivesList.size() )
228  m_basicShapes = aPrimitivesList;
229 
230  // Only one polygon is expected (pad area = only one copper area)
231  return MergePrimitivesAsPolygon();
232 }
233 
234 bool D_PAD::AddPrimitives( const std::vector<PAD_CS_PRIMITIVE>& aPrimitivesList )
235 {
236  for( const auto& prim : aPrimitivesList )
237  m_basicShapes.push_back( prim );
238 
239  return MergePrimitivesAsPolygon();
240 }
241 
242 
243 // clear the basic shapes list and associated data
245 {
246  m_basicShapes.clear();
248 }
249 
250 
251 bool D_PAD::buildCustomPadPolygon( SHAPE_POLY_SET* aMergedPolygon, int aError )
252 
253 {
254  SHAPE_POLY_SET aux_polyset;
255 
256  for( unsigned cnt = 0; cnt < m_basicShapes.size(); ++cnt )
257  {
258  const PAD_CS_PRIMITIVE& bshape = m_basicShapes[cnt];
259 
260  switch( bshape.m_Shape )
261  {
262  case S_CURVE:
263  {
264  std::vector<wxPoint> ctrlPoints = { bshape.m_Start, bshape.m_Ctrl1, bshape.m_Ctrl2, bshape.m_End };
265  BEZIER_POLY converter( ctrlPoints );
266  std::vector< wxPoint> poly;
267  converter.GetPoly( poly, bshape.m_Thickness );
268 
269  for( unsigned ii = 1; ii < poly.size(); ii++ )
270  {
272  aux_polyset, poly[ ii - 1 ], poly[ ii ], aError, bshape.m_Thickness );
273  }
274  break;
275  }
276 
277  case S_SEGMENT: // usual segment : line with rounded ends
278  {
280  aux_polyset, bshape.m_Start, bshape.m_End, aError, bshape.m_Thickness );
281  break;
282  }
283 
284  case S_ARC: // Arc with rounded ends
285  {
286  TransformArcToPolygon( aux_polyset, bshape.m_Start, bshape.m_End, bshape.m_ArcAngle,
287  aError, bshape.m_Thickness );
288  break;
289  }
290 
291  case S_CIRCLE: // ring or circle
292  {
293  if( bshape.m_Thickness ) // ring
295  aux_polyset, bshape.m_Start, bshape.m_Radius, aError, bshape.m_Thickness );
296  else // Filled circle
297  TransformCircleToPolygon( aux_polyset, bshape.m_Start, bshape.m_Radius, aError );
298  break;
299  }
300 
301  case S_POLYGON: // polygon
302  if( bshape.m_Poly.size() < 2 )
303  break; // Malformed polygon.
304  {
305  // Insert the polygon:
306  const std::vector< wxPoint>& poly = bshape.m_Poly;
307  aux_polyset.NewOutline();
308 
309  if( bshape.m_Thickness )
310  {
311  SHAPE_POLY_SET polyset;
312  polyset.NewOutline();
313 
314  for( unsigned ii = 0; ii < poly.size(); ii++ )
315  {
316  polyset.Append( poly[ii].x, poly[ii].y );
317  }
318 
319  int numSegs = std::max(
320  GetArcToSegmentCount( bshape.m_Thickness / 2, aError, 360.0 ), 6 );
321  polyset.Inflate( bshape.m_Thickness / 2, numSegs );
322 
323  aux_polyset.Append( polyset );
324  }
325  else
326  for( unsigned ii = 0; ii < poly.size(); ii++ )
327  aux_polyset.Append( poly[ii].x, poly[ii].y );
328  }
329  break;
330 
331  default:
332  break;
333  }
334  }
335 
336  aux_polyset.Simplify( SHAPE_POLY_SET::PM_FAST );
337 
338  // Merge all polygons with the initial pad anchor shape
339  if( aux_polyset.OutlineCount() )
340  {
341  aMergedPolygon->BooleanAdd( aux_polyset, SHAPE_POLY_SET::PM_STRICTLY_SIMPLE );
342  aMergedPolygon->Fracture( SHAPE_POLY_SET::PM_STRICTLY_SIMPLE );
343  }
344 
345  return aMergedPolygon->OutlineCount() <= 1;
346 }
347 
348 /* Merge all basic shapes, converted to a polygon in one polygon,
349  * return true if OK, false in there is more than one polygon
350  * in aMergedPolygon
351  */
353 {
354  auto board = GetBoard();
355  int maxError = ARC_HIGH_DEF;
356 
357  if( board )
358  maxError = board->GetDesignSettings().m_MaxError;
359 
360  // if aMergedPolygon == NULL, use m_customShapeAsPolygon as target
361 
362  if( !aMergedPolygon )
363  aMergedPolygon = &m_customShapeAsPolygon;
364 
365  aMergedPolygon->RemoveAllContours();
366 
367  // Add the anchor pad shape in aMergedPolygon, others in aux_polyset:
368  // The anchor pad is always at 0,0
369  switch( GetAnchorPadShape() )
370  {
371  default:
372  case PAD_SHAPE_CIRCLE:
373  TransformCircleToPolygon( *aMergedPolygon, wxPoint( 0, 0 ), GetSize().x / 2, maxError );
374  break;
375 
376  case PAD_SHAPE_RECT:
377  {
378  SHAPE_RECT rect( -GetSize().x / 2, -GetSize().y / 2, GetSize().x, GetSize().y );
379  aMergedPolygon->AddOutline( rect.Outline() );
380 
381  break;
382  }
383  }
384 
385  if( !buildCustomPadPolygon( aMergedPolygon, maxError ) )
386  return false;
387 
388  m_boundingRadius = -1; // The current bounding radius is no longer valid.
389 
390  return aMergedPolygon->OutlineCount() <= 1;
391 }
392 
394  wxPoint aPosition, double aRotation ) const
395 {
396  if( aMergedPolygon->OutlineCount() == 0 )
397  return;
398 
399  // Move, rotate, ... coordinates in aMergedPolygon according to the
400  // pad position and orientation
401  aMergedPolygon->Rotate( -DECIDEG2RAD( aRotation ) );
402  aMergedPolygon->Move( VECTOR2I( aPosition ) );
403 }
404 
406 {
407  SHAPE_POLY_SET poly;
408 
409  if( !buildCustomPadPolygon( &poly, ARC_LOW_DEF ) )
410  return false;
411 
412  const int minSteps = 10;
413  const int maxSteps = 50;
414 
415  int stepsX, stepsY;
416 
417  auto bbox = poly.BBox();
418 
419  if( bbox.GetWidth() < bbox.GetHeight() )
420  {
421  stepsX = minSteps;
422  stepsY = minSteps * (double) bbox.GetHeight() / (double )(bbox.GetWidth() + 1);
423  }
424  else
425  {
426  stepsY = minSteps;
427  stepsX = minSteps * (double) bbox.GetWidth() / (double )(bbox.GetHeight() + 1);
428  }
429 
430  stepsX = std::max(minSteps, std::min( maxSteps, stepsX ) );
431  stepsY = std::max(minSteps, std::min( maxSteps, stepsY ) );
432 
433  auto center = bbox.Centre();
434 
435  auto minDist = std::numeric_limits<int64_t>::max();
436  int64_t minDistEdge;
437 
439  {
440  minDistEdge = GetSize().x;
441  }
442  else
443  {
444  minDistEdge = std::max( GetSize().x, GetSize().y );
445  }
446 
447  OPT<VECTOR2I> bestAnchor( []()->OPT<VECTOR2I> { return NULLOPT; }() );
448 
449  for ( int y = 0; y < stepsY ; y++ )
450  {
451  for ( int x = 0; x < stepsX; x++ )
452  {
453  VECTOR2I p = bbox.GetPosition();
454  p.x += rescale( x, bbox.GetWidth(), (stepsX - 1) );
455  p.y += rescale( y, bbox.GetHeight(), (stepsY - 1) );
456 
457  if ( poly.Contains(p) )
458  {
459 
460  auto dist = (center - p).EuclideanNorm();
461  auto distEdge = poly.COutline(0).Distance( p, true );
462  if ( distEdge >= minDistEdge )
463  {
464  if ( dist < minDist )
465  {
466  bestAnchor = p;
467  minDist = dist;
468  }
469  }
470  }
471  }
472  }
473 
474  if ( bestAnchor )
475  {
476  aPos = *bestAnchor;
477  return true;
478  }
479 
480  return false;
481 }
double EuclideanNorm(const wxPoint &vector)
Euclidean norm of a 2D vector.
Definition: trigo.h:128
void Rotate(double aAngle, const VECTOR2I &aCenter={ 0, 0 })
Function Rotate rotates all vertices by a given angle.
static wxString ShowShape(STROKE_T aShape)
Function ShowShape converts the enum STROKE_T integer value to a wxString.
int m_boundingRadius
radius of the circle containing the pad shape
Definition: class_pad.h:851
std::vector< PAD_CS_PRIMITIVE > m_basicShapes
for free shape pads: a list of basic shapes, in local coordinates, orient 0, coordinates relative to ...
Definition: class_pad.h:868
void SetShape(STROKE_T aShape)
int OutlineCount() const
Returns the number of outlines in the set
const SHAPE_LINE_CHAIN Outline() const
Definition: shape_rect.h:146
static const int dist[10][10]
Definition: ar_matrix.cpp:326
void BooleanAdd(const SHAPE_POLY_SET &b, POLYGON_MODE aFastMode)
Performs boolean polyset union For aFastMode meaning, see function booleanOp
void AddPrimitiveArc(wxPoint aCenter, wxPoint aStart, int aArcAngle, int aThickness, bool aMergePrimitives=true)
arc basic shape
PAD_SHAPE_T GetAnchorPadShape() const
Function GetAnchorPadShape.
Definition: class_pad.h:247
void AddPrimitiveCurve(wxPoint aStart, wxPoint aEnd, wxPoint aCtrl1, wxPoint aCtrl2, int aThickness, bool aMergePrimitives=true)
curve basic shape
Classes BOARD_ITEM and BOARD_CONNECTED_ITEM.
void GetPoly(std::vector< wxPoint > &aOutput, int aMinSegLen=0)
Converts Bezier curve to a polygon.
bool GetBestAnchorPosition(VECTOR2I &aPos)
bool AddPrimitives(const std::vector< PAD_CS_PRIMITIVE > &aPrimitivesList)
Add to the basic shape list.
void ExportTo(DRAWSEGMENT *aTarget)
Export the PAD_CS_PRIMITIVE parameters to a DRAWSEGMENT useful to draw a primitive shape.
wxPoint m_Start
angle of an arc, from its starting point, in 0.1 deg
Definition: class_pad.h:98
polygon (not yet used for tracks, but could be in microwave apps)
int Distance(const VECTOR2I &aP, bool aOutlineOnly=false) const
Function Distance()
usual segment : line with rounded ends
void Move(wxPoint aMoveVector)
returns the start point of an arc
void TransformArcToPolygon(SHAPE_POLY_SET &aCornerBuffer, wxPoint aCentre, wxPoint aStart, double aArcAngle, int aError, int aWidth)
Function TransformArcToPolygon Creates a polygon from an Arc Convert arcs to multiple straight segmen...
bool Contains(const VECTOR2I &aP, int aSubpolyIndex=-1, int aAccuracy=0, bool aUseBBoxCaches=false) const
Returns true if a given subpolygon contains the point aP.
void RotatePoint(int *pX, int *pY, double angle)
Definition: trigo.cpp:208
void Inflate(int aAmount, int aCircleSegmentsCount, CORNER_STRATEGY aCornerStrategy=ROUND_ALL_CORNERS)
Performs outline inflation/deflation.
VECTOR2< int > VECTOR2I
Definition: vector2d.h:594
void SetBezControl2(const wxPoint &aPoint)
wxPoint m_Ctrl1
is also the start point of the arc
Definition: class_pad.h:100
void AddPrimitivePoly(const SHAPE_POLY_SET &aPoly, int aThickness, bool aMergePrimitives=true)
Has meaning only for free shape pads.
segment with non rounded ends
int m_Radius
thickness of segment or outline For filled S_CIRCLE shape, thickness = 0.
Definition: class_pad.h:96
const auto NULLOPT
Definition: optional.h:9
std::vector< wxPoint > m_Poly
Bezier Control point 2.
Definition: class_pad.h:102
void Move(const VECTOR2I &aVector) override
bool MergePrimitivesAsPolygon(SHAPE_POLY_SET *aMergedPolygon=NULL)
Merge all basic shapes, converted to a polygon in one polygon, in m_customShapeAsPolygon.
SHAPE_POLY_SET.
Arcs (with rounded ends)
Helper class to handle a primitive (basic shape: polygon, segment, circle or arc) to build a custom p...
Definition: class_pad.h:89
virtual BOARD * GetBoard() const
Function GetBoard returns the BOARD in which this BOARD_ITEM resides, or NULL if none.
a few functions useful in geometry calculations.
void Simplify(POLYGON_MODE aFastMode)
Simplifies the polyset (merges overlapping polys, eliminates degeneracy/self-intersections) For aFast...
SHAPE_POLY_SET m_customShapeAsPolygon
for free shape pads: the set of basic shapes, merged as one polygon, in local coordinates,...
Definition: class_pad.h:873
Bezier Curve.
wxPoint m_End
is also the center of the circle and arc
Definition: class_pad.h:99
int NewOutline()
Creates a new empty polygon in the set and returns its index
CONST_ITERATOR CIterate(int aFirst, int aLast, bool aIterateHoles=false) const
STROKE_T m_Shape
Definition: class_pad.h:92
void Fracture(POLYGON_MODE aFastMode)
Converts a set of polygons with holes to a singe outline with "slits"/"fractures" connecting the oute...
Pad object description.
wxPoint m_Ctrl2
Bezier Control point 1.
Definition: class_pad.h:101
void SetStart(const wxPoint &aStart)
bool buildCustomPadPolygon(SHAPE_POLY_SET *aMergedPolygon, int aError)
void AddPrimitiveCircle(wxPoint aCenter, int aRadius, int aThickness, bool aMergePrimitives=true)
ring or circle basic shape
void SetPolyPoints(const std::vector< wxPoint > &aPoints)
int m_Thickness
S_SEGMENT, S_ARC, S_CIRCLE, S_POLYGON only (same as DRAWSEGMENT)
Definition: class_pad.h:93
int AddOutline(const SHAPE_LINE_CHAIN &aOutline)
Adds a new outline to the set and returns its index
void SetLocalCoord()
Set relative coordinates from draw coordinates.
Bezier curves to polygon converter.
Definition: bezier_curves.h:35
Class to handle a graphic segment.
void CustomShapeAsPolygonToBoardPosition(SHAPE_POLY_SET *aMergedPolygon, wxPoint aPosition, double aRotation) const
When created, the corners coordinates are relative to the pad position, orientation 0,...
const SHAPE_LINE_CHAIN & COutline(int aIndex) const
void RemoveAllContours()
Removes all outlines & holes (clears) the polygon set.
void AddPrimitiveSegment(wxPoint aStart, wxPoint aEnd, int aThickness, bool aMergePrimitives=true)
segment basic shape
void TransformCircleToPolygon(SHAPE_POLY_SET &aCornerBuffer, wxPoint aCenter, int aRadius, int aError)
Function TransformCircleToPolygon convert a circle to a polygon, using multiple straight lines.
double DECIDEG2RAD(double deg)
Definition: trigo.h:218
T rescale(T aNumerator, T aValue, T aDenominator)
Function rescale()
Definition: util.h:84
coord_type GetHeight() const
Definition: box2.h:197
void TransformSegmentToPolygon(SHAPE_POLY_SET &aCornerBuffer, wxPoint aStart, wxPoint aEnd, int aError, int aWidth)
Function TransformRoundedEndsSegmentToPolygon convert a segment with rounded ends to a polygon Conver...
boost::optional< T > OPT
Definition: optional.h:7
void SetEnd(const wxPoint &aEnd)
void SetAngle(double aAngle)
Function SetAngle sets the angle for arcs, and normalizes it within the range 0 - 360 degrees.
void TransformRingToPolygon(SHAPE_POLY_SET &aCornerBuffer, wxPoint aCentre, int aRadius, int aError, int aWidth)
Function TransformRingToPolygon Creates a polygon from a ring Convert arcs to multiple straight segme...
const wxSize & GetSize() const
Definition: class_pad.h:300
EDGE_MODULE class definition.
void Rotate(const wxPoint &aRotCentre, double aAngle)
Rotates the primitive about a point.
const BOX2I BBox(int aClearance=0) const override
Function BBox()
int GetArcToSegmentCount(int aRadius, int aErrorMax, double aArcAngleDegree)
bool SetPrimitives(const std::vector< PAD_CS_PRIMITIVE > &aPrimitivesList)
Import to the basic shape list.
void DeletePrimitivesList()
clear the basic shapes list
double m_ArcAngle
radius of a circle
Definition: class_pad.h:97
void SetBezControl1(const wxPoint &aPoint)
int Append(int x, int y, int aOutline=-1, int aHole=-1, bool aAllowDuplication=false)
Appends a vertex at the end of the given outline/hole (default: the last outline)
void SetWidth(int aWidth)